Windows 10上的CreateProcess API失败,错误代码122

时间:2018-08-28 12:12:42

标签: c++ winapi visual-c++

我正在使用CreateProcess api启动批处理文件。该代码在Windows 7上工作正常,但在Windows 10上失败。 以下是代码段:

CString param; //it holds the very long string of command line arguments 
wstring excFile = L"C:\\program files\\BatchFile.bat";
wstring csExcuPath = L"C:\\program files";
wstring exeWithParam = excFile + _T(" ");
exeWithParam = exeWithParam.append(param);
STARTUPINFO si = { sizeof(si) };
PROCESS_INFORMATION pi;
TCHAR lpExeWithParam[8191];
_tcscpy_s(lpExeWithParam, exeWithParam.c_str());
BOOL bStatus = CreateProcess(NULL, lpExeWithParam, NULL, NULL, TRUE, CREATE_NEW_CONSOLE | CREATE_BREAKAWAY_FROM_JOB, NULL, csExcuPath.c_str(), &si, &pi);

DWORD err;
if (!bStatus)
{
    err = GetLastError();
}

使用上面的代码,它正在调用一个批处理文件,该批处理文件将启动具有给定参数的可执行文件。此代码仅在我们产品中的Windows 10上不起作用。 GetLastError返回错误代码122,该代码错误为“传递给系统调用的数据区域太小”。如何找出导致此错误的原因以及如何解决?

但是,在示例测试应用程序中使用相同的代码时,不会给出任何错误和通过。 任何提示/提示为何导致它在Windows 10上失败。

3 个答案:

答案 0 :(得分:2)

您需要使用cmd.exe文件作为参数执行.bat,不要尝试直接执行.bat

此外,您不需要lpExeWithParam,可以将exeWithParam直接传递给CreateProcess()

请尝试以下类似操作:

CString param; //it holds the very long string of command line arguments
...
wstring excFile = L"C:\\program files\\BatchFile.bat";
wstring csExcuPath = L"C:\\program files";
wstring exeWithParam = L"cmd.exe /c \"" + excFile + L"\" ";
exeWithParam.append(param);

STARTUPINFOW si = { sizeof(si) };
PROCESS_INFORMATION pi = {};

BOOL bStatus = CreateProcessW(NULL, &exeWithParam[0]/*or exeWithParam.data() in C++17*/, NULL, NULL, TRUE, CREATE_NEW_CONSOLE | CREATE_BREAKAWAY_FROM_JOB, NULL, csExcuPath.c_str(), &si, &pi);
if (!bStatus)
{
    DWORD err = GetLastError();
    ...
}
else
{
    ...
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
}

答案 1 :(得分:0)

错误122等同于ERROR_INSUFFICIENT_BUFFER,我认为这里的线索是“它包含很长的命令行参数字符串”。

多长时间?在Windows 10上,该限制可能会更低-我建议您进行实验(二进制印章)。

此外,=SUMIF(B2:B20, A2, E1:E10)的{​​{3}}指出您必须显式启动CreateProcess才能运行批处理文件,所以我想您应该按照其说明进行操作。

答案 2 :(得分:-2)

我认为要运行批处理文件,必须将lpApplicationName设置为cmd.exe,并将lpCommandLine设置为以下参数:/ c加上批处理文件的名称

相关问题