c++ - 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 上失败。
解决方案
您需要以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);
}
推荐阅读
- sql - 如何在 WHERE 条件中组合 MIN 和 MAX
- javascript - 使用 `axios.interceptors` 获取新令牌
- java - Spring 4 应用程序关闭应用程序上下文
- java - 如何在杰克逊中取消多个嵌套元素?
- python - TypeError,试图解析一个 Token 值但不可能
- rust - 为什么我需要克隆一个移动的变量?
- c# - 例外:从“Amazon.Runtime.Internal.Util.MD5Stream”上的“位置”获取值时出错
- powershell - Powershell [ComponentModel.Win32Exception] 铸造不一致
- php - 无法访问数据库中的 Laravel 活动日志属性
- python - Python脚本从pycharm正确运行,但不能从批处理文件中运行