Code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <signal.h>
#include <math.h>
// RLIM_INFINITY - UNLIMITED
// RLIMIT_CPU - CPU TIME / IN SEC
// RLIMIT_AS - TOTAL VIRTUAL MEMORY
// RLIMIT_RSS - TOTAL RESIDENT SIZE
// RLIMIT_DATA - The RLIMIT_DATA limit specifies the maximum
// amount of bytes the process data segment can occupy.
// The data segment for a process is the area in which dynamic memory is located
// (that is, memory allocated by malloc() in C,
//or in C++, with new()).
static void signal_beforedeath(int signo)
{
fprintf(stderr,"\nsignal recvied %d \n",signo);
sleep(5);
//exit(0);
}
int main (int argc, char *argv[])
{
struct rlimit tp,hh,core;
struct rusage la;
int i,s1,s2;
char *s;
core.rlim_cur=0;
core.rlim_max=0;
setrlimit(RLIMIT_CORE,&core); // GOOD!! NO CORE FILES WILL BE CREATED.
s1=RLIMIT_CPU;
s2=RLIMIT_DATA;
if ((getrlimit(s1,&tp)==0)&&(getrlimit(s2,&hh)==0))
{
printf("CPU LIMIT: %d %d\nMEMORY LIMIT %d %d\n",tp.rlim_cur,tp.rlim_max,hh.rlim_cur,hh.rlim_max);
tp.rlim_cur=1;
tp.rlim_max=2;
hh.rlim_cur=10000000; // 10mb
hh.rlim_max=20000000; // 20mb
if ((setrlimit(s1,&tp)==0)&&(setrlimit(s2,&hh)==0)&&(setrlimit(RLIMIT_AS,&hh)==0))
{
if ((getrlimit(s1,&tp)==0)&&(getrlimit(s2,&hh)==0))
{
printf("CPU LIMIT UPDATED: %d %d (CPU/s)\nMEMORY LIMIT UPDATED %d %d MB/s\n",
tp.rlim_cur,tp.rlim_max,hh.rlim_cur,hh.rlim_max);
signal(SIGSEGV, signal_beforedeath);
// CPU TEST
signal(SIGXCPU, signal_beforedeath);
for (i = 0; i < 50000000; i++)
{
if ((s=malloc(9000000)) == NULL)
{
printf("error on malloc 9MB\n");
}
if (s) free(s);
if ((s=malloc(15000000)) == NULL)
{
printf("error on malloc 15MB\n");
}
if (s) free(s);
if ((s=malloc(25000000)) == NULL)
{
printf("error on malloc 25MB\n");
}
if (s) free(s);
getrusage(RUSAGE_SELF,&la);
//printf("[%d][%d][%d]",ENOMEM,errno,s2);
printf("resident: %d\n",la.ru_maxrss);
printf("total amount of memory: %d\n",la.ru_ixrss);
printf("CPU: %d\n",la.ru_idrss);
printf("CPU: %d\n",la.ru_isrss);
printf("CPU: %d\n",la.ru_minflt);
printf("CPU: %d\n",la.ru_majflt);
printf("CPU: %d\n",la.ru_nswap);
printf("CPU: %d\n",la.ru_inblock);
printf("CPU: %d\n",la.ru_oublock);
printf("CPU: %d\n",la.ru_msgsnd);
printf("CPU: %d\n",la.ru_msgrcv);
printf("CPU: %d\n",la.ru_nsignals);
printf("CPU: %d\n",la.ru_nvcsw);
printf("CPU: %d\n",la.ru_nivcsw);
// sleep(2);
}
}
else
{
printf("Call failed 2\n");
}
}
}
else
{
printf("Call failed 1\n");
}
return 0;
}