简体   繁体   English

当我尝试从管道读取而不写入时会发生什么?

[英]What happens when I try to read from a pipe without writing to it?

With this operation I expected to get an error because I'm reading from nothing, but in fact the program seems to keep attempting to read until someone writes to it.通过此操作,我预计会出现错误,因为我从无到有读取,但实际上该程序似乎一直在尝试读取,直到有人写入为止。 If there are no writes it will be stuck in an indefinite loop trying to read and will not proceed.如果没有写入,它将陷入尝试读取的无限循环中并且不会继续。

What exactly happens behind the scene here, do the function kept looping, or is it waiting for a signal, or is something else going on?这里的幕后到底发生了什么,函数是一直循环,还是在等待信号,或者是其他什么事情? Is it still taking CPU resources?它还在占用 CPU 资源吗?

Also, is it possible to make the program return an error code/print out something when trying to read without any writes?此外,是否有可能使程序在尝试读取而不进行任何写入时返回错误代码/打印出某些内容? I don't really need to do it, just wondering if it's possible.我真的不需要这样做,只是想知道是否可能。

This is normal behavior.这是正常行为。 If nothing is available to read, the reading process will block until there is.如果没有可用的读取,读取过程将阻塞,直到有。 It will not consume CPU time while blocking;阻塞时不会消耗CPU时间; the OS will put it to sleep until another process writes to the pipe.操作系统会将其置于睡眠状态,直到另一个进程写入管道。

Keep in mind that pipes were designed to be somewhat transparent;请记住,管道设计得有点透明; a simple filter-type program should not have to care whether the input is a file or a pipe.一个简单的过滤器类型的程序不应该关心输入是文件还是管道。 If every program that wanted to be able to read from a pipe (think grep ) had to include special handling to wait until the writer was ready, it would be very tedious for those programmers.如果每个希望能够从管道中读取的程序(想想grep )都必须包含特殊处理以等待编写器准备就绪,那么对于那些程序员来说,这将是非常乏味的。 This behavior means that reading from pipes doesn't require doing anything special.这种行为意味着从管道读取不需要做任何特殊的事情。

If you don't want to block if no data is available, you can set the O_NONBLOCK status flag on the file descriptor, either when you open(2) it, or with fcntl(fd, F_SETFL, ...) .如果您不想在没有数据可用时阻塞,您可以在文件描述符上设置O_NONBLOCK状态标志,无论是在您open(2)时,还是使用fcntl(fd, F_SETFL, ...) In this case, when no data is available, read(2) will return -1 and set errno to EAGAIN or EWOULDBLOCK .在这种情况下,当没有数据可用时, read(2)将返回-1并将errnoEAGAINEWOULDBLOCK This means, of course, that every time you read from the file descriptor, you have to write code to handle such a case.这当然意味着,每次从文件描述符读取时,都必须编写代码来处理这种情况。

You can also use select(2) or poll(2) to wait until data is available, optionally with a timeout.您还可以使用select(2)poll(2)等待数据可用,可选择超时。

It is also possible to arrange it so that a signal arriving during the blocking will cause read(2) to return -1 and set errno to EINTR .也可以安排它,以便在阻塞期间到达的信号将导致read(2)返回-1并将errnoEINTR This depends on system call restarting semantics and is a little bit complicated.这取决于系统调用重新启动语义,并且有点复杂。

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

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