4
votes

I am trying to get the value of environment variable $PATH in Linux using a simple C++program as bellow:

#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;
}

I used two different methods: using pipe and using getenv method. They both output this:

/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

Interestingly the actual value of PATH is something different!

enter image description here

Why my C++ program is showing a different value for PATH?

Edit 1: I am running my C++ program in Eclipse IDE.

Edit 2: Compiling the program directly (without Eclipse IDE) shows the correct PATH value!

enter image description here

Edit 3: I found the answer in here too.

1
What happens when you don't run your program in eclipse? - Galik
Your PATH can be altered by some config file, either for bash, or for NETBEANS. Check your .profile, .bashrc, .bash-profile in your home directory. - Tomáš Šíma
Your PATH is different between eclipse and your shell. - knivil
@Galik: Without Eclipse, it shows the PATH value correctly! I have updated my question. So Eclipse is responsible for this? - ManiAm
that may be becase, eclipse does not run on bash profile - Panda

1 Answers

4
votes

A process inherits the environment from the process that created it.

This is how Linux works, along with many other operating systems.

If you launch a program from Eclipse, that program inherits Eclipse's environment.
If you launch a program from the shell, that program inherits the shell's environment, including the modifications to PATH you have in your init files.

Since Eclipse has inherited its environment from whichever process launched it, you should see the expected output if you launch Eclipse from the shell instead of through your desktop GUI.