Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How make child process with same environment variables as parrent plus it's own in windows?

In windows for creating new child proccess I'm using CreateProcess function:

BOOL WINAPI CreateProcess(
  __in_opt     LPCTSTR lpApplicationName,
  __inout_opt  LPTSTR lpCommandLine,
  __in_opt     LPSECURITY_ATTRIBUTES lpProcessAttributes,
  __in_opt     LPSECURITY_ATTRIBUTES lpThreadAttributes,
  __in         BOOL bInheritHandles,
  __in         DWORD dwCreationFlags,
  __in_opt     LPVOID lpEnvironment,
  __in_opt     LPCTSTR lpCurrentDirectory,
  __in         LPSTARTUPINFO lpStartupInfo,
  __out        LPPROCESS_INFORMATION lpProcessInformation
);

Here we can see that CreateProcess can get lpEnvironment parameter to specify environment variables of new process and if it's NULL, the child will have same environment as parrent. Now I want the child to have same environment as parrent plus environment vars specified in lpEnvironment (i.e. merged environment of parent process and specified ones). How would you suggest to do this? Should I take all envs of parent, merge them with new ones and pass them all to CreateProcess?

like image 625
Mihran Hovsepyan Avatar asked Sep 04 '25 17:09

Mihran Hovsepyan


1 Answers

I think you are on the right track. Get existing env block, append your new stuff, pass it to CreateProcess function, then destroy the new env block.

To get current block use GetEnvironmentStrings. Appending new variables you will probably have to do by simple string manipulations. The environment block is simply concecutive sequence of null-terminated strings, with double null at the end, as described here. You might want to check first if you are appending new env variable or updating existing one, in case if it is already defined.

like image 60
seva titov Avatar answered Sep 07 '25 16:09

seva titov