当前位置:  技术问答>linux和unix

fock的简单问题

    来源: 互联网  发布时间:2016-09-10

    本文导语:    1 #include    2 #include    3 #include    4    5    6 int main(int argc,char *argv[])   7 {   8     pid_t pid;   9     char *message;  10     int n;  11   12     printf("fork program starting.n");  13     pid=fork();  14    ...

  1 #include 
  2 #include 
  3 #include 
  4 
  5 
  6 int main(int argc,char *argv[])
  7 {
  8     pid_t pid;
  9     char *message;
 10     int n;
 11 
 12     printf("fork program starting.n");
 13     pid=fork();
 14     switch(pid)
 15     {
 16         case -1:
 17             perror("fork failed.");
 18             exit(1);
 19         case 0:
 20             message="This is the child.";
 21             n=5;
 22             break;
 23         default:
 24             message="This is the parent.";
 25             n=3;
 26             break;
 27     }
 28     for(;n>0;n--)
 29     {
 30         puts(message);
 31         sleep(1);
 32     }
 33 
 34     exit(0);
 35 }
 

直接运行显示的结果为:
$ ./a
fork program starting.
This is the parent.
This is the child.
This is the parent.
This is the child.
This is the parent.
This is the child.
This is the child.
$ This is the child.


使用GDB单步观察的时候
(gdb) run
Starting program: /home/wangjun/scode/linux/a 

Breakpoint 1, main (argc=1, argv=0xbffff464) at fock1.c:12
12 printf("fork program starting.n");
(gdb) display pid
1: pid = 2637812
(gdb) s
fork program starting.
13 pid=fork();
1: pid = 2637812
(gdb) s
This is the child.
14 switch(pid)
1: pid = 6387
(gdb) This is the child.
This is the child.
This is the child.
This is the child.                         //这里为什么连续输出4个同样的,肯定和正常运行程序的结果不一样了
24 message="This is the parent.";
1: pid = 6387
……


另外请教这个程序的运行过程(详细步骤),为什么会产生这么多的输出

|
从第14行switch(pid)开始之后的所有代码,都要在父进程和子进程各执行一次。子进程里面pid=0,执行case 0;父进程里面pid>0,执行default
 28     for(;n>0;n--)
 29     {
 30         puts(message);
 31         sleep(1);
 32     }
这个循环在父进程和子进程都要执行。父进程里面n=3,子进程里面n=5。所以一共输出8行,3个parent,5个child

|
用gdb调试多进程的程序会有一些问题,需要一点特殊的处理。
例如,使用GDB调试某个进程,如果该进程fork了子进程,GDB会继续调试该进程,子进程会不受干扰地运行下去。所以,当你在gdb里面step的时候,父进程停了,子进程还在不断的输出。


|

|


顶一下,fork被调用后,系统就根据父进程,生成一个子进程,要自行的代码是相同的,
因此,fork函数从父子进程各返回一次.

    
 
 

您可能感兴趣的文章:

  • 问一个关于fock的问题
  •  
    本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • fock()开出的子进程的进程ID是否进程ID都大于父进程的?


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3