首页 > 解决方案 > CreateProcess api 在 Windows 10 上失败,错误代码为 122

问题描述

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

标签: c++winapivisual-c++

解决方案


您需要以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);
}

推荐阅读