前端之家收集整理的这篇文章主要介绍了
执行shell命令的popen和system函数封装,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
linux下执行shell命令的popen和system函数封装:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/wait.h>
int shell_popen(const char * cmd)
{
if(!cmd)
{
printf("shell_popen cmd is NULL!\n");
return -1;
}
printf("shell_popen : %s\n",cmd);
FILE * fp;
int ret;
char buf[1024];
if((fp = popen(cmd,"r")) == NULL)
{
printf("shell_popen error: %s/n",strerror(errno));
return -1;
}
else
{
while(fgets(buf,sizeof(buf),fp))
{
if(buf[strlen(buf)-1] == '\n')
{
buf[strlen(buf)-1] = '\0';
}
printf("%s\n",buf);
}
if((ret = pclose(fp)) == -1)
{
printf("shell_popen fail = [%s]\n",strerror(errno));
return -1;
}
else
{
if(WIFEXITED(ret))
{
if(0 == WEXITSTATUS(ret))
{
printf("shell_popen run shell script successfully,status = [%d]\n",WEXITSTATUS(ret));
ret = 0;
}
else
{
printf("shell_popen run shell script fail,WEXITSTATUS(ret));
ret = -1;
}
}
else if(WIFSIGNALED(ret))
{
printf("shell_popen abnormal termination,signal number = [%d]\n",WTERMSIG(ret));
ret = -1;
}
else if(WIFSTOPPED(ret))
{
printf("shell_popen process stopped,WSTOPSIG(ret));
ret = -1;
}
else
{
printf("shell_popen run shell unknown error,ret = [%d]\n",ret);
ret = -1;
}
}
}
return ret;
}
int shell_system(const char * cmd)
{
if(!cmd)
{
printf("shell_system cmd is null\n");
return -1;
}
printf("shell_system : %s\n",cmd);
int ret = 0;
typedef void (*sighandler_t)(int);
sighandler_t old_handler;
old_handler = signal(SIGCHLD,SIG_DFL);
ret = system(cmd);
signal(SIGCHLD,old_handler);
if(ret == -1)
{
printf("shell_system fail = [%s]\n",strerror(errno));
ret = -1;
}
else
{
if(WIFEXITED(ret))
{
if(0 == WEXITSTATUS(ret))
{
printf("shell_system run shell script successfully,WEXITSTATUS(ret));
ret = 0;
}
else
{
printf("shell_system run shell script fail,WEXITSTATUS(ret));
ret = -1;
}
}
else if(WIFSIGNALED(ret))
{
printf("shell_system abnormal termination,WTERMSIG(ret));
ret = -1;
}
else if(WIFSTOPPED(ret))
{
printf("shell_system process stopped,WSTOPSIG(ret));
ret = -1;
}
else
{
printf("shell_system run shell unknown error,ret);
ret = -1;
}
}
return ret;
}
int main(int argc,char* argv[])
{
if(argc <= 1)
{
return 0;
}
printf("-----------------------------------------\n");
shell_popen(argv[1]);
printf("-----------------------------------------\n");
shell_system(argv[1]);
return 0;
}
原文链接:https://www.f2er.com/bash/389605.html