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


最近在写一个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

原创文章,作者:kepupublish,如若转载,请注明出处:https://blog.ytso.com/tech/aiops/278149.html

(0)
上一篇 2022年8月1日 03:09
下一篇 2022年8月1日 03:10

相关推荐

发表回复

登录后才能评论