1#include <sys/types.h>2#include <sys/resource.h>3#include <sys/time.h>4#include <unistd.h>5#include <stdio.h>6#include <math.h>7 8 voidWork ()9 {TenFILE *F; One inti; A Doublex=4.5; -f=tmpfile (); - for(i=0;i<10000; i++); the { -fprintf (F,"Do some output\n");//writes a string to a temporary file 10000 - if(Ferror (f)) - { +fprintf (stderr,"Error writing to temporary file\n"); -Exit1); + } A}//Complete at for(i=0;i<1000000; i++) -X=log (x*x+3.21);//do some arithmetic operations - } - - intMain () - { in structrusage r_usage; - structRlimit R_limit; to intPriority ; + - Work (); theGetrusage (Rusage_self, &r_usage);//The first parameter indicates that only the current program's usage information is returned and is saved in the second argument * $printf"CPU usage:user=%ld.%0 6ld,system=%ld.%0 6ld\n",Panax Notoginseng R_usage.ru_utime.tv_sec,r_usage.ru_utime.tv_usec, -R_USAGE.RU_STIME.TV_SEC,R_USAGE.RU_STIME.TV_USEC);//print out CPU consumption the +priority=getpriority (prio_process, Getpid ()); Aprintf"Current priority =%d\n", priority);//get current priority level the +Getrlimit (Rlimit_fsize,&r_limit);//get current file limit -printf"Current fsize limit:soft=%ld, hard=%ld\n", R_limit.rlim_cur,r_limit.rlim_max); $ $R_limit.rlim_cur=2048; -r_limit.rlim_max=4096; -printf"Setting a 2k file size limit\n"); theSetrlimit (rlimit_fsize,&r_limit); - Wuyi Work (); theExit0); -}
Run effect
1[Email protected]:~/c_program$./Limits2CPU usage:user=0.056000, system=0.0000003Current priority =04Current Fsize limit:soft=-1, hard=-15 Setting a 2k file size limit6[Email protected]:~/c_program$ Ulimit7 Unlimited8[Email protected]:~/c_program$ Nice./Limits9CPU usage:user=0.060000, system=0.000000TenCurrent priority =Ten OneCurrent Fsize limit:soft=-1, hard=-1 ASetting a 2k file size limit
Linux Environment resource restriction routines