fsync is a POSIX 1003.1b-1993 standard function which flushes the write buffers associated with an open file descriptor (filehandle). This node describes primarily the fsync found in the GNU C library, glibc, but most of the information may be applicable to other C libraries as well.

fsync's prototype (found in unistd.h) is:

int fsync(int fildes)

where fildes is the file descriptor whose write buffers are to be flushed. fsync does not return until all data associated with the file is written to the appropriate device; when it does, it returns 0 on success, and returns -1 on error, as well as setting errno appropriately:

  1. EBADF - fildes is not a valid file descriptor.
  2. EINVAL - this function is unimplemented by the system.

Note that this function is a cancellation point for multi-threaded programs; protect calls to fsync with cancellation handlers if necessary.

When it is not necessary to flush metadata associated with the file descriptor in question (for instance if the file is of a fixed size), it is possible to use fdatasync instead of fsync, which may be faster; fdatasync will be emulated by a call to fsync if necessary. See also the function sync, which does the same thing except flushing write buffers for the whole system, rather than just one descriptor.

(Most information paraphrased from the GNU C Library Reference Manual, which is under the GNU Free Documentation License.)