标签:
在「Advanced.Programming.in.the.UNIX.Environment, 3rd.Edition」一書中的8.3節 (p. 230),有個小程式,如下,是用來說明 UNIX 環境中,使用 fork 產生子行程 (child process),要注意的一些事,先看一下程式:
1 #include <stdio.h> 2 #include <unistd.h> 3 4 int globvar = 6; 5 char buf[] = "a write to stdout\n"; 6 7 int main(void) { 8 int var; 9 pid_t pid; 10 11 var = 88; 12 if (write(STDOUT_FILENO, buf, sizeof(buf)-1) != sizeof(buf)-1) 13 printf("write error"); 14 printf("before fork\n"); 15 16 if ((pid = fork()) < 0) { 17 printf("fork error"); 18 } 19 else if (pid == 0) { 20 globvar++; 21 var++; 22 } 23 else { 24 sleep(2); 25 } 26 27 printf("pid = %ld, getpid = %ld, glob = %d, var = %d\n", (long) pid, (long) getpid(), globvar, var); 28 _exit(0); 29 }
上面的程式很簡單的利用 fork 產生一個子行程,等待 2 秒後,印出一段訊息,顯示父行程與子行程的 pid (process id)、共用變數及區域變數,執行結果如下: (我的程式命名為 forEx01.c)
[steven@CentOS7 Debug]$ ./forkEx01
a write to stdout
before fork
pid = 0, getpid = 9214, glob = 7, var = 89
pid = 9214, getpid = 9213, glob = 6, var = 88
[steven@CentOS7 Debug]$
标签:
原文地址:http://www.cnblogs.com/stevwn/p/4556430.html