views:

533

answers:

3

In this case the application which sets the environment variable is executed in/from the application that needs to access the env.var. The Main() Return Values (C# Programming Guide) msdn article discusses its use within a batch file. If I try the same, everything is fine; but what is required is to run not from a batch script but from within an application.

Process.Start("app","args"); // app sets the env.var.
string envVar = System.Environment.GetEnvironmentVariable("ERRORLEVEL");

was obviously unsuccessful. Process.Start made the "app" work in a completely different environment I believe. In other words, I need to run "app" in the same environment as the caller application in order to reach the environment variable it sets.

+1  A: 

The environment variables are inherited to child processes but each child gets a copy - if you change the parent's environment afterwards, this will not reflect in the child.

This is for security reasons: If the variables were shared, processes could see into each other's memory which would cause all kinds of problems.

So the solution is to set the variable before starting the new process.

If you need to communicate with an existing child process, use a pipe.

Aaron Digulla
Therefore, may I conclude that if the child changes an envirnment variable there is no way the parent knows, accesses the new value?
tafa
Exactly. Both operates on individual copies.
Aaron Digulla
A: 

Each application runs with it's own copy of the environment so a child process cannot influence the environment of the parent. This is true all the way down to CreateProcess where the environment is an input/optional parameter - i.e. one-way.

There are many IPC mechanisms you have available from named pipes to sockets to shared memory to files ... the list goes on.

But the suspect that files are going to be the easiest for you.

You could have the child process create a file that contains the name/value pairs you want which the calling application could then load and use. The format could be something basic like:

key=value key2=value2

a bit more complex (but maybe easier to work with) like XML ... or any custom format you want.

Bubbafat
+1  A: 

If you're just trying to set the child's environment from the parent:

var p = new Process();
p.StartInfo.EnvironmentVariables["TEST_ENV"] = "From parent";
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = @"C:\src\bin\Debug\ChildProc.exe";
p.Start();

If you don't want the child to inherit the parent process environment:

var psi = new ProcessStartInfo();
psi.EnvironmentVariables["TEST_ENV"] = "From parent";
psi.UseShellExecute = false;
psi.FileName = @"C:\src\bin\Debug\ChildProc.exe";
Process.Start(psi);
omellet