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)?
Best Answer
To begin with, note that
argv[0]
is not necessarily the program name. It is what the caller puts intoargv[0]
of theexecve
system call (e.g. see this question on Stack Overflow). (All other variants ofexec
are not system calls but interfaces toexecve
.)Suppose, for instance, the following (using
execl
):/var/tmp/mybackdoor
is what is executed butargv[0]
is set totop
, and this is whatps
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?