在Linux上,若是一个程序中须要实行shell 指令,能够有如下几种方法: system(): 实行一个shell指令,回来该指令实行后的回来值 popen():实行一个shell指令,从回来的文件描述符中读出指令实行后输出的内容 本身写fork(), dup2(), execl, wait4,经过execl中实行“/bin/sh -c "来获得实行效果 system()只能获得指令实 http://www.star1234.info/linked/20130316.do 行回来值,得不到输出的效果。popen()正好相反。 下面的system_ex()能够兼而有之,它是经过第三种方法来实行shell指令。 int system_ex(char* cmd, char* output, int size) { int fd[2]; pid_t pid; int n, count; int wait_val = 0; if(cmd == NULL){ return -1; } /* no need to save output, use original system() */ if(output == NULL || size <= 0){ return system(cmd); } if (pipe(fd) < 0){ return -1; } if ((pid = fork()) < 0){ close(fd[0]); close(fd[1]); return -1; } else if (pid > 0){//parent close(fd[1]);//close write pipe count = 0; while (count < size){ n = read(fd[0], output count, size-count); if(n <= 0){ break; } count = n; } output[size - 1] = '\0'; /*terminate the string */ close(fd[0]); if (wait4(pid, http://www.star1111.info/linked/20130316.do