定义
misc/init-misc.c
这个下面的内容其实很早就有了,一般不这么用。但是知道这个之后,或许可以使用一下,因为程序实际跑的时候,会调用到__init_misc函数。其实就是一个指针,帮我们指向了argv[0]的地址。这段代码的历史很早了,也许_init_misc可以做更多的事情。其实没人建议这么用,也没有标准定义,做不了兼容。
char *__progname_full = (char *) "";
char *__progname = (char *) "";
weak_alias (__progname_full, program_invocation_name)
weak_alias (__progname, program_invocation_short_name)
void
__init_misc (int argc, char **argv, char **envp)
{
if (argv && argv[0])
{
char *p = strrchr (argv[0], '/');
if (p == NULL)
__progname = argv[0];
else
__progname = p + 1;
__progname_full = argv[0];
}
}
使用方法
extern char * __progname;
glibc的调用关系
program_invocation_short_name
man 3 program_invocation_name
program_invocation_name, program_invocation_short_name - obtain name used to invoke calling program
#define _GNU_SOURCE /* See feature_test_macros(7) */ 这个宏定义是必须的
#include <errno.h>
extern char *program_invocation_name;
extern char *program_invocation_short_name; 、、需要先声明外部的变量
program_invocation_name,包含触发程序的命令名称(如果是给链接,就是链接名称)。和main函数的参数argv[0]内容意义,只是这个变量的定义域是全局的。
program_invocation_short_name contains the basename component of name that was used to invoke the calling program. That is, it is the same value as program_invocation_name, with all text up to and including the final slash (/), if any, removed.
这两个变量是glibc在启动程序时自动初始化的。
需要注意,这两个变量是GNU扩展的功能,需要注意兼容问题。
The Linux-specific /proc/[number]/cmdline file provides access to similar information.
需要注意的问题
如果是建立的链接来触发可执行文件,那么这里的变量内容是,链接名称;systemd就是利用了这么个特性。
} else if (strstr(program_invocation_short_name, "poweroff")) {
arg_action = ACTION_POWEROFF;
return halt_parse_argv(argc, argv);
从 errno.h 看
#ifdef __USE_GNU 、、 其实用的是这个宏
/* The full and simple forms of the name with which the program was
invoked. These variables are set up automatically at startup based on
the value of argv[0]. */
extern char *program_invocation_name;
extern char *program_invocation_short_name;