如何编写一个安全的read函数
来源:互联网 发布:java多线程写入数据库 编辑:程序博客网 时间:2024/06/06 10:44
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.
- 如何编写一个安全的read函数
- 如何安全的Hook一个函数
- 如何编写一个线程安全的程序或者函数库?
- 如何编写一个没有主函数的C程序
- 如何编写异常安全的C++代码
- 如何编写异常安全的C++代码
- 如何编写异常安全的C++代码
- 如何编写异常安全的C++代码
- 如何编写异常安全的C++代码
- 如何编写异常安全的C++代码
- 如何编写异常安全的C++代码
- 如何编写安全的Java代码
- 如何编写异常安全的C++代码
- 如何编写线程安全的DLL
- 如何编写异常安全的C++代码
- 如何编写异常安全的C++代码
- 如何编写异常安全的C++代码
- 如何编写异常安全的C++代码
- FreeBSD内核锁机制(ZZ)
- C语言的复杂声明
- Linux 内核代码阅读 pid.c
- iOS开发知识要点
- 重新定义malloc和free 防止内存泄漏
- 如何编写一个安全的read函数
- [转]Win32编程系列之ActiveX控件的使用
- C#程序打包安装部署之生成Windows安装程序
- access 数据库 和 mssql 时间是不同的
- MYSQL用source命令导入数据库出现unknown command '\'
- 百度地图api 详细说明与配置 《一》
- mongodb like查询
- Still Image Colorization
- 美化表单——自定义单选按钮和复选按钮