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

会有一股神秘感。 提交于 2019-12-05 20:30:58

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!