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


Python os.getpgid方法代码示例

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


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

示例1: raise_sigint

# 需要导入模块: import os [as 别名]
# 或者: from os import getpgid [as 别名]
def raise_sigint():
    """
    Raising the SIGINT signal in the current process and all sub-processes.

    os.kill() only issues a signal in the current process (without subprocesses).
    CTRL+C on the console sends the signal to the process group (which we need).
    """
    if hasattr(signal, 'CTRL_C_EVENT'):
        # windows. Need CTRL_C_EVENT to raise the signal in the whole process group
        os.kill(os.getpid(), signal.CTRL_C_EVENT)
    else:
        # unix.
        pgid = os.getpgid(os.getpid())
        if pgid == 1:
            os.kill(os.getpid(), signal.SIGINT)
        else:
            os.killpg(os.getpgid(os.getpid()), signal.SIGINT) 
开发者ID:aetros,项目名称:aetros-cli,代码行数:19,代码来源:__init__.py

示例2: terminate_process

# 需要导入模块: import os [as 别名]
# 或者: from os import getpgid [as 别名]
def terminate_process():
    if m2ee:
        logging.info("stopping app...")
        if not m2ee.stop():
            if not m2ee.terminate():
                m2ee.kill()
    try:
        this_process = os.getpgid(0)
        logging.debug(
            "Terminating process group with pgid=%s", format(this_process)
        )
        os.killpg(this_process, signal.SIGTERM)
        time.sleep(3)
        os.killpg(this_process, signal.SIGKILL)
    except OSError:
        logging.exception("Failed to terminate all child processes") 
开发者ID:mendix,项目名称:cf-mendix-buildpack,代码行数:18,代码来源:start.py

示例3: _setPgid

# 需要导入模块: import os [as 别名]
# 或者: from os import getpgid [as 别名]
def _setPgid(pid, pgid):
    """set pgid of a process, ignored exception caused by race condition
    that occurs if already set by parent or child has already existed"""
    # Should just ignore on EACCES, as to handle race condition with parent
    # and child.  However some Linux kernels (seen in 2.6.18-53) report ESRCH
    # or EPERM.  To handle this is a straight-forward way, just check that the
    # change has been made.  However, in some cases the change didn't take,
    # retrying seems to make the problem go away.
    for i in range(0,5):
        try:
            os.setpgid(pid, pgid)
            return
        except OSError:
            if os.getpgid(pid) == pgid:
                return
            time.sleep(0.25) # sleep for retry
    # last try, let it return an error
    os.setpgid(pid, pgid)

# FIXME: why not use pipes.quote? 
开发者ID:ComparativeGenomicsToolkit,项目名称:Comparative-Annotation-Toolkit,代码行数:22,代码来源:pipeline.py

示例4: kill_em_all

# 需要导入模块: import os [as 别名]
# 或者: from os import getpgid [as 别名]
def kill_em_all(sig, frame):
    """
        Terminate all processes while capturing a SIGINT from the user
    """
    logger_gen.info('CTRL-C received, exiting')
    if is_windows():
        multiprocessing.sys.exit(1)
    
    else:
        pid = os.getpid()
        pgid = os.getpgid(pid)
        sid = os.getsid(os.getpid())
        
        # if launched with --no-xserver
        if pid == sid:
            os.killpg(pgid, signal.SIGKILL)
        else:
            time.sleep(4)
            multiprocessing.sys.exit(1) 
开发者ID:maaaaz,项目名称:webscreenshot,代码行数:21,代码来源:webscreenshot.py

示例5: test_start_and_terminate

# 需要导入模块: import os [as 别名]
# 或者: from os import getpgid [as 别名]
def test_start_and_terminate(self):
        local_task_job = mock.Mock()
        local_task_job.task_instance = mock.MagicMock()
        local_task_job.task_instance.run_as_user = None
        local_task_job.task_instance.command_as_list.return_value = [
            'airflow', 'tasks', 'test', 'test_on_kill', 'task1', '2016-01-01'
        ]

        runner = StandardTaskRunner(local_task_job)
        runner.start()
        time.sleep(0.5)

        pgid = os.getpgid(runner.process.pid)
        self.assertGreater(pgid, 0)
        self.assertNotEqual(pgid, os.getpgid(0), "Task should be in a different process group to us")

        processes = list(self._procs_in_pgroup(pgid))

        runner.terminate()

        for process in processes:
            self.assertFalse(psutil.pid_exists(process.pid), "{} is still alive".format(process))

        self.assertIsNotNone(runner.return_code()) 
开发者ID:apache,项目名称:airflow,代码行数:26,代码来源:test_standard_task_runner.py

示例6: test_start_and_terminate_run_as_user

# 需要导入模块: import os [as 别名]
# 或者: from os import getpgid [as 别名]
def test_start_and_terminate_run_as_user(self):
        local_task_job = mock.Mock()
        local_task_job.task_instance = mock.MagicMock()
        local_task_job.task_instance.run_as_user = getpass.getuser()
        local_task_job.task_instance.command_as_list.return_value = [
            'airflow', 'tasks', 'test', 'test_on_kill', 'task1', '2016-01-01'
        ]

        runner = StandardTaskRunner(local_task_job)

        runner.start()
        time.sleep(0.5)

        pgid = os.getpgid(runner.process.pid)
        self.assertGreater(pgid, 0)
        self.assertNotEqual(pgid, os.getpgid(0), "Task should be in a different process group to us")

        processes = list(self._procs_in_pgroup(pgid))

        runner.terminate()

        for process in processes:
            self.assertFalse(psutil.pid_exists(process.pid), "{} is still alive".format(process))

        self.assertIsNotNone(runner.return_code()) 
开发者ID:apache,项目名称:airflow,代码行数:27,代码来源:test_standard_task_runner.py

示例7: kill_proc

# 需要导入模块: import os [as 别名]
# 或者: from os import getpgid [as 别名]
def kill_proc(self, proc):
        """
        Stop the process if it is alive.
        Input:
          proc: dict: as created in start_proc()
        Return:
          str: information on what happened
        """
        if proc["process"].poll() == None:
            try:
                pgid = os.getpgid(proc["process"].pid)
                os.killpg(pgid, signal.SIGTERM)
            except:
                """
                Could already be dead
                """
            proc["process"].terminate()
            proc["runtime"] = time.time() - proc["start"]
            proc["running"] = False
            return "Process %s killed" % proc["process"].pid
        return "" 
开发者ID:idaholab,项目名称:civet,代码行数:23,代码来源:control.py

示例8: is_kernel_thread

# 需要导入模块: import os [as 别名]
# 或者: from os import getpgid [as 别名]
def is_kernel_thread(proc):
	if is_linux():
		"""Return True if proc is a kernel thread, False instead."""
		try:
			return os.getpgid(proc.pid) == 0
		# Python >= 3.3 raises ProcessLookupError, which inherits OSError
		except OSError:
			# return False is process is dead
			return False

	elif is_windows():
		return proc.pid == 0 or proc.pid == 4

	return False

#5.2 M 
开发者ID:turingsec,项目名称:marsnake,代码行数:18,代码来源:common.py

示例9: test_start_new_session

# 需要导入模块: import os [as 别名]
# 或者: from os import getpgid [as 别名]
def test_start_new_session(self):
        # For code coverage of calling setsid().  We don't care if we get an
        # EPERM error from it depending on the test execution environment, that
        # still indicates that it was called.
        try:
            output = subprocess.check_output(
                    [sys.executable, "-c",
                     "import os; print(os.getpgid(os.getpid()))"],
                    start_new_session=True)
        except OSError as e:
            if e.errno != errno.EPERM:
                raise
        else:
            parent_pgid = os.getpgid(os.getpid())
            child_pgid = int(output)
            self.assertNotEqual(parent_pgid, child_pgid) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:18,代码来源:test_subprocess.py

示例10: __init__

# 需要导入模块: import os [as 别名]
# 或者: from os import getpgid [as 别名]
def __init__(self, overhead_memory=2**30, cgroup_soft_limit=6 * 2 ** 30, cgroup_hard_limit=2 * 2 ** 30,
                 **kwargs):
        super(MemoryManager, self).__init__(**kwargs)

        # Create variables that will be set by future managers
        self.meta_learners = []
        # Private memory - physical memory that is only accesible to the process (e.g. no shared libs or arrays)
        self.child_private_memory = dict()
        self.learner_preference = []
        self.pid = os.getpid()
        self.pgid = os.getpgid(0)

        self.cgroup = 'backstreet_bayes_learners'
        # As long as program exits properly control group will be deleted after use
        self.cgroup_mem_limit = None  # limit for cgroup - set during first action
        self.overhead_memory = overhead_memory  # cgroup is limited to available mem - overhead
        self.cgroup_soft_limit = cgroup_soft_limit  # amount required inside the cgroup
        self.cgroup_hard_limit = cgroup_hard_limit  # Point at which emergency pause occurs

        self.password = os.environ.get('PW', '')  # Required to create and manage control groups 
开发者ID:jamesrobertlloyd,项目名称:automl-phase-2,代码行数:22,代码来源:managers.py

示例11: orphan_finder

# 需要导入模块: import os [as 别名]
# 或者: from os import getpgid [as 别名]
def orphan_finder(self):
        # Lists all the processes and finds ones in our group with parent 'init'
        # for ps in psutil.process_iter():
        #     if os.getpgid(ps.pid) == self.pgid:
        #         if ps.parent().name() == 'init':
        #             logger.error("Orphaned child with PID %d", ps.pid)
        #             ps.terminate()

        # More efficient - go through pids in tasks list
        with open('/sys/fs/cgroup/memory/{}/memory.usage_in_bytes'.format(self.cgroup), 'rb') as fp:
            for line in fp:
                pid = line.strip()
                if not pid:
                    continue
                pid = int(pid)
                try:
                    ps = psutil.Process(pid=pid)
                    if ps.parent().name() == 'init':
                        logger.error("Orphaned child with PID %d", pid)
                        ps.terminate()
                except (psutil.NoSuchProcess, psutil.AccessDenied, IOError):
                    pass 
开发者ID:jamesrobertlloyd,项目名称:automl-phase-2,代码行数:24,代码来源:managers.py

示例12: _FindLeadProcess

# 需要导入模块: import os [as 别名]
# 或者: from os import getpgid [as 别名]
def _FindLeadProcess(self):
    sudo_pid = os.getpgid(0)
    self._log.info('sudo_pid: %d', sudo_pid)
    ssh_pid = self._GetParentPID(sudo_pid)
    self._log.info('ssh_pid: %d', ssh_pid)
    if not ssh_pid:
      raise InternalError('Could not find the lead process')
    try:
      with open('/proc/%d/cmdline' % ssh_pid) as f:
        ssh_cmdline = f.read()
    except IOError:
      raise InternalError('Could not find the lead process')
    self._log.info('ssh_cmdline: %s', ssh_cmdline)
    if not ssh_cmdline.startswith('sshd: '):
      if self._params.debug:
        self._log.info('skipping SSH invocation check by --debug')
        return None
      raise InternalError('Not invoked from SSH')
    return sudo_pid 
开发者ID:google,项目名称:catnip,代码行数:21,代码来源:sandbox.py

示例13: execute

# 需要导入模块: import os [as 别名]
# 或者: from os import getpgid [as 别名]
def execute(self,dt):
        if self.finished: return "finished"
        if not self.running:
            self.process = Process(target = executeInProcessGroup, args = (self,))
            self.process.start()
            print "timeshare child PID:",self.process.pid
            os.setpgid(self.process.pid,self.process.pid)
            print "timeshare process group",os.getpgid(self.process.pid)
            assert os.getpgid(self.process.pid) == self.process.pid
            print "my process group",os.getpgrp(),"which should be",os.getpgid(0)
            assert os.getpgid(self.process.pid) != os.getpgid(0)
            self.running = True
        else:
            os.killpg(self.process.pid, signal.SIGCONT)
        
        self.process.join(dt)
        if self.process.is_alive():
            os.killpg(self.process.pid, signal.SIGSTOP)
            return "still running"
        else:
            self.finished = True
            return self.q.get() 
开发者ID:ellisk42,项目名称:TikZ,代码行数:24,代码来源:timeshare.py

示例14: cgroups_run_timed_subprocess

# 需要导入模块: import os [as 别名]
# 或者: from os import getpgid [as 别名]
def cgroups_run_timed_subprocess(command, *args, cgroup=None, timeout=1, **kwargs):
    """
    Starts a subprocess, waits for it and returns (exitcode, output, erroutput)
    """
    if cgroup is None:
        raise ValueError("No cgroup given")
    p = cgroups_Popen(command, *args, cgroup=cgroup, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=setsid,
                      **kwargs)
    output = b""
    err = b""
    try:
        while p.poll() is None:
            (o, e) = p.communicate(None, timeout=timeout)
            output += o
            err += e
    # On hangup kill the program (and children)
    except subprocess.TimeoutExpired:
        killpg(getpgid(p.pid), signal.SIGKILL)

    return p.returncode, output, err 
开发者ID:tum-i22,项目名称:macke,代码行数:22,代码来源:cgroups.py

示例15: _run_subprocess

# 需要导入模块: import os [as 别名]
# 或者: from os import getpgid [as 别名]
def _run_subprocess(*args, **kwargs):
    """
    Starts a subprocess, waits for it and returns (exitcode, output, erroutput)
    """
    p = subprocess.Popen(*args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=setsid, **kwargs)
    output = b""
    err = b""
    try:
        while p.poll() is None:
            (o, e) = p.communicate(None, timeout=1)
            output += o
            err += e
    # On hangup kill the program (and children)
    except subprocess.TimeoutExpired:
        killpg(getpgid(p.pid), signal.SIGKILL)

    return p.returncode, output, err 
开发者ID:tum-i22,项目名称:macke,代码行数:19,代码来源:Fuzzer.py


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