+ -
当前位置:首页 → 问答吧 → linux进程fork求教,谢谢

linux进程fork求教,谢谢

时间:2010-08-12

来源:互联网

求教,源程序如下(t1.c):
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main()
{
  pid_t child = 0;
  int i,n;
  i = 0;
  n = 0;

  printf("%d befor %d\n",getpid(),i);
  if((child = fork()) <= 0) goto App;
  else printf("%d:%d,产生的child进程号为[%d]\n",getpid(),i,child);
App:
  printf("mypid is %d,my i is %d,my father is %d,my child is %d\n",getpid(),i,getppid(),child);

  return 0;
}
编译命令是:gcc -o 11 t1.c
执行结果为:
7895 befor 0
7895:0,产生的child进程号为[7896]
mypid is 7895,my i is 0,my father is 7409,my child is 7896
7895 befor 0
mypid is 7896,my i is 0,my father is 1,my child is 0

我想问一下,父进程7895产生的子进程7409 goto到App之后,其子进程输出完mypid is 那句话之后不是就退出了吗?
但是为什么7895 befor 0会输出两次呢?谢谢了

作者: sdaubin   发布时间: 2010-08-12

my father is 1 ??

你咋执行的程序?撒平台?

作者: lenky0401   发布时间: 2010-08-12

本帖最后由 sdaubin 于 2010-08-12 18:27 编辑

Ubuntu下gcc -o 11 t1.c

执行./11

因为main的主进程A已经结束,它之前产生的子进程B对应的父进程号会变为原来父进程A的父进程
也就是系统启动时的主进程init。

作者: sdaubin   发布时间: 2010-08-12

我这边只输出一遍
这个是跟buffer有关的,child会将parent的buffer也拷贝一份的



QUOTE:
kernel@fairland:~/tmp$ ./fork
7632 befor 0
7632:0,产生的child进程号为[7633]
mypid is 7632,my i is 0,my father is 7583,my child is 7633
mypid is 7633,my i is 0,my father is 7632,my child is 0




QUOTE:
kernel@fairland:~/tmp$ ./fork >log
kernel@fairland:~/tmp$ cat log
7635 befor 0
7635:0,产生的child进程号为[7636]
mypid is 7635,my i is 0,my father is 7583,my child is 7636
7635 befor 0
mypid is 7636,my i is 0,my father is 1,my child is 0

作者: churchmice   发布时间: 2010-08-12

谢谢楼上的,明白了,谢谢

作者: sdaubin   发布时间: 2010-08-12