Why is the data not dumped to the file when exiting the process?

int main(int argc, char *argv[]) { FILE *fp = fopen("a.txt", "wt"); fprintf(fp, "AAAA"); // No flush. and No close raise(SIGTERM); exit(EXIT_SUCCESS); } 

result: No data has written to a.txt

I expected that everything will be fine. Because the system will close the file descriptor, then the file system driver will clear the unrelated data in its Close method. But this is not so. I tested this code on EXT4, ubuntu 11.10

Question: I thought that all file systems should hide non-solid data during its closed processing.
Does Posix have no rule?

PS This code worked well (well cleaned) on NTFS, Win7

 int _tmain(int argc, _TCHAR* argv[]) { HANDLE h = CreateFile(L"D:\\a.txt", GENERIC_READ|GENERIC_WRITE, 0, 0, OPEN_ALWAYS, 0, 0); BYTE a[3]; memset(a, 'A', 3); DWORD dw; WriteFile(h, (PVOID)a, 3, &dw, 0); TerminateProcess(GetCurrentProcess(), 1); return 0; } 

Edit:
I checked it again with the write system call. And he blushed well.

 int main(int argc, char** argv) { int fd = open("a.txt", O_CREAT|O_TRUNC|O_WRONLY); char buf[3]; memset(buf, 'A', 3); size_t result = write(fd, buf, 3); raise(SIGTERM); exit(EXIT_SUCCESS); return 0; } 
+6
source share
2 answers

It has nothing to do with file system drivers. The problem is that CRT buffers the file stream itself. You set the buffer size with setvbuf (), it uses the default value if you do not use this function. Where you use WriteFile (), there is no buffering in the application; the output is buffered in the file system cache of the operating system. Immunity to sudden interruptions to the application.

You will need to call fflush () to achieve the same.

+5
source

This has nothing to do with the file system; rather, it is the behavior of the C implementation used, which determines when open threads are reset or not.

On POSIX, the default action for a SIGTERM signal is:

Abnormal completion of the process. The process ends with all the consequences of _exit () ...

_exit() equivalent to _exit() according to the C standard, and the choice of whether to set thread streams is not specified by the standard:

The functions _Exit () and _exit () must not call the functions registered with atexit () and any registered signal handlers. Whether open threads are open or closed, or temporary files are deleted - this is an implementation definition ...

Assuming you are using glibc on Linux, from the documentation (my attention):

When a process terminates for any reason - either because the program terminates or as a result of a signal - the following events occur:

  • All open file descriptors are closed in the process. See Low Level Input / Output. Note that threads are not automatically reset when the process terminates ; see I / O in streams.

I am not familiar with Windows' WriteFile and TerminateProcess , so I cannot comment on what documented behavior is.

+7
source

Source: https://habr.com/ru/post/896468/


All Articles