【发布时间】:2020-01-07 15:49:15
【问题描述】:
我正在努力巩固我对谁在何时以及为什么会阻止打开、写入和读取命名管道的理解。
以下代码暗示使用O_WRONLY | O_NONBLOCK 打开命名管道是无效的,但我不确定我的代码中是否存在一些我不理解的错误,或者这是否普遍正确。
// main.c
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
int main( int argc, char* argv[] )
{
int wfd = open( "/tmp/foo", O_WRONLY | O_NONBLOCK );
printf( "wfd[%d]\n", wfd );
if ( wfd >= 0 )
{
int res = write( wfd, "0", 1 );
printf( "write: [%d], errno[%d(%s)]\n", res, errno, strerror( errno ) );
sleep(3);
printf( "writer ending!\n" );
}
return 0;
}
> ls -l /tmp/foo
prwxrwxrwx. 1 user user 0 Sep 4 10:35 /tmp/foo
>
> gcc -g main.c && ./a.out
wfd[-1]
问题:为什么用O_WRONLY | O_NONBLOCK打开命名管道会返回一个无效的文件描述符?
我怀疑这与需要同时打开读取和写入端的管道有关,而我解决此问题的陈旧方法(通过非阻塞地打开一端)由于这个原因失败了。但我找不到任何支持该假设或解释该观察结果的具体文档。
【问题讨论】:
标签: c linux pipe named-pipes