首页 > 代码库 > linux c 使用vfork时产生的疑问

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;
}

运行结果为:

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


问题来了,为什么var值不是9????














linux c 使用vfork时产生的疑问