Created
January 29, 2019 12:32
-
-
Save makotom/02cc431bef274fad657907798a9595b3 to your computer and use it in GitHub Desktop.
Let's learn about open(2) (called by fopen(3))
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <unistd.h> | |
| #define TEST_TXT "test.txt" | |
| void phase1(void) { | |
| FILE * fp = fopen(TEST_TXT, "w"); | |
| fprintf(fp, "hoge\n"); | |
| fclose(fp); | |
| sleep(10); // During this, try `$ cat test.txt` | |
| } | |
| void phase2(void) { | |
| FILE * fp = fopen(TEST_TXT, "w"); | |
| fprintf(fp, "fuga\n"); | |
| sleep(10); // During this, try `$ cat test.txt` | |
| fclose(fp); | |
| } | |
| int main(void) { | |
| phase1(); | |
| phase2(); | |
| return 0; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ cat test.txttwice as instructed.You should find that
hogeon the first attempt, andhogenorfuga) on the second attempt.In this code
fopen(3)is called withwoption. This calls syscallopen(2)withO_TRUNCset. On Linux,open(2)callsdo_truncate, as a result of callingdo_sys_open,do_filp_open,path_openat,do_last, andhandle_truncate. Sincedo_truncateinstantly updates inode upon call, the target file becomes empty immediately. Changes made byfprintf(3)in this code would not be flushed untilfclose(3)called.