僵尸进程:
第一种,在父进程中通过调用waitpid;
第二种,在父进程中将子进程结束时产生SIGCHLD信号忽略;
第三种,在子进程中再次创建孙子进程,然后子进程退出,孙进程被init进程收养,它退出后,init进程将其回收,但子进程还得自己回收。
第一种
1: /*
2: * =====================================================================================
3: *
4: * Filename: p15.c
5: *
6: * Description:
7: *
8: * Version: 1.0
9: * Created: 03/16/2013 01:19:15 PM
10: * Revision: none
11: * Compiler: gcc
12: *
13: * Author: YOUR NAME (),
14: * Company:
15: *
16: * =====================================================================================
17: */
18: #include <stdio.h>
19: #include <signal.h>
20: #include <unistd.h>
21: #include <stdlib.h>
22:
23: pid_t pid;
24:
25: void handler(int arg)
26: {
27: waitpid(pid, NULL, 0);
28: }
29:
30:
31: int main(void)
32: {
33: signal(SIGCHLD, handler);
34:
35: if((pid = fork()) < 0)
36: {
37: perror("fail to fork");
38: exit(-1);
39: }
40:
41: if(pid == 0)
42: {
43: printf("child close\n");
44: exit(0);
45: }
46: else
47: {
48: while(1);
49: }
50:
51: }
第二种:
1: /*
2: * =====================================================================================
3: *
4: * Filename: p15.c
5: *
6: * Description:
7: *
8: * Version: 1.0
9: * Created: 03/16/2013 01:19:15 PM
10: * Revision: none
11: * Compiler: gcc
12: *
13: * Author: YOUR NAME (),
14: * Company:
15: *
16: * =====================================================================================
17: */
18: #include <stdio.h>
19: #include <signal.h>
20: #include <unistd.h>
21: #include <stdlib.h>
22:
23: pid_t pid;
24:
25:
26: int main(void)
27: {
28: signal(SIGCHLD, SIG_IGN);
29:
30: if((pid = fork()) < 0)
31: {
32: perror("fail to fork");
33: exit(-1);
34: }
35:
36: if(pid == 0)
37: {
38: printf("child close\n");
39: exit(0);
40: }
41: else
42: {
43: while(1);
44: }
45:
46: }
第三种
1: /*
2: * =====================================================================================
3: *
4: * Filename: p15.c
5: *
6: * Description:
7: *
8: * Version: 1.0
9: * Created: 03/16/2013 01:19:15 PM
10: * Revision: none
11: * Compiler: gcc
12: *
13: * Author: YOUR NAME (),
14: * Company:
15: *
16: * =====================================================================================
17: */
18: #include <stdio.h>
19: #include <signal.h>
20: #include <unistd.h>
21: #include <stdlib.h>
22:
23: pid_t pid;
24:
25:
26: int main(void)
27: {
28: signal(SIGCHLD, SIG_IGN);
29:
30: if((pid = fork()) < 0)
31: {
32: perror("fail to fork");
33: exit(-1);
34: }
35:
36: if(pid == 0)
37: {
38: if(fork() == 0)
39: {
40: printf("grandchild closed");
41: exit(0);
42: }
43: printf("child close\n");
44: exit(0);
45: }
46: else
47: {
48: while(1);
49: }
50:
51: }