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

标签 c bsd

来自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/

相关文章:

c - 进程中锁定了多少内存

shell - 如何在 BSD 查找中使用 xargs?

c - Linux shell 不执行我的 c 程序

c - linux下如何加速连续程序启动?

c - GCC 关于 const 限定符的警告是否正确?

linux - bsd rc.d 的重生选项

linux - "file"程序和fifo

c - 如何从指向 C 中指针的指针获取单个字符?

c - 为什么这些 while 循环不混合我给它们的数字?