我正在使用 tmpnam() 在进程 1 中生成临时文件名。 打开该文件并将文件名发送到另一个进程 2. 另一个进程 2 打开并写入该文件。
但是,我只是想知道如果我的进程 1 终止,该文件是否会被操作系统删除。看起来这件事并没有发生。在这种情况下,我有哪些选择,以便在进程 1 终止后我不会有文件残留。
最佳答案
不,当您的进程终止时,内核不会删除打开的文件。
但是,您可以在进程终止之前删除打开的文件,并且只要您保持打开状态,该文件仍然会存在。但是,您将无法再按名称打开文件 - 任何进一步的访问都只能通过打开的文件句柄进行。
例如
fname="/tmp/tempfilename";
fd=open(fname,O_RDWR);
unlink(fname);
/* fd is still a valid handle that can be written to, read from,
lseeked on, or passed to a child process. It will go away
when the process exits.
*/
/* Important note: if you create a temp file like this on a
NFS filesystem, there will be a phantom file named something like
.nfsfile12983719
that will stick around until the file descriptor is closed.
If you delete this file, it will be re-created.
*/
或者,您可以使用 tmpfile(3)
,它的作用大致相同,除了它
返回 FILE *
而不是 fd。
关于linux - 当进程终止时内核是否删除打开的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15167793/