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 <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
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?