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)
python类setpgrp()的实例源码
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
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()
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,)
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
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
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)
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
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
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
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
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
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,
)
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)
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 = []
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
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()
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
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
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()
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)
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'))
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()
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)
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
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) + ['&'])
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()
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
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
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'])