如何读取Glibc代码中的环境变量

发布于 2024-12-25 13:57:31 字数 286 浏览 1 评论 0原文

我想通过读取环境变量来禁用/启用 printf() 输出到屏幕,类似于 LD_DEBUG 的工作方式。

我想控制./stdio-common/printf.c

因此,如果在环境变量中表示禁用 printf() 它会调用,

int
__printf (const char *format, ...)
{
  return done;
}

否则它会执行原始代码。我将如何实施这个?

I want to disable/enable printf() output to screen by reading an environment variable, similar to how LD_DEBUG works.

I want to control ./stdio-common/printf.c.

So if in environment variable says disable printf() it call

int
__printf (const char *format, ...)
{
  return done;
}

else it executes the original code. How would I implement this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅浅淡淡 2025-01-01 13:57:31

使用 getenv。有关详细信息,请参阅getenv(3)

Use getenv. See getenv(3) for details.

国产ˉ祖宗 2025-01-01 13:57:31

推荐的方法是使用 ANSI 提供的解决方案作为 getenv() 函数以获得最大的可移植性:

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
    char * env = getenv(“PROMPT”)); 

    if(env)
        puts(env);
    else
    puts(“The environmental variable not available”);

    return 0;
}

还有其他非标准方法可以执行相同的操作,但不推荐。

main() 的第三个参数可以是 char **envp 广泛用于获取有关环境的信息,并且是非标准

int main(int argc, char **argv, char **envp)
{
    while(*envp)
        printf("%s\n",*envp++);
}

main() 中使用第三个参数严格符合标准。

还有另一种广泛使用的非标准访问环境变量的方法,那就是通过environ外部变量。

int i=0;
extern char ** environ;

while(environ[i])
    printf("\n%s",environ[i++]);

注意:这些示例不完整并且缺乏错误处理。

The recommended way is to use the solution provided by ANSI as getenv() function for maximum portability:

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
    char * env = getenv(“PROMPT”)); 

    if(env)
        puts(env);
    else
    puts(“The environmental variable not available”);

    return 0;
}

There are other non-standard ways of doing the same which is not recommended.

The third argument to main() could be char **envp is used widely to get the information about the environment and is non-standard.

int main(int argc, char **argv, char **envp)
{
    while(*envp)
        printf("%s\n",*envp++);
}

Using the third argument in main() is not strictly conforming to standard.

There is another widely used non-standard way of accessing the environmental variables and that is through the environ external variable.

int i=0;
extern char ** environ;

while(environ[i])
    printf("\n%s",environ[i++]);

NOTE: The examples are in-complete and lacks error handling.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文