一种在linux下启动shell进程并取得控制台输出的方法

windows下通过如下方法可以实现启动一个shell进程并等待进程结束取得进程返回值
//SHELLEXECUTEINFO ShExecInfo = {0};
nRetCode = ShellExecuteEx(&ShExecInfo);
WaitForSingleObject(ShExecInfo.hProcess, INFINITE);
GetExitCodeProcess(ShExecInfo.hProcess, &dwRetCode);

linux下无论fork() execXXX() system() waitpid()都无法实现类似需求。
用如下方法可以实现类似需求,前提是被调进程需要在控制台上输出如下内容 "my exit code is XXX"
int pipe_execute(const char * cmdstring){
char buff[512];
FILE *fstream=NULL;
int ret = -1;
memset(buff,0,sizeof(buff)); 
if(NULL==(fstream=popen(cmdstring,"r")))      
{      
fprintf(stderr,"execute command [%s] failed: %s",cmdstring,strerror(errno));      
return -1;      
}
while (fgets(buff, sizeof(buff), fstream))
{
printf(">%s",buff);
int t = 0;
if (sscanf(buff, " my exitcode is  %d", &t))
{
ret = t;
printf("|fetched result %d", ret);
}
}    
pclose(fstream);
return ret;
}
posted @ 2014-11-09 19:55  AllyDale  阅读(64)  评论(0)    收藏  举报