Printing the PID of a program immediately before it runs I need to know (for monitoring purposes) the PID of a program immediately before I start it. There could be multiple of the same program launched at the same time, so monitoring ps or top isn't really an option. It dawned on me as I was exploring various bash-related options that I could make use of C's exec functions to try and pull this off. With that in mind, I whipped up this little piece of code:

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;sys/types.h&gt;
#include &lt;unistd.h&gt;

int main(int argc, char **argv)
{
    char **argv_copy;
    int i;

    if (argc &gt;= 2)
    {
        argv_copy = malloc(argc * sizeof *argv_copy);

        for (i = 1; i &lt; argc; i++)
        {
            argv_copy[i-1] = argv[i];
        }
        argv_copy[argc] = (char *) NULL;

        printf("%lu\n", (long unsigned) getpid());

        execvp(argv[1], argv_copy);
    }
    return 0;
}


It works as expected - it immediately prints out the PID of the process and then loads the actual process I want to run. What I'm not convinced of is the security or robustness of this little hack. I don't need it to be 100% bullet-proof security-wise, but if you can drive an SUV through it I'd like to know.

Could I get some advice on these two areas specifically?
Bug
This line:

    argv_copy[argc] = (char *) NULL;


should be:
    argv_copy[argc-1] = NULL;

You are removing one argument so you need to terminate the array at the right place.
Copy unneeded
Instead of:

    execvp(argv[1], argv_copy);


you could do:
    execvp(argv[1], &amp;argv[1]);

and avoid making a copy.