Jeffrey
Jeffrey

Reputation: 4506

How to make the COM host process avoid inheriting the environment variables from the parent process

My OS is Win7 x64. I have two exe named ComHost.exe and ClientApp.exe.

The ComHost.exe is a standalone exe and also a the COM host for the out-of-process COM.

ClientApp.exe creates the COM instance by calling the CoCreateInstance(...). When create the COM instance, the process ComHost.exe starts.

In the windows environment variables, there is a variable "AppStatus=status1".

In the implementation of ClientApp.exe, the code is like that

int ret = putenv("AppStatus=status2"); // Change the environment variable.
// do something
CoCreateInstance(...); // Start ComHost.exe

In the implementation of ComHost.exe, I get the viriable value with the code

char * pStatus = getenv("AppStatus");

Case 1: If start the ComHost.exe by double click it, the value of pStatus is "status1".

Case 2: If start the ComHost.exe in ClientApp.exe, the value of pStatus is "status2". It inherits the environment variables of the parent process ClientApp.exe.

My question is:

I want ComHost.exe always reads the variable value defined by OS not the value inherited from the parent process. That means, in case 2, I want to get the value "status1". Is it possible?

Upvotes: 0

Views: 325

Answers (1)

MSalters
MSalters

Reputation: 179799

If you double-click the "ComHost.exe" process, you're probably doing so from Explorer.EXE. That means you don't get the "variable value defined by OS". You just inherit it from Explorer.EXE (which, admittably, is started in a special way during login.)

Behind the scenes, we're always using CreateProcess or a variant thereof. Its default behavior it to create a new process, copying the environment variables of the calling process. As you're not in charge of creating that new process (in case 2, COM is), you can't alter this behavior.

So, therefore, in both cases, getenv will get you the inherited value, and in case 2 you cannot get the value "that you would have inherited from Explorer.EXE".

Upvotes: 2

Related Questions