执行与execvp命令 [英] Executing a command with execvp

查看:115
本文介绍了执行与execvp命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有命令字符串数组我想执行调用 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];
...

我如何与 execvp

推荐答案

下面是给你一个可能的使用例子。这需要的命令,从它的参数执行,也​​可以取消对硬codeD的例子。

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

我建议你在它们各自的手册页查找的命令。
对于 execvp ,该声明是

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] 应该是一样的文件按约定和 argv的 NULL 封端。

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

这篇关于执行与execvp命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆