3
votes

i am making binary semaphore shared between multiple processes(not threads , Process Only) using POSIX in C language. if i create binary semaphore using mutex,

 typedef struct BIN_SEMA
  { 
     pthread_cond_t  cv;    /* cond. variable 
                                   - used to block threads */
     pthread_mutex_t mutex; /* mutex variable
                             - used to prevents concurrent
                                    access to the variable "flag" */
     int     flag;          /* Semaphore state: 
                                    0 = down, 1 = up */
   } bin_sema;

i will be able to use it amongst the threads only , but i want to share between processes. so my question is, how to make binary semaphore using posix counting semaphores ?

1
Why would you ever make a binary semaphore like that? The mutex itself is already a binary semaphore. Also, if you're synchronizing separate processes, why don't you use the appropriate mechanisms for that: sem_open(), sem_init(), sem_wait(), sem_post(), sem_unlink()? - EOF
but your suggested methods are for counting semaphore. if i am taking sem_t *sem_id; then it is creating a counting semaphore. and i need binary semaphore. so asked this question ! - KrunalParmar
Gee, I wonder what kind of semaphore I'd get if I initiated a counting-semaphore with an initial value of 1. - EOF
It is answered by many people in stackoverflow. But , even if i am initiating with 1 , i am not getting binary semaphore.. Its still counting semaphore ! - KrunalParmar

1 Answers

2
votes

It's not clear what you mean by binary semaphore. If you mean something that can have two states, then a mutex or a semaphore initialized with one would be functionally equivalent.

If you want to share the semaphore across processes, you can use a named semaphore...

sem_t* sem = sem_open("/APP/SEMAPHORE", O_CREAT, (S_IRUSR | S_IWUSR), 1);

sem_wait(sem);

// do stuff

sem_post(sem);

// do more stuff

sem_unlink("/APP/SEMAPHORE");

To enforce a mutex across a processes, you can use a file...

const char* lock_file = ".lock";

const int fd_lock = open(lock_file, O_CREAT);

flock(fd_lock, LOCK_EX);

// do stuff

flock(fd_lock, LOCK_UN);

// do more stuff

close(fd_lock);    
unlink(lock_file);