简体   繁体   中英

Wait for child process to terminate when using waitpid

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?

You can use waitpid() to wait for the child inside signal handler of parent also. This does make sure that parent will wait for child even though it receives signal. Some advices are as below.

  1. Why do you think it is a C++ program?
  2. signal handler name you set for sa_handler is wrong. handle_sigint() is not defined.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM