在没有/proc/self/exe 的情况下查找当前可执行文件的路径 [英] Finding current executable's path without /proc/self/exe

查看:33
本文介绍了在没有/proc/self/exe 的情况下查找当前可执行文件的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,Linux 使用/proc/self/exe 很容易.但是我想知道是否有一种方便的方法可以在具有跨平台接口的 C/C++ 中找到当前应用程序的目录.我已经看到一些项目在使用 argv[0],但它似乎并不完全可靠.

It seems to me that Linux has it easy with /proc/self/exe. But I'd like to know if there is a convenient way to find the current application's directory in C/C++ with cross-platform interfaces. I've seen some projects mucking around with argv[0], but it doesn't seem entirely reliable.

如果你不得不支持,比如说,没有/proc/的 Mac OS X,你会怎么做?使用 #ifdefs 来隔离特定于平台的代码(例如 NSBundle)?或者尝试从 argv[0]、$PATH 等推导出可执行文件的路径,冒着在边缘情况下发现错误的风险?

If you ever had to support, say, Mac OS X, which doesn't have /proc/, what would you have done? Use #ifdefs to isolate the platform-specific code (NSBundle, for example)? Or try to deduce the executable's path from argv[0], $PATH and whatnot, risking finding bugs in edge cases?

推荐答案

一些特定于操作系统的接口:

Some OS-specific interfaces:

  • Mac OS X: _NSGetExecutablePath() (man 3 dyld)
  • Linux: readlink /proc/self/exe
  • Solaris: getexecname()
  • FreeBSD: sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1
  • FreeBSD if it has procfs: readlink /proc/curproc/file (FreeBSD doesn't have procfs by default)
  • NetBSD: readlink /proc/curproc/exe
  • DragonFly BSD: readlink /proc/curproc/file
  • Windows: GetModuleFileName() with hModule = NULL

还有第三方库可用于获取此信息,例如 其中如骄傲的回答中所述,或者如果您使用 Qt,QCoreApplication::applicationFilePath()如评论中所述.

There are also third party libraries that can be used to get this information, such as whereami as mentioned in prideout's answer, or if you are using Qt, QCoreApplication::applicationFilePath() as mentioned in the comments.

可移植(但不太可靠)的方法是使用 argv[0].尽管调用程序可以将其设置为任何内容,但按照惯例,它被设置为可执行文件的路径名或使用 $PATH 找到的名称.

The portable (but less reliable) method is to use argv[0]. Although it could be set to anything by the calling program, by convention it is set to either a path name of the executable or a name that was found using $PATH.

一些shell,包括bash和ksh,设置环境变量"_" 到可执行文件在执行之前的完整路径.在这种情况下,您可以使用 getenv("_") 来获取它.然而,这是不可靠的,因为并非所有 shell 都这样做,并且它可以被设置为任何东西,或者是从父进程遗留下来的,而父进程在执行你的程序之前没有改变它.

Some shells, including bash and ksh, set the environment variable "_" to the full path of the executable before it is executed. In that case you can use getenv("_") to get it. However this is unreliable because not all shells do this, and it could be set to anything or be left over from a parent process which did not change it before executing your program.

这篇关于在没有/proc/self/exe 的情况下查找当前可执行文件的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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