ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

利用有名信号量(named semaphore)实现进程同步

2022-08-01 02:01:26  阅读:193  来源: 互联网

标签:named 进程同步 信号量 semaphore close sem open


最近在写一个C/C++程序,父进程需要根据子进程的pid准备一些环境,子进程需要一直挂起,直到父进程的准备工作结束。经google发现可以使用named samaphore来实现进程同步。

有名信号量 named semaphore

linux操作系统中,通过为信号量命名,不同进程可以实现同步。相关api有sem_open sem_close sem_unlink
sem_open创建或打开一个named semaphore。sem_close为当前进程关闭一个信号量,如果没有被显式调用,进程退出时会被隐式调用。sem_unlink取消对name的绑定,如果有一个进程调用了sem_unlink,而且所有使用相应的信号量的进程都已经退出或者调用了sem_close,相应的信号量会立即被系统删除。调用sem_unlink之后继续使用sem_open操作相同的name,则会产生一个与先前不相同的信号量。

A named semaphore is identified by a name of the form /somename; that is, a null-terminated string of up to NAME_MAX-4 (i.e., 251) charac ters consisting of an initial slash, followed by one or more characters, none of which are slashes. Two processes can operate on the same named semaphore by passing the same name to sem_open(3).
The sem_open(3) function creates a new named semaphore or opens an existing named semaphore. After the semaphore has been opened, it can be operated on using sem_post(3) and sem_wait(3). When a process has finished using the semaphore, it can use sem_close(3) to close the semaphore. When all processes have finished using the semaphore, it can be removed from the system using sem_unlink(3).

例子

//子进程
int call_back(void *args) {
  sem_t *sem = sem_open("/semaphore", 0); //打开一个先前已经创建的名为/semaphore的信号量,注意名字必须以/开头。第二个参数为0表示要打开一个信号量。
  sem_wait(sem); //等待信号量的值大于0
  sem_close(sem); //主动关闭信号量(即使不这样做,当本进程退出时也会隐式调用)
  sem_unlink("/semaphore"); //取消绑定

  /*do something*/

  return 0;
}

int main {

  sem_t *sem = sem_open("/semaphore", O_CREAT, 0644, 0); //最后一个参数表示将信号量初始化为0,O_CREAT表示如果/semaphore对应的信号量不存在则创建一个named semephore

  char *child_stack = new char[STACK_SIZE];
  const int STACK_SIZE = 1024*1024;
  int flags = SIGCHLD;
  void *args;
  int pid = clone(call_back, child_stack + STACK_SIZE, flags, args); //创建子线程
  
  /*prepare something for child process base on pid*/

  sem_post(sem);
  sem_close(sem);

  waitpid(pid, NULL, 0);

  delete[] child_stack;
}

参考资料

https://stackoverflow.com/questions/15866597/how-to-use-named-semaphore-from-child
https://stackoverflow.com/questions/8359322/how-to-share-semaphores-between-processes-using-shared-memory
https://stackoverflow.com/questions/9537068/sem-close-vs-sem-unlink-when-process-terminates

标签:named,进程同步,信号量,semaphore,close,sem,open
来源: https://www.cnblogs.com/yuxiayizhengwan/p/16538798.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有