这是我的示例代码
#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++ - C++:使用waitpid时等待子进程终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61950473/