How to use execv and execvp

Step 1: First, we need to Generate an "executable" which takes 4 command line arguments.


 Neelkanth_39$ cat command_line_args_binary.c
#include <stdio.h>

int main( int argc, char *argv[] )  {

    if( argc == 5 ) {
        printf("The argument supplied is process name:%s  arguments:%s %s %s %s\n",
                    argv[0],
                    argv[1],
                    argv[2],
                    argv[3],
                    argv[4]);
    }
    else if( argc > 5 ) {
        printf("Too many arguments supplied.\n");
    }
    else {
        printf("4 arguments expected\n");
    }
}

Neelkanth_39$ gcc -o command_line_args_binary command_line_args_binary.c
Neelkanth_39$ ./command_line_args_binary
4 arguments expected
Neelkanth_39$ ./command_line_args_binary 1 2 3 4
The argument supplied is process name:./command_line_args_binary  arguments:1 2 3 4

Step 2: Pass the above generated path of executable and it's arguments to execvp

Neelkanth_39$
Neelkanth_39$ cat execvp_example.c
#include <stdio.h>
#include <unistd.h>

void main() {
    char *name[] = {
        "./command_line_args_binary",        /* 1st arguement absolute path of the executable*/
        "1",
        "2",
        "3",
        "4",
        NULL
    };
    execvp(name[0], name);
}


Neelkanth_39$
Neelkanth_39$ gcc -o execvp_example execvp_example.c
Neelkanth_39$ ./execvp_example
The argument supplied is process name:./command_line_args_binary  arguments:1 2 3 4
Neelkanth_39$
Neelkanth_39$
Neelkanth_39$


Step 3: Pass the above generated executable and it's arguments to execv

Neelkanth_39$ cat execv_example.c
#include <stdio.h>
#include <unistd.h>

void main()
{
    char *name[] = {
        "command_line_args_binary",    /* 1st argument name of the executable */
        "1",
        "2",
        "3",
        "4",
        NULL
    };

    execv(name[0], name);
}



Neelkanth_39$ gcc -o execv_example execv_example.c
Neelkanth_39$ ./execv_example
The argument supplied is process name:./command_line_args_binary  arguments:1 2 3 4