fork函数
例1:
#include <stdio.h> #include <unistd.h> int global_var = 1; int main(int argc, char* argv[]) { int var = 10; if(fork() == 0) { printf("child process global_var = %d var = %d\n", ++global_var, ++var); } printf("pid = %d global_var = %d var = %d\n", getpid(), global_var, var); return 0; }
输出:
pid = 12681 global_var = 1 var = 10
child process global_var = 2 var = 11
pid = 12682 global_var = 2 var = 11
例2:
#include <stdio.h> #include <unistd.h> int global_var = 1; int main(int argc, char* argv[]) { int var = 10; if(fork() == 0) { printf("child process global_var = %d var = %d\n", ++global_var, ++var); } else { printf("pid = %d global_var = %d var = %d\n", getpid(), global_var, var); } return 0; }
输出:
pid = 12870 global_var = 1 var = 10
child process global_var = 2 var = 11
例3:
#include <stdio.h> #include <unistd.h> int global_var = 1; int main(int argc, char* argv[]) { int var = 10; if(fork() == 0) { printf("child process global_var = %d var = %d\n", ++global_var, ++var); exit(0); //return 0; } printf("pid = %d global_var = %d var = %d\n", getpid(), global_var, var); return 0; }
输出:
pid = 12920 global_var = 1 var = 10
child process global_var = 2 var = 11