匿名管道通讯实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | // 生成bat文件 std::ofstream ofs( "network_check.bat" ); ofs << "@echo Webservice connect check begin" << std::endl; ofs << "@echo 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( "Webservice connect check end" ) != std::string::npos) { break ; } } // 释放资源 CloseHandle(hWrite); CloseHandle(hRead); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合终身会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步