检查解锁文件是否成功 - fcntl

时间:2017-03-20 18:39:48

标签: c unix posix locks fcntl

在编写代码来训练一些unix锁时,我遇到了一个问题。所以我的问题是 - 如何正确检查解锁是否成功完成?我查看了手册中的示例并执行了此操作:

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

后来:

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

0 个答案:

没有答案