免费注册 查看新帖 |

Chinaunix

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

[Linux] 请教vfork为何会不停创建进程 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2014-02-14 12:35 |只看该作者 |倒序浏览
程序如下:
  1. int main(int argc, char *argv[])
  2. {
  3.         pid_t pid;
  4.         static int count = 0;

  5.         pid = vfork();
  6.         if (0 == pid)
  7.         {
  8. //                exit(0);   /* 加与不加exit 区别很大 */
  9.         }
  10.         else
  11.         {
  12.                 sleep(2);
  13.                 printf("(%d)my child is %d\n", pid);
  14.         }

  15.         return 0;
  16. }
复制代码


如果加上exit,则一切正常,显示结果如下:
  1. $ ./a.out
  2. (0)count: 0
  3. (2)my child is 4432
复制代码


如果去掉exit,则main会被反复调用,创建无数个子进程,结果如下:
  1. $ ./a.out
  2. (0)count: 0
  3. (2)my child is 4399
  4. (2)count: 1
  5. (4)my child is 4400
  6. (4)count: 2
  7. (6)my child is 4401
  8. (6)count: 3
  9. (8)my child is 4402
  10. (8)count: 4
  11. (10)my child is 4403
  12. (10)count: 5
  13. (12)my child is 4404
  14. (12)count: 6
  15. (14)my child is 4405
  16. (14)count: 7
  17. (16)my child is 4406
  18. (16)count: 8
  19. .......
复制代码

我知道不加exit是不对的,但无法理解为什么不加exit会导致main函数被反复调用,为何会创建如此多子进程?

论坛徽章:
95
程序设计版块每日发帖之星
日期:2015-09-05 06:20:00程序设计版块每日发帖之星
日期:2015-09-17 06:20:00程序设计版块每日发帖之星
日期:2015-09-18 06:20:002015亚冠之阿尔艾因
日期:2015-09-18 10:35:08月度论坛发贴之星
日期:2015-09-30 22:25:002015亚冠之阿尔沙巴布
日期:2015-10-03 08:57:39程序设计版块每日发帖之星
日期:2015-10-05 06:20:00每日论坛发贴之星
日期:2015-10-05 06:20:002015年亚冠纪念徽章
日期:2015-10-06 10:06:482015亚冠之塔什干棉农
日期:2015-10-19 19:43:35程序设计版块每日发帖之星
日期:2015-10-21 06:20:00每日论坛发贴之星
日期:2015-09-14 06:20:00
2 [报告]
发表于 2014-02-14 12:43 |只看该作者
本帖最后由 MMMIX 于 2014-02-14 12:43 编辑

回复 1# fireaxe


    你把 vfork(2) 用错了,看看手册中这段描述:

(From POSIX.1) The vfork() function has the same effect as fork(2), except that the behavior is undefined if the process created by vfork() either modifies any data other than a variable of type pid_t used to store the return value from vfork(),  or returns  from  the  function in which vfork() was called, or calls any other function before successfully calling _exit(2) or one of the exec(3) family of functions.

论坛徽章:
11
技术图书徽章
日期:2014-03-01 14:44:34天蝎座
日期:2014-05-21 22:11:59金牛座
日期:2014-05-30 17:06:14
3 [报告]
发表于 2014-02-14 14:00 |只看该作者
是啊,既然是undefined,那么程序core或电脑死机或硬盘分区格式化或给老板发辞职信都是可以接受的。

论坛徽章:
6
申猴
日期:2013-10-08 17:32:32金牛座
日期:2013-10-18 19:45:53天秤座
日期:2013-10-18 20:17:34处女座
日期:2014-02-11 10:10:29丑牛
日期:2014-02-15 10:44:15巳蛇
日期:2014-02-18 22:05:54
4 [报告]
发表于 2014-02-15 17:11 |只看该作者
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP