Here is my example code
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#include <errno.h>
id_t pid;
void handle_sigterm(int sig)
{
printf("handle me \n");
}
void forkexample()
{
// child process because return value zero
pid = fork();
int status = 0;
if (pid == 0)
{
printf("Hello from Child!\n");
char *newargv[] = { "test2", NULL };
char *newenviron[] = { NULL };
newargv[0] = "test2";
execve("test2", newargv, newenviron);
printf("error -> %d", errno);
fflush(stdout);
}
// parent process because return value non-zero.
else
{
struct sigaction psa;
psa.sa_handler = handle_sigterm;
sigaction(SIGTERM, &psa, NULL);
printf("Hello from Parent!\n");
fflush(stdout);
int result = waitpid(pid, &status, 0);
printf("result -> %d\n", result);
fflush(stdout);
}
}
int main()
{
printf("pid -> %d\n", getpid());
forkexample();
return 0;
}
test2 is just a while(true)
. Lets say both parent and child process receive SIGTERM
at the time, how can I make parent process wait until child process terminates and then exit? I've read from documentation that:
The wait() function shall cause the calling thread to become blocked until status information generated by child process termination is made available to the thread, or until delivery of a signal whose action is either to execute a signal-catching function or to terminate the process
So it means that when SIGTERM
is received in parent, it exits the wait()
and the process is killed. But I want it to wait until child terminates and then exit. How can I achieve that?