ãã¡ã¤ã«ã«æ¸ããã¿ãè¡ã£ããããªãã fsync ããã
é常ããªãã®èããç¡ãã«ããã°ã©ã ããã¡ã¤ã«ã«æ¸ããã¿ãè¡ã£ãå¾ãéæªãã·ã¹ãã ãã¯ã©ãã·ã¥ããã¨ãã¡ã¤ã«ã失ãããå¯è½æ§ããããé常ã®ãã¡ã¤ã«æ¸ãè¾¼ã¿ã¯ãã¡ã¤ã«ã«æ¸ãè¾¼ãã§ããããã«è¦ãã¦å®ã¯ãããã¡ãã¡ã¢ãªä¸ã«èãã¦ããã ãã ããã ããã®ã¡ã¢ãªä¸ã«èããããããããã¹ãã¬ã¼ã¸ã«æ¸ãè¾¼ããã¼ã¿ã®ãã¨ããã¼ãã£ãã¼ã¸ã¨è¨ããä½ãããªãã¦ããã¼ãã£ãã¼ã¸ã«æ¸ããã¾ãããã¼ã¿ã¯ã«ã¼ãã«ãå®æçã«ã¹ãã¬ã¼ã¸ã«æ¸ãè¾¼ãã®ã ããè¥å¹²ã®ã¿ã¤ã ã©ã°ãããããã®éã«ã¯ã©ãã·ã¥ããã¨ãã¼ã¿ã失ãããããã ããã¼ã¿ãæ¸ãè¾¼ãã ç´å¾ãããã¹ãã¬ã¼ã¸ã«æ¸ãåºãããå ´å㯠fsync ã·ã¹ãã ã³ã¼ã«ãå¼ã¶å¿ è¦ãããã
C ã C++ ã¨ãã£ãä½ã¬ã¤ã¤ã¼ãæ±ãè¨èªãªã fsync ãå¼ã¶ã ãã§è¯ãããJava ã®ãããªé«ç´è¨èªã§ã©ããã£ã¦ fsync ãçºåãããã°ãããã
é常ã®ãã¡ã¤ã«æ¸ãè¾¼ã¿
ä¸è¨ã®ãããªä¸è¬çãªãã¡ã¤ã«æ¸ãè¾¼ã¿ãã¸ãã¯ãå®è¡ããéã«å¼ã°ããã·ã¹ãã ã³ã¼ã«ãè¦ã¦ã¿ããã
public class SyncTest { public static void main(String[] args) throws IOException { File file = new File("/tmp/hello"); FileOutputStream output = new FileOutputStream(file); output.write("Hello, World!\n".getBytes("UTF-8")); output.close(); } }
ã·ã¹ãã ã³ã¼ã«ãè¦ãã«ã¯ strace ã使ãã
$ strace -f java SyncTest ... 18598 open("/tmp/hello", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 10 18598 fstat(10, {st_mode=S_IFREG|0664, st_size=0, ...}) = 0 18598 fcntl(10, F_GETFD) = 0 18598 fcntl(10, F_SETFD, FD_CLOEXEC) = 0 18598 write(10, "Hello, World!\n", 14) = 14 18598 close(10) ...
"Hello, World!\n" ã¨ããæååã write ã·ã¹ãã ã³ã¼ã«ã§æ¸ãè¾¼ãã å¾ãã¯ãã¼ãºãã¦ãããã¡ãªã¿ã« 10 ã¨ããå¤ã¯ãã¡ã¤ã«ãã£ã¹ã¯ãªãã¿ã
ãã¡ã¤ã«æ¸ãè¾¼ã¿å¾ã« fsync
ãã¦ãstrace ã®ãããã§æ´ã㦠fsync ãçºè¡ããã¦ãªããã¨ãå¤æããã
fsync ãçºè¡ããã«ã¯ãFileOutputStream#getFD ã§åå¾ã§ãããã¡ã¤ã«ãã£ã¹ã¯ãªãã¿ãªãã¸ã§ã¯ãã® sync ã¡ã½ãããå¼ã³åºãã°è¯ãã
public class SyncTest { public static void main(String[] args) throws IOException { File file = new File("/tmp/hello"); FileOutputStream output = new FileOutputStream(file); output.write("Hello, World!\n".getBytes("UTF-8")); output.getFD().sync(); // ãã®è¡ã追å output.close(); } }
ä¸è¨ã³ã¼ããå®è¡ãã¦ã·ã¹ãã ã³ã¼ã«ãç£è¦ãããã¨ã»ã»ã»
$ strace -f java SyncTest ... 19751 open("/tmp/hello", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 10 19751 fstat(10, {st_mode=S_IFREG|0664, st_size=0, ...}) = 0 19751 fcntl(10, F_GETFD) = 0 19751 fcntl(10, F_SETFD, FD_CLOEXEC) = 0 19751 write(10, "Hello, World!\n", 14) = 14 19751 fsync(10) = 0 <- fsync ãå¼ã°ãã¦ãã 19751 close(10) = 0 ...
ç¡äº fsync ãå¼ã°ãã¦ãããããã§ãã¹ãã¬ã¼ã¸ã«æ¸ãè¾¼ã¾ãããã¨ãä¿è¨¼ãããã以åããå®å ¨ã§ãé害ã«å¼·ãããã°ã©ã ã«ãªã£ãã
ã¾ã¨ã
ä½ãç´ãããã¼ã¿ãä¸æçãªãã¼ã¿ã¯ããã¾ã§ãã£ã¡ããããªãã¦ãè¯ããããããªãããããã§ã¯ãªããã¼ã¿ãæ¸ãè¾¼ãã æã¯ã§ããã ã fsync ããããå¿ããããã
æ¯å finally æ§æ㧠fsync çºè¡ããã®ã¯è¨è¿°ãå¿ããèµ·ããã®ã§ãã¦ã¼ãã£ãªãã£åã㦠flush, sync, close ããã£ã¦ããããããªå½¢ã«ãã¦ãããã»ããè¯ãã ããã