创建一个进程和两个管道,实现与进程通信
// createprocess_.cpp : 定义控制台应用程序的入口点。 // #include <Windows.h> #include <stdio.h> #include <stdlib.h> #include <tchar.h> #include <conio.h> #include <windows.h> #include <MMSystem.h> int main(int argc, char* argv[]) { //Main_t: char commanline[40]; char Inch; char cnt = 0; char *pComman; TCHAR szCommanLine[] = TEXT("C:\\Documents and Settings\\Administrator\\My Documents\\Visual Studio 2010\\....exe"); TCHAR szCommandLine[] = TEXT("openvpn --config client.ovpn"); DWORD dwMode; HANDLE hStdinRead, hStdinWrite, hStdoutRead, hStdoutWrite; SECURITY_ATTRIBUTES sa; STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory((&si),sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_FORCEONFEEDBACK; ZeroMemory((&pi),sizeof(pi)); sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; CreatePipe(&hStdinRead, &hStdinWrite, &sa, 0); CreatePipe(&hStdoutRead, &hStdoutWrite, &sa, 0); si.cb = sizeof(STARTUPINFO); si.lpReserved = si.lpDesktop = si.lpTitle = NULL; si.dwFlags = STARTF_USESTDHANDLES; si.cbReserved2 = 0; si.lpReserved2 = NULL; si.hStdInput = hStdinRead; si.hStdOutput = hStdoutWrite; si.hStdError = hStdoutWrite; if (!CreateProcess(szCommanLine,//szCommanLine szCommandLine,//NULL NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, NULL, NULL, &si, &pi) ) { char ch; printf("Create Process false:%d\n",GetLastError()); printf("Do you want try agin?(Y/N)"); ch = getchar(); if (ch=='Y') { CloseHandle(pi.hProcess); CloseHandle(pi.hThread); system("cls"); // goto Main_t; exit(0); } } else { printf("The application program you want already execute.....\n"); //wait for the process exits. WaitForSingleObject(pi.hProcess,INFINITE); printf("The program is closing....\n"); //close the process and thread handles. CloseHandle(pi.hProcess); CloseHandle(pi.hThread); // system("cls"); // goto Main_t; } char lpBuffer[256]; memset(lpBuffer,0,sizeof(lpBuffer)); DWORD nBytesRead; while(1) { if (ReadFile(hStdoutWrite,lpBuffer,sizeof(lpBuffer) - 1,&nBytesRead,NULL)) { printf("%s\n",lpBuffer); } else Sleep(100); } return 0; }
上面程序没有对一些函数调用的返回参数的判断,这是个不好的习惯。。。。鉴
这个程序使用了createpipe and createprocess 可以创建一个进程。
进程创建的参数,第一个参数不为空则必定为以.exe结尾的字符串;第二个参数根据第一个参数而不同,一般为命令行。
世界如此的美好,江山如此的多娇!
---阳光正能量--->>>>>>>>>>>>>>>