linux编程,慎用system()

经过阅读 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;
	}
}  


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值