fork()函數用於產生一個子進程,和當前的進程並行執行。通過判斷fork函數的返回值可以區分是父進程還是子進程,如果返回爲0,則爲子進程。
對於fork函數的執行方式,自己還是存在一些不明,寫了一個簡單的測試程序測試fork函數的一些性質。
測試程序如下:
#include <stdio.h>
#include <unistd.h>
int main(void)
{
pid_t pid;
int test = 3;
FILE* fp;
fp = fopen("test.txt", "w");
printf("This is the start!\n");
if ((pid = fork()) == 0)
{
fprintf(fp, "child\n");
printf("This is the child process.\n");
printf("child: test = %d\n", test);
fclose(fp);
}
else
{
fprintf(fp, "parent\n");
test = 200;
printf("This is the parent process.\n");
printf("parent: test = %d\n", test);
fclose(fp);
}
return 0;
}
執行的結果爲:
This is the start!
This is the parent process.
parent: test = 200
This is the child process.
child: test = 3
生成的test.txt文件的內容爲:
parent
child
分析:
首先,This is the start. 這句只在屏幕上輸出一次。因此fork函數創建的子進程沒有從頭開始執行,而是從當前開始執行的。
其次,關於變量test的值,可以看到,子進程的變量與父進程變量的值是一樣的,但是沒有共享。因爲父進程改變了局部變量的值,並沒有影響到子進程。
最後,關於test.txt文件的內容。該文件沒有隻顯示parent或者child,因此兩個進程中的fclose函數必有一個沒有關閉文件。而是兩個都關閉後,文件才真正的關閉。