问题描述
我正在尝试使用 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,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,&lock);
close (fd);
解决方法
当您没有检查 fcntl
的结果时,您声称已锁定文件是非常大胆的。
无论如何,这是预期的行为。获得锁只是防止其他人获得锁。[1]它不会阻止任何人读取或写入文件。
- 写锁防止任何人获得锁,而读锁仅防止获得写锁。