使用 waitpid 时等待子进程终止
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 -> %dn", result);
fflush(stdout);
}
}
int main()
{
printf("pid -> %dn", getpid());
forkexample();
return 0;
}
test2只是一个while(true)
。假设父进程和子进程都接收SIGTERM
,如何让父进程等到子进程终止然后退出?我从文档中读到:
wait((函数将导致调用线程被阻塞 直到状态信息 由子进程生成的终止可供线程使用,或者直到传递 其操作是执行信号捕获函数或终止进程的信号
因此,这意味着当在父级中接收到SIGTERM
时,它会退出wait()
并且进程被终止。但我希望它等到孩子终止,然后退出。我怎样才能做到这一点?
你也可以使用 waitpid(( 在父级的信号处理程序中等待子级。这确实可以确保父级即使收到信号也会等待子项。一些建议如下。
- 你为什么认为这是一个C++计划?
- 为sa_handler设置的信号处理程序名称错误。 handle_sigint(( 未定义。
相关文章:
- 终止 QProcess 不会终止子进程
- 什么时候最好在子进程中使用 CPU 或 I/O 密集型代码 [ C++ ]
- 子进程更新共享 mmap 内存,但父进程没有更改
- 使用 waitpid 时等待子进程终止
- 使用重定向标准处理子进程中的 kbhit
- 由 JOB 中的进程启动的子进程是否可以将 JOB 属性设置为脱离作业?
- 检测到由于操作系统内存不足而导致子进程终止
- 使用信号检测子进程何时终止的最佳方法是什么?
- 无法检测子进程是否已终止
- 我无法使用终止进程杀死子进程
- 子进程在 fork 中 3 秒后自行终止
- 截获非终止子进程C++的stdout
- 当父NT服务被终止/崩溃时,终止子进程
- Fork进程:在子进程终止时恢复父进程(Linux)
- 在所有子进程终止后,不能运行父进程
- Dup2()导致子进程提前终止
- 从Python子进程终止时的c++调用函数
- CreateProcess,使子进程在父进程被终止时被终止
- 何时应该终止MPI子进程
- 杀死父进程时终止所有子进程