简体   繁体   English

为什么打开命名管道会非阻塞地返回无效的文件描述符?

[英]Why does opening a named pipe non-blockingly return an invalid file descriptor?

I'm trying to solidify my understanding of who blocks when and why wrt opening, writing to, and reading from named pipes. 我试图巩固我对谁阻止何时,为什么阻止打开,写入和读取命名管道的理解。

The following code implies that it's invalid to open a named pipe with O_WRONLY | O_NONBLOCK 下面的代码暗示使用O_WRONLY | O_NONBLOCK打开命名管道是无效的O_WRONLY | O_NONBLOCK O_WRONLY | O_NONBLOCK , but I'm not sure whether there's just some bug in my code I don't understand, or if this is generally true. 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]

Question : Why does opening the named pipe with O_WRONLY | O_NONBLOCK 问题 :为什么用O_WRONLY | O_NONBLOCK打开命名管道? O_WRONLY | O_NONBLOCK return an invalid file descriptor? O_WRONLY | O_NONBLOCK返回无效的文件描述符?

I have a suspicion that this has to do with pipes requiring both read and write ends to be open simultaneously, and my hackneyed way of getting around this (by opening one end non-blockingly) fails for this reason. 我怀疑这与需要同时打开读取端和写入端的管道有关,而我顽固解决这一问题的方法(通过无阻塞地打开一端)因此失败。 But I haven't been able to find any specific documentation that either backs up that hypothesis or otherwise explains this observation. 但是我找不到任何支持该假设或以其他方式解释此观察结果的特定文档。

mkfifo(3) - Linux man page: mkfifo(3) -Linux手册页:

See fifo(7) for nonblocking handling of FIFO special files. 有关FIFO特殊文件的非阻塞处理,请参见fifo(7)

fifo(7) - Linux man page: fifo(7) -Linux手册页:

A process can open a FIFO in nonblocking mode. 进程可以非阻塞模式打开FIFO。 In this case, opening for read only will succeed even if no-one has opened on the write side yet, opening for write only will fail with ENXIO (no such device or address) unless the other end has already been opened. 在这种情况下,即使没有人在写侧打开过,只读打开也将成功, 除非ENXIO (没有这样的设备或地址)打开,否则仅写打开将失败,除非另一端已经打开。

John's answer is correct, but to address your specific question, it's not "returning an invalid file descriptor". John的答案是正确的,但是要解决您的特定问题,并不是“返回无效的文件描述符”。 open returns -1 to indicate an error. open返回-1表示错误。 In that case you can check errno (like you're doing for write ) to see the cause of the error. 在这种情况下,您可以检查errno (就像您正在执行write )以查看错误原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM