Documentation ¶
Overview ¶
Package execpath provides APIs for returning the absolute path to the executable file of the running program.
exePath, err := execpath.Get() if err != nil { fmt.Println(err.Error()) } // Prints /path/to/your/executable fmt.Printf(exePath)
Determining the path to the executable of the currently running program is difficult. Many programs read os.Args[0], sometimes combining it with the working directory to determine the path, but this approach is fragile and yields incorrect results because:
- The program may be in the PATH, and invoked without specifying any path to the executable.
- The program may have changed directories after it was invoked.
- The value of os.Args[0] is not required to be set to the invoking path. Most shells follow a convention of setting os.Args[0] to the path used to invoke the executable, but your program may be invoked by an unconventional shell, forked from a non-shell process, started as a Windows service, etc.
Each operating system has a platform-specific API that is guaranteed to return a proper path to the executable file. Package execpath provides GetNative(), which uses the following platform-specific APIs which will always return the proper executable path, if successful:
- Windows: GetModuleFileName
- Linux: /proc/self/exe
- OS X: _NSGetExecutablePath
- FreeBSD: /proc/curproc/file
- OpenBSD: /proc/curproc/file
- NetBSD: /proc/curproc/exe
Package execpath also implements the naive heuristic methods which involve examining os.Args[0] or checking directories in the PATH.
Lastly, execpath provides Get(), the API you should prefer, which calls GetNative() and falls back to using heuristic methods if GetNative() fails.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Get ¶
Get returns the path to the current executable or an error on failure. This is the preferred API because it attempts to use the native method and falls back to heuristic methods on failure. In order, it calls:
GetNative()
GetArg0() if GetNative() fails ¶
GetPath() if GetArg0() fails
func GetArg0 ¶
GetArg0 returns the executable path by examining the value of os.Args[0], combining it with the working directory if necessary. Because os.Args[0] is set by convention, the returned path is not guaranteed to be correct, even if GetArg0 does not return an error.
func GetNative ¶
GetNative returns the executable path by calling a platform-specific API. The API used for each platform is specified as follows:
- Windows: GetModuleFileName - Linux: /proc/self/exe - OS X: _NSGetExecutablePath - FreeBSD: /proc/curproc/file - OpenBSD: /proc/curproc/file - NetBSD: /proc/curproc/exe
Types ¶
This section is empty.