使用execvp执行命令

时间:2015-10-11 23:39:21

标签: c execvp

我想通过调用execvp()来执行一系列命令字符串:

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

如何使用execvp执行命令?

1 个答案:

答案 0 :(得分: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;
}