【发布时间】:2022-11-13 21:00:53
【问题描述】:
我使用 fork() 创建进程并将 exit(0) 放在最后,然后将 atexit(func) 放在最后,这样我可以在进程退出或不退出时收到通知以避免僵尸进程。 但是,atexit 没有输出,所以我想也许我已经制作了僵尸进程。谁能告诉我为什么我的 atexit 输出没有显示?
//fork parent process (first process fork):
if ((pid = fork()) == 0) {
printf("parent1: %d in %d\n", getpid(), getpgid(pid));
atexit(endfunc);
char* argf[MAXARGS];
int a;
printf("buf: %s\n", buf);
if (strchr(cmdline, '|') != NULL) {
a = make_tokens(buf, 0, argf, "|");
printf("In pipe\n");
int fd[200][2];
pid_t pids[200];
for (int i = 0; i < a - 1; i++) {
pipe(fd[i]);
//somewhere in parent fork child:
if ((pids[0] = fork()) == 0) {
printf("child: %d in %d\n", getpid(), getpgid(pid));
atexit(endfunc);
close(fd[0][0]);
for (int i = 1; i < a - 1; i++) {
close(fd[i][0]);
close(fd[i][1]);
}
char* arg[MAXARGS];
parseline(argf[0], arg);
execvp(arg[0], arg);
exit(0);
}
//at the end of parent process wait for childrens
pid_t wpid;
for (int i = 0; i < a; i++) {
wpid = waitpid(pids[i], NULL, 0);
if (wpid < 0) {
perror("waitpids");
}
else if (wpid >= 0) {
printf("wait for %d\n", pids[i]);
}
exit(0);//parent process exit
//endfunc: function for atexit()
void endfunc(void) {
printf("process %d ended\n", getpid());
}
这是我输入 ls -al | 后的输出grep t:
mini> ls -al | grep t
parent1: 23154 in 23140
buf: ls -al | grep t
In pipe
child: 23155 in 23140
child: 23156 in 23140
//output for command
wait for 23155
wait for 23156
process 23154 ended
wait for 23154
正如我们所见,父进程已经结束并打印了 atexit。但是,子进程已经创建,但是子进程的 atexit 还没有出来。我的子进程还没有退出吗?
【问题讨论】:
-
旁白:
printf("child: %d in %d\n", getpid(), getpgid(pid));--> What is the correct printf specifier for printing pid_t。