getting the path to the executing program

Per Larsson per at L4i.se
Thu Jan 8 19:02:11 EST 2004


On Thursday 08 January 2004 18.06, Hal Daume III wrote:
> is there a function, related to getProgName, which returns the (absolute)
> path to the current program?
>
> basically, i want to be able to read a file which i know will be in the
> same directory as the current program, but not necessarily in the same
> directory that we're running it from.

I don't know how to do this in a portable way, but on unix/linux you can use 
the standard trick of reading the symbolic link
/proc/<process-id>/exe .

For example:

import System.Posix.Files  (readSymbolicLink)
import System.Posix.Process (getProcessID)

main = do
    pid <- getProcessID
    path <- readSymbolicLink ("/proc/" ++ (show pid) ++ "/exe")
    putStrLn ("Absolute path of this program is " ++ path)

PS. This doesn't work with interpreted code (Hugs, GHCi) in which case
you get the path to the interpreter itself.

Cheers
Per
    
		









More information about the Haskell mailing list