我使用 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 沒有出來。我的子行程還沒有退出嗎?
uj5u.com熱心網友回復:
從atexit手冊頁:
成功呼叫其中一個
exec(3)函式后,將洗掉所有注冊。
因為成功的exec呼叫將替換行程代碼,包括您注冊的那個atexit,所以您的退出代碼不能再被呼叫,因此是“未注冊的”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/532219.html
標籤:Clinux
