当某个进程打开文件时,unlink() 会做什么?

When some process has a file open, what will unlink() do?

来自 APUE

#include <unistd.h>
int unlink(const char *pathname);

Only when the link count reaches 0 can the contents of the file be deleted. One other condition prevents the contents of a file from being deleted: as long as some process has the file open, its contents will not be deleted. When a file is closed, the kernel first checks the count of the number of processes that have the file open. If this count has reached 0, the kernel then checks the link count; if it is 0, the file’s contents are deleted.

  1. 如果进程中execve()正在使用一个文件,它是否将其计为"the process has the file open"?

  2. 如果某个进程有文件正在打开或execve()编辑,将unlink()立即return0或-1,或者等到进程关闭文件或 execve() 完成 运行 并执行其工作?

1) 进程通过 execve 继承的文件句柄将保持打开状态,直到明确关闭或进程退出。

2) unlink 不会阻塞。它将简单地删除路径并减少硬链接文件的引用计数,此时文件系统可以删除引用的文件并在文件不再被任何进程打开后释放与其关联的 space 。 unlink 将 return 0 除非出现 I/O 或权限错误等

对于 execve-d or mmap-ed, the kernel also considers that (inside the kernel) the file descriptor is used (so the kernel inode has a refcount which is positive). See also inode(7) and proc(5). Notice the ETXTBSY error code in errno(3). An executable could even remove itself during execution (see this and that) 的文件,文件的 inode 一直保留到进程终止或执行其他操作 execve.

因此不会释放文件等内部数据(直到 execvemmap 被禁用)