经过阅读 Linux下使用system()函数一定要谨慎 和 linux下代替system的基于管道的popen和pclose函数 实现了在C语言编程封装的system接口
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
typedef void (*sighandler_t)(int);
int sys_cmd_run(const char *cmd, int flag)
{
//printf("[%s]%s flag[%d]\r\n",__FUNCTION__, cmd, flag);
if( NULL == cmd )
{
//如果cmd为空,返回非零值,一般为1
return 1;
}
if( strlen(cmd) ==0 )
{
//如果cmd为空,返回非零值,一般为1
return 2;
}
if (flag == 0)
{
pid_t status;
sighandler_t old_handler;
old_handler = signal(SIGCHLD, SIG_DFL);
status = system(cmd);
signal(SIGCHLD, old_handler);
//printf("[%s] status=%d\r\n",__FUNCTION__,status);
if(status < 0)
{
// 这里务必要把errno信息输出或记入Log
printf("[%s]%s\t error: %s", __FUNCTION__, cmd, strerror(errno));
}
if(WIFEXITED(status))
{
//取得cmd 执行结果
//printf("[%s]%s child process normal termination [%d], cmd return [%d]\r\n",__FUNCTION__, cmd, status, WEXITSTATUS(status));
}
else if(WIFSIGNALED(status))
{
//如果cmd 被信号中断,取得信号值
printf("[%s]%s child process abnormal termination [%d], signal number [%d]\r\n",__FUNCTION__, cmd, status, WTERMSIG(status));
}
else if(WIFSTOPPED(status))
{
//如果cmdstring被信号暂停执行,取得信号值
printf("[%s]%s child process stopped [%d], signal number [%d]\r\n",__FUNCTION__, cmd, status, WTERMSIG(status));
}
else
{
printf("[%s] system(%s) return [%d]\r\n",__FUNCTION__, cmd, status);
}
return status;
}
else
{
FILE *fp;
int rc = 0;
/*执行预先设定的命令,并读出该命令的标准输出*/
fp = popen(cmd, "r");
if(NULL == fp)
{
printf("[%s]%s\t popen error: %s", __FUNCTION__, cmd, strerror(errno));
return -1;
}
/*等待命令执行完毕并关闭管道及文件指针*/
rc = pclose(fp);
if( rc <0 )
{
// 这里务必要把errno信息输出或记入Log
printf("[%s]%s\t pclose error: %s", __FUNCTION__, cmd, strerror(errno));
}
if(WIFEXITED(rc))
{
//取得cmd 执行结果
//printf("[%s]%s child process normal termination [%d], cmd return [%d]\r\n",__FUNCTION__, cmd, rc, WEXITSTATUS(rc));
}
else if(WIFSIGNALED(rc))
{
//如果cmd 被信号中断,取得信号值
printf("[%s]%s child process abnormal termination [%d], signal number [%d]\r\n",__FUNCTION__, cmd, rc, WTERMSIG(rc));
}
else if(WIFSTOPPED(rc))
{
//如果cmdstring被信号暂停执行,取得信号值
printf("[%s]%s child process stopped [%d], signal number [%d]\r\n",__FUNCTION__, cmd, rc, WTERMSIG(rc));
}
else
{
printf("[%s]%s pclose return [%d]\r\n",__FUNCTION__, cmd, rc);
}
return rc;
}
}