xv6, line by line
user/rm.c

user/rm.c

C · 23 lines · annotated 100% · user program / library · upstream

About this file

rm name ... removes each name from its directory with the unlink system call (sys_unlink). Removing a name is not quite the same as deleting a file. A file can have several names (hard links, made by user/ln.c); unlink removes one of them and decrements the inode’s link count (nlink). The file’s blocks are freed only when no name is left and no process has it open: iput checks both when the last reference is dropped.

xv6’s rm also removes directories, as long as they are empty (Unix rm refuses unless given -r or -d; there is also a separate rmdir). It cannot remove . or ...

Read before: user/mkdir.c, which has the same structure. Read next: user/ln.c.

5int
6main(int argc, char *argv[])
7{
8 int i;
10 if (argc < 2) {
11 fprintf(2, "Usage: rm files...\n");
12 exit(1);
13 }
15 for (i = 1; i < argc; i++) {
16 if (unlink(argv[i]) < 0) {
17 fprintf(2, "rm: %s failed to delete\n", argv[i]);
18 break;
19 }
20 }
22 exit(0);