版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/t60339/article/details/76919372
创建管道
std::string sLog;
HANDLE hRead1, hWrite1, hRead2, hWrite2;
SECURITY_ATTRIBUTES sat;
sat.nLength = sizeof(SECURITY_ATTRIBUTES);
sat.bInheritHandle = true;
sat.lpSecurityDescriptor = nullptr;
if(!CreatePipe(&hRead1,&hWrite1,&sat,0))
{
sLog = "管道1创建失败...";
return false;
}
if(!CreatePipe(&hRead2,&hWrite2,&sat,0))
{
sLog = "管道2创建失败...";
CloseHandle(hRead1);
CloseHandle(hWrite1);
return false;
}
创建进程并重定向
STARTUPINFO startupinfo;
startupinfo.cb = sizeof(STARTUPINFO);
GetStartupInfo(&startupinfo);
startupinfo.hStdError = hWrite2;
startupinfo.hStdOutput = hWrite2;
startupinfo.hStdInput = hRead1;
startupinfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
startupinfo.wShowWindow = SW_HIDE;
PROCESS_INFORMATION pinfo;
std::string sCmd = "plink.exe -ssh -P 22 [email protected]";
if(!CreateProcess(NULL, (LPSTR)sCmd.c_str(), NULL, NULL, TRUE, NULL, NULL, NULL, &startupinfo, &pinfo))
{
sLog = "进程创建失败...";
CloseHandle(hRead1);
CloseHandle(hWrite1);
CloseHandle(hRead2);
CloseHandle(hWrite2);
return false;
}
CloseHandle(pinfo.hThread);
CloseHandle(pinfo.hProcess);
发送数据
DWORD byteWrite = 0;
sCmd = "help\r\n";
WriteFile(hWrite1, sCmd.c_str(), sCmd.length(), &byteWrite, NULL);
if(byteWrite == sCmd.length())
return true;
else
return false;
读取数据
读之前应先查看管道是否有数据
DWORD byteRead;
if(!PeekNamedPipe(hRead2,NULL,0,NULL,&byteRead,NULL))
{
return false;
}
if(byteRead <= 0)
{
sLog = "管道无数据\n";
return true;
}
char buffer[1024] = {0};
ReadFile(hRead2, buffer, 4095, &byteRead, NULL);