Python os.setpgrp() Examples

The following are code examples for showing how to use os.setpgrp(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: core-framework   Author: RedhawkSDR   File: io_helpers.py    (license) View Source Project 6 votes vote down vote up
def plot(self):
        if _domainless._DEBUG == True:
            print "Plot:plot()"

        # Error checking before launching plot
        if self.usesPortIORString == None:
            raise AssertionError, "Plot:plot() ERROR - usesPortIORString not set ... must call connect() on this object from another component"
        if self._usesPortName == None:
            raise AssertionError, "Plot:plot() ERROR - usesPortName not set ... must call connect() on this object from another component"
        if self._dataType == None:
            raise AssertionError, "Plot:plot() ERROR - dataType not set ... must call connect() on this object from another component"

        plotCommand = str(self._eclipsePath) + "/bin/plotter.sh -portname " + str(self._usesPortName) + " -repid " + str(self._dataType) + " -ior " + str(self.usesPortIORString)
        if _domainless._DEBUG == True:
            print "Plot:plotCommand " + str(plotCommand)
        args = _shlex.split(plotCommand)
        if _domainless._DEBUG == True:
            print "Plot:args " + str(args)
        try:
            dev_null = open('/dev/null','w')
            sub_process = _subprocess.Popen(args,stdout=dev_null,preexec_fn=_os.setpgrp)
            pid = sub_process.pid
            self._processes[pid] = sub_process
        except Exception, e:
            raise AssertionError, "Plot:plot() Failed to launch plotting due to %s" % ( e) 
Example 2
Project: muesr   Author: bonfus   File: xcrysden.py    (license) View Source Project 6 votes vote down vote up
def run_xcrysden(fname, block=True):
    if config.XCrysExec == None:
        warnings.warn("XCrysDen executable not found. Check configs.")
        return False
    
    
    spargs = dict(
        args   = [config.XCrysExec, "--xsf", fname], 
        stdout = subprocess.PIPE, 
        stderr = subprocess.PIPE
    )
    
    if not block:
        if os.name == 'posix':
            spargs['preexec_fn'] = os.setpgrp
        elif os.name == 'nt':
            spargs['creationflags'] = subprocess.CREATE_NEW_PROCESS_GROUP
        
        
    p = subprocess.Popen(**spargs)
    
    if block:
        out, err = p.communicate()
    return True 
Example 3
Project: picire   Author: renatahodovan   File: parallel_loop.py    (license) View Source Project 6 votes vote down vote up
def _body(self, i, target, args):
        """
        Executes the given function in its own process group (on Windows: in
        its own process).

        :param i: The index of the current configuration.
        :param target: The function to run in parallel.
        :param args: The arguments that the target should run with.
        """
        if not is_windows:
            os.setpgrp()

        try:
            if not target(*args):
                self._break.value = 1
        except:
            logger.warning('', exc_info=True)
            self._break.value = 1

        self._slots[i] = 0

        with self._lock:
            self._lock.notify() 
Example 4
Project: Z3sec   Author: IoTsec   File: radios.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, radio):
        self.radio = radio

        # start wireshark
        spargs = dict(
            args=['wireshark', '-k', '-i', '-'],  # Read packets from stdin immediately
            stdin=subprocess.PIPE,
            stderr=open(os.devnull, 'w'),
        )
        if os.name == 'posix':
            spargs['preexec_fn'] = os.setpgrp
        elif os.name == 'nt':
            spargs['creationflags'] = subprocess.CREATE_NEW_PROCESS_GROUP

        self.wireshark_proc = subprocess.Popen(**spargs)
        self.pd = killerbee.PcapDumper(killerbee.DLT_IEEE802_15_4, self.wireshark_proc.stdin,) 
Example 5
Project: Chromium_DepotTools   Author: p07r0457   File: proc.py    (license) View Source Project 6 votes vote down vote up
def setup_limit(self):
        """set up the process limit"""
        assert currentThread().getName() == 'MainThread'
        os.setpgrp()
        if self._limit_set <= 0:
            if self.max_time is not None:
                self._old_usr2_hdlr = signal(SIGUSR2, self._hangle_sig_timeout)
                self._timer = Timer(max(1, int(self.max_time) - self._elapse_time),
                                    self._time_out)
                self._start_time = int(time())
                self._timer.start()
            if self.max_cpu_time is not None:
                self._old_max_cpu_time = getrlimit(RLIMIT_CPU)
                cpu_limit = (int(self.max_cpu_time), self._old_max_cpu_time[1])
                self._old_sigxcpu_hdlr = signal(SIGXCPU, self._handle_sigxcpu)
                setrlimit(RLIMIT_CPU, cpu_limit)
            if self.max_memory is not None:
                self._msentinel = MemorySentinel(1, int(self.max_memory) )
                self._old_max_memory = getrlimit(RLIMIT_AS)
                self._old_usr1_hdlr = signal(SIGUSR1, self._hangle_sig_memory)
                as_limit = (int(self.max_memory), self._old_max_memory[1])
                setrlimit(RLIMIT_AS, as_limit)
                self._msentinel.start()
        self._limit_set += 1 
Example 6
Project: node-gn   Author: Shouqun   File: proc.py    (license) View Source Project 6 votes vote down vote up
def setup_limit(self):
        """set up the process limit"""
        assert currentThread().getName() == 'MainThread'
        os.setpgrp()
        if self._limit_set <= 0:
            if self.max_time is not None:
                self._old_usr2_hdlr = signal(SIGUSR2, self._hangle_sig_timeout)
                self._timer = Timer(max(1, int(self.max_time) - self._elapse_time),
                                    self._time_out)
                self._start_time = int(time())
                self._timer.start()
            if self.max_cpu_time is not None:
                self._old_max_cpu_time = getrlimit(RLIMIT_CPU)
                cpu_limit = (int(self.max_cpu_time), self._old_max_cpu_time[1])
                self._old_sigxcpu_hdlr = signal(SIGXCPU, self._handle_sigxcpu)
                setrlimit(RLIMIT_CPU, cpu_limit)
            if self.max_memory is not None:
                self._msentinel = MemorySentinel(1, int(self.max_memory) )
                self._old_max_memory = getrlimit(RLIMIT_AS)
                self._old_usr1_hdlr = signal(SIGUSR1, self._hangle_sig_memory)
                as_limit = (int(self.max_memory), self._old_max_memory[1])
                setrlimit(RLIMIT_AS, as_limit)
                self._msentinel.start()
        self._limit_set += 1 
Example 7
Project: fishnet   Author: niklasf   File: fishnet.py    (license) View Source Project 6 votes vote down vote up
def open_process(command, cwd=None, shell=True, _popen_lock=threading.Lock()):
    kwargs = {
        "shell": shell,
        "stdout": subprocess.PIPE,
        "stderr": subprocess.STDOUT,
        "stdin": subprocess.PIPE,
        "bufsize": 1,  # Line buffered
        "universal_newlines": True,
    }

    if cwd is not None:
        kwargs["cwd"] = cwd

    # Prevent signal propagation from parent process
    try:
        # Windows
        kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
    except AttributeError:
        # Unix
        kwargs["preexec_fn"] = os.setpgrp

    with _popen_lock:  # Work around Python 2 Popen race condition
        return subprocess.Popen(command, **kwargs) 
Example 8
Project: depot_tools   Author: webrtc-uwp   File: proc.py    (license) View Source Project 6 votes vote down vote up
def setup_limit(self):
        """set up the process limit"""
        assert currentThread().getName() == 'MainThread'
        os.setpgrp()
        if self._limit_set <= 0:
            if self.max_time is not None:
                self._old_usr2_hdlr = signal(SIGUSR2, self._hangle_sig_timeout)
                self._timer = Timer(max(1, int(self.max_time) - self._elapse_time),
                                    self._time_out)
                self._start_time = int(time())
                self._timer.start()
            if self.max_cpu_time is not None:
                self._old_max_cpu_time = getrlimit(RLIMIT_CPU)
                cpu_limit = (int(self.max_cpu_time), self._old_max_cpu_time[1])
                self._old_sigxcpu_hdlr = signal(SIGXCPU, self._handle_sigxcpu)
                setrlimit(RLIMIT_CPU, cpu_limit)
            if self.max_memory is not None:
                self._msentinel = MemorySentinel(1, int(self.max_memory) )
                self._old_max_memory = getrlimit(RLIMIT_AS)
                self._old_usr1_hdlr = signal(SIGUSR1, self._hangle_sig_memory)
                as_limit = (int(self.max_memory), self._old_max_memory[1])
                setrlimit(RLIMIT_AS, as_limit)
                self._msentinel.start()
        self._limit_set += 1 
Example 9
Project: maas   Author: maas   File: avahi.py    (license) View Source Project 6 votes vote down vote up
def run(args, output=sys.stdout, stdin=sys.stdin):
    """Observe an Ethernet interface and print ARP bindings."""

    # First, become a progress group leader, so that signals can be directed
    # to this process and its children; see p.u.twisted.terminateProcess.
    os.setpgrp()

    if args.input_file is None:
        reader = _reader_from_avahi()
    elif args.input_file == "-":
        reader = _reader_from_stdin(stdin)
    else:
        reader = _reader_from_file(args.input_file)
    try:
        _observe_mdns(reader, output, args.verbose)
    except KeyboardInterrupt:
        # Suppress this exception and allow for a clean exit instead.
        # ActionScript would exit 1 if we allowed it to propagate, but
        # SIGINT/SIGTERM are how this script is meant to be terminated.
        pass 
Example 10
Project: wuye.vim   Author: zhaoyingnan911   File: proc.py    (license) View Source Project 6 votes vote down vote up
def setup_limit(self):
        """set up the process limit"""
        assert currentThread().getName() == 'MainThread'
        os.setpgrp()
        if self._limit_set <= 0:
            if self.max_time is not None:
                self._old_usr2_hdlr = signal(SIGUSR2, self._hangle_sig_timeout)
                self._timer = Timer(max(1, int(self.max_time) - self._elapse_time),
                                    self._time_out)
                self._start_time = int(time())
                self._timer.start()
            if self.max_cpu_time is not None:
                self._old_max_cpu_time = getrlimit(RLIMIT_CPU)
                cpu_limit = (int(self.max_cpu_time), self._old_max_cpu_time[1])
                self._old_sigxcpu_hdlr = signal(SIGXCPU, self._handle_sigxcpu)
                setrlimit(RLIMIT_CPU, cpu_limit)
            if self.max_memory is not None:
                self._msentinel = MemorySentinel(1, int(self.max_memory) )
                self._old_max_memory = getrlimit(RLIMIT_AS)
                self._old_usr1_hdlr = signal(SIGUSR1, self._hangle_sig_memory)
                as_limit = (int(self.max_memory), self._old_max_memory[1])
                setrlimit(RLIMIT_AS, as_limit)
                self._msentinel.start()
        self._limit_set += 1 
Example 11
Project: pyserver   Author: juhgiyo   File: subProcController.py    (license) View Source Project 6 votes vote down vote up
def create_subprocess(self, proc_name, arg):
        proc = None
        with self.lock:
            if proc_name in self.sub_proc_map:
                raise Exception('proc_name already exists!')
            try:
                def preexec_function():
                    os.setpgrp()

                proc = subprocess.Popen(arg
                                        , preexec_fn=preexec_function
                                        )
                self.sub_proc_map[proc_name] = proc
            except Exception as e:
                print e
                traceback.print_exc()
        return proc 
Example 12
Project: libSigNetSim   Author: vincent-noel   File: OptimizationExecution.py    (license) View Source Project 6 votes vote down vote up
def compile(self, nb_procs):

		if nb_procs > 1:
			target = "lsa.mpi"

		else:
			target = "lsa"

		cmd_comp = "make -f %sMakefile -C %s %s 1>/dev/null" % (
								self.getTempDirectory(),
								self.getTempDirectory(),
								target)

		res_comp = call(cmd_comp,
								stdout=open("%sout_optim_comp" % self.getTempDirectory(),"w"),
								stderr=open("%serr_optim_comp" % self.getTempDirectory(),"w"),
								shell=True, preexec_fn=setpgrp, close_fds=True)

		if res_comp != 0 or getsize(self.getTempDirectory() + "err_optim_comp") > 0:
			return self.OPTIM_FAILURE
		else:
			return self.OPTIM_SUCCESS 
Example 13
Project: slug   Author: xonsh   File: posix.py    (license) View Source Project 6 votes vote down vote up
def start(self):
        """
        Start the process.
        """
        preexec = None
        if hasattr(self, '_process_group_leader'):
            # This probably needs some kind of syncronization...
            if self._process_group_leader is ...:
                preexec = os.setpgrp
            else:
                pgid = self._process_group_leader.pid

                def preexec():
                    os.setpgid(0, pgid)

        self._proc = subprocess.Popen(
            # What to execute
            self.cmd,
            preexec_fn=preexec,
            # What IO it has
            stdin=self.stdin, stdout=self.stdout, stderr=self.stderr,
            # Environment it executes in
            cwd=self.cwd, env=self.environ,
        ) 
Example 14
Project: core-framework   Author: RedhawkSDR   File: test_01_DeviceManager.py    (license) View Source Project 5 votes vote down vote up
def test_RogueService(self):
        devmgr_nb, devMgr = self.launchDeviceManager("/nodes/test_BasicTestDevice_node/DeviceManager.dcd.xml")
        import ossie.utils.popen as _popen
        from ossie.utils import redhawk
        rhdom= redhawk.attach(scatest.getTestDomainName())

        serviceName = "fake_1"
        args = []
        args.append("sdr/dev/services/fake/python/fake.py")
        args.append("DEVICE_MGR_IOR")
        args.append(self._orb.object_to_string(devMgr))
        args.append("SERVICE_NAME")
        args.append(serviceName)
        exec_file = "sdr/dev/services/fake/python/fake.py"
        external_process = _popen.Popen(args, executable=exec_file, cwd=os.getcwd(), preexec_fn=os.setpgrp)

        time.sleep(2)

        names=[serviceName]
        for svc in devMgr._get_registeredServices():
            self.assertNotEqual(svc, None)
            self.assertEqual(svc.serviceName in names, True)

        for svc in rhdom.services:
            self.assertNotEqual(svc, None)
            self.assertEqual(svc._instanceName in names, True)

        # Kill the external services
        os.kill(external_process.pid, signal.SIGINT)

        time.sleep(1)

        # check rogue service is removed
        self.assertEquals(len(devMgr._get_registeredServices()), 0)
        self.assertEquals(len(rhdom.services), 0) 
Example 15
Project: core-framework   Author: RedhawkSDR   File: launcher.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, command, arguments, environment=None, stdout=None):
        self.__terminateRequested = False
        self.__command = command
        self.__arguments = arguments
        log.debug('%s %s', command, ' '.join(arguments))
        self.__process = Popen([command]+arguments, executable=command,
                               cwd=os.getcwd(), env=environment,
                               stdout=stdout, stderr=subprocess.STDOUT,
                               preexec_fn=os.setpgrp)
        self.__tracker = None
        self.__callback = None
        self.__children = [] 
Example 16
Project: core-framework   Author: RedhawkSDR   File: device.py    (license) View Source Project 5 votes vote down vote up
def _execute(self, command, options, parameters):
        """
        Launches the given command after SCA-specific processing has taken
        place in 'execute'. Override or extend this method in subclasses to
        have more control over the launching of components.

        Returns the pid of the new process.
        """
        args = [command]
        # SR:446, SR:447
        for param in parameters:
            if param.value.value() != None:
                args.append(str(param.id))
                # SR:453 indicates that an InvalidParameters exception should be
                # raised if the input parameter is not of a string type; however,
                # version 2.2.2 of the SCA spec is less strict in its wording. For
                # our part, as long as the value can be stringized, it is accepted,
                # to allow component developers to use more specific types.
                try:
                    args.append(str(param.value.value()))
                except:
                    raise CF.ExecutableDevice.InvalidParameters([param])
        self._log.debug("Popen %s %s", command, args)

        # SR:445
        try:
            sp = ossie.utils.Popen(args, executable=command, cwd=os.getcwd(), close_fds=True, stdin=self._devnull, preexec_fn=os.setpgrp)
        except OSError, e:
            # SR:455
            # CF error codes do not map directly to errno codes, so at present
            # we omit the enumerated value.
            self._log.error("subprocess.Popen: %s", e.strerror)
            raise CF.ExecutableDevice.ExecuteFail(CF.CF_NOTSET, e.strerror)

        pid = sp.pid
        self._applications[pid] = sp
        # SR:449
        self._log.debug("execute() --> %s", pid)
        self._log.debug("APPLICATIONS %s", self._applications)
        return pid 
Example 17
Project: ravel   Author: ravel-net   File: of.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def preexec_fn():
    # don't forward signals to child process
    # we need this when starting a Pox subprocess, so that SIGINTs from the CLI
    # aren't forwarded to Pox, causing it to terminate early
    os.setpgrp() 
Example 18
Project: abusehelper   Author: Exploit-install   File: roomgraph.py    (license) View Source Project 5 votes vote down vote up
def _start_worker(self):
        env = dict(os.environ)
        env["ABUSEHELPER_SUBPROCESS"] = ""

        # Find out the full package & module name. Don't refer to the
        # variable __loader__ directly to keep flake8 (version 2.5.0)
        # linter happy.
        fullname = globals()["__loader__"].fullname

        own_conn, other_conn = native_socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
        try:
            process = subprocess.Popen(
                [sys.executable, "-m", fullname],
                preexec_fn=os.setpgrp,
                stdin=other_conn.fileno(),
                close_fds=True,
                env=env
            )

            try:
                conn = socket.fromfd(own_conn.fileno(), socket.AF_UNIX, socket.SOCK_STREAM)
            except:
                process.terminate()
                process.wait()
                raise
        finally:
            own_conn.close()
            other_conn.close()
        return process, conn 
Example 19
Project: DL4MT   Author: thompsonb   File: pyro_utils.py    (license) View Source Project 5 votes vote down vote up
def __enter__(self):
        # The os.setpgrp() is passed in the argument preexec_fn so
        # it's run after the fork() and before  exec() to run the shell.
        my_env = os.environ.copy()
        for k, v in self.extra_env_vars.items():
            print('setting %s=%s (expanded to "%s") in environment' % (k, v, os.path.expandvars(str(v))))
            # Allow updates like PATH='/foo/bar/:$PATH'
            my_env[k] = os.path.expandvars(str(v))
        print 'command:', self.cmd
        self.proc = sp.Popen(self.cmd, shell=True, env=my_env, preexec_fn=os.setpgrp)
        time.sleep(5)  # give process a little time to start
        return self.proc 
Example 20
Project: pymotw3   Author: reingart   File: subprocess_signal_setpgrp.py    (license) View Source Project 5 votes vote down vote up
def show_setting_prgrp():
    print('Calling os.setpgrp() from {}'.format(os.getpid()))
    os.setpgrp()
    print('Process group is now {}'.format(
        os.getpid(), os.getpgrp()))
    sys.stdout.flush() 
Example 21
Project: chi   Author: rmst   File: util.py    (license) View Source Project 5 votes vote down vote up
def run_daemon(script, kwargs, executable=sys.executable):
  args = ['nohup', executable, script] + cmd_args(**kwargs)
  logger.debug(' '.join(args))
  return subprocess.Popen(args,
                          stdout=open('/dev/null', 'w'),
                          stderr=open('/dev/null', 'w'),
                          preexec_fn=os.setpgrp) 
Example 22
Project: pynapl   Author: marinuso   File: RunDyalog.py    (license) View Source Project 5 votes vote down vote up
def posix_dythread(inf,outf, dyalog=b"dyalog"):
    # find the path to IPC.dyalog
    ipcpath=to_bytes(os.path.dirname(SCRIPTFILE))+b'/IPC.dyalog'

    # find the path, Py.dyalog should be in the same folder
    path=to_bytes(os.path.dirname(SCRIPTFILE))+b'/Py.dyalog'
    
    # Run the Dyalog instance in this thread
    p=Popen([dyalog, b'-script'], stdin=PIPE, preexec_fn=os.setpgrp)
    s=script%(pystr(ipcpath),pystr(path),inf,outf)
    p.communicate(input=s.encode('utf8')) 
Example 23
Project: pynapl   Author: marinuso   File: RunDyalog.py    (license) View Source Project 5 votes vote down vote up
def win_dythread(dyalog, cygwin=False):

    startupinfo = None
    preexec_fn = None
    
    if not cygwin:
        # not cygwin 
        # hide the window
        # imported here because STARTUPINFO only exists on Windows
        import subprocess
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwflags = subprocess.STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = 0
    elif cygwin:
        # cygwin: we need to setpgrp like on Linux or Dyalog will crash
        preexec_fn = os.setpgrp 
    
        
    path=to_bytes(os.path.dirname(SCRIPTFILE))+b'/WinPySlave.dyapp'
    if cygwin: path=cyg_convert_path(path, b"--windows") 
    
    dyalog = pystr(dyalog)
    arg = pystr(b'DYAPP=' + path)
    
    x=Popen([dyalog, arg], startupinfo=startupinfo,
          preexec_fn=preexec_fn)
    x.communicate() 
Example 24
Project: icfpc2016-judge   Author: icfpc2016   File: devserver_main.py    (license) View Source Project 5 votes vote down vote up
def _run_cron_in_background():
    if os.environ.get('BOTTLE_CHILD'):
        return
    proc = subprocess.Popen(
        [sys.executable, '-m', 'hibiki.cron_main'] + sys.argv[1:],
        preexec_fn=os.setpgrp)
    def kill_cron():
        os.killpg(proc.pid, signal.SIGTERM)
        proc.wait()
    atexit.register(kill_cron) 
Example 25
Project: RocketTM   Author: kianxineki   File: rockettm_server.py    (license) View Source Project 5 votes vote down vote up
def safe_call(self, func, apply_max_time, body):
        # os.setpgrp()  # kill non propagate

        if 'gevent' not in sys.modules:
            return_dict = Manager().dict()
            p = Process(target=self.safe_worker, args=(func, return_dict,
                                                       apply_max_time, body))
            p.start()
            p.join()
        else:
            return_dict = {}
            self.safe_worker(func, return_dict, apply_max_time, body)

        return return_dict 
Example 26
Project: qqbot   Author: pandolia   File: common.py    (license) View Source Project 5 votes vote down vote up
def CallInNewConsole(args=None):
    args = sys.argv[1:] if args is None else args
    
    if not args:
        return 1

    osName = platform.system()

    if osName == 'Windows':
        return subprocess.call(['start'] + list(args), shell=True)
        
    elif osName == 'Linux':
        cmd = subprocess.list2cmdline(args)
        if HasCommand('mate-terminal'):
            args = ['mate-terminal', '-e', cmd]
        elif HasCommand('gnome-terminal'):
            args = ['gnome-terminal', '-e', cmd]
        elif HasCommand('xterm'):
            args = ['sh', '-c', 'xterm -e %s &' % cmd]
        else:
            return 1
            # args = ['sh', '-c', 'nohup %s >/dev/null 2>&1 &' % cmd]
        return subprocess.call(args, preexec_fn=os.setpgrp)
        
    elif osName == 'Darwin':
        return subprocess.call(['open','-W','-a','Terminal.app'] + list(args))
        
    else:
        return 1
        # return subprocess.Popen(list(args) + ['&']) 
Example 27
Project: trex-http-proxy   Author: alwye   File: trex_console.py    (license) View Source Project 5 votes vote down vote up
def do_tui (self, line):
        '''Shows a graphical console\n'''

        parser = parsing_opts.gen_parser(self,
                                         "tui",
                                         self.do_tui.__doc__,
                                         parsing_opts.XTERM)

        opts = parser.parse_args(line.split())
        if opts is None:
            return

        if opts.xterm:
            if not os.path.exists('/usr/bin/xterm'):
                print(format_text("XTERM does not exists on this machine", 'bold'))
                return

            info = self.stateless_client.get_connection_info()

            exe = './trex-console --top -t -q -s {0} -p {1} --async_port {2}'.format(info['server'], info['sync_port'], info['async_port'])
            cmd = ['/usr/bin/xterm', '-geometry', '111x49', '-sl', '0', '-title', 'trex_tui', '-e', exe]

            # detach child
            self.terminal = subprocess.Popen(cmd, preexec_fn = os.setpgrp)

            return


        with self.stateless_client.logger.supress():
            self.tui.show() 
Example 28
Project: gerrymanderer   Author: emusical   File: client.py    (license) View Source Project 5 votes vote down vote up
def _run_async(self, argv):

        def _preexec_fn():
            os.setpgrp()

        stdout = subprocess.PIPE
        stderr = subprocess.PIPE
        LOG.debug("Running cmd %s" % " ".join(argv))
        sp = subprocess.Popen(argv,
                              stdout=stdout,
                              stderr=stderr,
                              stdin=None,
                              preexec_fn=_preexec_fn)
        return sp 
Example 29
Project: BAG_framework   Author: ucb-art   File: gui.py    (license) View Source Project 5 votes vote down vote up
def start_viewer():
    cmd = [sys.executable, '-m', 'bag.io.gui']
    devnull = open(os.devnull, 'w')
    proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=devnull,
                            stderr=subprocess.STDOUT,
                            preexec_fn=os.setpgrp)
    return proc 
Example 30
Project: p4app   Author: p4lang   File: appprocrunner.py    (license) View Source Project 5 votes vote down vote up
def start(self):
        self.stdout_file = open(self.stdout_filename, 'w')
        self.cmd = self.formatCmd(self.host_conf['cmd'])
        self.proc = self.host.popen(self.cmd, stdout=self.stdout_file, shell=True, preexec_fn=os.setpgrp)

        print self.host.name, self.cmd

        if 'startup_sleep' in self.host_conf:
            sleep(self.host_conf['startup_sleep']) 
Example 31
Project: timmy   Author: openstack   File: tools.py    (license) View Source Project 5 votes vote down vote up
def setup_handle_sig(subprocess=False):
    if os.getpid() != os.getpgrp():
        os.setpgrp()
    sig_handler = main_handle_sig if not subprocess else sub_handle_sig
    for sig in [signal.SIGINT, signal.SIGTERM, signal.SIGHUP]:
        signal.signal(sig, sig_handler)
    signal.signal(signal.SIGUSR1, handle_sig_usr1) 
Example 32
Project: scapy-radio   Author: BastilleResearch   File: gnuradio.py    (license) View Source Project 5 votes vote down vote up
def sigint_ignore():
    import os
    os.setpgrp() 
Example 33
Project: borgcube   Author: enkore   File: server.py    (license) View Source Project 5 votes vote down vote up
def fork(self):
        pid = os.fork()
        if pid:
            log.debug('Forked worker PID is %d', pid)
            self.stats['forks'] += 1
        else:
            os.setpgrp()
            self.socket.close()
            self.socket = None
            exit_by_exception()
        return pid 
Example 34
Project: mdmscripts   Author: erikng   File: munki_auto_trigger.py    (license) View Source Project 5 votes vote down vote up
def main():
    munkicheck = ['/usr/local/munki/managedsoftwareupdate', '--auto']
    try:

        munki = subprocess.Popen(munkicheck, preexec_fn=os.setpgrp)
    except:  # noqa
        pass 
Example 35
Project: dockerproxy   Author: mdsecresearch   File: dockerproxy.py    (license) View Source Project 5 votes vote down vote up
def run_browser(self):
        configpath = expanduser("~/.dockerproxy.conf")
        logging.debug(configpath)
        if os.path.isfile(configpath):
            config = SafeConfigParser()
            config.read(configpath)
            httphandler = config.get('browser','httphandler')
            if "chrome" in httphandler:
                defaultbrowserpath = self.CHROMEPATH
            elif "firefox" in httphandler:
                defaultbrowserpath = self.FIREFOXPATH
            elif "safari" in httphandler:
                defaultbrowserpath = self.SAFARIPATH
            else:
                # *shrug* you're using something else
                defaultbrowserpath = self.SAFARIPATH

            #attempt to avoid cmd & arg injection
            defaultbrowserpath += " {}"
            cmd = shlex.split(defaultbrowserpath.format(pipes.quote(self.url)))

            if self.DEBUG:
                logging.debug("### Invoking: " + str(cmd))

            result = Popen(cmd, shell=False, env=self.ENVIRONMENT, stdin=None, stdout=None, stderr=None, close_fds=True, preexec_fn=os.setpgrp)
            # need to give the process a little time to load before exiting :)
            time.sleep(2)
            sys.exit(0)
        else:
            tkMessageBox.showinfo("Error", "Config file does not exist") 
Example 36
Project: dockerproxy   Author: mdsecresearch   File: dockerproxy.py    (license) View Source Project 5 votes vote down vote up
def run_throwaway(self):
        import getpass
        username = getpass.getuser()
        #attempt to avoid cmd & arg injection
        self.DOCKER_THROWAWAYCMDARGS = self.DOCKER_THROWAWAYCMDARGS.format(username, pipes.quote(self.url))
        cmd = shlex.split("docker " + self.DOCKER_THROWAWAYCMDARGS)

        if self.DEBUG:
            logging.debug("### Invoking: " + str(cmd))

        result = Popen(cmd, shell=False, env=self.ENVIRONMENT, stdin=None, stdout=None, stderr=None, close_fds=True, preexec_fn=os.setpgrp)
        #need to give the process a little time to load before exiting :)
        time.sleep(5)
        sys.exit(0) 
Example 37
Project: build   Author: freenas   File: utils.py    (license) View Source Project 5 votes vote down vote up
def sh_spawn(*args, **kwargs):
    logfile = kwargs.pop('log', None)
    mode = kwargs.pop('mode', 'w')
    nofail = kwargs.pop('nofail', False)
    detach = kwargs.pop('detach', False)
    cmd = e(' '.join(args), **get_caller_vars())
    if logfile:
        sh('mkdir -p', os.path.dirname(logfile))
        f = open(logfile, mode)

    def preexec():
        os.setpgrp()

    debug('sh: {0}', cmd)
    return subprocess.Popen(cmd, stdout=f if logfile else None, preexec_fn=preexec if detach else None, stderr=subprocess.STDOUT, shell=True) 
Example 38
Project: ifictionbot   Author: ykrivopalov   File: session.py    (license) View Source Project 5 votes vote down vote up
def start(self, path, game):
        info("chat %s: frob start", self._chat_id)
        self._process = await asyncio.create_subprocess_shell(
            'frob -iplain {}/{}.gam'.format(path, game),
            stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.STDOUT, preexec_fn=os.setpgrp)

        if os.path.exists(path + '/last.sav'):
            await self._read_output()  # just ignore all previous output
            self.restore_game('last')
        else:
            self._messages_to_skip = 1  # ignore frobTADS intro msg 
Example 39
Project: SMAC3   Author: automl   File: genericWrapper.py    (license) View Source Project 5 votes vote down vote up
def get_command_line_args_ext(self, runargs, config, ext_call):
        '''
        When production of the target algorithm is done from a source other than python,
        override this method to return a command call list to execute whatever you need to produce the command line.

        Args:
            runargs: a map of any non-configuration arguments required for the execution of the solver.
            config: a mapping from parameter name (with prefix) to parameter value.
            ext_call: string to call external program to get callstring of target algorithm
        Returns:
            A command call list to execute the command producing a single line of output containing the solver command string
        '''
        callstring_in = NamedTemporaryFile(suffix=".csv", prefix="callstring", dir=self._tmp_dir, delete=False)
        callstring_in.write("%s\n" %(runargs["instance"]))
        callstring_in.write("%d\n" %(runargs["seed"]))
        for name,value in config.items():
            callstring_in.write("%s,%s\n" %(name,value))
        callstring_in.flush()
        
        cmd = ext_call.split(" ")
        cmd.append(callstring_in.name)
        self.print_d(" ".join(cmd))
        try:
            io = Popen(cmd, shell=False, preexec_fn=os.setpgrp, stdout=PIPE, universal_newlines=True)
            self._subprocesses.append(io)
            out_, _ = io.communicate()
            self._subprocesses.remove(io)
        except OSError:
            self._ta_misc = "failed to run external program for output parsing : %s" %(" ".join(cmd))
            self._ta_runtime = self._cutoff
            self._exit_code = 2
            sys.exit(2)
        if not out_ :
            self._ta_misc = "external program for output parsing yielded empty output: %s" %(" ".join(cmd))
            self._ta_runtime = self._cutoff
            self._exit_code = 2
            sys.exit(2)
        callstring_in.close()
        os.remove(callstring_in.name)
        self._instance = runargs["instance"]
        return out_.strip('\n\r\b') 
Example 40
Project: SMAC3   Author: automl   File: genericWrapper.py    (license) View Source Project 5 votes vote down vote up
def process_results_ext(self, filepointer, out_args, ext_call):
        '''
        Args:
            filepointer: a pointer to the file containing the solver execution standard out.
            exit_code : exit code of target algorithm
        Returns:
            A map containing the standard AClib run results. The current standard result map as of AClib 2.06 is:
            {
                "status" : <"SAT"/"UNSAT"/"TIMEOUT"/"CRASHED"/"ABORT">,
                "quality" : <a domain specific measure of the quality of the solution [optional]>,
                "misc" : <a (comma-less) string that will be associated with the run [optional]>
            }
        '''
        
        cmd = ext_call.split(" ")
        cmd.append(filepointer.name)
        self.print_d(" ".join(cmd))
        try:
            io = Popen(cmd, shell=False, preexec_fn=os.setpgrp, stdout=PIPE, universal_newlines=True)
            self._subprocesses.append(io)
            out_, _ = io.communicate()
            self._subprocesses.remove(io)
        except OSError:
            self._ta_misc = "failed to run external program for output parsing"
            self._ta_runtime = self._cutoff
            self._exit_code = 2
            sys.exit(2)
        
        result_map = {}
        for line in out_.split("\n"):
            if line.startswith("status:"):
                result_map["status"] = line.split(":")[1].strip(" ")
            elif line.startswith("quality:"):
                result_map["quality"] = line.split(":")[1].strip(" ")
            elif line.startswith("misc:"):
                result_map["misc"] = line.split(":")[1]
        
        return result_map 
Example 41
Project: gitsome   Author: donnemartin   File: built_ins.py    (license) View Source Project 5 votes vote down vote up
def _subproc_pre():
    os.setpgrp()
    signal.signal(signal.SIGTSTP, lambda n, f: signal.pause()) 
Example 42
Project: PJON-python   Author: Girgitt   File: wrapper_client.py    (license) View Source Project 5 votes vote down vote up
def start_subproc(self):
        close_fds = False if sys.platform == 'win32' else True
        if sys.platform == 'win32':
            self._pipe = subprocess.Popen(self._subproc_command, shell=False, close_fds=close_fds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0, startupinfo=self._startupinfo, env=os.environ)
        elif sys.platform == 'linux2':
            self._pipe = subprocess.Popen(self._subproc_command, shell=False, close_fds=close_fds,
                                          stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                                          bufsize=0, env=os.environ, preexec_fn=os.setpgrp)

        self._birthtime = time.time() 
Example 43
Project: yawn   Author: aclowes   File: executor.py    (license) View Source Project 5 votes vote down vote up
def start_subprocess(self, execution_id: int, command: str, environment: dict, timeout: int) -> None:
        """
        Start a subprocess:
        - extend the parent process's environment with custom environment variables
        - track stdout and stderr file descriptors for later reading
        - set process group to facilitate killing any children of the command

        :param execution_id: the ID of the Execution instance being run
        :param command: a list of arguments, first argument must be an executable
        :param environment: environment variables from the WorkflowRun
        :param timeout: maximum number of seconds the process should be allowed to run for
        """
        process_environment = os.environ.copy()
        for key, value in environment.items():
            # all variables must be strings, be explicit so it fail in our code
            process_environment[key] = str(value)

        logger.info('Starting execution #%s', execution_id)

        process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                   preexec_fn=os.setpgrp, env=process_environment, shell=True)

        # store references to the process and file descriptors
        # Popen gives us io.BufferedReader; get the raw file handle instead
        execution = Execution(process, execution_id, timeout)
        self.pipes.update({
            process.stdout.raw: execution,
            process.stderr.raw: execution
        })
        self.running[execution_id] = execution 
Example 44
Project: stups-gotthard   Author: zalando-stups   File: cli.py    (license) View Source Project 5 votes vote down vote up
def setup_tunnel(user, odd_host, remote_host, remote_port, tunnel_port):
    tunnel_port = get_port(tunnel_port)

    if not tunnel_port:
        raise ClickException('Could not get a free local port for listening')

    ssh_command = ['ssh',
                   '-oExitOnForwardFailure=yes',
                   '-oBatchMode=yes',
                   '-L', '{}:{}:{}'.format(tunnel_port, remote_host, remote_port),
                   '{}@{}'.format(user, odd_host),
                   '-N']

    process = subprocess.Popen(ssh_command, preexec_fn=os.setpgrp)

    logging.debug("Testing if tunnel is listening")
    for i in range(10):
        try:
            time.sleep(0.1)
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect(('localhost', tunnel_port))
            s.close()
            return tunnel_port, process
        except Exception:
            pass
        finally:
            s.close()

    logging.warning("Could not connect to port {}, killing ssh process with pid {}".format(tunnel_port, process.pid))
    process.kill()
    process, tunnel_port = None, None

    return tunnel_port, process 
Example 45
Project: PyBitmessage-CLI   Author: Lvl4Sword   File: bitmessagecli.py    (license) View Source Project 5 votes vote down vote up
def run_bitmessage(self):
        if self.bm_active is not True:
            try:
                if sys.platform.startswith('win'):
                    self.enable_bm = subprocess.Popen(os.path.join(self.program_dir, 'bitmessagemain.py'),
                                                      stdout=subprocess.PIPE,
                                                      stderr=subprocess.PIPE,
                                                      stdin=subprocess.PIPE,
                                                      bufsize=0,
                                                      cwd=self.program_dir)
                else:
                    self.enable_bm = subprocess.Popen(os.path.join(self.program_dir, 'bitmessagemain.py'),
                                                      stdout=subprocess.PIPE,
                                                      stderr=subprocess.PIPE,
                                                      stdin=subprocess.PIPE,
                                                      bufsize=0,
                                                      cwd=self.program_dir,
                                                      preexec_fn=os.setpgrp,
                                                      close_fds=True)
                self.bm_active = True
            except OSError as e:
                if 'Permission denied' in e:
                    print('Got "Permission denied" when trying to access bitmessagemain.py')
                    print("Please double-check the permissions on the file and ensure it can be ran.")
                    print("Otherwise, it may be a folder permission issue.")
                else:
                    print('Is the CLI in the same directory as bitmessagemain.py?')
                self.kill_program()
            for each in self.enable_bm.stdout:
                if 'Another instance' in each:
                    if self.first_run is True:
#                        print("bitmessagemain.py is already running")
#                        print("Please close it and re-run the Bitmessage CLI")
#                        self.kill_program()
                        pass
                    break
                elif each.startswith('Running as a daemon.'):
                    self.bm_active = True
                    break 
Example 46
Project: maas   Author: maas   File: arp.py    (license) View Source Project 5 votes vote down vote up
def run(args, output=sys.stdout, stdin=sys.stdin,
        stdin_buffer=sys.stdin.buffer):
    """Observe an Ethernet interface and print ARP bindings."""

    # First, become a progress group leader, so that signals can be directed
    # to this process and its children; see p.u.twisted.terminateProcess.
    os.setpgrp()

    network_monitor = None
    if args.input_file is None:
        if args.interface is None:
            raise ActionScriptError("Required argument: interface")
        cmd = [get_path("/usr/lib/maas/network-monitor"), args.interface]
        cmd = sudo(cmd)
        network_monitor = subprocess.Popen(
            cmd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE)
        infile = network_monitor.stdout
    else:
        if args.input_file == '-':
            mode = os.fstat(stdin.fileno()).st_mode
            if not stat.S_ISFIFO(mode):
                raise ActionScriptError("Expected stdin to be a pipe.")
            infile = stdin_buffer
        else:
            infile = open(args.input_file, "rb")
    return_code = observe_arp_packets(
        bindings=True, verbose=args.verbose, input=infile, output=output)
    if return_code is not None:
        raise SystemExit(return_code)
    if network_monitor is not None:
        return_code = network_monitor.poll()
        if return_code is not None:
            raise SystemExit(return_code) 
Example 47
Project: maas   Author: maas   File: beaconing.py    (license) View Source Project 5 votes vote down vote up
def run(args, output=sys.stdout, stdin=sys.stdin,
        stdin_buffer=sys.stdin.buffer):
    """Observe an Ethernet interface and print beaconing packets."""

    # First, become a progress group leader, so that signals can be directed
    # to this process and its children; see p.u.twisted.terminateProcess.
    os.setpgrp()

    network_monitor = None
    if args.input_file is None:
        if args.interface is None:
            raise ActionScriptError("Required argument: interface")
        cmd = sudo(
            [get_path("/usr/lib/maas/beacon-monitor"), args.interface])
        network_monitor = subprocess.Popen(
            cmd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE)
        infile = network_monitor.stdout
    else:
        if args.input_file == '-':
            mode = os.fstat(stdin.fileno()).st_mode
            if not stat.S_ISFIFO(mode):
                raise ActionScriptError("Expected stdin to be a pipe.")
            infile = stdin_buffer
        else:
            infile = open(args.input_file, "rb")
    return_code = observe_beaconing_packets(input=infile, out=output)
    if return_code is not None:
        raise SystemExit(return_code)
    if network_monitor is not None:
        return_code = network_monitor.poll()
        if return_code is not None:
            raise SystemExit(return_code) 
Example 48
Project: kobo   Author: release-engineering   File: taskmanager.py    (license) View Source Project 5 votes vote down vote up
def fork_task(self, task_info):
        self.log_debug("Forking task %s" % self._task_str(task_info))

        pid = os.fork()
        if pid:
            self.log_info("Task forked %s: pid=%s" % (self._task_str(task_info), pid))
            return pid

        # in no circumstance should we return after the fork
        # nor should any exceptions propagate past here
        try:
            # set process group
            os.setpgrp()

            # set a do-nothing handler for sigusr2
            # do not use signal.signal(signal.SIGUSR2, signal.SIG_IGN) - it completely masks interrups !!!
            signal.signal(signal.SIGUSR2, lambda *args: None)

            # set a default handler for SIGTERM
            signal.signal(signal.SIGTERM, signal.SIG_DFL)

            # run the task
            self.run_task(task_info)
        finally:
            # die
            os._exit(os.EX_OK) 
Example 49
Project: containernet   Author: containernet   File: cluster.py    (license) View Source Project 5 votes vote down vote up
def _ignoreSignal():
        "Detach from process group to ignore all signals"
        os.setpgrp() 
Example 50
Project: containernet   Author: containernet   File: cluster.py    (license) View Source Project 5 votes vote down vote up
def _ignoreSignal():
        "Detach from process group to ignore all signals"
        os.setpgrp()