在什么情况下read()系统调用会返回0? [英] Under what circumstances does the read() syscall return 0?

查看:89
本文介绍了在什么情况下read()系统调用会返回0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看Unix中的 read 系统调用,该系统调用(至少在Linux中是)具有以下签名:[1]

I'm looking at the read syscall in Unix, which (at least in Linux) has this signature: [1]

ssize_t read(int fd, void* buf, size_t count);

让我们假设调用成功(即没有负的返回值),并且 count>0 (即缓冲区实际上可以存储非零数量的字节).在什么情况下 read()返回0?我可以想到以下几点:

Let's assume that the call succeeds (i.e. no negative return values) and that count > 0 (i.e. the buffer actually can store a nonzero amount of bytes). Under which circumstances would read() return 0? I can think of the following:

  • fd 引用常规文件并且到达文件末尾时.
  • fd 指向管道,套接字或FIFO的接收端时,发送端已关闭,并且管道/套接字/FIFO自己的缓冲区已用尽.
  • fd 指的是位于 ICANON 中的终端设备的从设备侧,并且 Ctrl-D 已发送到主设备侧时当行缓冲区为空时.
  • When fd refers to a regular file and the end of the file has been reached.
  • When fd refers to the receiving end of a pipe, socket or FIFO, the sending end has been closed and the pipe's/socket's/FIFO's own buffer has been exhausted.
  • When fd refers to the slave side of a terminal device that is in ICANON and Ctrl-D has been sent into the master side while the line buffer was empty.

我很好奇是否还有其他我不知道的情况,其中 read()将以0的结果返回.我特别感兴趣(由于原因)在上面列表中的最后一个情况下, read()返回一次,但随后在同一FD上调用 read()可能返回非零结果.如果答案仅适用于某种类型的Unix,我仍然对听到它感兴趣.

I'm curious if there are any other situations that I'm not aware of, where read() would return with a result of 0. I'm especially interested (because of reasons) in situations like the last one in the list above, where read() returns 0 once, but subsequent calls to read() on the same FD could return a nonzero result. If an answer only applies to a certain flavor of Unix, I'm still interested in hearing it.

[1]我知道此签名是针对libc包装程序的,而不是针对实际的syscall的,但这并不重要.

[1] I know this signature is for the libc wrapper, not the actual syscall, but that's not important right now.

推荐答案

  • 如果物理文件系统不支持从目录进行简单读取,则read()如果用于目录,则将返回0.
  • 如果没有进程打开要写入的管道,则read()返回0表示文件结束.
  • 如果流套接字上的连接断开,但是没有可用数据,则read()函数将0字节作为EOF返回.
  • 这篇关于在什么情况下read()系统调用会返回0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆