如何解决fcntl 不锁定/解锁文件 [Unix - C]
我正在尝试使用 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]它不会阻止任何人读取或写入文件。
- 写锁防止任何人获得锁,而读锁仅防止获得写锁。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。