Extract PID and parent PID from an output line from the PS command
764560
def _ps_extract_pid(self, line):
        
        this_pid = self.regex['pid'].sub(r'\g<1>', line)
        this_parent = self.regex['parent'].sub(r'\g<1>', line)
        
        # Return the main / parent PIDs
        return this_pid, this_parent
615922
def getpcmd(pid):
    
    if os.name == "nt":
        # Use wmic command instead of ps on Windows.
        cmd = 'wmic path win32_process where ProcessID=%s get Commandline 2> nul' % (pid, )
        with os.popen(cmd, 'r') as p:
            lines = [line for line in p.readlines() if line.strip("\r\n ") != ""]
            if lines:
                _, val = lines
                return val
    elif sys.platform == "darwin":
        # Use pgrep instead of /proc on macOS.
        pidfile = ".%d.pid" % (pid, )
        with open(pidfile, 'w') as f:
            f.write(str(pid))
        try:
            p = Popen(['pgrep', '-lf', '-F', pidfile], stdout=PIPE)
            stdout, _ = p.communicate()
            line = stdout.decode('utf8').strip()
            if line:
                _, scmd = line.split(' ', 1)
                return scmd
        finally:
            os.unlink(pidfile)
    else:
        # Use the /proc filesystem
        # At least on android there have been some issues with not all
        # process infos being readable. In these cases using the `ps` command
        # worked. See the pull request at
        # https://github.com/spotify/luigi/pull/1876
        try:
            with open('/proc/{0}/cmdline'.format(pid), 'r') as fh:
                if six.PY3:
                    return fh.read().replace('\0', ' ').rstrip()
                else:
                    return fh.read().replace('\0', ' ').decode('utf8').rstrip()
        except IOError:
            # the system may not allow reading the command line
            # of a process owned by another user
            pass

    # Fallback instead of None, for e.g. Cygwin where -o is an "unknown option" for the ps command:
    return '[PROCESS_WITH_PID={}]'.format(pid)
1102435
def _parse_proc_pid_cgroup(content):
    
    for ownCgroup in content:
        #each line is "id:subsystem,subsystem:path"
        ownCgroup = ownCgroup.strip().split(':')
        try:
            path = ownCgroup[2][1:] # remove leading /
        except IndexError:
            raise IndexError("index out of range for " + str(ownCgroup))
        for subsystem in ownCgroup[1].split(','):
            yield (subsystem, path)
200739
def read_pid_status(pid="self"):
    
    data = {}
    with open("/proc/%s/status" % (pid,), "rb") as status_file:
        for row in status_file:
            fields = row.split()
            if fields and fields[0] in [b"VmRSS:", b"Threads:", b"FDSize:"]:
                try:
                    data[fields[0].decode("ascii")[:-1]] = int(fields[1])
                except ValueError:
                    data[fields[0].decode("ascii")[:-1]] = fields[1].decode("ascii")
    return data
527549
def get_pid(options):
    """"""
    namespace = options['settings'] if options['settings'] else options['wsgi']
    return os.path.join('{}', '{}_{}.pid').format(PID_DIR, options['http_port'], namespace.replace('.', '_'))
1292993
def get_process_info(self, pid=None):
        '''
        

        '''

        pid = self._get_pid(pid)
        return self._call_rest_api('get', '/processes/'+pid, error='Failed to fetch process information')
290240
def __get_pid_by_scanning(self):
        ''
        dwProcessId = None
        dwThreadId = self.get_tid()
        with win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPTHREAD) as hSnapshot:
            te = win32.Thread32First(hSnapshot)
            while te is not None:
                if te.th32ThreadID == dwThreadId:
                    dwProcessId = te.th32OwnerProcessID
                    break
                te = win32.Thread32Next(hSnapshot)
        if dwProcessId is None:
            msg = "Cannot find thread ID %d in any process" % dwThreadId
            raise RuntimeError(msg)
        return dwProcessId
1221566
function ps (pids, options, done) {
  var pArg = pids.join(',')
  var args = ['-o', 'etime,pid,ppid,pcpu,rss,time', '-p', pArg]

  if (PLATFORM === 'aix') {
    args = ['-o', 'etime,pid,ppid,pcpu,rssize,time', '-p', pArg]
  }

  bin('ps', args, function (err, stdout, code) {
    if (err) return done(err)
    if (code === 1) {
      return done(new Error('No maching pid found'))
    }
    if (code !== 0) {
      return done(new Error('pidusage ps command exited with code ' + code))
    }
    var date = Date.now()

    // Example of stdout on *nix.
    // ELAPSED: format is [[dd-]hh:]mm:ss
    // RSS: is counted as blocks of 1024 bytes
    // TIME: format is [[dd-]hh:]mm:ss
    // %CPU: goes from 0 to vcore * 100
    //
    // Refs: http://www.manpages.info/linux/ps.1.html
    // NB: The columns are returned in the order given inside the -o option
    //
    //    ELAPSED   PID  PPID  %CPU     RSS        TIME
    // 2-40:50:53   430     1   3.0    5145  1-02:03:04
    //   40:50:53   432   430   0.0    2364  1-01:02:03
    //   01:50:50   727     1  10.0  348932       14:27
    //      00:20  7166     1   0.1    3756        0:00

    // Example of stdout on Darwin
    // ELAPSED: format is [[dd-]hh:]mm:ss
    // RSS: is counted as blocks of 1024 bytes
    // TIME: format is [[dd-]hh:]mm:ss.cc (cc are centiseconds)
    // %CPU: goes from 0 to vcore * 100
    //
    // Refs: https://ss64.com/osx/ps.html
    // NB: The columns are returned in the order given inside the -o option
    //
    //    ELAPSED   PID  PPID  %CPU     RSS           TIME
    // 2-40:50:53   430     1   3.0    5145  1-02:03:04.07
    //   40:50:53   432   430   0.0    2364  1-01:02:03.10
    //   01:50:50   727     1  10.0  348932       14:27.26
    //      00:20  7166     1   0.1    3756        0:00.02

    stdout = stdout.split(os.EOL)

    var statistics = {}
    for (var i = 1; i < stdout.length; i++) {
      var line = stdout[i].trim().split(/\s+/)

      if (!line || line.length !== 6) {
        continue
      }

      var pid = parseInt(line[1], 10)
      var hst = history.get(pid, options.maxage)
      if (hst === undefined) hst = {}

      var ppid = parseInt(line[2], 10)
      var memory = parseInt(line[4], 10) * 1024
      var etime = parseTime(line[0])
      var ctime = parseTime(line[5], true)

      var total = (ctime - (hst.ctime || 0))
      // time elapsed between calls in seconds
      var seconds = Math.abs(hst.elapsed !== undefined ? etime - hst.elapsed : etime)
      var cpu = seconds > 0 ? (total / seconds) * 100 : 0

      statistics[pid] = {
        cpu: cpu,
        memory: memory,
        ppid: ppid,
        pid: pid,
        ctime: ctime,
        elapsed: etime,
        timestamp: date
      }

      history.set(pid, statistics[pid], options.maxage)
    }

    done(null, statistics)
  })
}
1232042
private static function terminate_proc( $master_pid ) {

		$output = `ps -o ppid,pid,command | grep $master_pid`;

		foreach ( explode( PHP_EOL, $output ) as $line ) {
			if ( preg_match( '/^\s*(\d+)\s+(\d+)/', $line, $matches ) ) {
				$parent = $matches[1];
				$child  = $matches[2];

				if ( (int) $parent === (int) $master_pid ) {
					self::terminate_proc( $child );
				}
			}
		}

		if ( ! posix_kill( (int) $master_pid, 9 ) ) {
			$errno = posix_get_last_error();
			// Ignore "No such process" error as that's what we want.
			if ( 3 /*ESRCH*/ !== $errno ) {
				throw new RuntimeException( posix_strerror( $errno ) );
			}
		}
	}
745004
function pidOf( procName, callback ){
    if ( isString( procName )){
        var pids = [];

        procStat( procName, function( err, processes ){
            processes.object.forEach( function( proc ){
                pids.push( proc.pid )
            });

            callback( err, pids )
        })
    } else callback( new Error( 'A non-string process name was supplied' ), null, null )
}
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
142365
public static String pidMemoryUsage(int pid) throws IOException {
    Process process =
        new ProcessBuilder().command("ps", "-o", "pid,rss,vsz", "-p", Long.toString(pid)).start();

    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

    reader.readLine(); // Skip header

    String line = reader.readLine();
    String[] parts = line.trim().split("\\s+", 3);

    int readPid = Integer.parseInt(parts[0]);
    if (pid != readPid) {
      throw new RuntimeException("`ps` returned something unexpected: '" + line + "'");
    }

    long rss = Long.parseLong(parts[1]) * 1024;
    long vsz = Long.parseLong(parts[2]);

    // 0 pid, 1 rss, 2 vsz
    return String.format("%d\t%d", rss, vsz);
  }
687025
def get_process_mapping():
    
    output = subprocess.check_output([
        'ps', '-ww', '-o', 'pid=', '-o', 'ppid=', '-o', 'args=',
    ])
    if not isinstance(output, str):
        output = output.decode(sys.stdout.encoding)
    processes = {}
    for line in output.split('\n'):
        try:
            pid, ppid, args = line.strip().split(None, 2)
        except ValueError:
            continue
        processes[pid] = Process(
            args=tuple(shlex.split(args)), pid=pid, ppid=ppid,
        )
    return processes
129709
def get_process_mapping():
    
    with open('/proc/{0}/stat'.format(os.getpid())) as f:
        self_tty = f.read().split()[STAT_TTY]
    processes = {}
    for pid in os.listdir('/proc'):
        if not pid.isdigit():
            continue
        try:
            stat = '/proc/{0}/stat'.format(pid)
            cmdline = '/proc/{0}/cmdline'.format(pid)
            with open(stat) as fstat, open(cmdline) as fcmdline:
                stat = re.findall(r'\(.+\)|\S+', fstat.read())
                cmd = fcmdline.read().split('\x00')[:-1]
            ppid = stat[STAT_PPID]
            tty = stat[STAT_TTY]
            if tty == self_tty:
                processes[pid] = Process(
                    args=tuple(cmd), pid=pid, ppid=ppid,
                )
        except IOError:
            # Process has disappeared - just ignore it.
            continue
    return processes
1132528
def clear_stale_pids(pids, pid_dir='/tmp', prefix='', multi=False):
    ''
    if isinstance(pids, (int, float, long)):
        pids = [pids]
    pids = str2list(pids, map_=unicode)
    procs = map(unicode, os.listdir('/proc'))
    running = [pid for pid in pids if pid in procs]
    logger.warn(
        "Found %s pids running: %s" % (len(running),
                                       running))
    prefix = prefix.rstrip('.') if prefix else None
    for pid in pids:
        if prefix:
            _prefix = prefix
        else:
            _prefix = unicode(pid)
        # remove non-running procs
        if pid in running:
            continue
        if multi:
            pid_file = '%s%s.pid' % (_prefix, pid)
        else:
            pid_file = '%s.pid' % (_prefix)
        path = os.path.join(pid_dir, pid_file)
        if os.path.exists(path):
            logger.debug("Removing pidfile: %s" % path)
            try:
                remove_file(path)
            except OSError as e:
                logger.warn(e)
    return running
236805
def get_pid(name):
    """"""
    if not shutil.which("pidof"):
        return False

    try:
        subprocess.check_output(["pidof", "-s", name])
    except subprocess.CalledProcessError:
        return False

    return True
1326167
def get_pid(pid=None):
    '''
    '''
    if pid == None:
        if os.environ.get("PID",None) != None:
            pid = int(os.environ.get("PID"))
        # Then use current running script as process
        else:
            pid = os.getpid()
    print("pid is %s" %pid)
    return pid