c调用程序并失去其输出的方法
c调用程序并得到其输出的方法
1、windows
char buffer[1024]; STARTUPINFO si = {0}; PROCESS_INFORMATION pi = {0}; DWORD bytesRead; SECURITY_ATTRIBUTES sa = {0}; HANDLE hRead = NULL, hWrite = NULL; //设置管道读写句柄 sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; if (!CreatePipe(&hRead, &hWrite, &sa,0)) //创建管道 { return; } si.cb = sizeof(STARTUPINFO); GetStartupInfo(&si); si.hStdError = hWrite; // si.hStdOutput = hWrite; // si.wShowWindow = SW_HIDE; si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; //key step if (!CreateProcess(NULL, command, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi)) { CloseHandle(hWrite); CloseHandle(hRead); return; } WaitForSingleObject(pi.hProcess,INFINITE); // Close process and thread handles. CloseHandle(pi.hProcess); CloseHandle(pi.hThread); CloseHandle(hWrite); memset(buffer, 0, 1024); while(ReadFile(hRead, buffer, 1024, &bytesRead, NULL)) { PRINTLOG(buffer); memset(buffer, 0, 1024); } CloseHandle(hRead);
2、linux
char buf_ps[1024]; char ps[1024]={0}; char result[1024]; FILE *ptr; strcpy(ps, command); if((ptr=popen(ps, "r"))!=NULL) { while(fgets(buf_ps, 1024, ptr)!=NULL) { strcat(result, buf_ps); if(strlen(result)>1024) break; } pclose(ptr); ptr = NULL; } else { printf("popen %s error\n", ps); }command为需要执行的命令(带参数的)
版权声明:本文为博主原创文章,未经博主允许不得转载。