#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.
程序退出,而是它从来没有信号的信号。
欢迎摘自至U&L!我们有你的代码和结果应该是什么......实际结果是什么?你怎么确定信号量从未被发信号?你能编辑你的问题来添加它吗?到目前为止,我的代码中似乎没有发现任何错误 –