#define CPULIMITPATH "/usr/sbin/cpulimit" #include #include #include pid_t start_command(char *, char * const *); int main(int argc, char ** argv) { pid_t child_pid; char ** argumentspp; int i; char childpida[12]; char * const limcmdpp[] = { CPULIMITPATH, "-l1", "-b", "-p", childpida, /* [4] this gets changed later*/ NULL }; /* This array holds the arguments list. Must start with the name of the * command and end with NULL */ if(!(argumentspp = malloc(sizeof(char *) * (argc + 1)))) { perror("malloc"); exit(1); } if(argc < 2) { puts("This program starts your program in the background, and then \n" "sees that its cpu use is limited. Currently invokes cpulimit. \n" "There's a lot of room for improvement, like skipping cpulimit \n" "and just throttling the program here instead of using cpulimit. \n" "and exiting. \n" "Enter the program you want to run and its arguments as arguments"); exit(0); } argumentspp[0] = argv[1]; /* Copy the arguments over */ for(i = 2; i < argc; i++) { argumentspp[i - 1] = argv[i]; } argumentspp[i - 1] = NULL; child_pid = start_command(argumentspp[0], argumentspp); /* Run cpulimit on it */ snprintf(childpida, 12, "%d", child_pid); start_command(CPULIMITPATH, limcmdpp); return 0; } pid_t start_command(char * pathp, char * const * argvpp) { pid_t childpid; childpid = fork(); switch(childpid) { case -1: return -1; case 0: /* Child * * Thank you stack overflow 1618756 */ setsid(); chdir("/"); execvp(pathp, argvpp); perror(pathp); exit(0); default: /* Parent */ return childpid; } }