簡體   English   中英

即使我在另一端使用O_RDONLY打開(),也使用O_WRONLY塊進行Open()

[英]Open() with O_WRONLY blocks even though I open() with O_RDONLY on the other end

我正面臨標題所說的確切問題。

pid_t childpid;
int childfdRead, childfdWrite; // file descriptors for childs
int parentfdsRead[numWorker], parentfdsWrite[numWorker]; // file descriptors for parent

// store the fifo filenames
char *childPipeNameRead[numWorker];
char *childPipeNameWrite[numWorker];

// helper string to construct fifo filenames
char *suffix = (char*)malloc(20*sizeof(char));
char *fifoname = (char*)malloc(20*sizeof(char));

for(i = 0; i < numWorker; i++){
    // Fifo filename structure read
    sprintf(fifoname, "%s", PATH);
    sprintf(suffix, "_childRead%d", i);
    childPipeNameRead[i] = strdup(strcat(fifoname, suffix));
    mkfifo(childPipeNameRead[i], 0666);

    // Fifo filename structure write
    sprintf(fifoname, "%s", PATH);
    sprintf(suffix, "_childWrite%d", i);
    childPipeNameWrite[i] = strdup(strcat(fifoname, suffix));
    mkfifo(childPipeNameWrite[i], 0666);

    childpid = fork();

    if(childpid < 0){
        perror("fork\n");
    }

    else if(childpid == 0){
        // Open read and write pipes on childs.
        if((childfdRead = open(childPipeNameRead[i], O_RDONLY | O_NONBLOCK)) < 0)
            perror("child pipe:");

        printf("Child with id %d opened pipe with name %s\n", getpid(), childPipeNameRead[i]);

        if((childfdWrite = open(childPipeNameWrite[i], O_WRONLY)) < 0)
            perror("child pipe:");

        printf("Child with id %d opened pipe with name %s\n", getpid(), childPipeNameWrite[i]);
        break;
    }
    else{
        // Open read and write pipes for each child in the parent process.
        if((parentfdsRead[i] = open(childPipeNameRead[i], O_RDONLY | O_NONBLOCK)) < 0)
            perror("parent pipe:");
        printf("Parent with id %d opened pipe with name %s\n", getpid(), childPipeNameRead[i]);

        if((parentfdsWrite[i] = open(childPipeNameWrite[i], O_WRONLY)) < 0)
            perror("parent pipe:");
        printf("Parent with id %d opened pipe with name %s\n", getpid(), childPipeNameWrite[i]);
    }
}

該程序在父級和一個孩子打開其讀取管道(父級僅打開其中一個讀取管道)后掛起。 這是正常行為嗎? 我一直期望它可以打開所有管道,因為我正在使用O_RDONLY | O_NONBLOCK 父母和孩子均為O_RDONLY | O_NONBLOCK

問題是,你打開childPipeNameRead[i]在子和父進程讀。 同樣,您打開childPipeNameWrite[i]在兩個過程中進行編寫。

您需要在其中一個過程中做相反的事情。

暫無
暫無

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

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