简体   繁体   中英

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);
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM