Search code examples
cargumentsexecprogram-entry-pointargv

C Alternatives of EXEC() to Support Arguments?


In C I know what arguments passed to the program start with index 1. Let's suppose the first argument (which is in index 1) is some arbitrary text, argument 2 in program location/name and ALL others are arguments for that program (I don't know any limit)

After I forked a child process how can I make it run that program?

This is an example of what I used to do when there were no arguments passed:

int main (int argc, char *argv[]){
    run_prog(argv[2]);
}

void run_prog(char *prog_name)
{
    execl(prog_name, prog_name, NULL);
}

and this is how I used to run it:

./my_prog ignore_this hello_world.out

Solution

  • You can use the execv variant of the exec family of calls. From the execv man page:

    The execv(), execvp(), and execvpe() functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program. The first argument, by convention, should point to the filename associated with the file being executed. The array of pointers must be terminated by a NULL pointer.

    Since argv is already an array in the required format all you need to do is skip the args you are not interested in:

    void run_prog(char *argv[])
    {
        execv(argv[2], &argv[2]);
    }
    
    int main (int argc, char *argv[])
    {
        run_prog(argv);
    }