简体   繁体   English

使用waitpid时等待子进程终止

[英]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) . test2 只是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?假设父进程和子进程当时都收到SIGTERM ,我怎样才能让父进程等到子进程终止然后退出? 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 wait() function 将导致调用线程被阻塞,直到子进程终止生成的状态信息可供线程使用,或者直到传递一个信号,其动作是执行信号捕获 function 或终止进程

So it means that when SIGTERM is received in parent, it exits the wait() and the process is killed.所以这意味着当在父进程中收到SIGTERM时,它会退出wait()并且进程被杀死。 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.您也可以使用 waitpid() 在父级的信号处理程序中等待子级。 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?为什么你认为它是一个 C++ 程序?
  2. signal handler name you set for sa_handler is wrong.您为 sa_handler 设置的信号处理程序名称是错误的。 handle_sigint() is not defined. handle_sigint() 未定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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