如何编写一个安全的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.

原创粉丝点击