How do I set a ulimit from inside a Perl script that applies to its children?

泪湿孤枕 提交于 2019-11-30 13:47:38

You've already answered your question: use BSD::Resource.

There isn't anything in the Perl core that interfaces with setrlimit. If you can't (or won't) use the standard method, then you have to use a hack. Any of the methods you've already described would work. (Note that you could create a subroutine to prepend ulimit -s BLA; to every command, and then use that sub instead of system.)

You can always wrap your perl in a little shell script:

#!/bin/sh -- # --*-Perl-*--
ulimit -n 2048
exec /usr/bin/perl -x -S $0 ${1+"$@"}
#!/usr/bin/perl
#line 6

use strict;

# etc, etc....

It's ugly, and obviously, script start up time will be slightly longer.

Here's an example of how to set the cpu limit without using BSD::Resource (but assuming the perl system headers are there). To adapt to other resources, make the obvious changes.

require 'syscall.ph';
require 'sys/resource.ph';

# set the soft cpu limit to 1 (second), and the hard limit to 10.
$rstruct = pack "L!L!",1,10; # L! means native long unsigned int.
syscall(&SYS_setrlimit,&RLIMIT_CPU,$rstruct);

This assumes knowledge that rlim_t is in fact unsigned long; I don't know if there's a way to extract this info from the Perl headers.

I ended up prepending ulimit -s BLA to the commands that needed it. I specifically didn't want to go with BSD::Resource because it's not a default Perl package and was missing on about half of the existing dev machines. No user interaction was a specific requirement.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!