Executing a command with execvp

帅比萌擦擦* 提交于 2019-12-14 02:39:02

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/33071302/executing-a-command-with-execvp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!