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 use kill(<pid1>, 0)
to test if the process is still running. If its gone kill()
will fail with errno
set to ESRCH
.
Then let process 3 do the same for <pid2>
.
Then let process 3 terminate.
You need to use waitpid
in parent process to wait until child procsee is terminated. Read http://linux.die.net/man/2/waitpid for more details. Like this:
int status;
if (waitpid(cpid, &status, 0) < 0) { // where cpid is child process id
perror("waitpid");
exit(EXIT_FAILURE);
}
Also you need to correctly terminate child process using _exit(exitCode)
. Read http://linux.die.net/man/2/exit for more details.
EDIT: If you want to to terminate processes in order 1-2-3 just wait for parent process id in child process.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.