V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Distributions
Ubuntu
Fedora
CentOS
中文资源站
网易开源镜像站
herozem
V2EX  ›  Linux

vfork 在 linux 上的运行结果与 APUE 上描述不一致, 大家帮忙看看?

  •  
  •   herozem · Apr 6, 2015 · 3036 views
    This topic created in 4038 days ago, the information mentioned may be changed or developed.

    代码如下:

    #include "include/apue.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 fork\n");
    
      if ((pid = fork()) < 0) {
        err_sys("fork error");
      } else if (pid == 0) {
        /* child */
        glob++;
        var++;
        _exit(0);
      } 
    
      printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var);
      exit(0);
    }
    

    运行结果:

    $ ./a.out 
    before fork
    pid = 3317, glob = 6, var = 88
    

    APUE(第二版)第177页上说:
    运行示例得到:

    $ ./a.out 
    before fork
    pid = 3317, glob = 7, var = 89
    

    是不是因为Linux采用了COW(copy on write)技术从而导致行为不像规定中的那样, 子进程在调用_exitexec之前都在父进程的空间中运行呢?

    4 replies    2015-04-07 10:30:41 +08:00
    joyeblue
        1
    joyeblue  
       Apr 6, 2015
    lz给的例子中的代码是调用是fork,而不是调用的vfork。
    herozem
        2
    herozem  
    OP
       Apr 6, 2015
    @joyeblue 都是cp惹得祸。。谢谢提醒
    inevermore
        3
    inevermore  
       Apr 7, 2015
    。。
    jemyzhang
        4
    jemyzhang  
       Apr 7, 2015
    子进程对父进程中的同名变量的更改,不会影响到父进程的值
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5643 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 08:35 · PVG 16:35 · LAX 01:35 · JFK 04:35
    ♥ Do have faith in what you're doing.