使用C语言的POSIX使二进制信号量在多个进程(非线程,仅进程)之间共享 [英] Making binary semaphore shared between multiple processes(not threads , Process Only) using POSIX in C language

查看:344
本文介绍了使用C语言的POSIX使二进制信号量在多个进程(非线程,仅进程)之间共享的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C语言中的POSIX使二进制信号量在多个进程(不是线程,仅进程)之间共享. 如果我使用互斥锁创建二进制信号量,

 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;

我将只能在线程之间使用它,但是我想在进程之间共享. 所以我的问题是 如何使用posix计数信号量制作二进制信号量?

解决方案

目前尚不清楚您所说的 binary 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");

要在各个进程之间强制使用互斥锁,可以使用文件...

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

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 ?

解决方案

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

这篇关于使用C语言的POSIX使二进制信号量在多个进程(非线程,仅进程)之间共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆