Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we double state the executable name in `execlp`?

Tags:

c

exec

To run a command with execlp we do

execlp("ps", "ps", NULL);

A redundancy can be seen here, since we pass ps twice. This behavior is consistent across all exec variants.

Why does exec want such redundancy? Why isn't it written so that we can simply

execlp("ps", NULL);
like image 726
marmistrz Avatar asked Oct 29 '25 07:10

marmistrz


1 Answers

Other answers have explained that you may provide a different argv[0] than the name of the program, but haven't explained why you might want to do this.

Some programs behave differently depending on the name that's used to invoke them. A common example is shells, e.g. sh, bash, and csh. They check the first character of argv[0], and if this is - they operate as a login shell rather than a regular shell. So when /bin/login is invoking the user's login shell, it does something like:

execlp("/bin/bash", "-bash", (char*)NULL);

This way, bash knows that it's being run as part of a login and can behave accordingly. This could have been done using an option parameter, but then every program that might be used as a login shell would have to recognize that option (some special usernames have login shells that aren't really shells, but are other programs, and requiring them to support the same option as real shells might be problematic).

like image 113
Barmar Avatar answered Oct 31 '25 21:10

Barmar