lppier
lppier

Reputation: 1987

Semaphores in C Linux Programming

I'm taking over some C code running in Linux (Centos) with extensive use of semaphores. The way the code is written :

./Program1

This program launches a bunch of processes which makes use of mutexes and semaphores.

./Program2

This program also launches a bunch of processes which makes use of mutexes and semaphores.

I've realised that Program1 and Program2, they make use of semaphores with the same names. In Linux C programming, can different programs use the same semaphores? My guess is no, but the same naming is confusing the hell out of me. They are using the same source code to launch and handle the semaphores.

The semaphores are invoked using the following commands:

semget semctl semop I've read that these are called processes semaphores.. if Program1 creates SEMAPHORE1, can Program2 access SEMAPHORE1?

Appreciate any help here, thanks!

Upvotes: 1

Views: 1202

Answers (1)

paxdiablo
paxdiablo

Reputation: 881133

Assuming you mean named semaphores (or even unnamed semaphores stored in shared memory, both which can be created with sem_open), they generally are shared amongst processes.

Semaphores using semget and related calls use an ID key rather than a name but their usage patterns are similar.

Semaphores are one of the IPC (inter-process communication) methods.

You can create a one-process-only semaphore by using an unnamed variant in non-shared memory and this will only be accessible to threads of the given process but, in my experience, that's not a common use case. The semget family of calls can also give you process-private semaphores.

Mutexes, on the other hand, tend to be more used within a single process for inter-thread communication but there is even a variant of them that can work inter-process.

You create a pthread_mutexattr (attribute) which allows sharing of mutexes and then use that attribute when initialising the mutex you want to share. Obviously, the mutex needs to be in shared memory so that multiple processes can get at it.

Upvotes: 2

Related Questions