execvp system call problems

869 views Asked by At

I'm making a small shell to better understand C. I use the POSIX getline function to get a string and split it into tokens by the whitespace. But when I'm calling execvp() to make the system call, nothing happens.. If someone cal point to me where the issue I have, clearly I'm missing something probably small..(I didn't include the whole code so some curly brackets will be missing at the bottom, just ignore this sorry) Many thanks

        char *args[3];  // array for the command and arguments

        cmd = strtok(line, " ");            
        args[0] = cmd;              // put the first command in the array

        for(int i = 1; i < whitespace+1; ++i){

            cmd = strtok('\0', " \n");
            args[i] = cmd;              // fill the array of strings with the arguments
        }
        args[2] = '\0';    // assign last element to NULL


        pid = fork();

        if(pid != 0){        
            waitpid(-1, &stat, 0); 
        }
        else{

            char *const *test[1];
            test[0] = '\0';
            execvp("/bin/ls", test[0]);
            execvp(args[0], &args[1]);

Right at the end is where I'm having issues, I tried both versions of execvp seperately but neither work and I've been stuck on this issue for 2 days.. Any help appreciated thanks

1

There are 1 answers

0
user3386109 On BEST ANSWER

Here is a minimal example of how to make execvp work.

#include <stdio.h>
#include <unistd.h>

int main( void )
{
    char *test[2];              // declare an array of pointers
    test[0] = "/bin/ls";        // first arg is the path to the executable
    test[1] = NULL;             // NULL terminator indicates no additional args
    execvp( test[0], test );
}

Here's an explanation from the man page for execvp

The first argument, by convention, should point to the file name associated with the file being executed. The array of pointers must be terminated by a NULL pointer.