CreateProcess执行cmd指令 执行结果返回错误码87的可能原因
程序员文章站
2022-05-12 21:30:04
...
这是犯蠢的结果,这里踩了个坑
在createprocess的cmdline参数上构造的字符串前有一个空格,createprocess一直失败,偏偏我拷贝过来的其他指令都可以成功执行,我花了两个小时才找到我粘贴过来的cmd命令字符串最前面有一个空格,这个空格看的我想哭。不吐槽了上源码:
1、构造cmd指令
char chCmd[512] = {0};
char chRet[1024] = {0};
int nRet = 0;
//错误示例
//sprintf_s(chCmd, sizeof(chCmd), " auditpol /set /subcategory:\"进程创建\" /success:enable ");
sprintf_s(chCmd, sizeof(chCmd), "auditpol /set /subcategory:\"进程创建\" /success:enable");
nRet= ExecuteCmd(chCmd, chRet, sizeof(chRet) - 1);
2、执行cmd指令函数的源码
int CSmallTestDlg::ExecuteCmd(const CString &csCmd, char *pszRet, int nRetMaxSize/* = 102400*/)
{
if (csCmd.IsEmpty() || (NULL == pszRet) || (nRetMaxSize < 0))
{
return -1;
}
SECURITY_ATTRIBUTES sa = {0};
HANDLE hRead = NULL, hWrite = NULL;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
if (! CreatePipe(&hRead,&hWrite,&sa,0))
{
return -2;
}
STARTUPINFO si={sizeof(si)};
PROCESS_INFORMATION pi;
si.hStdError = hWrite;
si.hStdOutput = hWrite;
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
TCHAR* cmdline=(char *)(const char *)csCmd;
if (!CreateProcess(NULL,cmdline,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi))
//if(CreateProcessAsUser(hToken,NULL,cmdline,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi))
{
CloseHandle(hWrite);
CloseHandle(hRead);
return -3;
}
CloseHandle(hWrite);
int nIndex = 0;
DWORD byteRead = 0;
while(true)
{
if (! ReadFile(hRead, pszRet + nIndex, nRetMaxSize - 1,&byteRead,NULL))
{
break;
}
nIndex += byteRead;
}
CloseHandle(hRead);
return nIndex;
}
上一篇: CreateProcess的命令行参数
下一篇: 小案例:微型博客 - mokal同学