How to get the pathname of the current executable?

Blair P. Houghton bph at buengc.BU.EDU
Tue Feb 13 13:24:45 AEST 1990


In article <1990Feb7.211538.3894 at iwarp.intel.com> merlyn at iwarp.intel.com (Randal Schwartz) writes:
>In article <1610.25d028a3 at wums.wustl.edu>, bethge at wums writes:
>[wants to know how to find the name of the current executable]
>| Is there a better (more transparent) way?
>
>No.  This was hashed out about a year ago in either c.u.q or c.u.w.
>Basically, it boils down to the fact that you have no idea where you
>came from, and the closest you could come is to count on the shells to
>*mostly* give you the right answer *most* of the time in argv[0].
>However, programs that do execv() are free to provide *whatever* they
>want.  So, you're out of luck, and subject to spoofing.
>
>Just another UNIX hacker,

Sum hecker.

Take argv[0], if it doesn't have the path, or the full path,
cut it up to get the command name, say "prog", then strcat(3)
it onto "/usr/ucb/which" and call system(3):

    foo = "/usr/ucb/which prog"
    system(foo);

As long as you're still in the directory from which the
program was run, and as long as your path was the same
as the one set in your .cshrc (someone please tell me
why which(1) reads the .cshrc...) then you'll come up
with /usr/foo/bar/bletch/prog, barring surreptition.

As we saw last week, you can use any of a number
of rather machine-specific exec*() commands to get
which(1) to run, but only system(3) shows up in ANSI C.

Getting the output of which(1) back to the program can
take a number of routes, by a temporary file
("/usr/ucb/which prog > file"), or a socket, or dup'ping
streams, or...

				--Blair
				  "...but that's another
				   question..."



More information about the Comp.unix.questions mailing list