Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to open files which are not properly closed?

What happens if I do not close a file after writing to it?

Let us assume we got an too many open files error and due to that the program crashes.

Does the OS handle that for me? And if this damages the not-closed files, how do I notice that they are damaged?

like image 605
Michael Dorner Avatar asked Aug 18 '17 17:08

Michael Dorner


People also ask

What will happen if you dont close an open file?

As long as your program is running, if you keep opening files without closing them, the most likely result is that you will run out of file descriptors/handles available for your process, and attempting to open more files will fail eventually.

When we close the file using fclose () Buffer still remains in memory?

Closing a File The fclose(-) function returns zero on success, or EOF if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file.


2 Answers

From exit()

_exit() does close open file descriptors, and this may cause an unknown delay, waiting for pending output to finish.

Each return hides a system call to exit, so any unclosed descriptor is closed by the OS.

like image 74
Tony Tannous Avatar answered Oct 27 '22 07:10

Tony Tannous


Generally speaking, if you write to a file, then your application crashes, the operating system will flush the buffers to the disk and clean up for you. The same will occur if your program exits without explicitly closing the files. This does not damage files.

The bad situation is when you write to a file and someone pulls the plug out on the computer.

like image 2
user3344003 Avatar answered Oct 27 '22 07:10

user3344003