How can an application access the environment variable set by another application?

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

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

obviously not crowned with success. Process.Start made the “application” work in a completely different environment, in my opinion. In other words, I need to run the "application" in the same environment as the calling application in order to get the environment variable that it sets.

+3
source share
4 answers

If you are just trying to set up a parent child environment:

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 do not want the child to inherit the process parent:

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

Environment variables are inherited by the child processes, but each child receives a copy - if you subsequently change the parent environment, this will not affect the child.

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

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

If you need to communicate with an existing child process, use the channel.

+1

, . CreateProcess, / , .

IPC, ... .

, .

, /, , . - :

= 2 = 2

(, , ), XML... .

+1

. bash , .

Dot (.) Is a command that should not be confused with the specification of the current directory. The dot command invokes the next command in the parent environment. Thus, the process environment variables are the environment variables of the calling process.

0
source

Source: https://habr.com/ru/post/1710780/


All Articles