views:

490

answers:

5

Hi,

I have 10 processes running, each writing to the same file. I don't want multiple writers, so basically I am looking for a mutex/binary semaphore to protect file writes. The problem is I can't share the semaphore amongst 10 processes, so I am looking at using shared memory between 10 processes, and putting the semaphore inside shared memory so it can be accessed by each process.

Can anyone point me to documentation on this in C/C++ for Unix? Sample code to use this structure would be great.

Thanks

A: 

How about using UNIX IPC to create a shared queue. One process reads the queue and writes to file, all the other processes pushing data into queue.

stefanB
+1  A: 

Take a look at UNIX Network Programming Vol. 2 by W. Richard Stevens.

It is a best book ever written on this subject.

qrdl
+1  A: 

It sounds like you'd be better off using flock(2):

flock(fd, LOCK_EX);
n = write(fd, buf, count);
flock(fd, LOCK_UN);
caf
+3  A: 

Putting a semaphore in shared memory is not the best solution to this problem (if it would even work at all). You should investigate file locking, which is a UNIX feature specifically designed to provide exclusivity among file writers.

Specifically, check out:

For more explanatory material, see Advanced Programming in the UNIX Environment, section 14.3

Josh Haberman
+2  A: 

You could use PTHREAD mutexes. While initilazing a mutex you need to use pthread_mutexattr_setpshared function to make the mutex shared across processes and then put this inside a shared memory. All processes can attach to the shared memory and then access the mutex.

Also you could add additional attributes to the SHM based on your locking requirement (recursive, etc.,)

Aviator