簡體   English   中英

fork()新進程並寫入子進程和父進程的文件

[英]Fork() new process and write to files for child and parent processes

我是fork(),父進程和子進程的新手,並且難以理解我編寫的代碼背后的邏輯,但沒有達到我的預期。 這是我有的:

 int main (int argc, char** argv)
 {
     FILE *fp_parent;
     FILE *fp_child;

     fp_parent = fopen ("parent.out","w");
     fp_child = fopen ("child.out","w");

     int test_pid;
     printf ("GET HERE\n");

     fprintf (fp_parent,"Begin\n"); // MY CONCERN

     for (int i = 0; i < 1; i++) //for simplicity, just fork 1 process.
     {                          // but i want to fork more processes later
        test_pid = fork();
        if(test_pid < 0)
        {
          printf ("ERROR fork\n");
          exit (0);
        }
        else if(test_pid == 0) // CHILD
        {
          fprintf(fp_child,"child\n");
          break;
        }
        else //PARENT
        {
          fprintf(fp_parent,"parent\n");
        }
     }
     fclose(fp_parent);
     fclose(fp_child);
 }

所以上面代碼的輸出是:

 to stdout: GET HERE

 in parent.out:

 Begin

 parent

 Begin

 in child.out:

 child

我主要擔心的是我不太明白為什么“Begin”會被寫入parent.out兩次。 如果我完全刪除for循環,則只寫入一個“Begin”,這是預期的。

所以我認為這是因為fork()而且我肯定想念或者不理解它背后的一些邏輯。 你能幫我解釋一下嗎?

我的計划是能夠在parent.out中的for循環之前寫一些東西,並在parent.out中的for循環期間寫一些東西。 子進程將寫入child.out。

在C中,使用FILE結構的輸入/輸出操作在用戶進程級別進行緩沖。 在您的情況下,您寫入fp_parent的輸出實際上並未寫入磁盤,並且在fork時保存在本地緩沖區中。 fork創建整個過程的副本,包括包含Begin的緩沖區,這就是它在文件中出現兩次的原因。 嘗試把fflush(fp_parent); fork之前。 這將刷新緩沖區,臟線將從文件中消失。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM