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, status = [%d]\n", 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, signal number = [%d]\n", 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, status = [%d]\n", WEXITSTATUS(ret));
ret = 0;
}
else
{
printf("shell_system run shell script fail, status = [%d]\n", WEXITSTATUS(ret));
ret = -1;
}
}
else if(WIFSIGNALED(ret))
{
printf("shell_system abnormal termination, signal number = [%d]\n", WTERMSIG(ret));
ret = -1;
}
else if(WIFSTOPPED(ret))
{
printf("shell_system process stopped, signal number = [%d]\n", WSTOPSIG(ret));
ret = -1;
}
else
{
printf("shell_system run shell unknown error, ret = [%d]\n", 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;
}