Pages

Wednesday, 2 October 2019

Why is "rmdir" needed?

It's well known that in Unix, everything is a file. Of course, a directory/folder is a file too.

So deleting a directory is the same as deleting a file. But both the system call and command tools have separated calls/tools to do that.

On the system call level, we have "unlink()" to delete a file while "rmdir()" is used to delete a directory. Regarding tools, "rm" and "rmdir" co-exist for a long time.

Except for the ROOT directory, every file/directory has a parent directory. To delete a file/directory is actually to remove the entry inside its parent directory.

Whether or not you can delete a file/directory is NOT determined by the permission you have to the file/dir itself but by the permission to its parent directory. That means you can delete a file to which you don't have any permission.

What happens when deleting a file?

Actually, two main operations have to be done when deleting a file.

  • update the inode info
  • modify the data of its parent directory
The first operation let the FS know the file is deleted, while the second one makes the deleted file unsearchable.

What should happen when deleting a non-empty directory?

We may have two choices.

(1) just as deleting a file

This will cause the files inside to become orphaned. As their inodes don't get updated, they still occupy disk space while not searchable/visible. So this option is not good.

(2) recursively deleting every file/subdir inside

Sure it will work well. But this makes the syscall not simple and seems more like a policy rather than a mechanism, which is against the UNIX philosophy.


For command-line tools, "rm -r" just do what we want to do.
For system programming, you have to implement the policy by yourself.



No comments:

Post a Comment