1

I'm writing a C Linux program for college, using low-level file I/O (I have to use fcntl, basically). I need to lock 8 bytes past the end of the file, to append some new data. Trying this as below returns an Invalid argument error.

struct flock field_lock;
field_lock.l_type = F_WRLCK;
field_lock.l_whence = SEEK_CUR;
field_lock.l_start = 0;
field_lock.l_len = 2 * sizeof(int);
// ...
lseek(stocks_fd, 0, SEEK_END);
// ...
fcntl(stocks_fd, F_SETLKW, &field_lock);

Any idea how else I could achieve this, or what I'm doing wrong?

edit 1: https://gist.github.com/limelier/5a7ba8ab166a1f586a3c4feec355b83b Entire program with an improvement applied to the EOF locks and writing logic, as recommended in the comments below. Same problem still exists, though, and a sample output has been appended.

limelier
  • 11
  • 2
  • 3
    `fcntl(2)` indeed says "Bytes past the end of the file may be locked". Can you provide a more complete example, including how you open the file? – jamieguinan May 02 '19 at 14:37
  • Have you tried defining your lock relative to `SEEK_END` instead of `SEEK_CUR`? That would be more explicit, and would also remove the need to actually seek to the end of the file before locking the region. – John Bollinger May 02 '19 at 15:45
  • 1
    What error did you get? Besides, if you want to set `F_WRLCK`, your file descriptor must be open for writing. – Paul May 02 '19 at 15:50
  • 1
    Your approach works for me, both as given (with `SEEK_CUR` and `lseek` to end of file) and with the `SEEK_END` variation I suggested, in conjunction with a medium-sized file of random data. – John Bollinger May 02 '19 at 16:03
  • 1
    Your approach works for me too. Please provide more information, the whole program perhaps. :) – Paul May 02 '19 at 16:14
  • Thank you for the advice, this actually makes things much easier. However, I still can't get the problem to go away. I have pasted the program here (don't judge my horrid macros, I'm getting to those eventually :p) - https://gist.github.com/limelier/5a7ba8ab166a1f586a3c4feec355b83b Sorry the program is so long (and bloated by error handling), I can provide a more concise version a little later if it helps. – limelier May 03 '19 at 10:59
  • ^ the problem can be illustrated by running the program with an empty binary file and an instruction file containing "1 1" as arguments -- the output added to the gist for your convenience. – limelier May 03 '19 at 11:07
  • https://stackoverflow.com/questions/330793/how-to-initialize-a-struct-in-accordance-with-c-programming-language-standards – jamieguinan May 03 '19 at 14:10
  • @jamieguinan thanks for the recommendation! it'll definitely help simplify my code a bit. – limelier May 03 '19 at 14:46
  • I also commented on your gist. :) – jamieguinan May 03 '19 at 14:56

0 Answers0