如何在 C 中找到可执行文件的位置? [英] How do I find the location of the executable in C?

查看:25
本文介绍了如何在 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 的 Unix 上,真正直接可行的方法是:

  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆