[vox-tech] Identifying the directory that contains the currently running executable?

Ken Herron kherron+lugod at fmailbox.com
Fri Aug 27 12:12:29 PDT 2004


--On Friday, August 27, 2004 11:36:50 AM -0700 Bill Kendrick 
<nbs at sonic.net> wrote:

>> The program can examine argv[0], but
>> that may contain only the program name without the directory path, in
>> which case you would generally read the PATH environment variable and
>> look for the program in each directory listed. It's also possible for
>> argv[0] to contain an irrelevant or misleading string, so you
>> shouldn't  depend on it if security is an issue.
>
> Such as an alias, for example?  (I suppose I could try testing...)

The system call to execute a new program is called execve(). The shell, 
the perl exec command, the other libc exec* functions, etc. all end up 
calling execve() at some point.

Execve() takes three arguments:

1) The name of the program to execute.

2) An array of argument strings. These become the argv array for the new 
process.

3) An array of environment strings. These become the new process's 
environment.

When you call execve() yourself, e.g. from inside a C program, you can 
put anything you want in the argument and environment arrays. The kernel 
doesn't care if the name of the program to execute matches the first 
entry in the argument array. It doesn't care where the strings in the 
environment array came from.

All that stuff about argv[0] being the name of the process, and processes 
inheriting their environment from their parent process? It's all just 
convention. Shells follow these rules when they start subprocesses, so 
users and programs come to expect these rules, so other programs that 
start subprocesses follow the same rules unless there's a good reason not 
to.


-- 
Ken Herron


More information about the vox-tech mailing list