当前位置: 首页 > 工具软件 > ResourceSpace > 使用案例 >

python manager ulimit_Python resource.setrlimit方法代码示例

漆雕彬彬
2023-12-01

本文整理汇总了Python中resource.setrlimit方法的典型用法代码示例。如果您正苦于以下问题:Python resource.setrlimit方法的具体用法?Python resource.setrlimit怎么用?Python resource.setrlimit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块resource的用法示例。

在下文中一共展示了resource.setrlimit方法的23个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __exit__

​点赞 6

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def __exit__(self, *ignore_exc):

"""Restore Windows ErrorMode or core file behavior to initial value."""

if self.old_value is None:

return

if sys.platform.startswith('win'):

self._k32.SetErrorMode(self.old_value)

if self.old_modes:

import _testcapi

for report_type, (old_mode, old_file) in self.old_modes.items():

_testcapi.CrtSetReportMode(report_type, old_mode)

_testcapi.CrtSetReportFile(report_type, old_file)

else:

import resource

try:

resource.setrlimit(resource.RLIMIT_CORE, self.old_value)

except (ValueError, OSError):

pass

开发者ID:IronLanguages,项目名称:ironpython2,代码行数:21,

示例2: __enter__

​点赞 6

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def __enter__(self):

"""Try to save previous ulimit, then set it to (0, 0)."""

if resource is not None:

try:

self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)

resource.setrlimit(resource.RLIMIT_CORE, (0, 0))

except (ValueError, resource.error):

pass

if sys.platform == 'darwin':

# Check if the 'Crash Reporter' on OSX was configured

# in 'Developer' mode and warn that it will get triggered

# when it is.

#

# This assumes that this context manager is used in tests

# that might trigger the next manager.

value = subprocess.Popen(['/usr/bin/defaults', 'read',

'com.apple.CrashReporter', 'DialogType'],

stdout=subprocess.PIPE).communicate()[0]

if value.strip() == b'developer':

print "this tests triggers the Crash Reporter, that is intentional"

sys.stdout.flush()

开发者ID:IronLanguages,项目名称:ironpython2,代码行数:24,

示例3: test_urandom_failure

​点赞 6

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def test_urandom_failure(self):

# Check urandom() failing when it is not able to open /dev/random.

# We spawn a new process to make the test more robust (if getrlimit()

# failed to restore the file descriptor limit after this, the whole

# test suite would crash; this actually happened on the OS X Tiger

# buildbot).

code = """if 1:

import errno

import os

import resource

soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)

resource.setrlimit(resource.RLIMIT_NOFILE, (1, hard_limit))

try:

os.urandom(16)

except OSError as e:

assert e.errno == errno.EMFILE, e.errno

else:

raise AssertionError("OSError not raised")

"""

assert_python_ok('-c', code)

开发者ID:IronLanguages,项目名称:ironpython2,代码行数:23,

示例4: _set

​点赞 6

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def _set(self):

self.ulimit = {}

for key in self.ulimit_options:

set_value = self.params.get("vt_ulimit_%s" % key)

if not set_value:

continue

# get default ulimit values in tuple (soft, hard)

self.ulimit[key] = resource.getrlimit(self.ulimit_options[key])

logging.info("Setting ulimit %s to %s." % (key, set_value))

if set_value == "ulimited":

set_value = resource.RLIM_INFINITY

elif set_value.isdigit():

set_value = int(set_value)

else:

self.test.error("%s is not supported for "

"setting ulimit %s" % (set_value, key))

try:

resource.setrlimit(self.ulimit_options[key],

(set_value, set_value))

except ValueError as error:

self.test.error(str(error))

开发者ID:avocado-framework,项目名称:avocado-vt,代码行数:24,

示例5: set_ulimit

​点赞 6

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def set_ulimit():

"""Sets appropriate resource limits for the JS shell when on POSIX."""

try:

import resource

# log.debug("Limit address space to 4GB")

# This has to be twice the 2GB figure in:

# https://hg.mozilla.org/mozilla-central/annotate/7beb238a0ea0/js/src/jit/ProcessExecutableMemory.h#l26

# i.e. https://hg.mozilla.org/mozilla-central/rev/7beb238a0ea0 (bug 1542292) changed from 1GB to 2GB, so our

# number here in this file has to be changed from 2GB to 4GB or else the harness (m-err.txt) will show this:

# JS_Init failed: js::jit::InitProcessExecutableMemory() failed

# We cannot set a limit for RLIMIT_AS for ASan binaries

giga_byte = 2**30

resource.setrlimit(resource.RLIMIT_AS, (4 * giga_byte, 4 * giga_byte))

# log.debug("Limit corefiles to 0.5 GB")

half_giga_byte = int(giga_byte // 2)

resource.setrlimit(resource.RLIMIT_CORE, (half_giga_byte, half_giga_byte))

except ImportError:

# log.debug("Skipping resource import as a non-POSIX platform was detected: %s", platform.system())

return

开发者ID:MozillaSecurity,项目名称:funfuzz,代码行数:23,

示例6: create_executable_limits

​点赞 6

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def create_executable_limits(self) -> Optional[Callable[[], None]]:

try:

import resource

from dmoj.utils.os_ext import oom_score_adj, OOM_SCORE_ADJ_MAX

def limit_executable():

os.setpgrp()

# Mark compiler process as first to die in an OOM situation, just to ensure that the judge will not

# be killed.

try:

oom_score_adj(OOM_SCORE_ADJ_MAX)

except Exception:

import traceback

traceback.print_exc()

resource.setrlimit(resource.RLIMIT_FSIZE, (self.executable_size, self.executable_size))

return limit_executable

except ImportError:

return None

开发者ID:DMOJ,项目名称:judge-server,代码行数:24,

示例7: _EnforceProcessMemoryLimit

​点赞 6

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def _EnforceProcessMemoryLimit(self, memory_limit):

"""Enforces a process memory limit.

Args:

memory_limit (int): maximum number of bytes the process is allowed

to allocate, where 0 represents no limit and None a default of

4 GiB.

"""

# Resource is not supported on Windows.

if resource:

if memory_limit is None:

memory_limit = 4 * 1024 * 1024 * 1024

elif memory_limit == 0:

memory_limit = resource.RLIM_INFINITY

resource.setrlimit(resource.RLIMIT_DATA, (memory_limit, memory_limit))

开发者ID:log2timeline,项目名称:plaso,代码行数:18,

示例8: test_collision

​点赞 6

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def test_collision():

import resource

resource.setrlimit(resource.RLIMIT_NOFILE, (102400, 102400))

dd = {}

ls = []

for i in range(1 << 15):

key = str(hashlib.sha1(str(i)).hexdigest())

lck = key

print 'lock is', i, lck

l = Portlock(lck, timeout=8)

r = l.try_lock()

if not r:

print 'collide', i, l.addr

print l.socks

dd[l.addr] = i

ls.append(l)

开发者ID:bsc-s2,项目名称:pykit,代码行数:21,

示例9: test_operating_on_small_slices_of_lists

​点赞 6

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def test_operating_on_small_slices_of_lists(self):

with self.create_executor() as fora:

with fora.remotely:

#1 billion integers

a_list = range(1000000000)

#the first million integers

a_list_slice = a_list[:1000000]

with helpers.python:

resource.setrlimit(resource.RLIMIT_AS, (2 * 1024 * 1024 * 1024, -1))

sum_result = sum(a_list_slice)

a_list = None

sum_result = sum_result.toLocal().result()

self.assertEqual(sum_result, sum(range(1000000)))

开发者ID:ufora,项目名称:ufora,代码行数:20,

示例10: stdinpwn

​点赞 6

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def stdinpwn(self, payload):

resource.setrlimit(resource.RLIMIT_STACK, (-1, -1))

resource.setrlimit(resource.RLIMIT_CORE, (-1, -1))

P = Popen(self.target, stdin=PIPE)

print "[*] Sending buffer with lenght: " + str(len(payload))

P.stdin.write(payload)

while True:

line = sys.stdin.readline()

P.poll()

ret = P.returncode

if ret is None:

P.stdin.write(line)

else:

if ret == -11:

print "[*] Child program crashed with SIGSEGV"

else:

print "[-] Child program exited with code %d" % ret

break

print "\n If it does not work automatically, run on terminal: (cat buffer.txt ; cat) | {}".format(self.target)

开发者ID:m4n3dw0lf,项目名称:pythem,代码行数:22,

示例11: __exit__

​点赞 6

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def __exit__(self, *ignore_exc):

"""Restore Windows ErrorMode or core file behavior to initial value."""

if self.old_value is None:

return

if sys.platform.startswith('win'):

self._k32.SetErrorMode(self.old_value)

if self.old_modes:

import msvcrt

for report_type, (old_mode, old_file) in self.old_modes.items():

msvcrt.CrtSetReportMode(report_type, old_mode)

msvcrt.CrtSetReportFile(report_type, old_file)

else:

if resource is not None:

try:

resource.setrlimit(resource.RLIMIT_CORE, self.old_value)

except (ValueError, OSError):

pass

开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:21,

示例12: prevent_core_dump

​点赞 6

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def prevent_core_dump():

""" Prevent this process from generating a core dump.

Sets the soft and hard limits for core dump size to zero. On

Unix, this prevents the process from creating core dump

altogether.

"""

core_resource = resource.RLIMIT_CORE

try:

# Ensure the resource limit exists on this platform, by requesting

# its current value

resource.getrlimit(core_resource)

except ValueError as exc:

error = DaemonOSEnvironmentError(

"System does not support RLIMIT_CORE resource limit (%s)" % exc)

raise error

# Set hard and soft limits to zero, i.e. no core dump at all

core_limit = (0, 0)

resource.setrlimit(core_resource, core_limit)

开发者ID:candlepin,项目名称:virt-who,代码行数:24,

示例13: preexec_fn

​点赞 5

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def preexec_fn():

resource.setrlimit(resource.RLIMIT_CORE, (resource.RLIM_INFINITY, resource.RLIM_INFINITY))

开发者ID:dobin,项目名称:ffw,代码行数:4,

示例14: setupEnvironment

​点赞 5

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def setupEnvironment(config):

"""

Prepare the environment before the server is started.

For example asan options, working directory, ASLR and ulimit.

Note that for honggfuzz mode, most of this is ignored.

"""

# Silence warnings from the ptrace library

#logging.getLogger().setLevel(logging.ERROR)

# Most important is to set log_path so we have access to the asan logs

asanOpts = ""

asanOpts += "color=never:verbosity=0:leak_check_at_exit=false:"

asanOpts += "abort_on_error=true:log_path=" + config["temp_dir"] + "/asan"

os.environ["ASAN_OPTIONS"] = asanOpts

# Tell Glibc to abort on heap corruption but not dump a bunch of output

os.environ["MALLOC_CHECK_"] = "2"

# Check ASLR status

if "ignore_aslr_status" in config and config["ignore_aslr_status"] is False:

aslrStatusFile = "/proc/sys/kernel/randomize_va_space"

d = ""

with open(aslrStatusFile, "r") as f:

d = f.read()

if "disable_aslr_check" not in config and d is not "0":

logging.error("ASLR Enabled, please disable it:")

logging.error(" echo 0 | sudo tee /proc/sys/kernel/randomize_va_space")

sys.exit(1)

# set resources

if 'handle_corefiles' in config and config['handle_corefiles']:

resource.setrlimit(resource.RLIMIT_CORE, (resource.RLIM_INFINITY, resource.RLIM_INFINITY))

# set working directory

os.chdir(config["target_dir"])

开发者ID:dobin,项目名称:ffw,代码行数:39,

示例15: xtrabackup_instance

​点赞 5

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def xtrabackup_instance(instance, timestamp, initial_build):

""" Take a compressed mysql backup

Args:

instance - A hostaddr instance

timestamp - A timestamp which will be used to create the backup filename

initial_build - Boolean, if this is being created right after the server

was built

Returns:

A string of the path to the finished backup

"""

# Prevent issues with too many open files

resource.setrlimit(resource.RLIMIT_NOFILE, (131072, 131072))

backup_file = create_backup_file_name(instance, timestamp,

initial_build,

BACKUP_TYPE_XBSTREAM)

tmp_log = os.path.join(environment_specific.RAID_MOUNT,

'log', 'xtrabackup_{ts}.log'.format(

ts=time.strftime('%Y-%m-%d-%H:%M:%S', timestamp)))

tmp_log_handle = open(tmp_log, "w")

procs = dict()

cmd = create_xtrabackup_command(instance, timestamp, tmp_log)

log.info(' '.join(cmd + [' 2> ', tmp_log, ' | ']))

procs['xtrabackup'] = subprocess.Popen(cmd,

stdout=subprocess.PIPE,

stderr=tmp_log_handle)

safe_uploader.safe_upload(precursor_procs=procs,

bucket=environment_specific.BACKUP_BUCKET_UPLOAD_MAP[host_utils.get_iam_role()],

stdin=procs['xtrabackup'].stdout,

key=backup_file,

check_func=check_xtrabackup_log,

check_arg=tmp_log,

verbose=True)

log.info('Xtrabackup was successful')

return backup_file

开发者ID:pinterest,项目名称:mysql_utils,代码行数:39,

示例16: setnmaplimits

​点赞 5

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def setnmaplimits():

"""Enforces limits from NMAP_LIMITS global variable."""

for limit, value in viewitems(NMAP_LIMITS):

resource.setrlimit(limit, value)

开发者ID:cea-sec,项目名称:ivre,代码行数:6,

示例17: __exit__

​点赞 5

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def __exit__(self, *args):

"""Return core file behavior to default."""

if self.old_limit is None:

return

if resource is not None:

try:

resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)

except (ValueError, resource.error):

pass

开发者ID:IronLanguages,项目名称:ironpython2,代码行数:11,

示例18: _restore

​点赞 5

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def _restore(self):

for key in self.ulimit:

logging.info("Setting ulimit %s back to its default." % key)

resource.setrlimit(self.ulimit_options[key], self.ulimit[key])

开发者ID:avocado-framework,项目名称:avocado-vt,代码行数:6,

示例19: calculate

​点赞 5

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def calculate(expr: str, *, decimal_mode: bool = True):

import resource

limit = 2 * 1024 * 1024

resource.setrlimit(resource.RLIMIT_AS, (limit, limit))

e = Evaluator(decimal_mode=decimal_mode)

result = e.run(expr)

return result, e.symbol_table

开发者ID:item4,项目名称:yui,代码行数:11,

示例20: setResourceLimits

​点赞 5

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def setResourceLimits():

try:

import resource

except ImportError:

print('Module resource is not available, maybe i am running on Windows')

return

flimit = 65535

plimit = 65535

try:

resource.setrlimit(resource.RLIMIT_NOFILE, (flimit, flimit))

resource.setrlimit(resource.RLIMIT_NPROC, (plimit, plimit))

except Exception as ex:

print('Could not set resource limits due to {}'.format(ex))

开发者ID:hyperledger,项目名称:indy-plenum,代码行数:15,

示例21: setup_files_limit

​点赞 5

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def setup_files_limit():

try:

import resource

soft_fd_limit, hard_fd_limit = resource.getrlimit(resource.RLIMIT_NOFILE)

resource.setrlimit(resource.RLIMIT_NOFILE, (hard_fd_limit, hard_fd_limit))

except (ValueError, OSError):

print("Failed to increase the limit of opened files", flush=True, file=sys.stderr)

except ImportError:

pass

开发者ID:alexbers,项目名称:mtprotoproxy,代码行数:11,

示例22: bump_rlimit_nofile

​点赞 5

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def bump_rlimit_nofile() -> None:

try:

fno_soft, fno_hard = resource.getrlimit(resource.RLIMIT_NOFILE)

except resource.error:

logger.warning('could not read RLIMIT_NOFILE')

else:

if fno_soft < defines.EDGEDB_MIN_RLIMIT_NOFILE:

try:

resource.setrlimit(

resource.RLIMIT_NOFILE,

(min(defines.EDGEDB_MIN_RLIMIT_NOFILE, fno_hard),

fno_hard))

except resource.error:

logger.warning('could not set RLIMIT_NOFILE')

开发者ID:edgedb,项目名称:edgedb,代码行数:16,

示例23: prevent_core_dump

​点赞 5

# 需要导入模块: import resource [as 别名]

# 或者: from resource import setrlimit [as 别名]

def prevent_core_dump():

"""Prevent this process from generating a core dump."""

core_resource = resource.RLIMIT_CORE

try:

resource.getrlimit(core_resource)

except ValueError as ex:

raise DaemonError(

'Unable to limit core dump size: '

'system does not support RLIMIT_CORE resource limit') from ex

# Set hard & soft limits to 0, i.e. no core dump at all

resource.setrlimit(core_resource, (0, 0))

开发者ID:edgedb,项目名称:edgedb,代码行数:15,

注:本文中的resource.setrlimit方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。

 类似资料: