rsinha
rsinha

Reputation: 2227

Shared Memory Semaphore

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

Upvotes: 1

Views: 2894

Answers (5)

vpram86
vpram86

Reputation: 6010

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.,)

Upvotes: 2

Josh Haberman
Josh Haberman

Reputation: 4220

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

Upvotes: 3

caf
caf

Reputation: 239341

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

flock(fd, LOCK_EX);
n = write(fd, buf, count);
flock(fd, LOCK_UN);

Upvotes: 1

qrdl
qrdl

Reputation: 35008

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

It is a best book ever written on this subject.

Upvotes: 2

stefanB
stefanB

Reputation: 79930

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.

Upvotes: 1

Related Questions