tags:

views:

35

answers:

1

Hi,

I want to get the modified environment variables using C programme in Mac using bash terminal how to get it?

if i use getenv i will get only the default system defined environment variables but i am not getting the modified one. how to get it

A: 
#include <stdio.h>
int main()
{
        setenv("PATH","/mypath",1);
        printf("%s\n",getenv("PATH"));
        return(0);
}

The above program outputs:

/mypath

If however you execute env in bash after your C program, you will get the PATH value which is set by default for bash.

$ env
...
PATH=/usr/lib/qt-3.3/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/lib/ccache:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/user/bin
...

This is because the environment variables are modified only for that particular process which is running the C program, & not for the process running bash.

Edit:

Writing env.c as:

#include <stdio.h>
int main()
{
        printf("%s\n",getenv("PATH"));
        return(0);
}

followed by:

$ gcc env.c
$ export PATH=/bin
$ ./a.out

gives:

/bin

I don't see why it should be any different. (Did you do all the steps that I have done above?)

Kedar Soparkar
i have already modified "PATH" in my bash terminal.Now, i want to display the modified "PATH" using c-program.how to do it
Shadow
Could you properly explain the purpose of this exercise before I answer your question?
Kedar Soparkar
Just wanted to know that if i have modified any environment variable using bash terminal,can i get the modified value of the environmental variable using C program? Is it possible?
Shadow
Which command did you use to modify the environment variable?
Kedar Soparkar
Used the below specified commandexport PATH=some_value -- in bash terminalthen i used var_name = getenv ("PATH") -- in C ProgramOutput:Default value of PATH is displayed and not the modified value
Shadow
@Crypto: can i create an environment variable in Bash terminal and access it using c-program?
Shadow
Yes, you can simply type export NEW_VAR=NEW_VALUE, then access it in the program.
Kedar Soparkar
it will produce the output as 'nil' in the program
Shadow