简体   繁体   English

将CreateProcess与通过bat文件设置的环境变量一起使用

[英]Use CreateProcess with environment variables set via a bat file

I'm executing an external application using the CreateProcess function, in order which such application be executed I need run a .bat file before to set some environments variables. 我正在使用CreateProcess函数执行外部应用程序,为了执行这样的应用程序,我需要先运行.bat文件来设置一些环境变量。 The issue is when i call CreateProcess to run the bat file and then execute CreateProcess again for run the external app the environment variables are not used. 问题是当我调用CreateProcess来运行bat文件然后再次执行CreateProcess以运行外部应用程序时,不使用环境变量。 The question is how i can use the environment variables set in the bat file when I execute CreateProcess function the second time? 问题是我第二次执行CreateProcess函数时如何使用bat文件中设置的环境变量?

If the initial createprocess batch file is simply to setup the environment variables, create the enviornment variable block instead and pass it directly via the CreateProcess() call. 如果初始createprocess批处理文件只是设置环境变量,则改为创建enviornment变量块并通过CreateProcess()调用直接传递它。

Some sample code is available here for getting/setting environment variables and for passing a block to CreateProcess() http://www.delphidabbler.com/articles?article=6 这里有一些示例代码可用于获取/设置环境变量以及将块传递给CreateProcess() http://www.delphidabbler.com/articles?article=6

You can use CreateProcess() to run the OS's cmd.exe program to execute multiple commands at one time, eg: 您可以使用CreateProcess()来运行操作系统的cmd.exe程序,以便一次执行多个命令,例如:

TCHAR szCmd[(MAX_PATH * 3) + 16] = {0};
TCHAR szPathToCmdExe[MAX_PATH+1] = {0}
GetEnvironmentVariable(TEXT("COMSPEC"), szPathToCmdExe, MAX_PATH+1);
wsprintf(szCmd, TEXT("\"%s\" /C \"%s && %s\""), szPathToCmdExe, szPathToBat, szPathToProgram);
CreateProcess(NULL, szCmd, ...);

If you execute the other application from the batch file it would have those environment variables set. 如果从批处理文件中执行其他应用程序,则会设置这些环境变量。 You could pass the executable name as a parameter to the batch file. 您可以将可执行文件名作为参数传递给批处理文件。 When you set environment variables within the batch file, they only exist until that batch file exits. 在批处理文件中设置环境变量时,它们仅在该批处理文件退出之前存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM