Chinaunix

标题: vfork exit _exit [打印本页]

作者: ooaoodoop1    时间: 2012-06-03 18:43
标题: vfork exit _exit

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

#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为什么能打印出来呢?
作者: Moon_Bird    时间: 2012-06-03 19:49
回复 1# ooaoodoop1

从哪儿看出 不应该打印出来呢 ?
   
作者: ooaoodoop1    时间: 2012-06-03 20:52
回复 2# Moon_Bird


    最后父进程printf没有“\n”,父进程_exit退出时也不刷新标准输出,所以不应该打印出来最后的printf
作者: fdl19881    时间: 2012-06-03 22:13
回复 3# ooaoodoop1


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

作者: ooaoodoop1    时间: 2012-06-03 22:18
回复 4# fdl19881


    是的,请问原因是什么?
作者: fdl19881    时间: 2012-06-03 22:26
回复 5# ooaoodoop1


    见那边的回复,,我先回去了,过会再讨论。
作者: Moon_Bird    时间: 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。   
   
作者: ooaoodoop1    时间: 2012-06-03 23:50
回复 7# Moon_Bird


   哦,我用的是gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2