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 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ cat test.txt
twice as instructed.You should find that
hoge
on the first attempt, andhoge
norfuga
) on the second attempt.In this code
fopen(3)
is called withw
option. This calls syscallopen(2)
withO_TRUNC
set. On Linux,open(2)
callsdo_truncate
, as a result of callingdo_sys_open
,do_filp_open
,path_openat
,do_last
, andhandle_truncate
. Sincedo_truncate
instantly updates inode upon call, the target file becomes empty immediately. Changes made byfprintf(3)
in this code would not be flushed untilfclose(3)
called.