piątek, czerwca 12, 2009

LicensedCpus.c

Program dedykowany wszystkim dyrektorom IT, którzy nie wiedzą, że software licencjonowany na 2 CPU można uruchamiać na serwerze z 4 CPU.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sched.h>
#include <errno.h>
#include <string.h>

int get_num_cpus() {
int cnt = 0;
char *line = NULL;
size_t len = 0;
FILE *fp = fopen("/proc/stat", "r");
if (fp!=NULL) {
while (getline(&line, &len, fp)!=-1) {
if (line!=NULL && strstr(line, "cpu")!=NULL)
cnt++;
}
if (line)
free(line);
fclose(fp);
cnt--;
}
return cnt;
}

int main(int argc, char** argv) {
static cpu_set_t mask;
int user_mask, i=0, max, m=0;

if (argc<3) {
fprintf(stdout, "Usage: %s cpu_mask(int) command(full_path)\n",argv[0]);
exit(0);
}

user_mask = atoi(argv[1]);
max = 1 << (get_num_cpus()-1);
CPU_ZERO(&mask);
for (i=0; i<max; i++) {
if ( (user_mask & (1 << i)) == (1 << i)) {
CPU_SET(i, &mask);
m |= (1<<i);
}
}

if (sched_setaffinity(0, sizeof(mask), &mask)==0) {
fprintf(stdout, "Running %s with mask %d, cpus=%d\n", argv[2], m, max);
return execv(argv[2], argv+2);
}
else {
fprintf(stderr, "Cannot set cpu mask: %s. Effective mask was %d\n", strerror(errno), m);
exit(1);
}
}

0 komentarze: