#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int globVar = 5;
int main (void)
{
pid_t pid;
int var = 1, i;
printf("fork is different with vfork\n ");
// pid = fork();
pid = vfork();
switch(pid){
case 0:
i = 3;
while(i-- > 0)
{
printf("child process is running!\n");
globVar++;
var++;
}
printf("%d, %d\n",globVar,var);
break;
case 1:
perror("process creation failed!\n");
exit(0);
default:
i = 5;
while(i-- > 0)
{
printf("parent process is running\n");
globVar++;
var++;
sleep(1);
}
printf("%d, %d\n",globVar,var);
exit(0);
}
}
结果
[root@localhost labtwo]# ./diffork
fork is different with vfork
child process is running!
child process is running!
child process is running!
8, 4
parent process is running
parent process is running
parent process is running
parent process is running
parent process is running
13, 11345274
最后的父进程var的值不应该是9吗怎么会是11345274 谁能帮忙解一下疑惑?谢谢了