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.

3
  • 2
    One solution is write all commands into temporary bat-file and execute it. Commented Oct 14, 2014 at 10:57
  • Agree! That can be done. Let's see! if more solutions do exist. Commented Oct 14, 2014 at 11:05
  • possible duplicate of How to run two commands in one line in Windows CMD? Commented Oct 14, 2014 at 11:11

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@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!
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.

1 Comment

Edited my answer as per your suggestions so we have a clear solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.