簡體   English   中英

分叉的孩子“打印”兩次重定向標准輸出

[英]Forked child “prints” redirected stdout twice

在一段時間(1)內,我正在嘗試:

  • 用fork()產生一個子進程;

  • 重定向子進程標准輸出,以便父進程可以看到它

  • 從父進程在終端中打印結果

  • 重復

奇怪的是,子進程的輸出似乎被打印了兩次

// parentToChild  and  childToParent are the pipes I'm using

while(1) {

int pid = fork();
    if(pid < 0) {
    // error, get out
    exit(0);
} else if(pid != 0) {
    // parent process
    close(parentToChild[0]); // don't need read end of parentToChild
    close(childToParent[1]); // don't need write end of childToParent

    sleep(4);
    char respBuffer[400];
    int respBufferLength = read(childToParent[0], respBuffer, sizeof(respBuffer));
    printf("before\n");
    printf("parent tried to read something from its child and got: %s\n", respBuffer);
    printf("after\n");
} else if (pid == 0) {
    if(dup2(childToParent[1], STDOUT_FILENO) < 0) {
        // printf("dup2 error");
    };
    close(childToParent[1]);       
    close(childToParent[0]);

    close(parentToChild[1]);    // write end of parentToChild not used

    printf("child message");

    // if we don't exit here, we run the risk of repeatedly creating more processes in a loop
    exit(0);
}
}

我希望每次迭代時以下循環的輸出為:

before
parent tried to read something from its child and got: child message
after

但是,相反,在每次迭代中我得到:

before
parent tried to read something from its child and got: child message
after
child message

第二次打印“子消息”的原因是什么?

在調用fork()之前刷新stdout緩沖區似乎無法解決問題

有趣的是,刪除while循環並保持其他所有內容完好無缺

在循環的第一次迭代中,關閉childToParent[1] ,並且不重新創建管道,因此在循環的第二次迭代中,其嘗試重用那些封閉的管道,因此子級的dup2調用失敗,因此其printf進入終端。 同時,在父級中, read調用返回0而不向緩沖區寫入任何內容,因此您只打印舊內容。

暫無
暫無

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

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