2015-10-11 116 views
1

命令我有命令字符串我想執行的數組通過調用execvp()執行與execvp

char* commands[] = ["ls -l", "ps -a", "ps"]; 
char* command = commands[0]; 
... 

如何執行與execvp的命令?

+2

你必須單獨的命令和參數爲單獨的字符串:你希望每個命令行'{ 「LS」, 「-l」,NULL}'和'fork()的'和'execvp()'一次執行。你最後缺少一個'NULL'指針。 char * commands []'數組的最後一項必須是NULL指針。 –

+1

如果您要從命令行運行命令,它會是什麼樣子? – dbush

+0

如果我要從命令行運行它,它只會是「ls -l」 – user3133300

回答

1

以下是您可能的使用示例。這需要命令從其參數中執行,或者您可以取消註釋硬編碼示例。

我建議您在各自的手冊頁中查找使用的命令。 對於execvp,聲明是

int execvp(const char *file, char *const argv[]); 

argv[0]應該是一樣file按照慣例和argv應該是NULL封端的。

#include <stdlib.h> //exit 
#include <stdio.h> //perror 
#include <unistd.h> 
#include <sysexits.h> 
#include <errno.h> 
#include <sys/wait.h> 

int main(int argc, char** argv){ 
    int pid, status, ret; 
    if((pid=fork())<0) { perror("fork"); exit(EX_OSERR); } 

    if(!pid){ //Child 

    /* 
     char* args[] = { "ps", "-a", (char*)0 }; 
     execvp(args[0], args); 
    */ 

     //Execute arguments, already NULL terminated 
     execvp(argv[1], argv+1); 

    //exec doesn't exit; if it does, it's an error 
     perror(argv[1]); 

    //Convert exec failure to exit status, shell-style (optional) 
     switch(errno){ 
      case EACCES: exit(126); 
      case ENOENT: exit(127); 
      default:   exit(1); 
     } 
    } 

    //Wait on child 
    waitpid(pid, &status, 0); 

    //Return the same exit status as child did or convert a signal termination 
    //to status, shell-style (optional) 

    ret = WEXITSTATUS(status); 
    if (!WIFEXITED(status)) { 
     ret += 128; 
     ret = WSTOPSIG(status); 
     if (!WIFSTOPPED(status)) { 
      ret = WTERMSIG(status); 
     } 
    } 
    return ret; 
}