On a Unix-like system, a directory entry is a name that refers to an inode. Calling unlink() removes that name, but the kernel keeps the inode and its data alive while a process still has an open file descriptor for it. The storage is reclaimed only after the link count is zero and the final open reference has been closed.
This behavior is useful for temporary files that should disappear automatically when a process exits. It does not provide security: another process with sufficient permissions may still inspect or duplicate the descriptor, particularly through /proc/<pid>/fd on Linux.
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(void)
{
const char *path = "temporary-data.txt";
const char content[] = "still available\n";
struct stat info;
int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0600);
if (fd == -1) {
perror("open");
return EXIT_FAILURE;
}
ssize_t written = write(fd, content, sizeof(content) - 1);
if (written != (ssize_t)(sizeof(content) - 1)) {
if (written == -1) {
perror("write");
} else {
fprintf(stderr, "short write\n");
}
close(fd);
return EXIT_FAILURE;
}
if (unlink(path) == -1) {
perror("unlink");
close(fd);
return EXIT_FAILURE;
}
setvbuf(stdout, NULL, _IOLBF, 0);
printf("%s has been unlinked; descriptor %d remains open.\n", path, fd);
for (;;) {
if (fstat(fd, &info) == -1) {
perror("fstat");
break;
}
printf(
"links=%ju, size=%jd bytes\n",
(uintmax_t)info.st_nlink,
(intmax_t)info.st_size
);
sleep(1);
}
close(fd);
return EXIT_FAILURE;
} Compile and run it in a temporary directory:
cc -std=c11 -Wall -Wextra -pedantic unlinked-file.c -o unlinked-file
./unlinked-file The pathname disappears immediately, while the process keeps reporting output similar to links=0, size=16 bytes. The zero link count confirms that no directory entry names the inode. Pressing Ctrl+C terminates the process; the operating system closes the descriptor and can then reclaim the storage.
Recovering or Inspecting the Open File on Linux
Linux exposes a process's descriptors as symbolic links. With the process ID and descriptor number printed by the program, the data can be inspected or copied before the process exits:
cat /proc/<pid>/fd/<fd>
cp /proc/<pid>/fd/<fd> recovered-data.txt This is why unlinking an open file should be understood as controlling its lifetime and namespace entry, not as securely hiding or erasing it. For production temporary files, create a unique file safely with mkstemp(), unlink it immediately, and retain only the returned descriptor.