當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。