Executes a (shell) command in the background

        :return: the process' pid
160886
def execute_in_background(self):
        
        # http://stackoverflow.com/questions/1605520
        args = shlex.split(self.cmd)
        p = Popen(args)
        return p.pid
164450
def run_at_subprocess(self, use_subprocess, foo, *args, **kwrags):
        
        if use_subprocess is False:
            return foo(*args, **kwrags)

        child_pid = os.fork()
        if child_pid == 0:
            foo(*args, **kwrags)
            sys.exit(0)
        return os.waitpid(child_pid, 0)[1] == 0
1321803
def run_command(args, cwd = None, shell = False, timeout = None, env = None):
    '''
    
    '''
    from subprocess import PIPE, Popen
    from StringIO import StringIO
    import fcntl, os, signal
    p = Popen(args, shell = shell, cwd = cwd, stdout = PIPE, stderr = PIPE, env = env)
    tstart = time.time()
    buf = StringIO()

    # try to make it non-blocking
    try:
        fcntl.fcntl(p.stdout, fcntl.F_SETFL, fcntl.fcntl(p.stdout, fcntl.F_GETFL) | os.O_NONBLOCK)
    except Exception:
        pass

    while True:
        time.sleep(0.1)
        retcode = p.poll()
        try:
            buf.write(p.stdout.read())
        except Exception:
            pass
        if retcode is not None:
            break
        if timeout is not None and time.time() > tstart + timeout:
            print("timeout in process %u" % p.pid)
            try: 
                os.kill(p.pid, signal.SIGKILL)
            except OSError:
                pass
            p.wait()
    return buf.getvalue()
995595
def execute_command(command=None):
    """"""
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stdin = process.communicate()
    process.wait()
    return (stdout, stdin), process.returncode
1365106
def stop(self, sig=signal.SIGTERM):
        

        if self.pid is None:
            self.pid = self.read_pid()
        if self.pid is None:
            sp = BackgroundProcess.objects.filter(pk=1).first()
            if sp:
                self.pid = sp.pid
        if self.pid is None or self.pid == 0:
            logger.error("can't determine process id exiting.")
            return False
        if self.pid != getpid():
            # calling from outside the daemon instance
            logger.debug('send sigterm to daemon')
            try:
                kill(self.pid, sig)
                return True
            except OSError as e:
                if e.errno == errno.ESRCH:
                    return False
                else:
                    return False

        logger.debug('start termination of the daemon')
        BackgroundProcess.objects.filter(pk=self.process_id).update(
            last_update=now(),
            message='stopping..')

        timeout = time() + 60  # wait max 60 seconds
        self.kill_processes(signal.SIGTERM)
        while self.PROCESSES and time() < timeout:
            self.kill_processes(signal.SIGTERM)
            sleep(1)
        self.kill_processes(signal.SIGKILL)
        BackgroundProcess.objects.filter(pk=self.process_id).update(
            last_update=now(),
            message='stopped')
        logger.debug('termination of the daemon done')
        return True
677666
def shell_cmd(args, cwd=None):
  '''
  '''
  if cwd is None:
    cwd = os.path.abspath('.')
  if not isinstance(args, (list, tuple)):
    args = [args]
  ps = Popen(args, shell=True, cwd=cwd, stdout=PIPE, stderr=PIPE,
             close_fds=True)
  stdout, stderr = ps.communicate()
  if ps.returncode != 0:
    if stderr:
      stderr = stderr.strip()
    raise IOError('Shell command %s failed (exit status %r): %s' %\
      (args, ps.returncode, stderr))
  return stdout.strip()
1157847
def wait_to_start(self, pids=[]):
        '''
        

        '''
        actual_pids = self._get_pids(pids)
        return self.wait_for(pids=actual_pids, status_list=process_result_statuses+['in_process'])
252585
def system(*args)
      delayer.Deferred.Thread.new {
        Process.waitpid2(Kernel.spawn(*args))
      }.next{|_pid, status|
        if status && status.success?
          status
        else
          raise ForeignCommandAborted.new("command aborted: #{args.join(' ')}", process: status) end
      }
    end
1148724
def _psutil_kill_pid(pid):
    
    try:
        parent = Process(pid)
        for child in parent.children(recursive=True):
            child.kill()
        parent.kill()
    except NoSuchProcess:
        return
858163
def _exec_cmd(command):
    """"""
    proc = sp.Popen(command,
                    stdout=sp.PIPE,
                    shell=True)
    if six.PY2:
        res = proc.communicate()[0]
    else:
        res = proc.communicate(timeout=5)[0]
    return res, proc.returncode
1103939
def _run_shell_command(self, command, pipe_it=True):
        
        stdout = None
        if pipe_it:
            stdout = PIPE
        self.logger.debug('Executing shell command: %s' % command)
        return not bool(Popen(command, shell=True, stdout=stdout).wait())
221046
def execute(self, *, args: Union[list, tuple], options: dict) -> tuple:
        ''''''
        cmd = self._build_cmd(args)
        process = subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE,
                                   encoding='utf-8', shell=options.get('shell', False), env=options.get('env'))
        return process
33956
def running?
      Process.kill 0, @pid
      true
    rescue Errno::ESRCH
      false
    rescue Errno::EPERM
      true
    rescue
      false
    end
205883
def check_process(pidfile):
    
    # Check pid file
    try:
        handle = open(pidfile, 'r')
    except IOError as exc:
        if exc.errno == errno.ENOENT:
            # pid file disappeared
            return False, 0
        raise

    try:
        pid = int(handle.read().strip(), 10)
    except (TypeError, ValueError) as exc:
        raise EnvironmentError("Invalid PID file '%s' (%s), won't start!" % (pidfile, exc))
    finally:
        handle.close()

    # Check process
    try:
        os.kill(pid, 0)
    except EnvironmentError as exc:
        return False, pid
    else:
        return True, pid
187338
def get_shell(pid=None, max_depth=6):
    
    if not pid:
        pid = os.getpid()
    processes = dict(_iter_process())

    def check_parent(pid, lvl=0):
        ppid = processes[pid].get('parent_pid')
        shell_name = _get_executable(processes.get(ppid))
        if shell_name in SHELL_NAMES:
            return (shell_name, processes[ppid]['executable'])
        if lvl >= max_depth:
            return None
        return check_parent(ppid, lvl=lvl + 1)

    shell_name = _get_executable(processes.get(pid))
    if shell_name in SHELL_NAMES:
        return (shell_name, processes[pid]['executable'])
    try:
        return check_parent(pid)
    except KeyError:
        return None
1031315
function pidFind(pid) {
  if (!_.isFinite(pid)) return false;
  try {
    if (runningAsRoot()) {
      return process.kill(pid, 0);
    } else {
      return !!ps(pid);
    }
  } catch (e) {
    return false;
  }
}
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