c++ - C++:使用waitpid时等待子进程终止

标签 c++ linux process signals

这是我的示例代码

#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)。可以说父子进程同时都接收SIGTERM,如何让父进程等到子进程终止然后退出呢?我从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



因此,这意味着当在父级中接收到SIGTERM时,它将退出wait()并杀死进程。但是我希望它等到 child 终止然后退出。我该如何实现?

最佳答案

您也可以使用waitpid()等待父级信号处理程序中的子级。这样可以确保即使 parent 接收到信号, parent 也将等待 child 。一些建议如下。

  • 您为什么认为它是C++程序?
  • 您为sa_handler设置的
  • 信号处理程序名称错误。 handle_sigint()
    没有定义。
  • 关于c++ - C++:使用waitpid时等待子进程终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61950473/

    相关文章:

    linux - 从用户空间读取 IIO 设备数据

    java - 进程卡在 waitFor() 中

    php - MySQL 进程占用 150-400% CPU

    java - 如何知道我的程序是否正常终止?

    c++ - 如何为 wxGrid 单元格创建复选框更改事件

    php - 代码注入(inject)有助于在 Linux 上搜索和替换

    c++ - Eclipse C++ 格式化数组初始值设定项

    Linux如何使用rm和exclude开关

    javascript - 使用 IE 插件浏览器帮助对象 (BHO) 在 iframe 中访问正文(至少一些数据)

    c++ - 嵌套并行 for 循环 : "Parallel outer for loop" in "parallel inner for loop as a function"