glibc: __progname/__progname_full,获取程序运行名称;program_invocation_name

定义

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mzhan017

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值