c++ - 在 Eclipse 中使用 C++ 在 Linux 中获取环境变量 $PATH

标签 c++ environment-variables

我正在尝试使用一个简单的 C++ 程序在 Linux 中获取环境变量 $PATH 的值,如下所示:

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

int main ()
{
    // get PATH using pipe
    FILE* pip = popen("exec bash -c 'echo $PATH'", "r");
    if (!pip)
    {
        printf("can not open pipe!");
        return 1;
    }

    char lineversion[600];
    memset (lineversion, 0, sizeof(lineversion));
    if (!fgets(lineversion, sizeof(lineversion), pip))
    {
        printf("fgets error!");
        return 1;
    }

    std::cout << lineversion << std::endl;

    // get PATH using getenv
    char* pPath = getenv ("PATH");
    std::cout << pPath << std::endl;
}

我使用了两种不同的方法:使用管道和使用 getenv 方法。他们都输出这个:

/opt/texbin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/local/netbeans-7.3.1/bin

有趣的是,PATH 的实际值有所不同!

enter image description here

为什么我的 C++ 程序显示不同的 PATH 值?

编辑 1:我在 Eclipse IDE 中运行我的 C++ 程序。

编辑 2:直接编译程序(没有 Eclipse IDE)显示正确的 PATH 值!

enter image description here

编辑 3:我在 here 中找到了答案也是。

最佳答案

进程从创建它的进程继承环境。

这就是 Linux 以及许多其他操作系统的工作方式。

如果您从 Eclipse 启动一个程序,该程序将继承 Eclipse 的环境。
如果您从 shell 启动一个程序,该程序将继承 shell 的环境,包括对您在 init 文件中的 PATH 的修改。

由于 Eclipse 从启动它的任何进程继承它的环境,如果您从 shell 而不是通过桌面 GUI 启动 Eclipse,您应该会看到预期的输出。

关于c++ - 在 Eclipse 中使用 C++ 在 Linux 中获取环境变量 $PATH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36326868/

相关文章:

C++ const_iterator 不可取消引用?

java - 这个 SQL 会导致任何问题吗?

c++ - C++ 中的 cout 与 printf 给出不同的输出

r - 在 Ubuntu 上的 R Shiny App 中读取环境变量的最简单方法是什么?

python - Heroku Python 本地环境变量

c++ - 段错误 11 在不同机器上的行为

c++ - 静态变量的参数包扩展

远程收集事实时 JAVA_HOME 不在 Ansible 环境中

Docker 违背了环境变量的全部目的?

c - 如何在 macOs Mojave 上设置环境变量?