Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

call setrlimit to limit process resource usage

by jdporter (Canon)
on May 01, 2003 at 18:20 UTC ( #254756=snippet: print w/replies, xml ) Need Help??

On 2000/05/26, In <>, Bernie Cosell wrote:
> Can you set your process's (and most importantly, its children's)
> resource limits (via the setrlimit(2) system call) from Perl?

Surely. Here's an example, a wrapper around setrlimit(RLIMIT_CPU).

  # Note that I've hardcoded things like EPERM,EFAULT,EINVAL from sys/
  # SYS_setrlimit from sys/syscall.h, and RLIMIT_CPU from sys/resource
  # it might be preferable to h2ph the respective .h files...

  sub set_max_cpu_time
    my $n_seconds = shift;
    my $s = pack( 'LL', $n_seconds, $n_seconds+1 );
    $! = 0;
    if ( syscall( 128, 0, $s ) == -1 )  # SYS_setrlimit, RLIMIT_CPU
      if ( $! == 1 )  # EPERM
        die "$!; Sorry, you need to be superuser to do that.\n";
      elsif ( $! == 14 )  # EFAULT
        die "$!; Error: argument to setrlimit pointed to an illegal ad
      elsif ( $! == 22 )  # EINVAL
        die "$!; Error: the new rlim_cur exceeds the new rlim_max,
          or the limit specified cannot be lowered because current usa
          is already higher than the limit.\n";

  # test it:
  set_max_cpu_time( 8 );
  my $n = 0;
  while ( 1 ) { $n++ }
  # Hmm, mysteriously dumps core after about 8 seconds!  :-)

Replies are listed 'Best First'.
Re: call setrlimit to limit process resource usage
by jaldhar (Vicar) on May 01, 2003 at 19:33 UTC

    Nice but did you know there already is a module BSD::Resource for doing this? And it's a lot more portable than your code.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://254756]
holli enters he monastery hall, freezing but happy to have built the most beautiful snowman in the history of mankind
[holli]: tbh, the thing looks more like quasimode but hey, the thought matters. and it has blue LEDs as eyes
[holli]: we had solid 8cm fresh snow overnight. that is quite unusual for the area

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2017-12-18 05:57 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (467 votes). Check out past polls.