views:

94

answers:

3

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.

+1  A: 

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.

Dave
+1  A: 

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

Amardeep
This will not work for me because I need to be able to access existing files. I just want to prevent them being written to simultaneously.
EpsilonVector
+2  A: 

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.

Justin Ethier