我们从Python开源项目中,提取了以下14个代码示例,用于说明如何使用resource.RLIMIT_CPU。
def setup_limit(self): """set up the process limit""" assert currentThread().getName() == 'MainThread' os.setpgrp() if self._limit_set <= 0: if self.max_time is not None: self._old_usr2_hdlr = signal(SIGUSR2, self._hangle_sig_timeout) self._timer = Timer(max(1, int(self.max_time) - self._elapse_time), self._time_out) self._start_time = int(time()) self._timer.start() if self.max_cpu_time is not None: self._old_max_cpu_time = getrlimit(RLIMIT_CPU) cpu_limit = (int(self.max_cpu_time), self._old_max_cpu_time[1]) self._old_sigxcpu_hdlr = signal(SIGXCPU, self._handle_sigxcpu) setrlimit(RLIMIT_CPU, cpu_limit) if self.max_memory is not None: self._msentinel = MemorySentinel(1, int(self.max_memory) ) self._old_max_memory = getrlimit(RLIMIT_AS) self._old_usr1_hdlr = signal(SIGUSR1, self._hangle_sig_memory) as_limit = (int(self.max_memory), self._old_max_memory[1]) setrlimit(RLIMIT_AS, as_limit) self._msentinel.start() self._limit_set += 1
def clean_limit(self): """reinstall the old process limit""" if self._limit_set > 0: if self.max_time is not None: self._timer.cancel() self._elapse_time += int(time())-self._start_time self._timer = None signal(SIGUSR2, self._old_usr2_hdlr) if self.max_cpu_time is not None: setrlimit(RLIMIT_CPU, self._old_max_cpu_time) signal(SIGXCPU, self._old_sigxcpu_hdlr) if self.max_memory is not None: self._msentinel.stop() self._msentinel = None setrlimit(RLIMIT_AS, self._old_max_memory) signal(SIGUSR1, self._old_usr1_hdlr) self._limit_set -= 1
def set_time_limit(time_limit): if time_limit is None: return assert can_set_limits() # Don't try to raise the hard limit. _, external_hard_limit = resource.getrlimit(resource.RLIMIT_CPU) if external_hard_limit == resource.RLIM_INFINITY: external_hard_limit = float("inf") assert time_limit <= external_hard_limit, (time_limit, external_hard_limit) # Soft limit reached --> SIGXCPU. # Hard limit reached --> SIGKILL. soft_limit, hard_limit = _get_soft_and_hard_time_limits( time_limit, external_hard_limit) _set_limit(resource.RLIMIT_CPU, soft_limit, hard_limit)
def _get_external_time_limit(): """Return external soft CPU limit in seconds or None if not set.""" if not can_set_limits(): return None return _get_external_limit(resource.RLIMIT_CPU)
def limitedTime(second, func, *args, **kw): # noqa second = fixTimeout(second) old_alarm = signal(SIGXCPU, signalHandler) current = getrlimit(RLIMIT_CPU) try: setrlimit(RLIMIT_CPU, (second, current[1])) return func(*args, **kw) finally: setrlimit(RLIMIT_CPU, current) signal(SIGXCPU, old_alarm)
def limitedTime(second, func, *args, **kw): second = fixTimeout(second) old_alarm = signal(SIGXCPU, signalHandler) current = getrlimit(RLIMIT_CPU) try: setrlimit(RLIMIT_CPU, (second, current[1])) return func(*args, **kw) finally: setrlimit(RLIMIT_CPU, current) signal(SIGXCPU, old_alarm)