![](/img/trans.png)
[英]What happens with unjoined and not detached threads when the whole process terminates?
[英]What happens after the parent of zombie process terminates?
我只是好奇,僵屍進程會發生什么,如果它的父母不在乎等待它。
假設,我們有一個父母和一個孩子。 子進程在父進程之前終止。
來自 APUE:
內核為每個終止進程保留少量信息......最低限度
此信息包括進程 ID、進程的終止狀態....
父級需要使用waitpid()
獲取此信息。
但是,如果父母不等待孩子就退出,會發生什么:
內核是否刪除了這些信息(當然沒有用)?
或者,它一直在收集這些垃圾?
這個實現是特定的嗎?
或者,有沒有標准的方法來處理這種情況?
孤兒進程由init
自動采用,它有一個標准的SIGCHLD
處理程序,它只會丟棄死進程的任何退出狀態。
在您的情況下,如果僵屍進程的父進程死亡,則 init 將采用僵屍孤兒並進行清理。
以下代碼對此進行了測試:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t child_pid;
if (child_pid = fork()) { // fork a child, child will exit straight away
char name[128];
sprintf(name, "/proc/%d/stat", child_pid);
char line[2048];
// read childs /proc/pid/stat, field 3 will give its status
FILE * fp = fopen(name, "r");
while (fgets(line, sizeof(line), fp))
puts(line);
fclose(fp);
usleep(5000000);
// by now the child will have exited for sure, repeat
fp = fopen(name, "r");
while (fgets(line, sizeof(line), fp))
puts(line);
fclose(fp);
// make another child to repeat the process and exit the parent
if (!fork()) {
usleep(5000000);
// both parent and child will have exited by now
fp = fopen(name, "r");
// this should fail because init has already cleaned up the child
if (!fp) {
perror("fopen");
return -1;
}
while (fgets(line, sizeof(line), fp))
puts(line);
fclose(fp);
}
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.