免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1837 | 回复: 4
打印 上一主题 下一主题

[C] linux进程fork求教,谢谢 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-08-12 17:59 |只看该作者 |倒序浏览
求教,源程序如下(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会输出两次呢?谢谢了

论坛徽章:
0
2 [报告]
发表于 2010-08-12 18:20 |只看该作者
my father is 1 ??

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

论坛徽章:
0
3 [报告]
发表于 2010-08-12 18:22 |只看该作者
本帖最后由 sdaubin 于 2010-08-12 18:27 编辑

Ubuntu下gcc -o 11 t1.c

执行./11

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

论坛徽章:
0
4 [报告]
发表于 2010-08-12 18:29 |只看该作者
我这边只输出一遍
这个是跟buffer有关的,child会将parent的buffer也拷贝一份的

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

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

论坛徽章:
0
5 [报告]
发表于 2010-08-12 18:36 |只看该作者
谢谢楼上的,明白了,谢谢
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP