天天看點

3程序狀态getrlimit()函數和setrlimit()函數



1修改程序資源限制,軟限制可改,最大值不能超過硬限制,硬限制隻有root使用者可以修改

檢視程序資源限制

cat /proc/self/limits

ulimit -a                                 

2getrlimit()函數和setrlimit()函數

a依賴的頭檔案

#include<sys/time.h>

#include<sys/resource.h>

b函數聲明

int getrlimit(int resource, struct rlimit*rlim);

int setrlimit(int resource, const structrlimit *rlim);

int prlimit(pid_t pid, int resource, conststruct rlimit *new_limit,

                  struct rlimit *old_limit);

函數說明:通過getrlimit,setrlimit,prlimit函數來獲得或者設定資源的limits

描述資訊

the getrlimit() and setrlimit() system calls get and set resource limitsrespectively. each resource has anassociated soft and hard limit,as

defined by the rlimit structure:

          struct rlimit {

              rlim_t rlim_cur; 

/* soft limit */

              rlim_t rlim_max; 

/* hard limit (ceiling for rlim_cur) */

          };

翻譯:這個getrlimit()和setrlimit()函數分别獲得和設定資源的limits,每個資源有一個關聯的軟限制和硬限制,它們被定義在rlimit結構體中。

the soft limit 

is  thevalue that the kernel enforces for the corre‐

      sponding resource. the hard limitacts 

as a ceiling  for the soft

      limit: an 

unprivileged process may set only its softlimit to a value

      in the range from 0 up to the hard limit, and (irreversibly) lower its

      hard  limit.   

a privileged process  (under linux: one 

with the

      cap_sys_resource capability) may make arbitrary changes to either limit

      value.

the resource argument must be one of:

rlimit_as

             the maximum size of the process'svirtual memory (address space)

             in bytes. 

this limit affects calls  to brk(2), mmap(2) 

and

             mremap(2), 

which fail with the error enomem uponexceeding this

             limit. 

also automatic stack expansion will fail (andgenerate a

             sigsegv 

that kills the process if no alternatestack has been

             made available viasigaltstack(2)). 

since the value isa long,

             on 

machines with a 32-bit long either thislimit is at most 2

             gib, or this resource isunlimited.

rlimit_core

             maximum size of core file. 

when 0 no core dump files are cre‐

             ated. 

when nonzero, larger dumps are truncated tothis size.

rlimit_cpu

             cpu time limit 

in seconds. when the process reaches the soft

             limit, it is sent a sigxcpusignal. 

the default action for this

             signal 

is to terminate the process. however, the signal can be

             caught, and the handler canreturn control to the main 

program.

             if 

the process continues to consume cputime, it will be sent

             sigxcpu once per second untilthe 

hard limit is  reached, at

             which 

time it is  sent sigkill. (this latter point describes

             linux behavior. 

implementations vary in how they  treat pro‐

             cesses 

which continue to  consume cpu time after reaching the

             soft limit. 

portable applications that need to catchthis sig‐

             nal 

should perform an orderly termination uponfirst receipt of

             sigxcpu.)

rlimit_data

             the maximum size of 

the process's data  segment (initialized

             data, 

uninitialized data, and heap). this limitaffects calls

             to brk(2) and sbrk(2), which failwith 

the error enomem  upon

             encountering the soft limit ofthis resource.

rlimit_fsize

             the maximum size of files that theprocess may create. 

attempts

             to extend a file beyond this 

limit result in  delivery of a

             sigxfsz 

signal.  by default, this signal terminates a process,

             but a process can catch thissignal instead, in which 

case  the

             relevant 

system call (e.g., write(2),truncate(2)) fails with

             the error efbig.

rlimit_locks (early linux 2.4 only)

             a limit on the combined number offlock(2) 

locks and fcntl(2)

             leases that this process mayestablish.

rlimit_memlock

             the 

maximum number of bytes of memory thatmay be locked into

             ram. 

in effect this limit is rounded down to thenearest multi‐

             ple 

of the  system page size.  this limit affects mlock(2) and

             mlockall(2) and the mmap(2)map_locked operation.  

since linux

             2.6.9 it also affects theshmctl(2) shm_lock operation, where it

             sets a maximum on the total bytesin shared memory segments (see

             shmget(2)) that may be locked bythe real user id of the calling

             process. 

the shmctl(2) shm_lock locks areaccounted for  sepa‐

             rately  

from  the per-process  memory locks established 

by

             mlock(2), mlockall(2), andmmap(2) 

map_locked; a process  can

             lock bytes up to this limit ineach of these two categories. in

             linux kernels before 2.6.9, thislimit controlled the amount of

             memory 

that could be  locked by a privileged process. since

             linux 2.6.9, no limits are placedon the amount of memory that a

             privileged 

process may lock, and this limit insteadgoverns the

             amount of memory that anunprivileged process may lock.

rlimit_msgqueue (since linux 2.6.8)

             specifies the limit on the numberof bytes that can be allocated

             for 

posix message queues  for the real user id of the calling

this limit is enforced for mq_open(3).  each message

             queue that the user createscounts (until it is removed) against

             this limit according to theformula:

                 bytes = attr.mq_maxmsg *sizeof(struct msg_msg *) +

                         attr.mq_maxmsg *attr.mq_msgsize

             where attr is the mq_attr 

structure specified as  the fourth

             argument to mq_open(3).

first addend in the formula, whichincludes sizeof(struct

             msg_msg *) (4 bytes onlinux/i386), ensures that the user cannot

             create 

an unlimited number of zero-lengthmessages (such mes‐

             sages nevertheless each consumesome system memory for bookkeep‐

             ing overhead).

rlimit_nice (since linux 2.6.12, but seebugs below)

             specifies 

a ceiling to  which the process's nice value can be

             raised using setpriority(2) ornice(2). 

the actual ceiling for

nice value is calculated as 20 - rlim_cur. (this strange‐

             ness occurs because negative 

numbers cannot be  specified as

             resource 

limit values, since they typically have special mean‐

             ings. 

for example, rlim_infinity typically is thesame as -1.)

      rlimit_nofile

             specifies a value one greaterthan the maximum 

file descriptor

             number 

that can be opened by this process. attempts (open(2),

             pipe(2), dup(2), etc.) 

to exceed this limit yield  the error

             emfile.  

(historically,  this limit was named rlimit_ofile on

             bsd.)

rlimit_nproc

             the maximum number of processes(or, more 

precisely on linux,

             threads) that can be created forthe real user id of the calling

upon encountering this limit, fork(2)fails with 

the

             error eagain.

      rlimit_rss

the limit (in  pages) of the process's resident set

             (the number of virtual pagesresident in ram). 

this limit has

             effect only in linux 2.4.x, x< 30, and there affects only calls

             to madvise(2) specifyingmadv_willneed.

      rlimit_rtprio (since linux 2.6.12, but see bugs)

             specifies a ceiling on thereal-time priority that 

may be  set

this process using  sched_setscheduler(2) 

and sched_set‐

             param(2).

rlimit_rttime (since linux 2.6.25)

             specifies a limit (inmicroseconds) on the amount 

of cpu time

             that a process scheduled under areal-time scheduling policy may

             consume without making a blockingsystem call. 

for the purpose

             of this limit, each time aprocess makes a blocking system call,

             the count of its consumed cputime is reset to 

zero.  the cpu

             time 

count is not reset if the process continues trying to use

             the cpu but is preempted, itstime slice expires, 

or it calls

             sched_yield(2).

             upon reaching the softlimit, the process is sent a sigxcpu sig‐

             nal. 

if the process catches or ignores this signaland contin‐

             ues consuming cpu time, thensigxcpu will be generated once each

             second until the hard limit 

is reached, at  which point the

             process is sent a sigkill signal.

intended use of this limit is to stop arunaway real-time

             process from locking up thesystem.

rlimit_sigpending (since linux 2.6.8)

             specifies the limit on the numberof signals that may be 

queued

the real user id of the calling process. both standard and

             real-time signals are counted forthe purpose of 

checking this

             limit.  however, the limit is enforced only forsigqueue(3); it

             is always possible to use kill(2)to queue one instance 

of  any

             of the signals that are notalready queued to the process.

      rlimit_stack

maximum size of the process stack, inbytes. upon reaching

             this limit, a sigsegv signal isgenerated. 

to handle this sig‐

             nal, 

a process must employ an alternatesignal stack (sigalt‐

             stack(2)).

             since linux 2.6.23, this limitalso 

determines the amount  of

             space used for the process'scommand-line arguments and environ‐

             ment variables; for details, seeexecve(2).

prlimit()

      the linux-specific prlimit() system call combines and extends the func‐

      tionality of 

setrlimit() and getrlimit().  it can be used to both set

      and get the resource limits of an arbitrary process.

      the resource argument has the same meaning as for setrlimit() and getr‐

      limit().

      if the 

new_limit argument is a not null, then therlimit structure to

      which it points is used to set new values for the soft and hard limits

      for resource. if the old_limitargument is a not null, then a success‐

      ful call to prlimit() places the previous soft and 

hard limits for

      resource in the rlimit structure pointed to by old_limit.

      the pid 

argument specifies the id of the process onwhich the call is

      to operate. if pid is 0, then thecall applies to the calling process.

      to set or get the resources of aprocess other than itself, the caller

      must have the cap_sys_resource capability, or the real, effective, and

      saved set user ids of the target process must match the real user id of

      the caller and the real, effective, and saved set group ids of the tar‐

      get process must match the real group id of the caller.

案例說明:

#define _gnu_source

#define _file_offset_bits 64

#include<stdio.h>

#include<time.h>

#include<stdlib.h>

#include<unistd.h>

#define errexit(msg)do{perror(msg);exit(exit_failure);} while(0)

int main(int argc,char *argv[])

{

struct rlimit old, new;

          struct rlimit *newp;

          pid_t pid;

          if (!(argc == 2 || argc == 4)) {

              fprintf(stderr, "usage: %s<pid> [<new-soft-limit> "

                      "<new-hard-limit>]\n", argv[0]);

              exit(exit_failure);

          }

          pid = atoi(argv[1]);       /* pidof target process */

          newp = null;

          if (argc == 4) {

              new.rlim_cur = atoi(argv[2]);

              new.rlim_max = atoi(argv[3]);

              newp = &new;

          /* set cpu time limit of target process; retrieve and display

             previous limit */

          if (prlimit(pid, rlimit_cpu, newp, &old) == -1)

              errexit("prlimit-1");

          printf("previous limits: soft=%lld; hard=%lld\n",

                  (long long) old.rlim_cur,(long long) old.rlim_max);

          /* retrieve and display new cpu time limit */

          if (prlimit(pid, rlimit_cpu, null, &old) == -1)

              errexit("prlimit-2");

          printf("new limits: soft=%lld; hard=%lld\n",

exit(exit_failure);

}

繼續閱讀