How to unlock using lockf()?

c, file, flock, linux, unix

Solution

Replace `int fdSource = (int)file;` with this:

int fd = fileno(file);

Also, if you are on a UNIX, you want `flock`, not `lockf`. To lock, do this:

flock(fd, LOCK_EX);

And to unlock:

flock(fd, LOCK_UN);

Problem

I want to read from txt file and append the next number in it, I want to use fork as well to work as a second process. In following code, I need help to unlock the file. I am unable to unlock the file. ``` int main() { int x; pid_t child = fork(); FILE *file; //flock(fileno(file),LOCK_EX); file = fopen ("list.txt", "r"); //printf("file is locked"); int fdSource = (int)file; if (fdSource > 0){ if (lockf(fdSource, F_LOCK, 0) == -1) x = readValue(file); return 0; /* FAILURE */ } else { return 1; } if (lockf(fdSource, F_ULOCK, 0) == -1){ printf("file is not lock"); appendValue(x); } else { return 1; } appendValue(x); } ```

Original source