1 #include <unistd.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4
5 int main()
6 {
7 pid_t fpid = 0;
8 printf("son/pa ppid pid fpid\n");
9
10 fpid = fork();
11 if (0 == fpid) {
12 printf("child %5d %5d %5d\n", getppid(), getpid(), fpid);
13 //exit(0);
14 }
15 else {
16 printf("parent %5d %5d %5d\n", getppid(), getpid(), fpid);
17 //exit(0);
18 }
19
20 fpid = fork();
21 if (0 == fpid)
22 printf("child %5d %5d %5d\n", getppid(), getpid(), fpid);
23 else
24 printf("parent %5d %5d %5d\n", getppid(), getpid(), fpid);
25
26 return 0;
27 }
son/pa ppid pid fpid
parent 14866 9802 9803
child 9802 9803 0
parent 14866 9802 9804
child 9802 9804 0
parent 9802 9803 9805
child 9803 9805 0
当前进程9802 --> 9803 --> 9805
当前进程9802 --> 9804
我们可以看出(1)当前进程9802 fork 出子进程 9803, 然后子进程又fork 出孙子进程 9805
(2)当前进程9802 fork 出子进程 9804
1 #include <unistd.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4
5 int main()
6 {
7 pid_t fpid = 0;
8 printf("son/pa ppid pid fpid\n");
9
10 fpid = fork();
11 if (0 == fpid) {
12 printf("child %5d %5d %5d\n", getppid(), getpid(), fpid);
13 exit(0);
14 }
15 else {
16 printf("parent %5d %5d %5d\n", getppid(), getpid(), fpid);
17 //exit(0);
18 }
19
20 fpid = fork();
21 if (0 == fpid)
22 printf("child %5d %5d %5d\n", getppid(), getpid(), fpid);
23 else
24 printf("parent %5d %5d %5d\n", getppid(), getpid(), fpid);
25
26 return 0;
27 }
son/pa ppid pid fpid
parent 14866 12028 12029
child 12028 12029 0
parent 14866 12028 12030
child 12028 12030 0
当前进程12028 --> 12029
当前进程12028 --> 12030
当前进程12028 fork出子进程12029后,子进程12029就退出了,当前进程接着又fork出另一个子进程12030
1 #include <unistd.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4
5 int main()
6 {
7 pid_t fpid = 0;
8 printf("son/pa ppid pid fpid\n");
9
10 fpid = fork();
11 if (0 == fpid) {
12 printf("child %5d %5d %5d\n", getppid(), getpid(), fpid);
13 //exit(0);
14 }
15 else {
16 printf("parent %5d %5d %5d\n", getppid(), getpid(), fpid);
17 exit(0);
18 }
19
20 fpid = fork();
21 if (0 == fpid)
22 printf("child %5d %5d %5d\n", getppid(), getpid(), fpid);
23 else
24 printf("parent %5d %5d %5d\n", getppid(), getpid(), fpid);
25
26 return 0;
27 }
son/pa ppid pid fpid
parent 14866 12100 12101
child 12100 12101 0
parent 1 12101 12102
child 12101 12102 0
当前进程12100 --> 12101 --> 12102
当前进程12100执行完fork就退出了,子进程12101接着又fork一个孙进程12102