#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;}
The result of the operation is:
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
The question comes, why is the Var value not 9????
Questions generated by Linux C when using Vfork