如何使子进程具有与父进程相同的环境变量以及它自己的Windows环境变量?
在Windows中创建新的子进程我使用CreateProcess
函数:
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
);
这里我们可以看到CreateProcess
可以获取lpEnvironment
参数来指定环境变量新进程,如果为 NULL,则子进程将具有与父进程相同的环境。现在我希望子进程具有与父进程相同的环境以及 lpEnvironment 中指定的环境变量(即父进程和指定进程的合并环境)。您建议如何执行此操作?我应该获取父级的所有环境,将它们与新的环境合并并将它们全部传递给 CreateProcess 吗?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你走在正确的道路上。获取现有的环境块,附加新的内容,将其传递给 CreateProcess 函数,然后销毁新的环境块。
要获取当前块,请使用 GetEnvironmentStrings。添加新变量可能需要通过简单的字符串操作来完成。环境块只是连续的以 null 结尾的字符串序列,末尾带有双 null,如所述 此处。您可能需要首先检查是否要附加新的环境变量或更新现有的环境变量(以防已定义)。
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.
使用 getenv 获取 crt env add你自己的和设置的
use getenv to get crt env add your own and set