[英]Define in C++ new environment variable and use it in bat file
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.很简单,我想在C++中使用SetEnvironmentVariable定义一个新的环境变量,然后调用一个使用它的bat文件。 This is my c++ code;这是我的 C++ 代码;
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 :我的 dummy.bat 文件是:
@echo off
echo GSDebbugingDir = %GSDebbugingDir%
if defined GSDebbugingDir mkdir c:\temp\dummy
pause
But this didn't out the value of GSDebbugingDir variable.但这并没有输出 GSDebbugingDir 变量的值。 What is the problem?问题是什么?
CreateProcess
documentation says: CreateProcess
文档说:
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.将 lpApplicationName 设置为 cmd.exe 并将 lpCommandLine 设置为以下参数:/c 加上批处理文件的名称。
Which makes sense because a .bat file by itself is not an executable module by itself.这是有道理的,因为 .bat 文件本身并不是一个可执行模块。 But, contrary to what the doc says the following code worked for me with UseApplicationName
NOT #defined, ie with "cmd.exe" placed into commandLine
但是,相反的是对医生说很适合我用下面的代码UseApplicationName
不#define的,即具有置入“cmd.exe的” commandLine
Also, to see the output of the bat file you probably want to remove that CREATE_NO_WINDOW
flag此外,要查看 bat 文件的输出,您可能想要删除该CREATE_NO_WINDOW
标志
//#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.此函数的 Unicode 版本 CreateProcessW 可以修改此字符串的内容。 Therefore, this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string).因此,此参数不能是指向只读内存的指针(例如 const 变量或文字字符串)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.