[Previous]
[Contents]
[Next]

fsync()

write to disk all currently queued data for a file

Synopsis:

#include <unistd.h>
int fsync( int fd );

Description:

The fsync() function writes to disk all the currently queued data for the open file specified by fd. All necessary file system information required to retrieve the data is also written to disk. The file access times are also updated.

The fsync() function is used when you wish to ensure that both the file data and file system information required to recover the complete file have been written to the disk.

The fsync() function doesn't return until the transfer is complete.

Returns:

0
Success
-1
An error occurred. errno is set to indicate the error. If the fsync() function fails, outstanding I/O operations aren't guaranteed to have been completed.

Errors:

EBADF
The fd argument isn't a valid file descriptor.
EINVAL
Synchronized I/O isn't supported for this file.
EIO
A physical I/O error occurred (for example, a bad block). The precise meaning is device-dependent.
ENOSYS
The fsync() function isn't supported.

Examples:

/*
 *    Write a file and make sure it's on disk.
 */
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

char buf[512];

void main()
{
    int fd;
    int i;

    if( ( fd = creat("fsync.demo", 0666) ) == -1 )
    {
      perror( "Error creating file" );
      exit( EXIT_FAILURE );
    }

    for( i = 0; i < 255; ++i )
    {
      memset( buf, i, sizeof( buf ) );
      if( write( fd, buf, sizeof(buf) ) != sizeof(buf) )
      {
          perror( "Error writing file" );
          exit( EXIT_FAILURE );
      }
    }

    if( fsync( fd ) == -1 )
    {
      perror( "Error sync'ing file" );
      exit( EXIT_FAILURE );
    }

    close( fd );
    exit( EXIT_SUCCESS );
}

Classification:

POSIX 1003.4

Safety:
Interrupt handler No
Signal handler Yes, but modifies errno
Thread Yes

See also:

errno, fdatasync(), fstat(), open(), stat(), write()


[Previous]
[Contents]
[Next]