免费注册 查看新帖 |

Chinaunix

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

vfork exit _exit [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-06-03 18:43 |只看该作者 |倒序浏览

大家好,我是新手。请大家看代码:

#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>
#include<sys/types.h>
int     glob = 6;       /* external variable in initialized data */

int
main(void)
{
    int     var;        /* automatic variable on the stack */
    pid_t   pid;

    var = 88;
    printf("before vfork\n");   /* we don't flush stdio */
    if ((pid = vfork()) < 0) {
        printf("vfork error");
    } else if (pid == 0) {      /* child */
        glob++;                 /* modify parent's variables */
        var++;
        exit(0);               /* child terminates */
    }
    /*
     * Parent continues here.
     */
    printf("pid = %d, glob = %d, var = %d", getpid(), glob, var);
    _exit(0);
}
执行结果:before vfork
pid = 15948, glob = 7, var = 89


请问:父进程的最后一个printf为什么能打印出来呢?

论坛徽章:
0
2 [报告]
发表于 2012-06-03 19:49 |只看该作者
回复 1# ooaoodoop1

从哪儿看出 不应该打印出来呢 ?
   

论坛徽章:
0
3 [报告]
发表于 2012-06-03 20:52 |只看该作者
回复 2# Moon_Bird


    最后父进程printf没有“\n”,父进程_exit退出时也不刷新标准输出,所以不应该打印出来最后的printf

论坛徽章:
0
4 [报告]
发表于 2012-06-03 22:13 |只看该作者
回复 3# ooaoodoop1


    你把子进程里头的exit改成_exit就打印不出来了!

论坛徽章:
0
5 [报告]
发表于 2012-06-03 22:18 |只看该作者
回复 4# fdl19881


    是的,请问原因是什么?

论坛徽章:
0
6 [报告]
发表于 2012-06-03 22:26 |只看该作者
回复 5# ooaoodoop1


    见那边的回复,,我先回去了,过会再讨论。

论坛徽章:
0
7 [报告]
发表于 2012-06-03 23:46 |只看该作者
回复 1# ooaoodoop1

man vfork:
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.

在vfork()创建的子进程中调用 exit()会影响父进程的状态,产生未定义行为。
在gcc4.1.2下是不会输出最后的printf。   
   

论坛徽章:
0
8 [报告]
发表于 2012-06-03 23:50 |只看该作者
回复 7# Moon_Bird


   哦,我用的是gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP