在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