欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

Linux系统调用fsync函数详解

程序员文章站 2022-07-07 09:53:59
Linux fsync函数主要用于将同步内存中所有已修改的文件数据到储存设备,多用于备份... 13-11-14...
功能描述:

同步内存中所有已修改的文件数据到储存设备。

用法:
#include <unistd.h>

int fsync(int fd);

参数:
fd:文件描述词。

返回说明:
成功执行时,返回0。失败返回-1,errno被设为以下的某个值
ebadf: 文件描述词无效
eio : 读写的过程中发生错误

erofs, einval:文件所在的文件系统不支持同步

强制把系统缓存写入文件sync和fsync函数,, fflush和fsync的联系和区别2010-05-10 11:25传统的u n i x实现在内核中设有缓冲存储器,大多数磁盘i / o都通过缓存进行。当将数据写
到文件上时,通常该数据先由内核复制到缓存中,如果该缓存尚未写满,则并不将其排入输出
队列,而是等待其写满或者当内核需要重用该缓存以便存放其他磁盘块数据时,再将该缓存排
入输出队列,然后待其到达队首时,才进行实际的i / o操作。这种输出方式被称之为延迟写
(delayed write)(bach 〔1 9 8 6〕第3章详细讨论了延迟写)。延迟写减少了磁盘读写次数,但是
第4章文件和目录8 7
下载
却降低了文件内容的更新速度,使得欲写到文件中的数据在一段时间内并没有写到磁盘上。当
系统发生故障时,这种延迟可能造成文件更新内容的丢失。为了保证磁盘上实际文件系统与缓
存中内容的一致性,u n i x系统提供了s y n c和f s y n c两个系统调用函数。
#include <unistd.h>
void sync(void);
int fsync(intf i l e d e s) ;
返回:若成功则为0,若出错则为-1
s y n c只是将所有修改过的块的缓存排入写队列,然后就返回,它并不等待实际i / o操作结束。
系统精灵进程(通常称为u p d a t e )一般每隔3 0秒调用一次s y n c函数。这就保证了定期刷新内
核的块缓存。命令s y n c ( 1 )也调用s y n c函数。
函数f s y n c只引用单个文件(由文件描述符f i l e d e s指定),它等待i / o结束,然后返回。f s y n c可
用于数据库这样的应用程序,它确保修改过的块立即写到磁盘上。比较一下f s y n c和o _ s y n c标
志(见3 . 1 3节)。当调用f s y n c时,它更新文件的内容,而对于o _ s y n c,则每次对文件调用w r i t e
函数时就更新文件的内容。


fflush和fsync的联系和区别
[zz ] http://blog.chinaunix.net/u2/73874/showart_1421917.html

1.提供者fflush是libc.a中提供的方法,fsync是系统提供的系统调用。2.原形fflush接受一个参数file *.fflush(file *);fsync接受的时一个int型的文件描述符。fsync(int fd);3.功能fflush:是把c库中的缓冲调用write函数写到磁盘[其实是写到内核的缓冲区]。fsync:是把内核缓冲刷到磁盘上。

c库缓冲-----fflush---------〉内核缓冲--------fsync-----〉磁盘


再转一篇英文的

write-back support
ubifs supports write-back, which means that file changes do not go to the flash media straight away, but they are cached and go to the flash later, when it is absolutely necessary. this helps to greatly reduce the amount of i/o which results in better performance. write-back caching is a standard technique which is used by most file systems like ext3 or xfs.
in contrast, jffs2 does not have write-back support and all the jffs2 file system changes go the flash synchronously. well, this is not completely true and jffs2 does have a small buffer of a nand page size (if the underlying flash is nand). this buffer contains last written data and is flushed once it is full. however, because the amount of cached data are very small, jffs2 is very close to a synchronous file system.
write-back support requires the application programmers to take extra care about synchronizing important files in time. otherwise the files may corrupt or disappear in case of power-cuts, which happens very often in many embedded devices. let's take a glimpse at linux manual pages:
$ man 2 write
....
notes
a successful return from write() does not make any guarantee that data
has been committed to disk. in fact, on some buggy implementations, it
does not even guarantee that space has successfully been reserved for
the data. the only way to be sure is to call fsync(2) after you are
done writing all your data.
...
this is true for ubifs (except of the "some buggy implementations" part, because ubifs does reserves space for cached dirty data). this is also true for jffs2, as well as for any other linux file system.
however, some (perhaps not very good) user-space programmers do not take write-back into account. they do not read manual pages carefully. when such applications are used in embedded systems which run jffs2 - they work fine, because jffs2 is almost synchronous. of course, the applications are buggy, but they appear to work well enough with jffs2. but the bugs show up when ubifs is used instead. please, be careful and check/test your applications with respect to power cut tolerance if you switch from jffs2 to ubifs. the following is a list of useful hints and advices.
if you want to switch into synchronous mode, use the -o sync option when mounting ubifs; however, the file system performance will drop - be careful; also remember that ubifs mounted in synchronous mode provides less guarantees than jffs2 - refer this section for details.
always keep in mind the above statement from the manual pages and run fsync() for all important files you change; of course, there is no need to synchronize "throw-away" temporary files; just think how important is the file data and decide; and do not use fsync() unnecessarily, because this will hit the performance;
if you want to be more accurate, you may use fdatasync(), in which cases only data changes will be flushed, but not inode meta-data changes (e.g., "mtime" or permissions); this might be more optimal than using fsync() if the synchronization is done often, e.g., in a loop; otherwise just stick with fsync();
in shell, the sync command may be used, but it synchronizes whole file system which might be not very optimal; and there is a similar libc sync() function;
you may use the o_sync flag of the open() call; this will make sure all the data (but not meta-data) changes go to the media before the write() operation returns; but in general, it is better to use fsync(), because o_sync makes each write to be synchronous, while fsync() allows to accumulate many writes and synchronize them at once;
it is possible to make certain inodes to be synchronous by default by setting the "sync" inode flag; in a shell, the chattr +s command may be used; in c programs, use the fs_ioc_setflags ioctl command; note, the mkfs.ubifs tool checks for the "sync" flag in the original fs tree, so the synchronous files in the original fs tree will be synchronous in the resulting ubifs image.
let us stress that the above items are true for any linux file system, including jffs2.
fsync() may be called for directories - it synchronizes the directory inode meta-data. the "sync" flag may also be set for directories to make the directory inode synchronous. but the flag is inherited, which means all new children of this directory will also have this flag. new files and sub-directories of this directory will also be synchronous, and their children, and so forth. this feature is very useful if one needs to create a whole sub-tree of synchronous files and directories, or to make all new children of some directory to be synchronous by default (e.g., /etc).
the fdatasync() call for directories is "no-op" in ubifs and all ubifs operations which change directory entries are synchronous. however, you should not assume this for portability (e.g., this is not true for ext2). similarly, the "dirsync" inode flag has no effect in ubifs.
the functions mentioned above work on file-descriptors, not on streams (file *). to synchronize a stream, you should first get its file descriptor using the fileno() libc function, then flush the stream using fflush(), and then synchronize the file using fsync() or fdatasync(). you may use other synchronization methods, but remember to flush the stream before synchronizing the file. the fflush() function flushes the libc-level buffers, while sync(), fsync(), etc flush kernel-level buffers.
please, refer this faq entry for information about how to atomically update the contents of a file. also, the theodore tso's article is a good reading.
write-back knobs in linux
linux has several knobs in "/proc/sys/vm" which you may use to tune write-back. the knobs are global, so they affect all file-systems. please, refer the "documentation/sysctl/vm.txt" file fore more information. the file may be found in the linux kernel source tree. below are interesting knobs described in ubifs context and in a simplified form.
dirty_writeback_centisecs - how often the linux periodic write-back thread wakes up and writes out dirty data. this is a mechanism which makes sure all dirty data hits the media at some point.
dirty_expire_centisecs - dirty data expire period. this is maximum time data may stay dirty. after this period of time it will be written back by the linux periodic write-back thread. iow, the periodic write-back thread wakes up every "dirty_writeback_centisecs" centi-seconds and synchronizes data which was dirtied "dirty_expire_centisecs" centi-seconds ago.
dirty_background_ratio - maximum amount of dirty data in percent of total memory. when the amount of dirty data becomes larger, the periodic write-back thread starts synchronizing it until it becomes smaller. even non-expired data will be synchronized. this may be used to set a "soft" limit for the amount of dirty data in the system.
dirty_ratio - maximum amount of dirty data at which writers will first synchronize the existing dirty data before adding more. iow, this is a "hard" limit of the amount of dirty data in the system.
note, ubifs additionally has small write-buffers which are synchronized every 3-5 seconds. this means that most of the dirty data are delayed by dirty_expire_centisecs centi-seconds, but the last few kib are additionally delayed by 3-5 seconds.
ubifs write-buffer
ubifs is asynchronous file-system (read this section for more information). as other linux file-system, it utilizes the page cache. the page cache is a generic linux memory-management mechanism. it may be very large and cache a lot of data. when you write to a file, the data are written to the page cache, marked as dirty, and the write returns (unless the file is synchronous). later the data are written-back.
write-buffer is an additional ubifs buffer, which is implemented inside ubifs, and it sits between the page cache and the flash. this means that write-back actually writes to the write-buffer, not directly to the flash.
the write-buffer is designated to speed-up ubifs on nand flashes. nand flashes consist of nand pages, which are usually 512, 2kib or 4kib in size. nand page is the minimal read/write unit of nand flash (see this section).
write-buffer size is equivalent to nand page size (so it is tiny comparing to the page cache). it's purpose is to accumulate small writes, and write full nand pages instead of partially filled. indeed, imagine we have to write 4 512-byte nodes with half a second interval, and nand page size is 2kib. without write-buffer we would have to write 4 nand pages and waste 6kib of flash space, while write-buffer allows us to write only once and waste nothing. this means we write less, we create less dirty space so ubifs garbage collector will have to do less work, we save power.
well, the example shows an ideal situation, and even with the write-buffer we may waste space, for example in case of synchronous i/o, or if the data arrives with long time intervals. this is because the write-buffer has an associated timer, which flushes it every 3-5 seconds, even if it isn't full. we do this for data integrity reasons.
of course, when ubifs has to write a lot of data, it does not use write buffer. only the last part of the data which is smaller than the nand page ends up in the write-buffer and waits more for data, until it is flushed by the timer.
the write-buffer implementation is a little more complex, and we actually have several of them - one for each journal head. but this does not change the basic idea behind the write-buffer.
few notes with regards to synchronization:
"sync()" also synchronizes all write-buffers;
"fsync(fd)" also synchronizes all write-buffers which contain pieces of "fd";
synchronous files, as well as files opened with "o_sync", bypass write-buffers, so the i/o is indeed synchronous for this files;
write-buffers are also bypassed if the file-system is mounted with the "-o sync" mount option.
take into account that write-buffers delay the data synchronization timeout defined by "dirty_expire_centisecs" (see here) by 3-5 seconds. however, since write-buffers are small, only few data are delayed.
ubifs in synchronous mode vs jffs2
when ubifs is mounted in synchronous mode (-o sync mount options) - all file system operations become synchronous. this means that all data are written to flash before the file-system operations return.
for example, if you write 10mib of data to a file f.dat using the write() call, and ubifs is in synchronous mode, then ubifs guarantees that all 10mib of data and the meta-data (file size and date changes) will reach the flash media before write() returns. and if a power cut happens after the write() call returns, the file will contain the written data.
the same is true for situations when f.dat has was opened with o_sync or has the sync flag (see man 2 chattr).
it is well-known that the jffs2 file-system is synchronous (except a small write-buffer). however, ubifs in synchronous mode is not the same as jffs2 and provides somewhat less guarantees that jffs2 does with respect to sudden power cuts.
in jffs2 all the meta-data (like inode atime/mtime/ctime, inode size, uid/gid, etc) are stored in the data node headers. data nodes carry 4kib of (compressed) data. this means that the meta-data information is duplicated in many places, but this also means that every time jffs2 writes a data node to the flash media, it updates inode size as well. so when jffs2 mounts it scans the flash media, finds the latest data node, and fetches the inode size from there.
in practice this means that jffs2 will write these 10mib of data sequentially, from the beginning to the end. and if you have a power cut, you will just lose some amount of data at the end of the inode. for example, if jffs2 starts writing those 10mib of data, write 5mib, and a power cut happens, you will end up with a 5mib f.dat file. you lose only the last 5mib.
things are a little bit more complex in case of ubifs, where data are stored in data nodes and meta-data are stored in (separate) inode nodes. the meta-data are not duplicated in each data node, like in jffs2. ubifs never writes data nodes beyond the on-flash inode size. if it has to write a data node and the data node is beyond the on-flash inode size (the in-memory inode has up-to-data size, but it is dirty and was not flushed yet), then ubifs first writes the inode to the media, and then it starts writing the data. and if you have an interrupt, you lose data nodes and you have holes (or old data nodes, if you are overwriting). lets consider an example.
user creates an empty file f.dat. the file is synchronous, or ubifs is mounted in synchronous mode. user calls the write() function with a 10mib buffer.
the kernel first copies all 10mib of the data to the page cache. inode size is changed to 10mib as well and the inode is marked as dirty. nothing has been written to the flash media so far. if a power cut happens at this point, the user will end up with an empty f.dat file.
ubifs sees that the i/o has to be synchronous, and starts synchronizing the inode. first of all, it writes the inode node to the flash media. if a power cut happens at this moment, the user will end up with a 10mib file which contains no data (hole), and if he read this file, he will get 10mib of zeroes.
ubifs starts writing the data. if a power cut happens at this point, the user will end up with a 10mib file containing a hole at the end.
note, if the i/o was not synchronous, ubifs would skip the last step and would just return. and the actual write-back would then happen in back-ground. but power cuts during write-back could anyway lead to files with holes at the end.
thus, synchronous i/o in ubifs provides less guarantees than jffs2 i/o - ubifs has an effect of holes at the end of files. in ideal world applications should not assume anything about the contents of files which were not synchronized before a power-cut has happened. and "mainstream" file-systems like ext3 do not provide jfss2-like guarantees.
however, ubifs is sometimes used as a jffs2 replacement and people may want it to behave the same way as jffs2 if it is mounted synchronously. this is doable, but needs some non-trivial development, so this was not implemented so far. on the other hand, there was no strong demand. you may implement this as an exercise, or you may try to convince ubifs authors to do this.
synchronization exceptions for buggy applications
as this section describes, ubifs is an asynchronous file-system, and applications should synchronize their files whenever it is required. the same applies to most linux file-systems, e.g. xfs.
however, many applications ignore this and do not synchronize files properly. and there was a huge war between user-space and kernel developers related to ext4 delayed allocation feature. please, see the theodore tso's blog post. more information may be found in this lwn article.
in short, the flame war was about 2 cases. the first case was about the atomic re-name, where many user-space programs did not synchronize the copy before re-naming it. the second case was about applications which truncate files, then change them. there was no final agreement, but the "we cannot ignore the real world" argument found ext4 developers' understanding, and there were 2 ext4 changes which help both problems.
roughly speaking, the first change made ext4 synchronize files on close if they were previously truncated. this was a hack from file-system point of view, but it "fixed" applications which truncate files, write new contents, and close the files without synchronizing them.
the second change made ext4 synchronize the renamed file.
well, this is not exactly correct description, because ext4 does not write the files synchronously, but actually initiates asynchronous write-out of the files, so the performance hit is not very high. for the truncation case this means that the file is synchronized soon after it is closed. for the re-name case this means that ext4 writes data before it writes the re-name meta-data.
however, the application writers should never rely on these things, because this is not portable. instead, they should properly synchronize files. the ext4 fixes were because there were many broken user-space applications in the wild already.
we have plans to implement these features in ubifs, but this has not been done yet. the problem is that ubi/mtd are fully synchronous and we cannot initiate asynchronous write-out, so we'd have to synchronously write files on close/rename, which is slow. so implementing these features would require implementing asynchronous i/o in ubi, which is a big job. but feel free to do this :-).