tags:

views:

248

answers:

5

I am trying to display, set & modify PATH environment variable from a C program. I am doing something like this:-

char *cmd[] = { "echo", "$PATH", (char *)0 };
if (execlp("echo", *cmd) == -1)

But I am not getting the results.

A: 

try this:

char *cmd[] = { "$PATH", (char *)0 };
if (execlp("echo", cmd) == -1)
Preet Sangha
No it doesn't work.
AJ
+6  A: 

You should use getenv(), there's no need to go through a shell:

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

int main(void)
{
   printf("PATH='%s'\n", getenv("PATH"));

   return EXIT_SUCCESS;
}

But you won't be able to change the value. Environment variables are inherited into child processes, but the child has its own copy. You can't change the shell's environment from a different program, regardless in which language it's written. You can of course change your own process' value, but that's not what you asked to do.

In the shell itself, you can change its current environment settings, but only there. This is why you need to use "source" to run shells scripts that change the environment.

unwind
You're fast. I'll add that you can type `man getenv` for the quite informative manual page.
phoku
Thanks. The thing that slows me down the most is the curious inability to type backslashes in the markdown editor. :)
unwind
unwind, I had never had troubles with backslashes... But that must have been the cause why you have no closing single quote in your string ;-)
Michael Krelin - hacker
@hacker: Thanks, fixed. Whenever I press backslash in the answer-editor, it gets immediately replaced by `enter code here`, with the text part selected so the next keypress replaces it.
unwind
unwind. Weird. Never happened to me (yet).
Michael Krelin - hacker
@hacker: This is increasingly off-topic, but I took it to meta.stackoverflow.com, and it seems to be a bug in the editor component.
unwind
+2  A: 

If you want to display $PATH, try this:

#include <stdlib.h>

printf("PATH: %s\n",getenv("PATH"));

if you want to modify it, use setenv() or putenv().

Michael Krelin - hacker
A: 
#include <stdio.h>
#include <stdlib.h>

...

char *pPath;
pPath = getenv("PATH");
if (pPath!=NULL)
    printf ("The current path is: %s",pPath);
putenv("PATH=somepath");

...
Philip Davis
A: 

Better solutions already given, but by way of explanation; the $PATH variable is parsed and translated by the command shell, not the echo command itself. The solutions already suggested use getenv() to obtain the environment variable's value instead.

To invoke the command shell to perform this:

system( "echo $PATH" ) ;

but that solution is somewhat heavyweight since it invokes a new process and the entire command processor just to do that.

Clifford