fsync() — Write changes to direct-access storage

Standards

Standards / Extensions C or C++ Dependencies

POSIX.1
XPG4
XPG4.2
Single UNIX Specification, Version 3

both  

Format

#define _POSIX1_SOURCE 2
#include <unistd.h>

int fsync(int fildes);

General description

Transfers all data for the file indicated by the open file descriptor fildes to the storage device associated with fildes. fsync() does not return until the transfer has completed, or until an error is detected.

Returned value

If successful, fsync() returns 0.

If unsuccessful, fsync() returns -1 and sets errno to one of the following values:
Error Code
Description
EBADF
fildes is not a valid open file descriptor.
EINVAL
The file is not a regular file.

Example

CELEBF48
⁄* CELEBF48 *⁄
#define _POSIX_SOURCE
#include <fcntl.h>
#include <sys⁄stat.h>
#include <sys⁄types.h>
#include <unistd.h>
#undef _POSIX_SOURCE
#include <stdio.h>
#include <stdlib.h>

#define mega_string_len 250000

main() {
  char *mega_string;
  int  fd, ret;
  char fn[]="fsync.file";

  if ((mega_string = (char*) malloc(mega_string_len)) == NULL)
    perror("malloc() error");
  else if ((fd = creat(fn, S_IWUSR)) < 0)
    perror("creat() error");
  else {
    memset(mega_string, 's', mega_string_len);
    if ((ret = write(fd, mega_string, mega_string_len)) == -1)
      perror("write() error");
    else {
      printf("write() wrote %d bytes\n", ret);
      if (fsync(fd) != 0)
        perror("fsync() error");
      else if ((ret = write(fd, mega_string, mega_string_len)) == -1)
        perror("write() error");
      else
        printf("write() wrote %d bytes\n", ret);
    }
    close(fd);
    unlink(fn);
  }
}
Output
write() wrote 250000 bytes
write() wrote 250000 bytes

Related information