How can I change Windows shell (cmd.exe) environment variables from C++?

前端 未结 4 992
耶瑟儿~
耶瑟儿~ 2021-01-07 09:20

I would like to write a program that sets an environment variable in an instance of the shell (cmd.exe) it was called from. The idea is that I could store some state in thi

4条回答
  •  佛祖请我去吃肉
    2021-01-07 09:57

    In Windows when one process creates another, it can simply let the child inherit the current environment strings, or it can give the new child process a modified, or even completely new environment.

    See the full info for the CreateProccess() win32 API

    There is no supported way for a child process to reach back to the parent process and change the parent's environment.

    That being said, with CMD scripts and PowerShell, the parent command shell can take output from the child process and update its own environment. This is a common technique.

    personly, I don't like any kind of complex CMD scripts - they are a bitch to write an debug. You may want to do this in PowerShell - there is a learning curve to be sure, but it is much richer.

提交回复
热议问题