简体   繁体   English

C程序:getenv在GDB / DDD中返回NULL

[英]C program: getenv return NULL in GDB/DDD

I try to call getenv in my C code, this can return correct env string in terminal, while it returns NULL in GDB/DDD. 我尝试在C代码中调用getenv,这可以在终端中返回正确的env字符串,而在GDB / DDD中返回NULL。

void main() {
  char * a = getenv("ANCHOR_STEM");
  if (strlen(a)>0)
    printf("%s\n", a);
}

The GDB/DDD is started from the same terminal. GDB / DDD从同一终端启动。 Even I "show environment", this env exists. 即使我“显示环境”,这个环境也存在。

Anyone any idea? 有人知道吗?

OS/Tools version info: RHEL Linux hostname1 2.6.32-754.3.5.el6.x86_64 #1 SMP Thu Aug 9 11:56:22 EDT 2018 x86_64 GNU/Linux GNU gdb (GDB) 7.12 gcc (GCC) 6.3.0 操作系统/工具版本信息:RHEL Linux hostname1 2.6.32-754.3.5.el6.x86_64#1 SMP Thu Aug 9 11:56:22 EDT 2018 x86_64 GNU / Linux GNU gdb(GDB)7.12 gcc(GCC)6.3.0

include proper header files 包括适当的头文件

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

Treat warning as error. 将警告视为错误。

Even I "show environment", this env exists. 即使我“显示环境”,这个环境也存在。

When GDB invokes your program, it starts a new shell to run this program in. 当GDB调用您的程序时,它将启动一个新的Shell来运行该程序。

When the environment changes for the target program, most often this is the result of your shell initialization file ( ~/.bashrc , ~/.kshrc , etc.) changing the environment. 当目标程序的环境发生更改时,大多数情况下这是外壳初始化文件( ~/.bashrc~/.kshrc等)更改环境的结果。

It is a really bad idea to change environment for non-interactive shells. 更改非交互式shell的环境确实是一个坏主意。 Documentation on how to avoid it. 有关如何避免这种情况的文档

If getenv returns NULL it is because it does not find the environment variable. 如果getenv返回NULL,则是因为找不到环境变量。 but still you have to be careful. 但还是要小心 This instruction if (strlen(a)>0) becomes illegal, if getenv(....) , fails. if (strlen(a)>0)变为非法,则此指令失败;如果getenv(....) ,此指令失败。 getenv sends back NULL and this instruction crash the program. getenv发送回NULL,此指令使程序崩溃。 It's better to test the validity of the pointer before to execute this line if (strlen(a)>0) -> which is not necessarily useful. if (strlen(a)>0) ->不一定有用,则最好在执行此行之前测试指针有效性

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

int main() {
    char * a = getenv("ANCHOR_STEM");
    if( NULL != a ){
        (void)puts(a);
        return EXIT_SUCCESS;
    }
    (void)puts("none");
    return EXIT_FAILURE;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM