我打算在父进程休眠 10 秒时将以下代码作为子进程分叉并执行“sleep 3”。我希望父进程在 3 秒后收到 SIGCHLD,当“睡眠 3”完成时。
这不会发生,而是我得到:
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>
在接下来的 7 秒内(此时父进程退出)。
问题是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;
}