创建进程 API 失败,在窗口 122 上出现错误代码 10

CreateProcess api failing with error code 122 on windows 10

本文关键字:错误代码 窗口 API 进程 失败 创建      更新时间:2023-10-16

我正在使用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 上失败。

您需要以.bat文件作为参数执行cmd.exe,不要尝试直接执行.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);
}

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

到底有多长? Windows 10 的限制可能更低 - 我建议您进行实验(二进制印章(。

此外,CreateProcess的文档指出您必须显式启动cmd.exe才能运行批处理文件,因此我想您应该按照它所说的去做。

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