Why do some symbolic links affect program behavior

executablefilenamessymlink

One thing that has been puzzling me for some time is this:

% which halt
/sbin/halt
% file /sbin/halt
/sbin/halt: symbolic link to `reboot'

However, executing sudo halt does, of course, not reboot the system. Why is that?

There are several other programs working that way, for example pdflatex.

Best Answer

Every program can see the full command line that was used to run it (except for wildcards and variables, which the shell expands).

In a C program, the command line is stored in argv, which is short for argument vector.
The progam's name is the first element of argv, i.e. argv[0].

Clearly in the case of halt and reboot, the program is changing its behavior based on argv[0].

From bash, you can see the full command line used to run a program using ps -p <pid> -o cmd or cat /proc/<pid>/cmdline.

Note that there is another type of link called a hard link that will have the same effect. On my system for example, sudo and sudoedit are the same file with two different names, and different behaviors.

ls -i can help you find those commands, e.g.:

$ ls -il | awk '$3 != 1 { print }'
total 156872
2491111 -rwsr-xr-x 2 root   root     127560 2011-01-20 05:03 sudo
2491111 -rwsr-xr-x 2 root   root     127560 2011-01-20 05:03 sudoedit

See man ln for more details about hard links if you're not familiar with them.

Related Question