开发者

Preventing threads from writing to the same file

开发者 https://www.devze.com 2023-01-03 05:38 出处:网络
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 开发者_Python百科subsequent attempt to open it by another t

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 开发者_Python百科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.


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.


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.


Use the O_CREATE and O_EXCL flags to open(). That way the call will fail if the file already exists.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号