Reputation: 61
I have written a program which opens a file and repeatedly creates a child process which prints the content of the file to the standard output. If I run this program on the background and alter the content of the file the new content will be printed. However if I remove the read permissions for the file or delete the file the program will not change its behaviour. I don't understand why this happens.
This is the code:
fd = open(argv[1], O_RDONLY);
if (fd == -1) {
perror("catloop: open");
return EXIT_FAILURE;
}
while (1) {
pid = fork();
if (pid == -1) {
perror("catloop: fork");
(void) close(fd);
return EXIT_FAILURE;
}
if (pid == 0) {
char c;
(void) lseek(fd, 0, SEEK_SET);
while (read(fd, &c, 1) == 1) {
write(STDOUT_FILENO, &c, 1);
}
(void) close(fd);
return EXIT_SUCCESS;
}
(void) waitpid(pid, NULL, 0);
sleep(1);
}
(void) close(fd);
Thank you
Upvotes: 0
Views: 82
Reputation: 6739
Assuming UNIX/Linux-like behavior:
The file permissions are only checked when the file is opened. Once you have the file open, it doesn't matter what the permissions are anymore.
The program can still read the file after you delete it because the file itself isn't removed if something has it open. When you do an rm
, that just removes the directory entry for the file. Normally, when the last hard link to a file is removed, the file data is also removed. However, if one or more processes have the file open, the file (i.e., the inode) remains and can still be accessed by those processes. Once the last process closes the file, the file is removed.
Upvotes: 1