如何编写一个安全的read函数

ssize_t safe_read(int fd, void *buf, size_t count)
{
	ssize_t n;

	do {
		n = read(fd, buf, count);
	} while (n < 0 && errno == EINTR);

	return n;
}

我们大多知道在使用read函数时,返回0表示读到文件的末端,返回值大于1表示读到文件的字节数,如果返回-1时,表示错误,那么是否我们需要在返回-1时认定这个现象时错误的呢,

有一些常见的错误返回值

 EAGAIN Non-blocking  I/O has been selected using O_NONBLOCK and no data was immediately available for reading.

EAGAIN 在非阻塞的I/O中read时,如果没有数据则立即返回,并返回 EAGAIN 错误

EINTR  The call was interrupted by a signal before any data was read.

EINTR 大家知道linux时可抢占的内核,所以在执行时可能被其他的进程打断,我们认为这是一个正常的行为,需要重新读取。这一错误码在网络编程的时候特别重要。


下面是一些常见的错误不多做解释

EBADF  fd is not a valid file descriptor or is not open for reading.      

EFAULT buf is outside your accessible address space.

EINVAL fd is attached to an object which is unsuitable for reading;  or

              the  file  was  opened  with  the  O_DIRECT flag, and either the
              address specified in buf, the value specified in count,  or  the
              current file offset is not suitably aligned.

 EIO    I/O error. This will happen for example when the process is in a
              background process group, tries to  read  from  its  controlling
              tty,  and  either it is ignoring or blocking SIGTTIN or its pro-
              cess group is orphaned.  It may also occur when there is a  low-
              level I/O error while reading from a disk or tape.

EISDIR fd refers to a directory.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值