如何在C中找到可执行文件的位置? [英] How do I find the location of the executable in C?
问题描述
在C/C ++中是否可以找到当前已执行程序的位置(完整路径)?
Is there a way in C/C++ to find the location (full path) of the current executed program?
(argv[0]
的问题在于它没有提供完整路径.)
(The problem with argv[0]
is that it does not give the full path.)
推荐答案
总结:
-
在具有
/proc
的Unixes上,真正简单可行的方法是:
On Unixes with
/proc
really straight and realiable way is to:
-
readlink("/proc/self/exe", buf, bufsize)
(Linux)
readlink("/proc/curproc/file", buf, bufsize)
(FreeBSD)
readlink("/proc/self/path/a.out", buf, bufsize)
(Solaris)
在没有/proc
的Unix上(即,如果以上失败):
On Unixes without /proc
(i.e. if above fails):
-
如果argv [0]以"/"(绝对路径)开头,则为路径.
If argv[0] starts with "/" (absolute path) this is the path.
否则,如果argv [0]包含"/"(相对路径),则将其附加到cwd (假设尚未更改).
Otherwise if argv[0] contains "/" (relative path) append it to cwd (assuming it hasn't been changed yet).
否则,在$PATH
中的目录中搜索可执行文件argv[0]
.
Otherwise search directories in $PATH
for executable argv[0]
.
然后,检查可执行文件是否实际上不是符号链接可能是合理的. 如果可以解决,则相对于符号链接目录.
Afterwards it may be reasonable to check whether the executable isn't actually a symlink. If it is resolve it relative to the symlink directory.
/proc方法中不需要此步骤(至少对于Linux). proc符号链接在那里直接指向可执行文件.
This step is not necessary in /proc method (at least for Linux). There the proc symlink points directly to executable.
请注意,正确设置argv[0]
取决于调用过程.
在大多数情况下是正确的,但是有时候调用进程不能被信任(例如setuid可执行文件).
Note that it is up to the calling process to set argv[0]
correctly.
It is right most of the times however there are occasions when the calling process cannot be trusted (ex. setuid executable).
在Windows上:使用GetModuleFileName(NULL, buf, bufsize)
On Windows: use GetModuleFileName(NULL, buf, bufsize)
这篇关于如何在C中找到可执行文件的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!