#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