getenv()返回环境为null?

时间:2017-12-07 01:03:28

标签: c shell

我正在尝试使用以下代码在c和bash中打印当前目录中的可执行文件:

system("EXEC_PATH=$(find . -maxdepth 1 -type f -executable)");
printf("executables are: %s\n", getenv("EXEC_PATH"));

但是,当我编译并运行c代码时,得到的结果是:

executables are: (null)

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

system()正在创建一个新的shell并在那里设置环境,然后在shell退出时抛弃它。

getenv()正在使用"当前"的环境过程

尝试获取系统调用的结果并使用putenv修改当前环境。

答案 1 :(得分:0)

我用popen和fgets尝试了Ahmed Masud的解决方案并得到了一个有效的解决方案:

    char buff[BUFSIZ];
    char elf_arr
    FILE *fp = popen("find . -maxdepth 1 -type f -executable","r");
    while (fgets( buff, BUFSIZ, fp ) != NULL ) {
            printf("executables are: %s\n", buff);
    }
    pclose(fp);
相关问题