It is very simple, I want to define a new environment variable in C++ using SetEnvironmentVariable, and then call a bat file that use it. This is my c++ code;
PROCESS_INFORMATION processInformation = { 0 };
STARTUPINFO startupInfo = { 0 };
SetEnvironmentVariable("GSDebbugingDir", "Hello");
BOOL result = CreateProcess(NULL,
"dummy.bat"),
NULL,
NULL,
FALSE,
CREATE_NO_WINDOW,
NULL,
NULL,
&startupInfo,
&processInformation);
And my dummy.bat file is :
@echo off
echo GSDebbugingDir = %GSDebbugingDir%
if defined GSDebbugingDir mkdir c:\temp\dummy
pause
But this didn't out the value of GSDebbugingDir variable. What is the problem?
CreateProcess
documentation says:
To run a batch file, you must start the command interpreter ; set lpApplicationName to cmd.exe and set lpCommandLine to the following arguments: /c plus the name of the batch file.
Which makes sense because a .bat file by itself is not an executable module by itself. But, contrary to what the doc says the following code worked for me with UseApplicationName
NOT #defined, ie with "cmd.exe" placed into commandLine
Also, to see the output of the bat file you probably want to remove that CREATE_NO_WINDOW
flag
//#define UseApplicationName
#ifdef UseApplicationName
TCHAR commandLine[] = _T(" /c dummy.bat");
#else
TCHAR commandLine[] = _T("cmd.exe /c dummy.bat");
#endif
BOOL result = CreateProcess(
#ifdef UseApplicationName
_T("cmd.exe"),
#else
NULL,
#endif
commandLine,
NULL,
NULL,
FALSE,
0, //CREATE_NO_WINDOW,
NULL,
NULL,
&startupInfo,
&processInformation);
BTW pay attention that
The Unicode version of this function, CreateProcessW, can modify the contents of this string. Therefore, this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.