我编译这个文件并在一个控制台中运行它。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
/* l_type l_whence l_start l_len l_pid */
struct flock fl = {F_WRLCK, SEEK_SET, 0, 0, 0 };
int fd;
fl.l_pid = getpid();
if (argc > 1)
fl.l_type = F_RDLCK;
if ((fd = open("lockdemo.c", O_RDWR)) == -1) {
perror("open");
exit(1);
}
printf("Press <RETURN> to try to get lock: ");
getchar();
printf("Trying to get lock...");
if (fcntl(fd, F_SETLKW, &fl) == -1) {
perror("fcntl");
exit(1);
}
printf("got lock\n");
printf("Press <RETURN> to release lock: ");
getchar();
fl.l_type = F_UNLCK; /* set to unlock same region */
if (fcntl(fd, F_SETLK, &fl) == -1) {
perror("fcntl");
exit(1);
}
printf("Unlocked.\n");
close(fd);
return 0;
}
它输出:
ZJ:~/Documents/c$ ./a.out
press <RETURN> to try to get lock:
Trying to get lock...got lock
press <RETURN> to release lock:
我打开另一个控制台并 vi lockdemo.c 并成功修改了 lockdemo.c。为什么?这个文件不是被锁了吗?当我打开另一个控制台时
ZJ:~/Documents/c$ ./a.out
press <RETURN> to try to get lock:
a.out 一直在运行 getchar(),甚至无法执行 printf("尝试获取锁..."); 我完全糊涂了。