使用 waitpid 时等待子进程终止

Wait for child process to terminate when using waitpid

本文关键字:子进程 终止 等待 waitpid 使用      更新时间:2023-10-16

这是我的示例代码

#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 -> %dn", result);
fflush(stdout);
}
} 
int main() 
{ 
printf("pid -> %dn", getpid());
forkexample(); 
return 0; 
} 

test2只是一个while(true)。假设父进程和子进程都接收SIGTERM,如何让父进程等到子进程终止然后退出?我从文档中读到:

wait((函数将导致调用线程被阻塞 直到状态信息 由子进程生成的终止可供线程使用,或者直到传递 其操作是执行信号捕获函数或终止进程的信号

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

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

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