【问题标题】:Wait for child process to terminate when using waitpid使用waitpid时等待子进程终止
【发布时间】:2020-09-09 00:37:00
【问题描述】:

这是我的示例代码

#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 读到:

wait() 函数会导致调用线程被阻塞 直到状态信息 由子进程终止生成的线程可用,或者直到交付一个 信号,其动作是执行信号捕获功能或终止进程

所以这意味着当父级收到SIGTERM时,它会退出wait()并且进程被杀死。但我希望它等到孩子终止然后退出。我怎样才能做到这一点?

【问题讨论】:

  • 除了信号函数名称中的拼写错误(现已修复)外,您的 cod 确实在父级中处理 SIGTERM,因此应该按预期运行。有什么问题?

标签: c++ linux process signals


【解决方案1】:

您也可以使用 waitpid() 在父级的信号处理程序中等待子级。这确实确保父母会等待孩子,即使它收到信号。一些建议如下。

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

【讨论】:

  • 1.你是对的,它应该被标记为 C 而不是 C++。 2. 固定
猜你喜欢
  • 2020-01-15
  • 1970-01-01
  • 1970-01-01
  • 2013-11-08
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 1970-01-01
相关资源
最近更新 更多