c - 函数 getenv() 总是返回 null

标签 c

<分区>

我的程序

int main(void){
printf("Log file location : %s\n", getenv("LOG_FILE"));
return 0;
}

总是打印空值。

但是我已经在

中设置了环境

/etc/nagios/.profile 文件,其中我的用户是“nagios”,通过 export LOG_FILE=/root/log

当我在终端中执行“env”命令时,我也能看到同样的结果。

最佳答案

函数getenv如果你忘记写 #include <stdlib.h> 会显示一个非常有趣的结果进入文件的标题。

例如代码:

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

int main(void){
  printf("Log file location : %s\n", getenv("LOG_FILE"));
  return 0;
}

效果很好:

LOG_FILE="log" ./a.out 
Log file location : log

但是当我注释掉第二行时,我得到:

LOG_FILE="log" ./a.out 
Segmentation fault (core dumped)

关于c - 函数 getenv() 总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15969195/

相关文章:

c++ - 函数指针寻址具有多个参数的函数

c - 如何判断 FILE* 是否引用一个目录?

c++ - 为 Mac OS X 设置 WindowsHookEx?

c++ - 当 Matlab 中仅接受 Int32Ptr 时,以字符串形式返回错误号

c - uint64_t 的计算结果错误

C 指针通过函数指向指针

c - timeval和time_t如何转换?

c - 写入具有不同文件名的单独文件

C: 宏产生警告 "statement with no effect"

C:缺少指针的一些逻辑