防止线程写入同一文件
我正在 Linux 内核 2.4 中实现类似 FTP 的协议(家庭作业),我的印象是,如果打开一个文件进行写入,则任何后续尝试由另一个线程打开它的操作都会失败,直到我实际尝试并发现它会通过。
我该如何防止这种情况发生?
PS:我使用 open() 打开文件。
PS2:我需要能够访问现有文件。我只是想防止它们被同时写入。
I'm implementing an FTP-like protocol in Linux kernel 2.4 (homework), and I was under the impression that if a file is open for writing any subsequent attempt to open it by another thread should fail, until I actually tried it and discovered it goes through.
How do I prevent this from happening?
PS: I'm using open() to open the file.
PS2: I need to be able to access existing files. I just want to prevent them being written to simultaneously.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以保留打开文件的列表,然后在打开文件之前检查它是否已被另一个线程打开。这种方法的一些问题是:
程序完成后,需要将文件从列表中删除。
程序完成
You could keep a list of open files, and then before opening a file check to see if it has already been opened by another thread. Some issues with this approach are:
You will need to use a synchronization primitive such as a Mutex to ensure the list is thread-safe.
Files will need to be removed from the list once your program is finished with them.
系统级文件锁定是基于进程的,因此您不能使用它。您将需要使用进程级锁定。例如,通过使用 pthread 定义互斥体(锁)。
System-level file locking is process-based, so you cannot use it. You will need to use process-level locking. For example, by defining a mutex (lock) using pthreads.
使用 O_CREATE 和 O_EXCL 标志来 open()。这样,如果文件已经存在,调用将会失败。
Use the O_CREATE and O_EXCL flags to open(). That way the call will fail if the file already exists.