fcntl如何知道哪个进程持有锁定文件?

时间:2018-07-17 18:53:05

标签: c fcntl

我是fcntl锁定的新手,并按照以下示例使用c代码在Linux中创建示例锁定:http://www.informit.com/articles/article.aspx?p=23618&seqNum=4

我想知道如何才能打印出哪个进程持有锁定文件以及哪个进程正在等待锁定。我考虑使用l_pid来找出持有锁的进程ID,但是我不确定这样做的正确方法。 打印出哪个进程持有锁的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

man 2 fcntl页所述,您可以使用F_GETLK获取具有冲突锁的进程ID(如果冲突锁是与进程相关的锁)。例如,

/* Return 0 if descriptor locked exclusively, positive PID if
   a known process holds a conflicting lock, or -1 if the
   descriptor cannot be locked (and errno has the reason).
*/
static pid_t  lock_exclusively(const int fd)
{
    struct flock  lock;
    int           err = 0;

    if (fd == -1) {
        errno = EINVAL;
        return -1;
    }

    lock.l_type = F_WRLCK;
    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 0;
    if (!fcntl(fd, F_SETLK, &lock))
        return 0;

    /* Remember the cause of the failure */
    err = errno;

    lock.l_type = F_WRLCK;
    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 0;
    lock.l_pid = 0;
    if (fcntl(fd, F_GETLK, &lock) == 0 && lock.l_pid > 0)
        return lock.l_pid;

    errno = err;
    return -1;
}

请注意,fd必须处于打开状态才能进行读取和写入。我建议使用open(path, O_RDWR | O_NOCTTY)open(path, O_WRONLY | O_NOCTTY)。将 any 文件描述符关闭到同一文件将释放锁定。

有人可能会说在第二次lock通话之前重置fcntl()成员是不必要的,但是在此我还是要谨慎一点。

关于如何举报,我只用

int    fd;
pid_t  p;

fd = open(path, O_RDWR | O_NOCTTY);
if (fd == -1) {
    fprintf(stderr, "%s: Cannot open file: %s.\n",
                    path, strerror(errno));
    exit(EXIT_FAILURE);
}

p = lock_exclusively(fd);
if (p < 0) {
    fprintf(stderr, "%s: Cannot lock file: %s.\n",
                    path, strerror(errno));
    exit(EXIT_FAILURE);
} else
if (p > 0) {
    fprintf(stderr, "%s: File is already locked by process %ld.\n",
                    path, (long)p);
    exit(EXIT_FAILURE);
}

/* fd is now open and exclusive-locked. */

用户始终可以运行例如ps -o cmd= -p PID来查看是什么命令(或者您可以尝试在Linux中阅读/proc/PID/cmdline)。

答案 1 :(得分:0)

从示例代码中:

printf ("locking\n");
/* Initialize the flock structure. */
memset (&lock, 0, sizeof(lock));
lock.l_type = F_WRLCK;
/* Place a write lock on the file. */
fcntl (fd, F_SETLKW, &lock);

printf ("locked; hit Enter to unlock... ");

您需要将fcntl (fd, F_SETLKW, &lock);更改为:

if (fcntl (fd, F_SETLK, &lock) == -1) {
  printf ("File is locked by pid %i\n", lock.l_pid);
  return 0;
}

如果F_SETLKW命令无法获得锁定,则会阻塞。如果无法获得锁,则F_SETLK将返回。确实,代码在获得-1返回值之后还应该检查errno == EACCESSerrno == EAGAIN