无法访问argv [0],如何获得程序名称? [英] Without access to argv[0], how do I get the program name?
问题描述
我知道程序名称是作为第一个参数传递的,下一个简单的示例会将其打印到标准输出中:
I know the program name is passed as the first argument, and next simple example will print it to the standard output :
#include <iostream>
int main ( int argc, char *argv[] )
{
std::cout<<argv[0]<<std::endl;
}
有获取程序名称的函数吗?
Is there a function to get the program name?
编辑
我从外壳启动程序,上面的代码将始终打印程序名称(我使用的是fedora 9,但我确定它可以在其他发行版中使用).
I am starting the program from the shell, and the above code will always print the program name (I am using fedora 9, but I am sure it works in other distros).
我发现/proc/self/目录可能包含我要查找的内容,但是我找不到该目录中的确切内容.
I have found that /proc/self/ directory might contain what I am looking for, but I couldn't find what exactly in that directory.
推荐答案
不,没有这样的功能.Linux将程序名称存储在 __ progname
中,但这不是公共接口.如果您想将其用于警告/错误消息,请使用 err(3)
函数.
No, there is no such function. Linux stores the program name in __progname
, but that's not a public interface. In case you want to use this for warnings/error messages, use the err(3)
functions.
如果要运行的程序的完整路径,请在/proc/self/exe
上调用 readlink
:
If you want the full path of the running program, call readlink
on /proc/self/exe
:
char *program_path()
{
char *path = malloc(PATH_MAX);
if (path != NULL) {
if (readlink("/proc/self/exe", path, PATH_MAX) == -1) {
free(path);
path = NULL;
}
}
return path;
}
(我相信 __ progname
设置为 argv [0]
的基本名称.请确保查看glibc源代码.)
(I believe __progname
is set to the basename of argv[0]
. Check out the glibc sources to be sure.)
这篇关于无法访问argv [0],如何获得程序名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!