【发布时间】:2021-08-14 04:05:21
【问题描述】:
我正在尝试使用 fcntl lib(在 UNIX c 编程中)来锁定或解锁文件,但似乎没有锁定,我不知道为什么。我没有收到任何错误,看起来程序在执行锁定但实际上我可以读/写文件并且没有被锁定
if (enter == 2){
getchar ();
int fd;
struct flock lock;
char file[20];
printf ("Enter file name:");
fgets(file,20,stdin);
printf ("opening %s\n", file);
//Open a file descriptor to the file
fd = open (file, O_RDWR);
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_SETLK, &lock);
printf ("locked; hit Enter to unlock... ");
//Wait for the user to hit Enter
getchar ();
printf ("unlocking\n");
//Release the lock
lock.l_type = F_UNLCK;
fcntl (fd, F_SETLK, &lock);
close (fd);
【问题讨论】:
-
锁定只是建议性的。其他进程需要检查文件是否设置了此建议锁。