HiveBrain v1.2.0
Get Started
← Back to all entries
patterncModerate

Printing the PID of a program immediately before it runs

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theprogramprintingpidbeforerunsimmediately

Problem

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 
#include 
#include 
#include 

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

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

        for (i = 1; i < 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?

Solution

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], &argv[1]);


and avoid making a copy.

Code Snippets

argv_copy[argc] = (char *) NULL;
argv_copy[argc-1] = NULL;
execvp(argv[1], argv_copy);
execvp(argv[1], &argv[1]);

Context

StackExchange Code Review Q#136026, answer score: 12

Revisions (0)

No revisions yet.