int executeCMD(const char *cmd, char *result)
{
if(cmd==NULL)
{
ERR_MSG("The cmd is null");
return -1;
}
int status;
int ret;
char ps[1024]={0};
strcpy(ps, cmd);
strcat(ps," 2>>/dev/null");
FILE *ptr;
ptr=popen(ps, "r");
size_t read_len = 0;
if(!ptr)
{
ERR_MSG_FORMAT("popen %s error/n", ps);
return -1;
}
int len = 1024;
char buf[1024]={0};
while(1)
{
read_len = fread(buf,1,len-1,ptr);
if(ferror(ptr))
{
ERR_MSG("fread error");
pclose(ptr);
return -1;
}
else
{
buf[read_len-1] = '\0';
strcat(result,buf);
memset(buf,0,len);
if(read_len < len -1) break;
}
}
status = pclose(ptr);
if(WIFEXITED(status))
{
ret = WEXITSTATUS(status);
LOG_DEBUG_FORMAT("status = [%d], ret = [%d], errno:[%s]", status, ret, strerror(errno));
}
else
{
ERR_MSG("Command exit abnormally!");
ret = -1;
}
return ret;
}
Linux 后台执行命令的函数
最新推荐文章于 2023-10-18 16:28:32 发布