Contents of argv[0]

Juergen Wagner gandalf at csli.Stanford.EDU
Mon Aug 21 16:01:40 AEST 1989


In some article I wrote a long time ago:
> This effectively means that in general, argv[0] cannot
> be treated as a reliable source for the path name! [RTFM]

Referring to this, gisle at ifi.uio.no (Gisle Hannemyr) wrote:
>Is there anything that can be relied upon for this?

In a response, henry at utzoo.uucp (Henry Spencer) writes:
>No.

There are partial solutions to the problem, which are too complex for most
cases. In most cases, the simplest thing to do is to rely on the fact that
certain conventions are observed, and depending on the environment, the
path name can be obtained in one of several ways:

[1] Directly from argv[0] (which could be the correct path name).

[2] From argv[0] and getenv("PATH") by simulating the shell's interpretation
    of the search path.

[3] In an operating system dependent way. E.g. by examining the inode
    associated with the text segment of the current process, ... Maybe
    it is would be a good idea to associate with each process a description
    of the file the executable image came from... This shouldn't be too
    difficult, in fact, in most cases, one could do something like that
    by modifying the exec*() routines in the C library such that they
    record their first argument in an environment variable "EXEC_PATH"
    which is passed to the new process.

Usually, [1] and [2] cover the cases one is interested in. Other pathological
cases might be very interesting but not necessarily important.

Happy hacking,
Juergen Wagner		   			gandalf at csli.stanford.edu
						 wagner at arisia.xerox.com

PS: Also note that the most famous example of argv[0] not being the program
    name is the way 'login' calls login shells as "-sh" or "-csh"...

PPS: It is important to hang on to the idea of conventions (same theme can
     be found in that ongoing discussion about main() or not main()). They
     can make like much easier (and reduce our problem to cases [1] and [2]).



More information about the Comp.lang.c mailing list