Check if PID is running for Windows systems
329909
def _is_pid_running_on_windows(pid):
    
    import ctypes.wintypes

    kernel32 = ctypes.windll.kernel32
    handle = kernel32.OpenProcess(1, 0, pid)
    if handle == 0:
        return False
    exit_code = ctypes.wintypes.DWORD()
    ret = kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code))
    is_alive = (ret == 0 or exit_code.value == _STILL_ALIVE)  # pylint: disable=undefined-variable
    kernel32.CloseHandle(handle)
    return is_alive
955549
def is_running(process_id: int) -> bool:
    
    pstr = str(process_id)
    encoding = sys.getdefaultencoding()
    s = subprocess.Popen(["ps", "-p", pstr], stdout=subprocess.PIPE)
    for line in s.stdout:
        strline = line.decode(encoding)
        if pstr in strline:
            return True
    return False
976828
def status(self):
        """"""
        my_name = os.path.basename(sys.argv[0])
        if self._already_running():
            message = "{0} (pid  {1}) is running...\n".format(my_name, self.pid)
            sys.stdout.write(message)
            return 0
        sys.stdout.write("{0} is stopped\n".format(my_name))
        return 3
45225
def is_obsoleted_by_pid(pid):
    
    return d1_gmn.app.models.ScienceObject.objects.filter(
        obsoleted_by__did=pid
    ).exists()
220694
def windows_worker_pids
      tasklist_output = `tasklist /FI "IMAGENAME eq ruby.exe" /FO list`.encode("UTF-8", Encoding.locale_charmap)
      tasklist_output.split($/).select { |line| line =~ /^PID:/ }.collect { |line| line.gsub(/PID:\s+/, '') }
    end
54753
def get_process_pid(process_name):
    
    try:
        pid_filename = get_pid_filename(process_name)
        with open(pid_filename, mode='r') as pid_file:
            pid = int(pid_file.read().strip())
    except IOError:
        pid = None
    return pid
245317
function isRunning(pid, callback) {
    if (!pid) {
        return callback(false);
    }

    cp.exec(util.format(process.platform === 'win32' ?
        'tasklist /fi "PID eq %s" | findstr /i "node.exe"'
        : 'ps -f -p %s | grep "node"', pid),
        function (err, stdout, stderr) {
            callback(!err && !!stdout.toString().trim());
        });
}
1175061
protected function isRunning($pid)
    {
        if (! $pid) {
            return false;
        }

        try {
            return Process::kill($pid, 0);
        } catch (Throwable $e) {
            return false;
        }
    }
859458
def detect_process(cls, headers):
    """"""

    try:
      if 'Libprocess-From' in headers:
        return PID.from_string(headers['Libprocess-From']), False
      elif 'User-Agent' in headers and headers['User-Agent'].startswith('libprocess/'):
        return PID.from_string(headers['User-Agent'][len('libprocess/'):]), True
    except ValueError as e:
      log.error('Failed to detect process: %r' % e)
      pass

    return None, None
617979
public function isRunning($pid = null)
    {
        $process = $this->getProcess($pid);

        return !$process ? false : true;
    }
1159240
def pid(self):
    
    self._assert_bound()
    return PID(self._context.ip, self._context.port, self.name)
1328436
def get_extra_pids(self):
        
        while not self.is_retired:
            for proc in psutil.process_iter():
                for conn in proc.connections():
                    if conn.laddr.port == self.port:
                        self.logger.debug(f'py4j server for {self.name} appears to have pid {proc.pid}')
                        return [proc.pid]
            if self.is_executable_configured():
                # The helper process will start java and report the PID. Nothing to do here.
                return []
            time.sleep(1)
            if self.java_executable_path is None:
                self.logger.info(
                    "Can't auto-start java because no executable is configured. Please start java manually!")
            else:
                self.logger.info(f"Can't auto-start java because {self.java_executable_path} is not found. "
                                 "Please start java manually!")
624465
def identify_window(pid, text):
    """"""
    proc = None
    path = None
    uas = Session.query(UserApp).filter(UserApp.window_text == text)
    nontext = Session.query(UserApp).filter(UserApp.window_text == None)
    if uas.count():
        proc = psutil.Process(pid)
        try:
            path = proc.exe()
        except psutil.AccessDenied:
            path = proc.name()
        logger.debug("Trying to identify app, path=%s", path)
        app = uas.filter(UserApp.path == path).first()
        if app:
            return app, proc
    if nontext.count():
        if proc == None:
            proc = psutil.Process(pid)
            path = proc.exe()
            app = nontext.filter(UserApp.path == path).first()
            if app:
                return app, proc
    return None, None
666300
def status(self):
        """"""
        if self.pidfile is None:
            raise DaemonError('Cannot get status of daemon without PID file')

        pid = self._read_pidfile()
        if pid is None:
            self._emit_message(
                '{prog} -- not running\n'.format(prog=self.prog))
            sys.exit(1)

        proc = psutil.Process(pid)
        # Default data
        data = {
            'prog': self.prog,
            'pid': pid,
            'status': proc.status(),
            'uptime': '0m',
            'cpu': 0.0,
            'memory': 0.0,
        }

        # Add up all the CPU and memory usage of all the
        # processes in the process group
        pgid = os.getpgid(pid)
        for gproc in psutil.process_iter():
            try:
                if os.getpgid(gproc.pid) == pgid and gproc.pid != 0:
                    data['cpu'] += gproc.cpu_percent(interval=0.1)
                    data['memory'] += gproc.memory_percent()
            except (psutil.Error, OSError):
                continue

        # Calculate the uptime and format it in a human-readable but
        # also machine-parsable format
        try:
            uptime_mins = int(round((time.time() - proc.create_time()) / 60))
            uptime_hours, uptime_mins = divmod(uptime_mins, 60)
            data['uptime'] = str(uptime_mins) + 'm'
            if uptime_hours:
                uptime_days, uptime_hours = divmod(uptime_hours, 24)
                data['uptime'] = str(uptime_hours) + 'h ' + data['uptime']
                if uptime_days:
                    data['uptime'] = str(uptime_days) + 'd ' + data['uptime']
        except psutil.Error:
            pass

        template = ('{prog} -- pid: {pid}, status: {status}, '
                    'uptime: {uptime}, %cpu: {cpu:.1f}, %mem: {memory:.1f}\n')
        self._emit_message(template.format(**data))
889177
def get_pid(name, path=None):
    '''
    
    '''
    if name not in list_(limit='running', path=path):
        raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
    info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
    pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
    return pid
298347
def is_running(self):
        
        try:
            kill(int(self.pid.get()), 0)
            return True
        
        # Process not running, remove PID/lock file if it exists
        except:
            self.pid.remove()
            self.lock.remove()
            return False
271038
def isPIDValid(self, pid):
        
        ## Slightly copied wholesale from http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid
        ## Thanks to http://stackoverflow.com/users/1777162/ntrrgc and http://stackoverflow.com/users/234270/speedplane
        class ExitCodeProcess(ctypes.Structure):
            _fields_ = [('hProcess', ctypes.c_void_p),
                        ('lpExitCode', ctypes.POINTER(ctypes.c_ulong))]
        SYNCHRONIZE = 0x100000
        PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
        process = self._kernel32.OpenProcess(SYNCHRONIZE|PROCESS_QUERY_LIMITED_INFORMATION, 0, pid)
        if not process:
            return False
        ec = ExitCodeProcess()
        out = self._kernel32.GetExitCodeProcess(process, ctypes.byref(ec))
        if not out:
            err = self._kernel32.GetLastError()
            if self._kernel32.GetLastError() == 5:
                # Access is denied.
                logging.warning("Access is denied to get pid info.")
            self._kernel32.CloseHandle(process)
            return False
        elif bool(ec.lpExitCode):
            # There is an exit code, it quit
            self._kernel32.CloseHandle(process)
            return False
        # No exit code, it's running.
        self._kernel32.CloseHandle(process)
        return True