匿名管道通讯实现
程序员文章站
2022-10-15 22:06:32
// 生成bat文件 std::ofstream ofs("network_check.bat"); ofs << "@echo 360os Webservice connect check begin" << std::endl; ofs << "@echo 360os Webservice co... ......
// 生成bat文件
std::ofstream ofs("network_check.bat");
ofs << "@echo 360os webservice connect check begin" << std::endl;
ofs << "@echo 360os webservice connect check end" << std::endl;
ofs.close();
// 创建管道
security_attributes sa;
sa.nlength = sizeof(security_attributes);
sa.binherithandle = true;
sa.lpsecuritydescriptor = null;
handle hread, hwrite;
if (!createpipe(&hread, &hwrite, &sa, 0))
{
dword derr = getlasterror();
cstring szinfo;
szinfo.format(_t("fail to create pipe error: %d"), derr);
outinfo = szinfo;
return false;
}
// 创建进程
startupinfo si = {sizeof(startupinfo)};
si.hstderror = hwrite;
si.hstdoutput = hwrite;
si.wshowwindow = sw_hide;
si.hstdinput = hread;
si.dwflags = startf_useshowwindow | startf_usestdhandles;
process_information pi;
cstring strcmd = _t("cmd.exe /c network_check.bat");
if (!createprocess(null, strcmd.getbuffer(), null, null, true, null, null, null, &si, &pi))
{
outinfo = _t("createprocess failed");
closehandle(hwrite);
closehandle(hread);
return false;
}
// 读取管道信息
std::string strresult;
char buff[1025] = {0};
while (1)
{
dword dwread = 0;
peeknamedpipe(hread, buff, 4, &dwread, null, null);
if (0 == dwread)
{
continue;
}
zeromemory(buff, sizeof(buff));
readfile(hread, buff, 1024, &dwread, null);
strresult += buff;
char* pstr = new char[strlen(buff) + 1];
strcpy_s(pstr, strlen(buff) + 1, buff);
::sendmessage(m_hwnd, wm_msg_testinfo, (wparam)pstr,0);
if (strresult.find("360os webservice connect check end") != std::string::npos)
{
break;
}
}
// 释放资源
closehandle(hwrite);
closehandle(hread);
closehandle(pi.hthread);
closehandle(pi.hprocess);
下一篇: 真不愧是教语文的啊!