Search code examples
clinuxfilehardlink

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


From 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. If a file is being used by execve() in a process, does it count it as "the process has the file open"?

  2. If some process has the file being open or execve()ed, will unlink() immediately return 0 or -1, or wait till the process closes the file or execve() finishes running and performs its job?


Solution

  • 1) The file handles inherited by processes via execve will remain open until explicitly closed or the process exits.

    2) unlink will not block. It will simply remove the path and decrement the reference count of the hard-linked file, at which point the filesystem may remove the referenced file and free the space associated with it once the file is no longer opened by any process. unlink will return 0 unless there was an I/O or permissions error, etc.