KrunalParmar
KrunalParmar

Reputation: 1114

Making binary semaphore shared between multiple processes(not threads , Process Only) using POSIX in C language

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 ?

Upvotes: 4

Views: 2448

Answers (1)

Jason
Jason

Reputation: 3917

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);

Upvotes: 2

Related Questions