Getting path to executed program file

Tom Lane tgl at zog.cs.cmu.edu
Thu Jul 26 01:26:50 AEST 1990


In article <1990Jul25.064956.22757 at mintaka.lcs.mit.edu>, jik at athena.mit.edu (Jonathan I. Kamens) writes:
> In article <9995 at pt.cs.cmu.edu>, tgl at zog.cs.cmu.edu (Tom Lane) writes:
> |> Is there any way for a program to discover the path name of the file
> |> from which it was executed?
> 
> [Jonathan provides a chunk of code written by Greg Limes (limes at sun.com),
>  which uses argv[0] and the PATH environment string to try to determine
>  where the current executable file came from.]

Thanks for posting this code; I had been planning to write the same thing,
and this saves me from reinventing the wheel.  The business about following
a symbolic link to the real executable is a nice refinement that I hadn't
thought of.

HOWEVER, this doesn't really answer my question.  There are a couple of
assumptions implicit in this method, which Greg didn't document:

  1. It has to assume that argv[0] is identical to the path parameter
     given to exec.  The manuals I've checked say "by convention, argv[0]
     must be supplied and must point to a string identical to path
     *or path's last component*" (emphasis added).
     If the invoking program follows that last clause, then we'll fail
     when the user does something like
	$ ../otherdir/progname  parameters
     The shells I've tried around here seem to make argv[0] be the whole
     string, but who knows whether they all do?

  2. It has to assume that the exec call was execlp() or execvp(),
     and not one of the other forms of exec.  With the other forms,
     a simple name will always be found in the current directory.
     With execlp/execvp, this is true only if PATH contains "." as its
     first element.

In practice these problems probably don't materialize often, so Greg's
code probably gets the right answer 99% of the time.  Still, I would
like to know if it is possible to avoid these assumptions.

-- 
				tom lane
Internet: tgl at cs.cmu.edu
UUCP: <your favorite internet/arpanet gateway>!cs.cmu.edu!tgl
BITNET: tgl%cs.cmu.edu at cmuccvma
CompuServe: >internet:tgl at cs.cmu.edu



More information about the Comp.unix.wizards mailing list