免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2016 | 回复: 6

vfork 高手帮忙解释,提前谢谢了 [复制链接]

论坛徽章:
0
发表于 2010-09-02 14:07 |显示全部楼层
我在学习vfork时,写了一个这样的程序
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. int main()
  4. {
  5.         printf("begin\n");
  6.         vfork();
  7.         return 0;
  8. }
复制代码
运行后输出为很多行
begin
.....
begin

如果把代码改为
  1. #include <stdio.h>
  2. #include <unistd.h>

  3. int main()
  4. {
  5.         printf("begin\n");
  6.         vfork();
  7.         _exit(0);
  8.         return 0;
  9. }
复制代码
就只输出一行
begin

我想问一下高手为什么我去掉_exit(0)后会输出多行"begin",而我只有一个输出语句呀?

论坛徽章:
2
CU十二周年纪念徽章
日期:2013-10-24 15:41:34处女座
日期:2013-12-27 22:22:41
发表于 2010-09-02 15:53 |显示全部楼层
有点意思。vfork的父进程与子进程是共用地址空间的,子进程会先运行。可能是第一个程序里编译器自动插入了exit ()刷新父进程了缓存,造成了地址空间内部混乱。
第二个程序里手动加了_exit(0),没有刷新缓存,子进程没有改动父进程的地址空间的内容。所以输出正常
至于为什么会出现N多begin就不太清楚了。
vfork是被废弃掉的调用,BSD里引入它是想避免fork时拷贝父进程的地址空间。所以使用vfork的正常行为是让子进程马上调用exec系列函数。但现在使用写时拷贝,一般不会用vfork了。
这种问题建议转到C版。。。。。。

论坛徽章:
0
发表于 2010-09-02 16:14 |显示全部楼层
运行代码1结果:
  1. [root@localhost test_project]# ./vfork
  2. begin
  3. Segmentation fault
复制代码
运行代码2结果:
[code][/code]

论坛徽章:
0
发表于 2010-09-02 16:16 |显示全部楼层
代码2运行结果:
  1. [root@localhost test_project]# ./vfork1
  2. begin
  3. [root@localhost test_project]#
复制代码

论坛徽章:
2
CU十二周年纪念徽章
日期:2013-10-24 15:41:34处女座
日期:2013-12-27 22:22:41
发表于 2010-09-02 21:24 |显示全部楼层
PC ,32位Fedora 12得到的结果跟LZ是一样的。

论坛徽章:
0
发表于 2010-09-03 10:17 |显示全部楼层
vfork()  differs  from  fork  in that the parent is suspended until the
       child makes a call to execve(2) or _exit(2).  The child shares all mem-
       ory  with  its parent, including the stack, until execve() is issued by
       the child.  The child must not return from the current function or call
       exit(), but may call _exit().
会不会是这个原因。

论坛徽章:
0
发表于 2010-09-07 13:32 |显示全部楼层
期待更好的解释~~~~
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP