【发布时间】:2009-04-20 18:54:54
【问题描述】:
我希望 Win32 进程启动外部脚本并能够检索它返回的 ERRORLEVEL。
反之亦然。只需在您的 Win32 应用程序中使用 exit(errorcode) 或 return errorcode;,调用脚本就会正确设置其 ERRORLEVEL 值。
但是,从 Win32 调用应用程序中,获取脚本错误代码并不完全相同。
我尝试使用 CreateProcess() 并调用 GetExitCodeProcess(),但它总是返回 0 而不是 ERRORLEVEL 的实际值。即使我用 exit %ERRORLEVEL%
结束我的调用脚本我最好的猜测是脚本不是一个进程。很可能 CMD.EXE 正在运行,并且很可能总是以 ExitCode 0 结束。我知道 ERRORLEVEL 与进程 ExitCode 值不同,我希望 CMD.EXE 会镜像它。
编辑:
对不起,我问了!我刚刚发现我的问题。我在批处理文件中使用 exit /b errorcode 而不是 exit errorcode。当您从命令行进行测试时,似乎 /b 选项的优点是只关闭正在运行的脚本,而不是 CMD.EXE。但是没有为 CMD.EXE 设置正确的 ExitCode 的缺点。
所以,为了后代,我正在做的是:
int LaunchScript(TCHAR *pCmdLineParam)
{
bool bResult;
PROCESS_INFORMATION pi;
STARTUPINFO si;
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
TCHAR cmdLine[256];
_tcscpy(cmdLine,L"Test.cmd");
_tcscat(cmdLine,L" ");
_tcscat(cmdLine,pCmdLineParam);
_tprintf(L"Process executing: %s\n",cmdLine);
bResult = CreateProcess(NULL, cmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)?true:false;
if (!bResult) {
_tprintf(L"CreateProcess() error - %d", GetLastError());
return -1;
}
DWORD result = WaitForSingleObject(pi.hProcess,15000);
if( result == WAIT_TIMEOUT ) {
return -2;
}
DWORD exitCode=0;
if( !GetExitCodeProcess(pi.hProcess,&exitCode) ) {
_tprintf(L"GetExitCodeProcess() error - %d", GetLastError());
return -1;
}
_tprintf(L"Process exitcode=%d\n",exitCode);
return exitCode;
}
我的“入口点”批处理文件如下所示:
@call %*
@exit %ERRORLEVEL%
我将我的脚本作为参数传递给入口点脚本。其他“子脚本”文件可以调用 exit /b 或 exit,因为所有内容都已涵盖。
【问题讨论】:
标签: winapi batch-file