Search code examples
cexecvp

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


I try to pass command line argument "ls -l /user/myuser" in my terminal and execute execvp in my main.
But somehow it gives me this error when i am debugging the code.

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

Solution

  • argv[0] is your executable, you need to pass the second argument in this case. Also don't do argv[argc + 1] = NULL; since the C standard says that argv is NULL terminated. This should work:

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