30

I'm writing a backup script which

  1. Copies the data to backup disk.
  2. Flushes the backup disk.
  3. Performs a hash integrity check.

Before I used to do sleep(60) for waiting a minute so that data is automatically flushed by the kernel. Which I guess is overkill so now I'm trying sudo hdparm -F --verbose /dev/disk but it reports error - HDIO_DRIVE_CMD(flushcache) failed: Invalid exchange multiple times.

I'm wondering is there any standard way to flush the cache to hard disk. I think there is because usb-creator-gtk does it, umount does it.

I'm using Ubuntu x64 9.10

PS: I'm trying to avoid "sync" because this page says that it is not safe. http://ubuntuforums.org/showthread.php?t=589975

Vikrant Chaudhary
  • 11,089
  • 10
  • 53
  • 68
  • 7
    To be clear, it is the `echo 3 > /proc/sys/vm/drop_caches` command that he thought wasn't safe. He was wrong anyway. – Gabe Mar 05 '10 at 03:01

2 Answers2

44

Does sync suffice?

Edit: regarding your edit - you are trying to avoid sync because some guy on the internet put a CYA disclaimer on his post? Maybe there is something wrong with sync of which I am unaware but that might be worth a 2nd post in itself.

Still, from the linux info pages:

sync writes any data buffered in memory out to disk. This can include (but is not limited to) modified superblocks, modified inodes, and delayed reads and writes. This must be implemented by the kernel; The sync program does nothing but exercise the 'sync' system call.

Duck
  • 26,924
  • 5
  • 64
  • 92
  • 1
    On OSX fsync is not enough. You need to use fcntl with F_FULLFSYNC. I've been told by some people that fsync is also not enough on Linux but I'm not sure. Linux does not have F_FULLFSYNC. – Matthew Mitchell Nov 04 '12 at 17:27
  • Thanks, `sync` with `-f` argument to flush out specific filesystem was exactly what I needed for testing power loss resilience of a certain configuration. – Hi-Angel Jun 15 '21 at 12:51
5

You want fsync (man section 2) function call, but if you're doing this in a script, you'll probably want to use the sync command (man section 8), which just calls sync().

George
  • 2,034
  • 1
  • 15
  • 16
  • 8
    Actually the command line "sync"(section 8) calls system function "sync()"(section2), not system function "fsync(int fd)" (section 2). In one case, all files are synced, in the other just a particular file that is still open is synced. – Mark Lakata Feb 12 '13 at 18:45
  • which one is the one that syncs all files and which one is the one that only syncs some? If fsync you mention is the one that syncs all pending writes then how do we access it? Is there a command for fsync? – Neal May 05 '16 at 20:07