Difference between revisions of "Interacting with the enviroment"

From Organic Design wiki
m
m
Line 26: Line 26:
  
 
<pre>
 
<pre>
#!/bin/sh
 
 
echo "printenv: $FOO"
 
echo "printenv: $FOO"
 
FOO=bar2
 
FOO=bar2

Revision as of 01:04, 14 March 2007

It's quite simple to read and write environment variables from C:

char *envvar;

if(envvar = getenv("FOO"))
	printf( "FOO=%s\n", envvar );

putenv("FOO=bar");

When you call a child process a copy of the enviroment is passed to this process. However, if the process changes enviroment variables, these changes will be lost once the process terminates.

The parent C program:

putenv("FOO=bar");

system("sh printenv");

if(envvar = getenv("FOO"))
	printf( "FOO=%s\n", envvar );

Executes a shell script (printenv) with system()

echo "printenv: $FOO"
FOO=bar2

The resulting output is:

printenv: bar
FOO=bar