gpt4 book ai didi

c - err/warn 函数如何获取程序名称?

转载 作者:行者123 更新时间:2023-12-05 02:28:57 25 4
gpt4 key购买 nike

来自err/warn联机帮助页:

The  err()  and  warn()  family of functions display a formatted error
message on the standard error output. In all cases, the last component
of the program name, a colon character, and a space are output. If the
fmt argument is not NULL, the printf(3)-like formatted error message is
output.

如果我调用:warn("message"); 它将输出如下内容:

a.out: message: (output of strerror here)

warn/err 函数如何找到程序的名称(在本例中为 a.out)完全可以访问 argv 吗?这与它们是 BSD 扩展有什么关系吗?

最佳答案

err/warn 函数在程序名称的基础名称前添加。根据this的回答因此,有几种方法可以在不访问 argv 的情况下获取程序名称。

一种方法是在/proc/self/exe 上调用readlink,然后在上面调用basename。演示这一点的简单程序:

#include <libgen.h>
#include <linux/limits.h>
#include <stdio.h>
#include <unistd.h>

char *
progname(void)
{
char path[PATH_MAX];

if (readlink("/proc/self/exe", path, PATH_MAX) == -1)
return NULL;

/* not sure if a basename-returned string should be
* modified, maybe don't use this in production */
return basename(path);
}

int
main(void)
{
printf("%s: this is my fancy warn message!\n", progname());
return 0;
}

您还可以使用非标准变量 __progname,它可能无法工作,具体取决于您的编译器,以及 program_invocation_short_name,它是 errno 中定义的 GNU 扩展。 h.

关于c - err/warn 函数如何获取程序名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72419226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com