我在代碼中創建子進程。當我調用fork()時,子進程應該從下一個語句開始執行,但在我的代碼中,子進程在fork調用之前執行語句。子進程執行fork調用之前寫入的語句
#include<stdio.h>
int main()
{
int pid;
FILE *fp;
fp = fopen("oh.txt","w");
fprintf(fp,"i am before fork\n");
pid = fork();
if(pid == 0)
{
fprintf(fp,"i am inside child block\n");
}
else{
fprintf(fp,"i inside parent block\n");
}
fprintf(fp,"i am inside the common block to both parent and child\n");
fclose(fp);
return 0;
}
這是它的輸出我得到
OUTPUT:
i am before fork
i inside parent block
i am inside the common block to both parent and child
i am before fork
i am inside child block
i am inside the common block to both parent and child
行「我是叉之前」應一次在文件中寫的,但它是由孩子寫兩次,家長。 爲什麼是這樣?
謝謝。
添加'fflush(FP)'你叉掉了。 – 2013-02-20 16:17:17