Problem while writing to a file...?

Hi, I have an issue with the file writing...

It is, Suppose that if I am writing some data to a file... and at the same time another user has opened the file and want to write in to the file(writing to the file at the same time)...the another has to know that someone has opened the file, mean while he has to write data to the buffer... Once the first user completes writing to the file...then the data in the buffer has to be written in the same file.

My problem is

  1. Which mode the file has to be opened using OPEN system call...
  2. How to make the other user know that 1st user has opened the file(File is opened in different systems...).

You are referring to file locks. IT may be slightly different on some versions of UNIX, especially older ones.

Read your system documentation on fnctl() - it allows you to lock files. Your sytem may also support lockf().

This comment applies only to C.

For shell scripts one way to do this is to use a separate file - a lock file. Kind of like a traffic light to control access to the file.

Here is an example of a simple lock file - it's use is to test if the file exists or not. If it exists, do not write to the file. If ti does not exist - create the empty lock file, do your write, remove the empty lock file - so each user takes turns.

Best way to lock a file in BASH? - Yahoo! Answers

Thank you for your reply...Yes, I'm using Fedora9 linux....and writing the program in C language....

My requirement is that both the users must able to write the data in to the file...

But how to know that another user has opened the file in write mode...So that 2nd user,mean while writes his data in to buffer and once the 1st user completes his writing, the data has to be placed into the file...

Will lsof() func helps?

Like jim says, read your system documentation on fcntl(). You can do advisory locking, in which you:

  • Open the file
  • Call ioctl(fileno, F_GETLK, &lockdata) where lockdata is a properly filled 'struct flock' structure, details on which are in the fcntl documentation.
  • If the lock succeeds, you have the file. If you don't, you don't.
  • If you locked the file, call ioctl again with F_SETLK to release your lock.