#include <windows.h>
int CmdHandle(LPSTR command,PHANDLE in,PHANDLE out) //运行正确返回0 错误返回负数
{
if(command==NULL | in == NULL | out == NULL)return 0; //检测参数是否正确
SECURITY_ATTRIBUTES SecurityAttributes;
HANDLE ShellStdinPipe = NULL;
HANDLE ShellStdoutPipe = NULL;
HANDLE hRead = NULL;
HANDLE hWrite = NULL;
//设置安全属性
SecurityAttributes.nLength = sizeof(SecurityAttributes);
SecurityAttributes.lpSecurityDescriptor = NULL; // 默认安全描述
SecurityAttributes.bInheritHandle = TRUE; // 继承句柄
if ( !CreatePipe(&hRead, &ShellStdoutPipe,&SecurityAttributes, 0) ) return -1; //创建读取管道
if ( !CreatePipe(&ShellStdinPipe, &hWrite,&SecurityAttributes, 0) ) //创建写入管道
{
CloseHandle (hRead);
return -1;
}
//管道创建完毕
//下面创建新进程并且把读写管道接入到新进程上
PROCESS_INFORMATION ProcessInformation;
STARTUPINFO si;
HANDLE ProcessHandle = NULL;
// 设置启动信息
ZeroMemory(&si,sizeof(si));
si.cb = sizeof(STARTUPINFO);
si.wShowWindow = SW_HIDE; //隐藏
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; //标准流选项可用 窗口选项可用
si.hStdInput
= ShellStdinPipe; //连接输入管道
si.hStdOutput = ShellStdoutPipe; //连接输出管道
// 将输出管道连接到子进程错误流
DuplicateHandle(GetCurrentProcess(), ShellStdoutPipe,
GetCurrentProcess(), &si.hStdError,
DUPLICATE_SAME_ACCESS, TRUE, 0);
//创建新进程
if (CreateProcess(NULL, command, NULL, NULL, TRUE, 0, NULL, NULL,
&si, &ProcessInformation))
{
ProcessHandle = ProcessInformation.hProcess;
CloseHandle(ProcessInformation.hThread);
}
else
{
CloseHandle(hRead);
CloseHandle(hWrite);
CloseHandle(ShellStdinPipe);
CloseHandle(ShellStdoutPipe);
return -2; //创建失败返回-2
}
CloseHandle(ShellStdinPipe);
CloseHandle(ShellStdoutPipe);
*in = hWrite;
*out = hRead;
return 0;
}