xv6, line by line
user/ln.c

user/ln.c

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

About this file

ln old new gives an existing file a second name: after ln a b, a and b are two hard links to the same inode, with the same contents and the same inode number (third column of ls). Neither is the original; rm a leaves the file reachable as b.

The work is one system call, link (sys_link). The kernel increments the inode’s link count (nlink) and adds a directory entry new pointing at the inode’s number, inside one transaction. It refuses if old does not exist, if old is a directory (a second name for a directory could make a cycle in the tree), if new already exists, if new’s parent directory does not exist, or if the link count is at its maximum.

xv6 has no symbolic links, so there is no -s option.

Read before: user/rm.c. Read next: kernel/sysfile.c (sys_link).

5int
6main(int argc, char *argv[])
7{
8 if (argc != 3) {
9 fprintf(2, "Usage: ln old new\n");
10 exit(1);
11 }
12 if (link(argv[1], argv[2]) < 0)
13 fprintf(2, "link %s %s: failed\n", argv[1], argv[2]);
14 exit(0);