简体   繁体   中英

Executing a command with execvp

I have an array of command strings I want to execute by calling execvp() :

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

How do I execute the command with execvp ?

Here's a possible usage example for you. This takes the command to execute from its arguments or you can uncomment the hardcoded example.

I recommend you look up the used commands in their respective man pages. For execvp , the declaration is

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

argv[0] should be the same as file by convention and argv should be NULL -terminated.

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM