linux下执行shell命令的popen和system函数封装:
#include
#include
#include
#include
#include
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;
}
总结
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
小编个人微信号 jb51ccc
喜欢与人分享编程技术与工作经验,欢迎加入编程之家官方交流群!