posix - 为什么信号量不起作用?

标签 posix fork semaphore

#include <stdio.h>
#include <sys/types.h>
#include <iostream>
#include <unistd.h>
#include <fstream>
#include <string>
#include <semaphore.h>

using namespace std;

int main(int argc, char *argv[]){
  int pshared = 1;
  unsigned int value = 0;
  sem_t sem_name;
  sem_init(&sem_name, pshared, value);

  int parentpid = getpid();
  pid_t  pid = fork();

  if (parentpid == getpid()){
    cout << "parent id= " << getpid() << endl;
    sem_wait(&sem_name);
    cout << "child is done." << endl;
  }

  if (parentpid != getpid()){
    cout << "child id= " << getpid() << endl;
    for (int i = 0; i < 10; i++)
      cout << i << endl;

    sem_post(&sem_name);
} 
  sleep(4);
  return 0; 
}

结果应该是:
parent id 123456.
child id 123457.
0
1
2
3
4
5
6
7
8
9
child is done.

程序退出,但它从不向信号量发出信号。

最佳答案

来自 sem_init的联机帮助页:

If pshared is nonzero, then the semaphore is shared between processes, and should be located in a region of shared memory (see shm_open(3), mmap(2), and shmget(2)). (Since a child created by fork(2) inherits its parent's memory mappings, it can also access the semaphore.) Any process that can access the shared memory region can operate on the semaphore using sem_post(3), sem_wait(3), etc.



POSIX 信号量是堆栈结构。它们不像文件描述符那样对内核维护的结构进行引用计数引用。如果要与两个进程共享一个 POSIX 信号量,则需要自己处理共享部分。

这应该有效:
#include <fstream>
#include <iostream>
#include <semaphore.h>
#include <stdio.h>
#include <string>
#include <sysexits.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>


int main(int argc, char *argv[]){
  using namespace std;
  sem_t* semp = (sem_t*)mmap(0, sizeof(sem_t), PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_SHARED, 0, 0 );
  if ((void*)semp == MAP_FAILED) { perror("mmap");  exit(EX_OSERR); } 

  sem_init(semp, 1 /*shared*/, 0 /*value*/);

  pid_t  pid = fork();
  if(pid < 0) { perror("fork");  exit(EX_OSERR); } 

  if (pid==0){ //parent
    cout << "parent id= " << getpid() << endl;
    sem_wait(semp);
    cout << "child is done." << endl;
  }else { //child
    cout << "child id= " << getpid() << endl;
    for (int i = 0; i < 10; i++)
      cout << i << endl;
    sem_post(semp);
  } 
  return 0; 
}

注:如果您只想要这种行为,那么 waitpid显然是要走的路。我假设您想要的是测试 POSIX 信号量。

关于posix - 为什么信号量不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33639631/

相关文章:

c# - 信号量会阻止指令重新排序吗?

c - POSIX 线程和信号掩码

c - 帮助基本线程概念/竞争条件

c - 在C中使用sys/sem.h,如何获取信号量值?

c - 家庭作业 - 一台服务器通过信号量和共享内存为多个客户端提供服务

创建 n 个 child ,每个 child 都有自己的管道

ubuntu - Upstart `unicorn` 忽略 umask

在 C 中将 time_t 转换为给定格式的字符串

C 管道写/读优先级

node.js - 将 GitHub 项目的分支发布到新的 NPM 模块,但保留与原始模块 merge 的选项?