#include <windows.h> #include <stdlib.h> void go(HWND hwnd) { char * ping = "IPCONFIG /all"; // 命令 char pbuf[1024]; // 缓存 DWORD len; STARTUPINFO si; PROCESS_INFORMATION pi; HANDLE hRead1, hWrite1; // 管道读写句柄 BOOL b; SECURITY_ATTRIBUTES saAttr; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; // 管道句柄是可被继承的 saAttr.lpSecurityDescriptor = NULL; // 创建匿名管道,管道句柄是可被继承的 b = CreatePipe(&hRead1, &hWrite1, &saAttr, 1024); if (!b) { MessageBox(hwnd, "管道创建失败。","Information",0); return ; } memset(&si, 0, sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; si.hStdOutput = hWrite1; // 设置需要传递到子进程的管道写句柄 // 创建子进程,运行ping命令,子进程是可继承的 if (!CreateProcess(NULL, ping, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) { itoa(GetLastError(), pbuf, 10); MessageBox(hwnd, pbuf,"Information",0); CloseHandle(hRead1); CloseHandle(hWrite1); return ; } // 写端句柄已被继承,本地则可关闭,不然读管道时将被阻塞 CloseHandle(hWrite1); // 读管道内容,并用消息框显示 len = 1000; DWORD l; while (ReadFile(hRead1, pbuf, len, &l, NULL)) { if (l == 0) break; pbuf[l] = '\0'; MessageBox(hwnd, pbuf, "Information",0); len = 1000; } MessageBox(hwnd, "ReadFile Exit","Information",0); CloseHandle(hRead1); return ; } int main(int argc, char* argv[]) { go( NULL ); return 0; }
文章转载自:http://blog.csdn.net/lpc_china/article/details/5847260