在我的main函数中从命令行传递参数并使用execvp

时间:2018-01-20 22:06:10

标签: c execvp

我尝试传递命令行参数" ls -l / user / myuser"在我的终端,并在我的主要执行execvp 但不知何故,当我调试代码时,它给了我这个错误。

Debugging terminal

int main(int argc, char *argv[]){
    pid_t pid;
    pid = fork();

    //negative value is failed, 0 is newly created child process
    if(pid < 0){
        fprintf(stderr, "Fork Failed");
        exit(-1);
    }else if(pid == 0){
        //fork() -> child process
        printf("You entered %d commands: \n", argc);
        argv[argc + 1] = NULL;
        execvp(argv[0],argv);
    }else{
        wait(NULL);
        printf("child complete\n");
        exit(0);
    }
   return 0;
}

1 个答案:

答案 0 :(得分:1)

argv[0]是您的可执行文件,在这种情况下您需要传递第二个参数。也不要做argv[argc + 1] = NULL;,因为C标准说argv是NULL终止的。 这应该有效:

int main(int argc, char *argv[]){
    pid_t pid;
    pid = fork();

    //negative value is failed, 0 is newly created child process
    if(pid < 0){
        fprintf(stderr, "Fork Failed");
        exit(-1);
    }else if(pid == 0){
        //fork() -> child process
        printf("You entered %d commands: \n", argc);
        execvp(argv[1],&argv[1]);
    }else{
        wait(NULL);
        printf("child complete\n");
        exit(0);
    }
   return 0;
}