Typical Unix/Linux programs accept the command line inputs as an argument count (int argc) and an argument vector (char *argv[]). The first element of argv is the program name - followed by the actual arguments. Why is the program name passed to the executable as an argument? Are there any examples of programs using their own name (maybe some kind of exec situation)?
Why does argv include the program name?
command line;c;arguments
To begin with, note that argv[0] is not necessarily the program name. It is what the caller puts into argv[0] of the execve system call (e.g. see this question on Stack Overflow). (All other variants of exec are not system calls but interfaces to execve.)Suppose, for instance, the following (using execl):execl(/var/tmp/mybackdoor, top, NULL);/var/tmp/mybackdoor is what is executed but argv[0] is set to top, and this is what ps or (the real) top would display. See this answer on U&L SE for more on this.Setting all of this aside: Before the advent of fancy filesystems like /proc, argv[0] was the only way for a process to learn about its own name. What would that be good for?Several programs customize their behavior depending on the name by which they were called (usually by symbolic or hard links, for example BusyBox's utilities; several more examples are provided in other answers to this question).Moreover, services, daemons and other programs that log through syslog often prepend their name to the log entries; without this, event tracking would become next to infeasible.