int ExeCmdByPopen(char *pCmd, char *pBuf, unsighed int len)
{
int count = 2000; /*最多读取2000行*/
FILE *fp = NULL;
char szRead[1024] = {0};
char *pTmp = NULL;
unsighed int nLen = 0;
int status = 0;
pid_t pid;
if(NULL == pCmd || 0 == len)
{
return XERROR;
}
fp = my_popen(pCmd, "r", &pid);//通过一个脚本中转,在脚本中关闭所有的文件描述符,exec fd
if(NULL == fp)
{
perror("XOS_ExeCmdByPopen:popen() failed");
return XERROR;
}
sleep(1);
if(NULL != pBuf)
{
pBuf[0] = '\0';
pTmp = pBuf;
while(count > 0 && NULL != fgets(pTmp, len, fp))
{
nLen = strlen(pTmp);
if(0 == nLen)/*缓存区不够*/
{
break;
}
pTmp += nLen;
len -= nLen;
count--;
}
}
else
{
/*防止脚本在执行的时候可能需要进行写操作,但这边父进程函数退出了,导致管道破坏*/
szRead[0] = '\0';
while(count > 0 && NULL != fgets(szRead, sizeof(szRead)-1, fp))
{
count--;
}
}
/* 下面 close和waitpid组合 相当于pclose.
-- 为了解决XOS_Popen与pclose搭配会产生僵尸进程的问题 */
close(fileno(fp));
while(waitpid(pid, &status, 0) < 0)
{
if(errno != EINTR)
{
status = -1;
break;
}
}
return status;
}