ManiAm
ManiAm

Reputation: 1841

Getting Environment Variable $PATH in Linux using C++ in Eclipse

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.

Upvotes: 4

Views: 1714

Answers (1)

molbdnilo
molbdnilo

Reputation: 66371

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.

Upvotes: 4

Related Questions