How can I sync 3 different processes with signals in Unix on C/C++?
I need: first process starts second process. Second process starts third process. After third process is started I want kill all processes in order 1 – 2 – 3.
I have no idea about using wait, signal, pause etc functions for this. Could you help me? Thanks.
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
using namespace std;
int main (int argc, char * const argv[]) {
pid_t three_pid;
pid_t second_pid;
pid_t first_pid;
cout << "child 1 is started" << endl;
pid_t pid;
if ((pid = fork()) == -1)
{
cout << "fork errror" << endl;
exit(EXIT_FAILURE);
}
else if (pid == 0)
{
second_pid = getpid();
cout << "child 2 is started" << endl;
pid_t pid2;
if ((pid2 = fork()) == -1)
{
cout << "fork 2 error" << endl;
exit(EXIT_FAILURE);
}
else if (pid2 == 0)
{
three_pid = getpid();
cout << "child 3 is started" << endl;
cout << "child 3 is TERMINATED" << endl;
}
else
{
cout << "child 2 is TERMINATED" << endl;
}
}
else
{
first_pid = getpid();
cout << "child 1 is TERMINATED" << endl;
}
}
To do this in a portable way let process 3 (the grandchild) call
kill(<pid1>, SIGKILL)and usekill(<pid1>, 0)to test if the process is still running. If its gonekill()will fail witherrnoset toESRCH.Then let process 3 do the same for
<pid2>.Then let process 3 terminate.