fork()函数问题

DestinyHot 2011-03-30 03:55:17
关于fork()函数创建子进程 ,是复制fork()语句后面的全部父进程吗?

书上有段fork()代码,执行起来有些不明白的地方!求高手讲解下,代码如下:

#include <stdio.h>
2 #include <stdlib.h>
3 #include <sys/types.h>
4 #include <unistd.h>
5 #include <sys/wait.h>
6
7 int main (void )
8 {
9 pid_t child1,child2,child;
10
11 child1 = fork();
12 child2 = fork();
13
14 if(child1 == -1)
15 {
16 printf("child1 fork error\n");
17 exit(1);
18 }
19 else if(child1 == 0)
20 {
21 printf("in child1 : execute 'ls -l'\n");
22 if(execlp("ls","ls","-l",NULL)<0)
23 {
24 printf("child1 execlp error\n");
25 }
26 }
27
28 if(child2 == -1)
29 {
30 printf("child2 fork error\n");
31 exit(1);
32 }
33 else if(child2 == 0)
34 {
35 printf("in child2 : sleep for 5 seconds and then exit\n");
36 sleep(5);
37 exit(0);
38 }
39 else
40 {
41 printf("in father process\n");
42 child=waitpid(child1,NULL,0);
43 if(child == child1)
44 {
45 printf("get child1 exit code\n");
46 }
47 else
48 {
49 printf("error \n");
50 }
51 do
52 {
53 child = waitpid(child2,NULL,WNOHANG);
54 if(child == 0)
55 {
56 printf("the child2 process has not exited\n");
57 sleep(1);
58 }
59 }
60 while(child == 0);
61
62 if(child == child2)
63 {
64 printf("get child2 exit code\n");
65 }
66 else
67 {
68 printf("error \n");
69 }
70 }
71 exit(0);
72 }

想问一下,为什么child1 和 child1再创建的子进程 不去执行对child2的判断语句!child1 也对child2进行过创建 也有child2的值阿 ,却在执行完child1 的判断直接结束掉了?是fork()函数的确定的代码段范围直到child1判断结束的地方?

我预想的输出结果应该是 2次 ls ,两次 in father ,两次 sleep
但结果是 两次 ls, 一次 in father 和 一次 sleep !
...全文
348 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
skineffect 2011-03-30
  • 打赏
  • 举报
回复
这个跟两个子进程执行的顺序有关系吧,我的机器上结果为:
in father process
in child2: sleep for 5 seconds and then exit.
in child1: execute 'ls -l'
in child1: execute 'ls -l'
...两个ls -l 的结果
get child1 exit code
the child2 process has not exited
the child2 process has not exited
the child2 process has not exited
the child2 process has not exited
the child2 process has not exited
get child2 exit code

我觉得可以这么理解我的结果:
child2先被fork出来,此时父进程还没有fork出child1, 于是child2又作为父进程(copy父进程的空间)fork出child1,这样便有两个child1进程,于是有两个ls -l输出。接着还剩一个最先的父进程和一个child2进程,父进程wait完child1进程后,接着通过waitpid循环等待child2进程,于是打印出上述结果。
感觉好麻烦。
chenxiancool 2011-03-30
  • 打赏
  • 举报
回复
1L 正解,
in father 1次:因为主进程的子进程或者子进程的子进程要么通过execlp将自己的程序镜像替换来结束,要 么通过exit(0)来结束,都不会运行到程序的第41行(输出 in father),只有主进程可以
sleep 1次:是子进程child2执行的结果
ls 2次:是子进程1和子进程1的子进程执行的结果
李亚超 2011-03-30
  • 打赏
  • 举报
回复
fork一次从fork出开始分离出子程序,执行,可以嵌套
justkk 2011-03-30
  • 打赏
  • 举报
回复
fork() 是一次调用,两次返回(分别是在父子进程中),对于父进程而言,fork()返回值就是子进程的进程ID(大于0),对于子进程而言,fork()返回值是0
所以根据if判断的结果,父子进程会执行不同的分支。

另外execlp执行成功后不会返回,整个进程空间被替换为被执行的程序(这儿就是ls),ls结束了,进程也就结束了

23,120

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧