2

Before running a cmd command in c++, I want to set some temporary environment variable, Which gets deleted with end of command line session. for e.g. before executing below cmd command, I want to set P4PASSWD perforce environment variable.

sprintf_s(p4Command, 500, "/C p4.exe print -o \"%s\" -q %s", destination, source);

LPCSTR Command = p4Command;

ShellExecute(0, "open", "cmd.exe", Command, 0, SW_HIDE);

This can be possible if we are allowed to execute multiple cmd commands in one session. But I don't know how it can be achieved.Please let me know if some more inputs are required.

Alex K.
  • 171,639
  • 30
  • 264
  • 288
Yogesh
  • 255
  • 5
  • 16

2 Answers2

5

Use CreateProcess to run p4.exe and pass a set of environment variables in the lpEnvironment parameter.

http://msdn.microsoft.com/en-us/library/windows/desktop/ms682009%28v=vs.85%29.aspx

CreateProcess gives you added benefits; you can wait for the process to terminate, you can retrieve the exit code etc.

  • 1
    Since you would be providing a custom environment block, the new process will not inherit the calling process's environment. If you need to do that, you will have to allocate an environment block that includes both the current environment values and the custom values. You can use `GetEnvironmentStrings()` to get the calling process's current environment values. – Remy Lebeau Oct 14 '14 at 21:43
  • @Gunther, Sorry for the late reply, I was not active for some reason. I tried with CreateProcess api and passed block of environment variables and it worked. Thanks! – Yogesh Oct 29 '14 at 12:12
3

Don't set environment variables for your own process as Gunther suggested earlier. The 7th parameter to CreateProcess is a new set of environment variables.

MSalters
  • 173,980
  • 10
  • 155
  • 350