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

Passing argument from command line in my main function and use execvp

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

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

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