C++-linux文件锁定状态下的读取操作

发布于 2017-02-09 10:32:06 字数 137 浏览 1213 评论 3

在linux中,可以对文件实施区域锁定,对文件的部分进行操作。但是对文件区域加锁之后,必须使用底层的read和write调用来访问文件中的数据,而不要使用更加高级的fread和fwrite调用。

这是为什么呢?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夜无邪 2017-06-19 01:03:16

文件描述符在文件指针结构体里面,还有很多其余的东西。所以不一样。

晚风撩人 2017-02-26 19:00:39

《Linux程序设计》(Beginning Linux Programming)有介绍到这个问题,直接将原文拷贝过来了。

When you’re using locking on regions of a file, it’s very important to use the lower-level read and write calls to access the data in the file, rather than the higher-level fread and fwrite. This is necessary because fread and fwrite perform buffering of data read or written inside the library, so executing an fread call to read the first 100 bytes of a file may (in fact almost certainly will) read more than
100 bytes and buffer the additional data
inside the library. If the program then uses fread to read the next 100 bytes, it will actually read data already buffered inside the library and not allow a low-level
read to pull more data from the file.

To see why this is a problem, consider two programs that wish to update the same file. Suppose the file consists of 200 bytes of data, all zeros. The first program starts first and obtains a write lock on the first 100
bytes of the file. It then uses fread to read in those 100 bytes. However, as shown in an earlier chapter, fread will read ahead by up to BUFSIZ(默认是4096字节) bytes at a time, so it actually reads the entire file into memory, but only passes the first 100 bytes back to the program.

The second program then starts. It obtains a write lock on the second 100 bytes of the program. This is successful because the first program locked only the first 100 bytes. The second program writes twos to bytes 100 to 199, closes the file, unlocks it, and exits. The first program then locks the second 100 bytes of the file and calls fread to read them in. As that data was already buffered in memory by the library, what the program actually sees is 100 bytes of zeros, not the 100 twos that actually exist in the file on the hard disk. This problem doesn’t occur when you’re using read and write.

想挽留 2017-02-18 20:29:49

当对文件区域加锁后,就必须使用系统调用read或write来访问数据,不能使用fread和fwrite,因为 fread/fwrite 是带缓冲的,read/write 不带缓冲,关于fread/fwrite因为带缓存可能出现的问题,可参看我的问题:调用fread后直接调用fwrite写不进去,反之也是,为什么?

两个程序打算更新同一个文件,假设文件为200个全零的字节组成。程序一先运行,并获得文件头100个字节的写锁,然后用fread来读取这100字节,它会读取多达BUFSIZE个字节的数据,实际上把整个200字节全读到了缓冲区。接着,程序二开始运行,获得文件后100字节的写锁,并把着100字节写成全1,操作成功,关闭并解锁。这时程序已锁定后100字节,再fread,尽管真正数据现在是全1,但是先前数据已被缓存,所以程序实际上只读到原来的100字节的全0.如果使用read和write就不会有这个问题了。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文