環境:Ubuntu 22.04
<aside> 📢
定義:A child that terminates, but has not been waited for becomes a "zombie".
也可以想成是 waited status 沒有人接收
</aside>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void){
pid_t pid;
int status;
if ((pid = fork()) < 0) { // pid == -1: error occurred
perror("fork");
exit(1);
}
/* Child */
if (pid == 0) // pid == 0: child process created
exit(0);
/* Parent
* Gives you time to observe the zombie using ps(1) ...
* sleep unit in windows: ms, in linux: s
*/
sleep(10);
/* ... and after that, parent wait(2)s its child's
* exit status, and prints a relevant message. */
pid = wait(&status);
if (WIFEXITED(status))
fprintf(stderr, "\\n\\t[%d]\\tProcess %d exited with status %d.\\n",
(int) getpid(), pid, WEXITSTATUS(status));
return 0;
}
gcc zombie_process.c -o zombie_process
ps -aux | grep zombie_process

<aside> 📢
定義:Parent fork 出 Child,但是 Parent 因某些原因提早執行完成或是被強迫中止,這時還在運行的 Child 就被稱作 Orphan
</aside>