孤儿进程:一个父进程退出,而它的一个或多个子进程还在运行,那么那些子进程将成为孤儿进程。孤儿进程将被init进程(进程号为1)所收养,并由init进程对它们完成状态收集工作。
僵尸进程将会导致资源浪费,而孤儿则不会。
#include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> main() { pid_t pid; pid = fork(); if(pid < 0) printf("error occurred!/n"); else if(pid == 0) { printf("Hi father! I'm a ZOMBIE/n"); exit(0); //(1) } else { sleep(10); wait(NULL); //(2) } }(1) 向父进程发送SIGCHILD信号
#include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> main() { pid_t pid; pid = fork(); if(pid < 0) printf("error occurred!/n"); else if(pid == 0) { sleep(6); printf("I'm a orphan/n"); exit(0); } else { sleep(1); printf("Children Bye!/n"); } }# ./a.out
int main(int argc, char **argv) { ... Signal(SIGCHLD, sig_chld); for(; } ... } void sig_chld(int signo) { pid_t pid; int stat; while ( (pid = waitpid(-1, &stat, WNOHANG)) >; 0) printf("child %d terminated/n", pid); return; }
#include <sys/types.h> #include <sys/wait.h> #include "ourhdr.h" int main(void) { pid_t pid; if ( (pid = fork()) < 0) err_sys("fork error"); else if (pid == 0) { /* first child */ if ( (pid = fork()) < 0) err_sys("fork error"); else if (pid > 0) exit(0); /* parent from second fork == first child */ /* We're the second child; our parent becomes init as soon as our real parent calls exit() in the statement above. Here's where we'd continue executing, knowing that when we're done, init will reap our status. */ sleep(2); printf("second child, parent pid = %d/n", getppid()); exit(0); } if (waitpid(pid, NULL, 0) != pid) /* wait for first child */ err_sys("waitpid error"); /* We're the parent (the original process); we continue executing, knowing that we're not the parent of the second child. */ exit(0); } //avoid zombie process by forking twice