簡體   English   中英

子進程在使用父級將數據寫入管道之前讀取數據

[英]Child process reads data before data is being written to pipe using parent

我正在使用fork()創建一個子進程,在父進程中我正在輸入5個整數並將其保存到數組中。 然后將該數據寫入管道。 然后子進程將從餅圖中讀取數據並將其打印到屏幕上。

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#define INPUT 5

int main() {
    int     fd[2];
    pid_t   childprocess;

    if((childprocess = fork()) < 0) {
        perror("Cannot fork child");
    }

    if(childprocess > 0) {
        // Parent
        int userInput[INPUT];

        close(fd[0]);

        for(int i = 0; i < INPUT; i++) {
            printf("Enter number %d: ", i+1);
            scanf("%d", &userInput[i]);
        }

        write(fd[1], userInput, sizeof(userInput) + 1);

    } else {
        // Child
        close(fd[1]);

        int parentData[INPUT];

        read(fd[0], parentData, sizeof(parentData));

        for(int i = 0; i < INPUT; i++) {
            printf("%d => %d", i+1, parentData[i]);
        }
    }

    return 0;
}

當我使用./a.out運行程序時,我會觀察到以下行為。

Enter number 1: 1 => -4731629522 => 327663 => 2005319684 => 15 => 1

管道實施導致此行為的方式是否有任何錯誤?

問題是文件描述符沒有被管道函數初始化。 當達到讀取功能時, fd[0]可能是無效的文件描述符。 讀取0個字節,寫入stdout的整數就是未初始化數組parentData 只需添加:

pipe(fd);

同步如何工作? 當使用有效的filedescriptor調用read函數時,內核會暫停/阻塞進程並等待,直到所請求的字節數( sizeof parentData )被另一個進程寫入管道。 然后內核從管道中復制字節。 這稱為阻塞IO。

注意:當寫入過程在達到所請求的字節數之前停止/關閉filedescriptor時,並非所有字節都寫入緩沖區。 read的返回值是讀取的字節數。

還有非阻塞IO。 在等待數據時,該過程可以執行其他操作。 它通常用一個線程實現,該線程從filedescriptor / socket(網絡IO)讀取(帶阻塞IO)並在完成時設置一個標志。

暫無
暫無

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

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