使用 waitpid 时等待 child 进程终止

Wait for child process to terminate when using waitpid

这是我的示例代码

#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 只是一个 while(true)。假设 parent 和 child 进程同时接收 SIGTERM,我怎样才能让 parent 进程等到 child 进程终止然后退出?我从 documentation 那里读到:

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

所以表示在parent中收到SIGTERM时,退出wait(),进程被杀死。但我希望它等到 child 终止然后退出。我怎样才能做到这一点?

您也可以使用 waitpid() 来等待 parent 的 child 内部信号处理程序。这确实确保 parent 将等待 child,即使它收到信号也是如此。一些建议如下。

  1. 为什么你认为它是 C++ 程序?
  2. 您为 sa_handler 设置的信号处理程序名称错误。 handle_sigint() 未定义。