Path: utzoo!attcan!uunet!cs.utexas.edu!tut.cis.ohio-state.edu!pt.cs.cmu.edu!zog.cs.cmu.edu!tgl From: tgl@zog.cs.cmu.edu (Tom Lane) Newsgroups: comp.unix.wizards Subject: Re: Getting path to executed program file Message-ID: <10004@pt.cs.cmu.edu> Date: 25 Jul 90 15:26:50 GMT References: <9995@pt.cs.cmu.edu> <1990Jul25.064956.22757@mintaka.lcs.mit.edu> Organization: Carnegie-Mellon University, CS/RI Lines: 43 In article <1990Jul25.064956.22757@mintaka.lcs.mit.edu>, jik@athena.mit.edu (Jonathan I. Kamens) writes: > In article <9995@pt.cs.cmu.edu>, tgl@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@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@cs.cmu.edu UUCP: !cs.cmu.edu!tgl BITNET: tgl%cs.cmu.edu@cmuccvma CompuServe: >internet:tgl@cs.cmu.edu