当父进程睡眠10秒时,我打算用下面的代码派生并执行“sleep 3”。我希望父进程在“sleep3”睡眠3秒后收到SIGCHLD。
这不会发生,相反我得到:
main
parent process
parent sleeping for 10s
child process
child start, command: /bin/sleep, args: 0x7fffc68c8000, env: 0x7fffc68c8020
ps -ef
显示chris 10578 10577 0 10:35 pts/25 00:00:00 /bin/sleep 3
后面跟着一个:
chris 10578 10577 0 10:35 pts/25 00:00:00 [sleep] <defunct>
在接下来的七秒内(父进程退出)。
问题是,从未调用过
clean_up_child_process
。我犯了什么错?
僵尸测试.c:
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <strings.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
pid_t child_pid;
sig_atomic_t child_exit_status;
void clean_up_child_process (int signal_number) {
printf("signal received\n");
/* Clean up the child process. */
int status;
wait (&status);
/* Store its exit status in a global variable. */
child_exit_status = status;
printf("child_exit_status %i\n", status);
}
int main(int argc, char **argv) {
printf("main\n");
int pid = fork();
if (pid == 0) {
printf("child process\n");
signal(SIGCHLD, clean_up_child_process);
char *args[] = { "/bin/sleep", "3", NULL };
char *env[] = { NULL };
printf("child start, command: %s, args: %p, env: %p\n", args[0], args, env);
int ret = execve(args[0], args, env);
// if we get here, then the execve has failed
printf("exec of the child process failed %i\n", ret);
} else if (pid > 0) {
printf("parent process\n");
child_pid = pid;
} else {
perror("fork failed\n");
}
printf("parent sleeping for 10s\n");
sleep(10);
return 0;
}
最佳答案
您告诉子进程等待子进程完成,然后子进程调用execve,execve不创建子进程,而是用您正在执行的程序替换当前程序
您可能希望父方拦截子方(即在执行signal
调用之前先进行fork
调用)。
关于c - SIGCHLD没有被捕获,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18228163/