c++调用子进程捕获输出(windows,linux)
Posted qianbo_insist
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c++调用子进程捕获输出(windows,linux)相关的知识,希望对你有一定的参考价值。
1、windows
在windows上使用API函数CreateProcessW函数或者winexe 来启动新的进程,执行cmd命令:
int execute(const TCHAR *childexe)
{
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 false;
}
HANDLE hTemp = GetStdHandle(STD_OUTPUT_HANDLE);
SetStdHandle(STD_OUTPUT_HANDLE,hTemp);
STARTUPINFO si = {0};
PROCESS_INFORMATION pi = {0};
si.cb = sizeof(STARTUPINFO);
GetStartupInfo(&si);
si.hStdError = hWrite;
si.hStdOutput = hWrite; si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
bRet = CreateProcess(NULL,childexe,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi);
if (!bRet))
{
CloseHandle(hWrite);
CloseHandle(hRead);
return false;
}
CloseHandle(hWrite);
char ReadBuff[256] = {0};
while(ReadFile(hRead,ReadBuff,256,&ReadNum,NULL))
{
ReadBuff[ReadNum] = '\\0';
cout << ReadBuff << "--" << ReadNum << endl;
}
cin.get();
return 0;
//WaitForSingleObject(pi.hProcess,INFINITE);
//CloseHandle(pi.hProcess);
//CloseHandle(pi.hThread);
//CloseHandle(hWrite);
//ReadFile(hRead, buffer, MAX_PATH_LENGTH, &bytesRead, NULL);
//CloseHandle(hRead);
}
2、linux
1 system函数可以运行命令行
2 popen打开一个命令行的管道
3 通过fgets获得该管道传输内容
在linux上运行的例子如下:
int g_stop = 0;
void execute(const char *cmd)
{
char buf_ps[1024];
char ps[1024]={0};
FILE *ptr;
strcpy(ps, cmd);
if((ptr=popen(ps, "r"))!=NULL)
{
while(fgets(buf_ps, 1024, ptr)!=NULL)
{
printf("%s\\n",buf_ps);
if(g_stop == 1)
break;
}
pclose(ptr);
ptr = NULL;
}
else
{
printf("popen %s error\\n", ps);
}
}
说明:
1、参数cmd为要执行的命令行,result为命令行运行结果。
2 、输入的cmd命令用… 2>&1 的形式,可以将标准错误读进来
以上是关于c++调用子进程捕获输出(windows,linux)的主要内容,如果未能解决你的问题,请参考以下文章