linux - 当进程终止时内核是否删除打开的文件

标签 linux file-io process

我正在使用 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/

相关文章:

unix - 获取脚本的调用者姓名

linux - PDOException SQLSTATE [HY000] : General error: 2006 MySQL server has gone away

matlab - 我如何解析这个以分号分隔的文件?

c++ - 读取文件并保存完全相同的文件c++

process - 阻塞等待和忙等待有什么区别?

ruby-on-rails - 如果我使用 w.keepalive,God Gem 会开始监视,但如果我使用 $god sidekiq start 则不会

c - 如何获取以太网设备列表

regex - sed 正则表达式地址范围

linux - 什么是零信号?

file-io - 创建用于测试文件访问的大型 csv 文件