Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!uwm.edu!zaphod.mps.ohio-state.edu!usc!snorkelwacker!mit-eddie!bu.edu!bu-cs!buengc!bph From: bph@buengc.BU.EDU (Blair P. Houghton) Newsgroups: comp.unix.questions Subject: Re: How to get the pathname of the current executable? Message-ID: <5378@buengc.BU.EDU> Date: 13 Feb 90 02:24:45 GMT References: <1610.25d028a3@wums.wustl.edu> <1990Feb7.211538.3894@iwarp.intel.com> Reply-To: bph@buengc.bu.edu (Blair P. Houghton) Followup-To: comp.unix.questions Organization: Boston Univ. Col. of Eng. Lines: 41 In article <1990Feb7.211538.3894@iwarp.intel.com> merlyn@iwarp.intel.com (Randal Schwartz) writes: >In article <1610.25d028a3@wums.wustl.edu>, bethge@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..."