作为
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)
. 关闭
任何
同一文件的文件描述符将释放锁。
有人可能会说,重新设置
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
查看这是什么命令(或者您可以尝试阅读
/proc/PID/cmdline
在Linux中)。