0

While writing a code to train some unix locks I have come across a problem. So my question is - how to properly check if unlocking has finished successfully? I looked at the example in manual and did this:

struct flock* createLock(int descr, int type, int byteno, int waiting){
  struct flock* fl = malloc(sizeof(flock));
  fl -> l_type = type;
  fl -> l_whence = SEEK_SET;
  fl -> l_start = byteno;
  fl -> l_len = 1;
  fl -> l_pid = getpid();

  int block;
  if(waiting == 0)
    block = F_SETLK;
  else
    block = F_SETLKW;

  if(fcntl(descr, block, fl) < 0){
    perror(ANSI_COLOR_YELLOW "fcntl" ANSI_COLOR_RESET);
    free(fl);
    return NULL;
  }
  return fl;
}

And later on:

if(strcmp(buf, unlock) == 0){
  int byteno;
  printf(ANSI_COLOR_BLUE "Insert byte number: " ANSI_COLOR_RESET);
  scanf("%d\n", &byteno);
  struct flock* fl = createLock(descr, F_UNLCK, byteno, 0);
  if(fl == NULL || fl->l_type != F_UNLCK){
    free(fl);
    continue;
  }
  fprintf(stdout, ANSI_COLOR_GREEN "Unlocked." ANSI_COLOR_RESET);
  free(fl);
  continue;
}
Kanes115
  • 119
  • 6
  • Why do you not consider the return value of fcntl to be good enough? – Zan Lynx Mar 20 '17 at 19:41
  • The only circumstance under which http://pubs.opengroup.org/onlinepubs/9699919799/functions/fcntl.html licenses `fcntl(fd, F_SETLK, (struct flock *){ ..., F_UNLCK, ... })` to fail, is if `fd` is an invalid file descriptor. Therefore the answer to your question is "You don't need to worry about this." – zwol Mar 20 '17 at 19:46

0 Answers0