fork函数实验总结

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

针对fork函数难以理解,根据网上的解释,参考他人代码,做了如下实验,并附以实验分析

2 #include

3 #include

4 #include

5 #include

6 #include

7

8 int main ()

9 {

10 pid_t pc,pr;

11 pc=fork();

(gdb)

12

13 if (pc<0)

14 {

15 printf("error fork.\n");

16

17 }

18 else if (pc==0)

19 {

20 printf("this is pc=%d\n",getpid());

21 sleep(5);

(gdb)

22 printf("5 s over\n");

23 //exit(0);

24 }

25 pr=fork();

26 if (pr==0)

27 {

28 printf("this is pr =%d\n",getpid());

29 }

30

31 else if (pr>0&&pc>0)

(gdb)

32 printf("this is main =%d",getpid());

33

34

35

36

37

38 }

(gdb) b 12

Breakpoint 1 at 0x804849d: file /home/lsp/fork3.c, line 12.

(gdb) b 19

Breakpoint 2 at 0x80484b7: file /home/lsp/fork3.c, line 19.

(gdb) b 24

Breakpoint 3 at 0x80484e4: file /home/lsp/fork3.c, line 24.

(gdb) b 26

Breakpoint 4 at 0x80484ec: file /home/lsp/fork3.c, line 26.

(gdb) run

Starting program: /home/lsp/fork3

Detaching after fork from child process 13200. ---说明pc=fork()函数已经建立子进程

this is pc=13200

Breakpoint 1, main () at /home/lsp/fork3.c:13

13 if (pc<0)

(gdb) 5 s over

this is pr =13201 --说明pc=fork()进程13200启动了新的子进程pr 其pid=13201

next

Breakpoint 3, main () at /home/lsp/fork3.c:25

25 pr=fork(); --父进程停在pr=fork()处,

(gdb) next

Detaching after fork from child process 13254.

this is pr =13254 --此处pr的pid=13254 与上一个pr=13201不同,这说明此处的pr是由main创建的

Breakpoint 4, main () at /home/lsp/fork3.c:26

26 if (pr==0)

(gdb) next

31 else if (pr>0&&pc>0)

(gdb) next

32 printf("this is main =%d",getpid());

(gdb) next

38 }

(gdb) next

0x00a6d5d6 in __libc_start_main () from /lib/libc.so.6

(gdb) next

Single stepping until exit from function __libc_start_main,

which has no line number information.

this is main =13199 ---main函数退出,器pid=13199

Program exited with code 023.

(gdb)

小结:这段代码总共有4个进程,pid分别为

13199--main这个父进程自身的pid

13200--main这个父进程建立的pc进程pid=13200

13201--pc这个子进程创建的子进程,即main的孙进程pr

13254--main这个父进程创建的子进程pr 此处的pr与上一处pc创建的不同,从其pid上可做区别。

这说明fork的工作原理:

1.pc=fork()函数创建自身时复制了如下代码段

12

13 if (pc<0)

14 {

15 printf("error fork.\n");

16

17 }

18 else if (pc==0)

19 {

20 printf("this is pc=%d\n",getpid());

21 sleep(5);

(gdb)

22 printf("5 s over\n");

23 //exit(0);

24 }

25 pr=fork();

26 if (pr==0)

27 {

28 printf("this is pr =%d\n",getpid());

29 }

30

31 else if (pr>0&&pc>0)

(gdb)

32 printf("this is main =%d",getpid());

33

34

35

36

37

38 }

2.pr=fork()函数创建自身时复制了如下代码段:

26 if (pr==0)

27 {

28 printf("this is pr =%d\n",getpid());

29 }

相关文档
最新文档