//cpulimit.c
/**
* Simple program to limit the cpu usage of a process
*
* Author: Angelo Marletta (marlonx80@hotmail.com)
*/
 
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/resource.h>
 
//pid of the controlled process
int pid;
 
//SIGINT signal handler
void quit(int sig) {
    //let the process continue if it's stopped
    kill(pid,SIGCONT);
    exit(0);
}
 
int main(int argc, char **argv) {
 
    if (argc!=3) {
        fprintf(stderr,"Usage: %s {pid} {max cpu percentage}\n",argv[0]);
        exit(1);
    }
    pid=atoi(argv[1]);
    int limit=atoi(argv[2]);
    if (limit>100) {
        fprintf(stderr,"limit must be in the range 0-100\n");
        exit(1);
    }
    //if possible renice this process, so it has more responsiveness
    if (setpriority(PRIO_PROCESS,getpid(),-20)!=0) {
        printf("Warning: cannot renice.\nTo work better you should run this program as root.\n");
    }
    signal(SIGINT,quit);
 
    //time quantum in microseconds
    int period=100000;
    struct timespec twork,tsleep; //time to work, and time to sleep
    twork.tv_sec=0;
    twork.tv_nsec=period*limit*10;
    tsleep.tv_sec=0;
    tsleep.tv_nsec=period*(100-limit)*10;
 
    while(1) {
        if (kill(pid,SIGSTOP)!=0) break;
        nanosleep(&tsleep,NULL);
        if (kill(pid,SIGCONT)!=0) break;
        nanosleep(&twork,NULL);
    }
 
    perror("kill()");
    exit(1);
}

usage :

gcc -o cpulimit cpulimit.c
cpulimit {seti pid} {cpu limit}
ressources/utils/cpulimit.txt · Last modified: 2013/06/16 22:51 (external edit)
 
 
Creative Commons License Powered by PHP Valid XHTML 1.0 April