函数fork
博文链接:
1. 代码示例:
1 #include "apue.h" 2 int glob = 6; 3 char buf[] = "a write to stdout\n"; 4 int main(void) 5 { 6 int var; 7 int pid; 8 var = 88; 9 if (write(STDOUT_FILENO, buf, sizeof(buf) - 1) != sizeof(buf) - 1) 10 { 11 err_sys("write error!\n"); 12 } 13 printf("before fork!\n"); 14 if ((pid = fork())<0) 15 { 16 err_sys("fork error!\n"); 17 } 18 else if (pid == 0) // this is child process for pid == 0 19 { 20 glob++; 21 var++; 22 } 23 else //this is parent process 24 { 25 sleep(2); //wait for child finishing 26 } 27 printf("pid= %d,glob= %d,var= %d\n", getpid(), glob, var); 28 exit(0); 29 }