当前位置: 首页>>代码示例>>Python>>正文


Python resource.setrlimit方法代码示例

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


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

示例1: __exit__

# 需要导入模块: 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,代码来源:__init__.py

示例2: __enter__

# 需要导入模块: 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,代码来源:test_subprocess.py

示例3: test_urandom_failure

# 需要导入模块: 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,代码来源:test_os.py

示例4: _set

# 需要导入模块: 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,代码来源:test_setup.py

示例5: set_ulimit

# 需要导入模块: 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,代码来源:js_interesting.py

示例6: create_executable_limits

# 需要导入模块: 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,代码来源:compiled_executor.py

示例7: _EnforceProcessMemoryLimit

# 需要导入模块: 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,代码来源:tools.py

示例8: test_collision

# 需要导入模块: 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,代码来源:portlock.py

示例9: test_operating_on_small_slices_of_lists

# 需要导入模块: 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,代码来源:testOutOfProcPython.py

示例10: stdinpwn

# 需要导入模块: 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,代码来源:xploit.py

示例11: __exit__

# 需要导入模块: 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,代码来源:__init__.py

示例12: prevent_core_dump

# 需要导入模块: 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,代码来源:daemon.py

示例13: preexec_fn

# 需要导入模块: 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,代码来源:servermanager.py

示例14: setupEnvironment

# 需要导入模块: 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,代码来源:targetutils.py

示例15: xtrabackup_instance

# 需要导入模块: 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,代码来源:backup.py


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