Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unlock using lockf()?

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);
}
like image 391
user1542921 Avatar asked Jul 21 '12 16:07

user1542921


1 Answers

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);
like image 55
Linuxios Avatar answered Nov 08 '22 15:11

Linuxios