Linux System Programming阅读笔记之---read(....)

关于read(...)返回值的正确判断:p30

File I/O 的 read(...)函数用法:

 

有问题的代码,只判断返回值为-1的情况。

 

unsigned long word;
ssize_t nr;
/* read a couple bytes into 'word' from 'fd' */
nr = read (fd, &word, sizeof (unsigned long));
if (nr == -1)
/* error */

 

 

Indeed, a call to read( ) can result in many possibilities:
• The call returns a value equal to len. All len read bytes are stored in buf. The
results are as intended.
• The call returns a value less than len, but greater than zero. The read bytes are
stored in buf. This can occur because a signal interrupted the read midway, an
error occurred in the middle of the read, more than zero, but less than len bytes’

worth of data was available, or EOF was reached before len bytes were read.
Reissuing the read (with correspondingly updated buf and len values) will read the
remaining bytes into the rest of the buffer, or indicate the cause of the problem.
• The call returns 0. This indicates EOF. There is nothing to read.
• The call blocks because no data is currently available. This won’t happen in nonblocking
mode.
• The call returns -1, and errno is set to EINTR. This indicates that a signal was
received before any bytes were read. The call can be reissued.
• The call returns -1, and errno is set to EAGAIN. This indicates that the read would
block because no data is currently available, and that the request should be reissued
later. This happens only in nonblocking mode.
• The call returns -1, and errno is set to a value other than EINTR or EAGAIN. This
indicates a more serious error.

 

正确做法:

 

ssize_t ret;
while (len != 0 && (ret = read (fd, buf, len)) != 0) {
  if (ret == -1) {
    if (errno == EINTR)
    continue;
    perror ("read");
    break;
  }
  len -= ret;
  buf += ret;
}

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值