c - 使用 O_WRONLY 的 Open() 阻塞,即使我在另一端使用 O_RDONLY 的 open()
问题描述
我正面临标题所说的确切问题。
代码
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
同时用于父母和孩子。
解决方案
问题是您在子进程和父进程中都childPipeNameRead[i]
可以阅读。同样,您可以在这两个过程中进行写作。childPipeNameWrite[i]
您需要在其中一个过程中执行相反的操作。
推荐阅读
- typescript - 如何在 typegoose 中使用 mongoosastic 插件
- c# - 将一个动作应用于多个对象 C#
- laravel - 将参数传递给路由时未定义路由
- splunk - 如何更改我的日志的 Splunk 转发器格式?
- postgresql - 创建数据库实例时出错:InvalidParameterValue:PostgreSQL 数据库的数据库引擎无效
- python - 根据时间数据绘制位置/轨迹
- python - 如何从数据框中提取列标题并将其添加到另一个数据框中?
- python - 将 netcdf4 与 Jupyter Notebook 一起使用
- python - How put an image in the upper left corner?
- c++ - 类型“字符串”无法解析