#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;
}
the result should be:
parent id 123456.
child id 123457.
0
1
2
3
4
5
6
7
8
9
child is done.
Program exits, but instead it never signals the semaphore.
XY Problem?
If what you want to do is to wait for your child process to be done, you do not need semaphores, but
wait
orwaitpid
. The following C code has your expected output.NOTE: I did in C because the only C++ you were using was initial declaration in a
for
loop and prints withcout << "blah" << endl;
Instead of using
sem_init()
, usesem_open()
. This is because the semaphore needs to be in shared address space rather than on the process stack where it gets duplicated through thefork()
.Taken from http://blog.superpat.com/2010/07/14/semaphores-on-linux-sem_init-vs-sem_open/
From
sem_init
's manpage:POSIX semaphores are on-the-stack structs. They aren't reference-counted references to a kernel-maintained struct like filedescriptors are. If you want to share a POSIX semaphore with two processes, you need to take care of the sharing part yourself.
This should work:
Note: If you want just this behavior, then
waitpid
is obviously the way to go. I'm assuming what you want is to test out POSIX semaphores.