gpt4 book ai didi

c - Open() with O_WRONLY 会阻塞,即使我 open() with O_RDONLY 在另一端

转载 作者:行者123 更新时间:2023-11-30 14:49:01 30 4
gpt4 key购买 nike

我正面临标题所说的确切问题。

代码

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对于 parent 和 child 来说。

最佳答案

问题是您打开 childPipeNameRead[i] 以便在子进程和父进程中读取。同样,您打开 childPipeNameWrite[i] 以便在两个进程中进行写入。

您需要在其中一个进程中执行相反的操作。

关于c - Open() with O_WRONLY 会阻塞,即使我 open() with O_RDONLY 在另一端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50074505/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com