linux c 使用vfork時產生的疑問

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int globvar=5;

int main(){
  pid_t pid;

 int var=1, i;
  printf("fork is diff with vfork\n");
 // pid=fork();
  pid=vfork();
  switch(pid){
  case 0:
    i=3;    
    while(i-->0){
     printf("child process is running\n");
     globvar++;
     var++;
     sleep(1);
    }
    printf("child's globvar=%d,var=%d\n",globvar,var);
   break;
  
  default:
    i=5;
    while(i-->0){
     printf("parent process is running\n");
     globvar++;
     var++;
     sleep(1);
    }
    printf("parent's globvar=%d,var=%d\n",globvar,var);


    exit(0);
  case -1:
    printf("process creation failed\n");
    exit(0);



}
 return 0;
}

運行結果爲:code

fork is diff with vfork
child process is running
child process is running
child process is running
child's globvar=8,var=4
parent process is running
parent process is running
parent process is running
parent process is running
parent process is running
parent's globvar=13,var=-1216646167

it


問題來了,爲何var值不是9????io

相關文章
相關標籤/搜索