使用system将输出结果输出到某个文件,读取该文件并删掉文件就可以替换popen方式,原因是popen可能导致大量的pipe/socket文件打开未关闭
int get_cmd_result(char *shellcmd, char *buffer , int size)
{
char cmdbuf[1024] = "0";
int ret = 0;
FILE *fp = NULL;
do
{
if( !shellcmd || !buffer )
{
break;
}
sprintf(cmdbuf, "%s > %s", shellcmd, SHELLCMD_INFO_FILE);
ret = system(cmdbuf);
if( -1 == ret || 127 == ret )
{
break;
}
fp = fopen(SHELLCMD_INFO_FILE, "r");
if(NULL == fp)
{
break;
}
memset(buffer, 0, size);
fread(buffer, size, 1, fp);
ret = strlen(buffer);
if(0 == ret)
{
break;
}
if('\n' == buffer[ret-1])
{
buffer[ret-1] = '\0';
}
unlink(SHELLCMD_INFO_FILE);
fclose(fp);
return 0;
}while(0);
if(fp)
{
fclose(fp);
}
return -1;
}