You can use POSIX (Portable Operating System Interface) standard file operation functions to create secure temporary files:
- Use open () to create a temporary file.
- Call unlink () to delete the file immediately. The temporary file will be removed from the current directory. However, inode will wait until all opened file descriptors are closed (reference count = 0) is deleted. Previously, it became an orphan (orphan inode) and the file cannot be viewed using ls or du. However, you can still know the existence of the file by running DF on the file system.
- Call close () to close the file after use, so that the file will completely disappear in the file system.
Temporary files created in this way have the following security:
- If the program crashes, the operating system will close all files opened by the program. The temporary file will disappear when it is closed, and will not remain in the file system.
- Users cannot access this file, so they cannot monitor and filter the content.
Of course, there are other methods: encryption, multiple overwriting of the file storage area to prevent data recovery, and so on. Alternatively, you can combine multiple methods to meet high security requirements.
Sample Code unlink_before_close.c
Compile and execute:
$ Gcc-O unlink_before_close unlink_before_close.c $./unlink_before_close