linux中的read和write系统调用

来源:互联网 发布:毒姐捏脸数据 编辑:程序博客网 时间:2024/04/27 20:27

linux中read和write系统调用

在这里小koala着重于read()和write()来读写普通文件,因为小koala在编写实际文件读写函数时,疏忽了一些重要的地方,造成无休止的向系统中写数据,最后系统崩溃。当时瞬间“三观”尽毁。现在较为详细地分析错误的原因,有问题或是模糊的话,希望大神们告诉小koala,先行谢过了。

在《深入理解linux内核》中虚拟文件系统一章中有这样的说明:

VFS所隐含的主要思想在于引入了一个通用的文件模型(common file model),这个模型能够表示所有支持的文件系统。linux内核对每个文件读写操作都必须使用一个指针,指向要访问的具体文件系统的适当函数。换句话说,当应用程序对read()或是write()调用引起内核调用相应的sys_read()或是sys_write()服务例程,文件在内核内存中是由一个file数据结构来表示的。这种数据结构中包含一个称为f_op的字段,该字段中包含一个指向专对某一个文件系统(如sysfs虚拟文件系统)的读写函数指针,sys_read()或是sys_write()查找到指向该函数的指针,并调用它。这样一来,应用程序的read()或是write()就被转化为相对间接的调用:

file->f_op->read() 或 file->f_op->write()

read()系统调用

#include <unistd.h>ssize_t read(int fd, void *buf, size_t nbytes);

在man手册中是这样解释的:

read() attempts t read up to count bytes from file descriptor fd into the buffer starting at buf. on files that support seeking, the read operation commences at the current file offset, and the file offset is incremented by the number of bytes read. if the current file offset is at or past the end of file,no bytes are read, and read() return zero.(有部分省略)

write()系统调用

#include <unistd.h>ssize_t write(int fd, void *buf, size_t nbytes);

在man手册中是这样解释的:

write() writes up to count bytes from the buffer pointed buf to the file referred to by the file descriptor fd. The number of bytes written may be less than count if ,for example, there si insufficient space on the underlying physical medium. for a seekable file writing takes place at the current file offset, and the file offset is incremented by the number of bytes actually written.(有部分省略)

所以read()和write()对实际底层文件读写,这与标准I/O读写有着根本上的区别。小koala曾经有写分析两者区别的博文:http://blog.csdn.net/u013592097/article/details/51896374

但是现在我想着重分析的是返回值!!分析我出现错误的原因归根到底是在返回值中。

read()返回值:读到的字节数,若已到文件尾,返回0;若错误发生,返回-1。

write()返回值:通常与参数nbytes相同,否则表示出错!!!这里的潜在意思有两层:1 若返回-1,那么写操作失败。 2(针对于具体文件的写操作file->f_op->write()指向的函数)返回值小于nbytes时,内核很可能会再次写余下的数据,形成死循环,文件系统写满,系统挂了!!!

所以在写实际的文件系统的写操作时一定注意其返回值,否则可能系统崩溃了。

0 0
原创粉丝点击