红联Linux门户
Linux帮助

fork的一个例子, 输出结果不明白

发布时间:2012-08-07 17:08:51来源:红联作者:linux08071151
#include
#include
#include
main ()
{
pid_t pid;
printf("fork!");
pid=vfork();


if (pid < 0)
printf("error in fork!");
else if (pid == 0)
printf("i am the child process, my process id is %d\n",getpid());
else
printf("i am the parent process, my process id is %d\n",getpid());
}
输出:
fork!i am the child process, my process id is 17757
i am the parent process, my process id is 17756
fork!i am the child process, my process id is 17758
怎么会输出三个语句呢
文章评论

共有 6 条评论

  1. 奶茶dsk 于 2012-08-10 17:37:23发表:

    NAME
    vfork - create a child process and block parent

    SYNOPSIS
    #include
    #include

    pid_t vfork(void);

    STANDARD DESCRIPTION
    (From XPG4 / SUSv2 / POSIX draft.) The vfork() function has the same
    effect as fork(), except that the behaviour 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() or one of the exec family of func-
    tions.


    vfork生成的进程和父进程共享页表,对进程的行为有特殊的要求,lz的代码是未定义的

  2. linux08071151 于 2012-08-10 11:40:13发表:

    5# z767900438


    首先感谢热友的解答 !刚接触linux,希望大家不吝赐教。加了exit(0)之后,当父进程执行完了之后,程序可以正常的退出,即输出前两条语句。我想知道为什么不加就会输出三条呢。

  3. z767900438 于 2012-08-09 22:22:10发表:

    建议楼主在末尾加个exit(0),再试试看可不可以

  4. linux08071151 于 2012-08-08 18:49:48发表:

    3# freelevei


    为什么最后又输出子进程的那部分了呢

  5. freelevei 于 2012-08-08 13:42:07发表:

    vfork创建的子进程与父进程共享的,子进程先返回。

  6. NetFlow 于 2012-08-08 08:44:22发表:

    这1圆不好挣啊