File Coverage

blib/lib/BSD/Resource.pm
Criterion Covered Total %
statement 61 65 93.8
branch 14 24 58.3
condition 2 3 66.7
subroutine 17 18 94.4
pod 4 6 66.7
total 98 116 84.5


line stmt bran cond sub pod time code
1             #
2             # Copyright (c) 1995-2004 Jarkko Hietaniemi. All rights reserved.
3             # This program is free software; you can redistribute it and/or
4             # modify it under the same terms as Perl itself.
5             #
6             # Resource.pm
7             #
8              
9             require 5.002;
10              
11             package BSD::Resource;
12              
13 7     7   299 use strict;
  7         62  
  7         111  
14 7     7   160 use vars qw(@ISA @EXPORT @EXPORT_OK $AUTOLOAD $VERSION);
  7         90  
  7         278  
15              
16             $VERSION = '1.28';
17              
18 7     7   109 use Carp;
  7         63  
  7         383  
19 7     7   1733 use AutoLoader;
  7         89  
  7         126  
20              
21             require Exporter;
22             require DynaLoader;
23              
24             @ISA = qw(Exporter DynaLoader);
25              
26             @EXPORT = qw(
27             PRIO_MAX
28             PRIO_MIN
29             PRIO_PGRP
30             PRIO_PROCESS
31             PRIO_USER
32             RLIMIT_AIO_MEM
33             RLIMIT_AIO_OPS
34             RLIMIT_AS
35             RLIMIT_CORE
36             RLIMIT_CPU
37             RLIMIT_DATA
38             RLIMIT_FSIZE
39             RLIMIT_LOCKS
40             RLIMIT_MEMLOCK
41             RLIMIT_NOFILE
42             RLIMIT_NPROC
43             RLIMIT_OFILE
44             RLIMIT_OPEN_MAX
45             RLIMIT_RSS
46             RLIMIT_STACK
47             RLIMIT_TCACHE
48             RLIMIT_VMEM
49             RLIM_INFINITY
50             RLIM_NLIMITS
51             RLIM_SAVED_CUR
52             RLIM_SAVED_MAX
53             RUSAGE_BOTH
54             RUSAGE_CHILDREN
55             RUSAGE_SELF
56             RUSAGE_THREAD
57             get_rlimits
58             getpriority
59             getrlimit
60             getrusage
61             setpriority
62             setrlimit
63             );
64              
65             Exporter::export_tags();
66              
67             @EXPORT_OK = qw(times);
68              
69             # Grandfather old foo_h form to new :foo_h form
70             sub import {
71 7     7   71     my $this = shift;
72 7 50       73     my @list = map { m/^\w+_h$/ ? ":$_" : $_ } @_;
  3         42  
73 7         67     local $Exporter::ExportLevel = 1;
74 7         110     Exporter::import($this,@list);
75             }
76              
77             bootstrap BSD::Resource;
78              
79             my $EINVAL = constant("EINVAL", 0);
80             my $EAGAIN = constant("EAGAIN", 0);
81              
82             sub AUTOLOAD {
83 61 100   61   11177311     if ($AUTOLOAD =~ /::(_?[a-z])/) {
84 13         203         $AutoLoader::AUTOLOAD = $AUTOLOAD;
85 13         333         goto &AutoLoader::AUTOLOAD;
86                 }
87 48         1143     local $! = 0;
88 48         423     my $constname = $AUTOLOAD;
89 48         638     $constname =~ s/.*:://;
90 48 100       523     return if $constname eq 'DESTROY';
91 34 50       500     my $val = constant($constname, @_ ? $_[0] : 0);
92 7     7   131     no strict 'refs';
  7         68  
  7         281  
93 34 50       414     if ($! == 0) {
    0          
    0          
94 34     66   1555         *$AUTOLOAD = sub { $val };
  66         2480  
95                 }
96                 elsif ($! == $EAGAIN) { # Not really a constant, so always call.
97 0     0   0         *$AUTOLOAD = sub { constant($constname, $_[0]) };
  0         0  
98                 }
99                 elsif ($! == $EINVAL) {
100 0         0         croak "$constname is not a valid BSD::Resource macro";
101                 }
102                 else {
103 0         0         croak "Your vendor has not defined BSD::Resource macro $constname, used";
104                 }
105 7     7   114     use strict 'refs';
  7         62  
  7         102  
106              
107 34         1441     goto &$AUTOLOAD;
108             }
109 7     7   109 use strict;
  7         90  
  7         115  
110              
111             =pod
112            
113             =head1 NAME
114            
115             BSD::Resource - BSD process resource limit and priority functions
116            
117             =head1 SYNOPSIS
118            
119             use BSD::Resource;
120            
121             #
122             # the process resource consumption so far
123             #
124            
125             ($usertime, $systemtime,
126             $maxrss, $ixrss, $idrss, $isrss, $minflt, $majflt, $nswap,
127             $inblock, $oublock, $msgsnd, $msgrcv,
128             $nsignals, $nvcsw, $nivcsw) = getrusage($ru_who);
129            
130             $rusage = getrusage($ru_who);
131            
132             #
133             # the process resource limits
134             #
135            
136             ($nowsoft, $nowhard) = getrlimit($resource);
137            
138             $rlimit = getrlimit($resource);
139            
140             $success = setrlimit($resource, $newsoft, $newhard);
141            
142             #
143             # the process scheduling priority
144             #
145            
146             $nowpriority = getpriority($pr_which, $pr_who);
147            
148             $success = setpriority($pr_which, $pr_who, $priority);
149            
150             # The following is not a BSD function.
151             # It is a Perlish utility for the users of BSD::Resource.
152            
153             $rlimits = get_rlimits();
154            
155             =head1 DESCRIPTION
156            
157             =head2 getrusage
158            
159             ($usertime, $systemtime,
160             $maxrss, $ixrss, $idrss, $isrss, $minflt, $majflt, $nswap,
161             $inblock, $oublock, $msgsnd, $msgrcv,
162             $nsignals, $nvcsw, $nivcsw) = getrusage($ru_who);
163            
164             $rusage = getrusage($ru_who);
165            
166             # $ru_who argument is optional; it defaults to RUSAGE_SELF
167            
168             $rusage = getrusage();
169            
170             The $ru_who argument is either C<RUSAGE_SELF> (the current process) or
171             C<RUSAGE_CHILDREN> (all the child processes of the current process)
172             or it maybe left away in which case C<RUSAGE_SELF> is used.
173            
174             The C<RUSAGE_CHILDREN> is the total sum of all the so far
175             I<terminated> (either successfully or unsuccessfully) child processes:
176             there is no way to find out information about child processes still
177             running.
178            
179             On some systems (those supporting both getrusage() and the POSIX
180             threads) there is also C<RUSAGE_THREAD>. The BSD::Resource supports the
181             C<RUSAGE_THREAD> if it is present but understands nothing more about the
182             POSIX threads themselves. Similarly for C<RUSAGE_BOTH>: some systems
183             support retrieving the sums of the self and child resource consumptions
184             simultaneously.
185            
186             In list context getrusage() returns the current resource usages as a
187             list. On failure it returns an empty list.
188            
189             The elements of the list are, in order:
190             index name meaning usually (quite system dependent)
191            
192             0 utime user time
193             1 stime system time
194             2 maxrss maximum shared memory or current resident set
195             3 ixrss integral shared memory
196             4 idrss integral or current unshared data
197             5 isrss integral or current unshared stack
198             6 minflt page reclaims
199             7 majflt page faults
200             8 nswap swaps
201             9 inblock block input operations
202             10 oublock block output operations
203             11 msgsnd messages sent
204             12 msgrcv messaged received
205             13 nsignals signals received
206             14 nvcsw voluntary context switches
207             15 nivcsw involuntary context switches
208            
209             In scalar context getrusage() returns the current resource usages as a
210             an object. The object can be queried via methods named exactly like
211             the middle column, I<name>, in the above table.
212            
213             $ru = getrusage();
214             print $ru->stime, "\n";
215            
216             $total_context_switches = $ru->nvcsw + $ru->nivcsw;
217            
218             For a detailed description about the values returned by getrusage()
219             please consult your usual C programming documentation about
220             getrusage() and also the header file C<E<lt>sys/resource.hE<gt>>.
221             (In B<Solaris>, this might be C<E<lt>sys/rusage.hE<gt>>).
222            
223             See also L</"KNOWN ISSUES">.
224            
225             =head2 getrlimit
226            
227             ($nowsoft, $nowhard) = getrlimit($resource);
228            
229             $rlimit = getrlimit($resource);
230            
231             The $resource argument can be one of
232            
233             $resource usual meaning usual unit
234            
235             RLIMIT_CPU CPU time seconds
236            
237             RLIMIT_FSIZE file size bytes
238            
239             RLIMIT_DATA data size bytes
240             RLIMIT_STACK stack size bytes
241             RLIMIT_CORE coredump size bytes
242             RLIMIT_RSS resident set size bytes
243             RLIMIT_MEMLOCK memory locked data size bytes
244            
245             RLIMIT_NPROC number of processes 1
246            
247             RLIMIT_NOFILE number of open files 1
248             RLIMIT_OFILE number of open files 1
249             RLIMIT_OPEN_MAX number of open files 1
250            
251             RLIMIT_LOCKS number of file locks 1
252            
253             RLIMIT_AS (virtual) address space bytes
254             RLIMIT_VMEM virtual memory (space) bytes
255            
256             RLIMIT_TCACHE maximum number of 1
257             cached threads
258            
259             RLIMIT_AIO_MEM maximum memory locked bytes
260             for POSIX AIO
261             RLIMIT_AIO_OPS maximum number 1
262             for POSIX AIO ops
263            
264             B<What limits are available depends on the operating system>.
265             See below for C<get_rlimits()> on how to find out which limits are
266             available, for the exact documentation consult the documentation of
267             your operatgiing system. The two groups (C<NOFILE>, CC<OFILE>,
268             <OPEN_MAX>) and (C<AS>, C<VMEM>) are aliases within themselves.
269            
270             Two meta-resource-symbols might exist
271            
272             RLIM_NLIMITS
273             RLIM_INFINITY
274            
275             C<RLIM_NLIMITS> being the number of possible (but not necessarily fully
276             supported) resource limits, see also the get_rlimits() call below.
277             C<RLIM_INFINITY> is useful in setrlimit(), the C<RLIM_INFINITY> is
278             represented as -1.
279            
280             In list context C<getrlimit()> returns the current soft and hard resource
281             limits as a list. On failure it returns an empty list.
282            
283             Processes have soft and hard resource limits. On crossing the soft
284             limit they receive a signal (for example the C<SIGXCPU> or C<SIGXFSZ>,
285             corresponding to the C<RLIMIT_CPU> and C<RLIMIT_FSIZE>, respectively).
286             The processes can trap and handle some of these signals, please see
287             L<perlipc/Signals>. After the hard limit the processes will be
288             ruthlessly killed by the C<KILL> signal which cannot be caught.
289            
290             B<NOTE>: the level of 'support' for a resource varies. Not all the systems
291            
292             a) even recognise all those limits
293             b) really track the consumption of a resource
294             c) care (send those signals) if a resource limit is exceeded
295            
296             Again, please consult your usual C programming documentation.
297            
298             One notable exception for the better: officially B<HP-UX> does not
299             support getrlimit() at all but for the time being, it does seem to.
300            
301             In scalar context getrlimit() returns the current soft and hard
302             resource limits as an object. The object can be queried via methods
303             C<cur> and C<max>, the current and maximum resource limits for the
304             C<$resource>, respectively.
305            
306             =head2 getpriority
307            
308             $nowpriority = getpriority($pr_which, $pr_who);
309            
310             # the default $pr_who is 0 (the current $pr_which)
311            
312             $nowpriority = getpriority($pr_which);
313            
314             # the default $pr_which is PRIO_PROCESS (the process priority)
315            
316             $nowpriority = getpriority();
317            
318             getpriority() returns the current priority. B<NOTE>: getpriority()
319             can return zero or negative values completely legally. On failure
320             getpriority() returns C<undef> (and C<$!> is set as usual).
321            
322             The priorities returned by getpriority() are in the (inclusive) range
323             C<PRIO_MIN>...C<PRIO_MAX>. The $pr_which argument can be any of
324             PRIO_PROCESS (a process) C<PRIO_USER> (a user), or C<PRIO_PGRP> (a
325             process group). The $pr_who argument tells which process/user/process
326             group, 0 signifying the current one.
327            
328             Usual values for C<PRIO_MIN>, C<PRIO_MAX>, are -20, 20. A negative
329             value means better priority (more impolite process), a positive value
330             means worse priority (more polite process).
331            
332             =head2 setrlimit
333            
334             $success = setrlimit($resource, $newsoft, $newhard);
335            
336             setrlimit() returns true on success and C<undef> on failure.
337            
338             B<NOTE>: A normal user process can only lower its resource limits.
339             Soft or hard limit C<RLIM_INFINITY> means as much as possible, the
340             real hard limits are normally buried inside the kernel and are B<very>
341             system-dependent.
342            
343             =head2 setpriority
344            
345             $success = setpriority($pr_which, $pr_who, $priority);
346            
347             # NOTE! If there are two arguments the second one is
348             # the new $priority (not $pr_who) and the $pr_who is
349             # defaulted to 0 (the current $pr_which)
350            
351             $success = setpriority($pr_which, $priority);
352            
353             # The $pr_who defaults to 0 (the current $pr_which) and
354             # the $priority defaults to half of the PRIO_MAX, usually
355             # that amounts to 10 (being a nice $pr_which).
356            
357             $success = setpriority($pr_which);
358            
359             # The $pr_which defaults to PRIO_PROCESS,
360            
361             $success = setpriority();
362            
363             setpriority() is used to change the scheduling priority. A positive
364             priority means a more polite process/process group/user; a negative
365             priority means a more impoite process/process group/user.
366             The priorities handled by setpriority() are [C<PRIO_MIN>,C<PRIO_MAX>].
367             A normal user process can only lower its priority (make it more positive).
368            
369             B<NOTE>: A successful call returns C<1>, a failed one C<0>.
370            
371             See also L</"KNOWN ISSUES">.
372            
373             =head2 times
374            
375             use BSD::Resource qw(times);
376            
377             ($user, $system, $child_user, $child_system) = times();
378            
379             The BSD::Resource module offers a times() implementation that has
380             usually slightly better time granularity than the times() by Perl
381             core. The time granularity of the latter is usually 1/60 seconds
382             while the former may achieve submilliseconds.
383            
384             B<NOTE>: The current implementation uses two getrusage() system calls:
385             one with RUSAGE_SELF and one with RUSAGE_CHILDREN. Therefore the
386             operation is not `atomic': the times for the children are recorded
387             a little bit later.
388            
389             B<NOTE>: times() is not imported by default by BSD::Resource.
390             You need to tell that you want to use it.
391            
392             B<NOTE: times() is not a "real BSD" function. It is older UNIX.>
393            
394             =head2 get_rlimits
395            
396             $rlimits = get_rlimits();
397            
398             B<NOTE: This is not a real BSD function. It is a convenience function.>
399            
400             get_rlimits() returns a reference to hash which has the names of the
401             available resource limits as keys and their indices (those which
402             are needed as the first argument to getrlimit() and setrlimit())
403             as values. For example:
404            
405             $r = get_rlimits();
406             print "ok.\n" if ($r->{'RLIM_STACK'} == RLIM_STACK);
407            
408             =head1 ERRORS
409            
410             =over 4
411            
412             =item *
413            
414             Your vendor has not defined BSD::Resource macro ...
415            
416             The code tried to call getrlimit/setrlimit for a resource limit that
417             your operating system vendor/supplier does not support. Portable code
418             should use get_rlimits() to check which resource limits are defined.
419            
420             =item *
421            
422             use PRIO..., not "PRIO_..."
423            
424             getpriority() and setpriority() use symbolic names, not strings,
425             for the constants.
426            
427             =item *
428            
429             use RLIMIT..., not "RLIMIT_..."
430            
431             getrlimit() and setrlimit() use symbolic names, not strings,
432             for the constants.
433            
434             =back
435            
436             =head1 EXAMPLES
437            
438             # the user and system times so far by the process itself
439            
440             ($usertime, $systemtime) = getrusage();
441            
442     &nb