def _check_fs_lock( fs_mount_path, lock_type, perm='' ): ''' Make sure no other ifdy processes are still using the given mount. Return True if none are, or False otherwise. ''' logger = logging.getLogger( 'util.mount.lock' ) if LOCK_TYPE_REMOUNT == lock_type: lock_path = FS_REMOUNT_LOCK_PATH elif LOCK_TYPE_MOUNT == lock_type: lock_path = FS_MOUNT_LOCK_PATH for pid_entry_iter in os.listdir( lock_path ): pid_lock_path = os.path.join( lock_path, pid_entry_iter ) # Check to make sure we're not looking at our own lock file. if int( pid_entry_iter ) == os.getpid(): continue # Check if the iterated process is still active. try: os.getsid( int( pid_entry_iter ) ) except OSError: logger.warn( 'No process found for PID {}. Removing lock...'.format( pid_entry_iter ) ) os.unlink( pid_lock_path ) continue # Check if the iterated process is locking this mount. with open( pid_lock_path ) as pid_lock_file: for fs_line in pid_lock_file: fs_status = fs_line.strip().split( ':' ) if fs_status[0] == fs_mount_path: if LOCK_TYPE_REMOUNT == lock_type: if perm == FS_ATTRIBS_OPPOSITE[fs_status[1]]: logger.warn( '"{}" in use by {}, not remounting with "{}".'.format( fs_status[0], pid_entry_iter, perm ) ) return False elif LOCK_TYPE_MOUNT == lock_type: logger.warn( '"{}" in use by {}, not unmounting.'.format( fs_status[0], pid_entry_iter ) ) return False # No locks found. return True
def _do_forks(self): """ Daemon fork operation Split out for debugging """ # Keep track of where we are log_debug('0th fork(): PID: %s PPID: %s SID: %s PGID: %s' % (os.getpid(), os.getppid(), os.getsid(0), os.getpgid(0))) # First fork so that parent can exit try: pid = os.fork() except (IOError, OSError) as e: # log or stderr something here # raise Exception "%s [%d]" % (e.strerror, e.errno) systemd_exit(os.EX_OSERR, SDEX_GENERIC) if (pid == 0): # First child log_debug('1st fork(): PID: %s PPID: %s SID: %s PGID: %s' % (os.getpid(), os.getppid(), os.getsid(0), os.getpgid(0))) # Become session leader os.setsid() # Keep track of things log_debug('1st fork(), setsid(): PID: %s PPID: %s SID: %s PGID: %s' % (os.getpid(), os.getppid(), os.getsid(0), os.getpgid(0))) # Optionally ignore SIGHUP import signal signal.signal(signal.SIGHUP, signal.SIG_IGN) # Second fork to orphan child and detach from controlling # terminal try: pid = os.fork() except (IOError, OSError) as e: # log or stderr something here? # raise Exception "%s [%d]" % (e.strerror, e.errno) systemd_exit(os.EX_OSERR, SDEX_GENERIC) if (pid != 0): # use _exit() as it does not pfaff around with pythonic cleanup # which is not needed this early... # Exit second parent os._exit(os.EX_OK) else: # Exit first parent os._exit(0) # Keep track of stuff log_debug('2nd fork(): PID: %s PPID: %s SID: %s PGID: %s' % (os.getpid(), os.getppid(), os.getsid(0), os.getpgid(0)))
def status(self): """ Getting daemon status """ try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() os.getsid(pid) return pid except Exception: return None
def start(self): pid = self._getpid() if pid: try: os.getsid(pid) sys.stderr.write("Daemon already running.\n") except: sys.stderr.write("pidfile %s already exists, but daemon is not running. Delete pidfile and retry.\n" % self.pidfile) sys.exit(1) self.daemonize() self.run()
def monitor(port=options.port): if port == '': return logger = logging.getLogger('monitor(%s)' % port) try: path = '%s/%s' % (RUN_PATH, port) pid = int(open(path).readline()) logger.debug('pid to check: %s', pid) os.getsid(pid) logger.info('pid %d seems ok' % pid) except IOError, e: logger.error(e)
def test_get_proc_pid_not_exists(self): """Get process must return empty list if pid doesn't exists.""" pid = 0 while True: pid = randrange(0, 2147483647, 1) try: os.getsid(pid) except OSError: break result = Agent.get_process(pids=[pid]) self.assertEqual(len(result['list']), 0, 'For not existing process should be ' 'json with 0 values')
def test_get_proc_skip_not_exist(self): """Get process returns result for existing and ignores not existing.""" pid = 0 while True: pid = randrange(0, 2147483647, 1) try: os.getsid(pid) except OSError: break current_pid = os.getpid() result = Agent.get_process(pids=[pid, current_pid]) self.assertEqual(len(result['list']), 1, 'For 1 existing process should be ' 'json with one result')
def _is_running_from_system_service(): """True if running from a systemd service. Be conservative here and only return true when we are certain about it (as ``--keep-unit`` is a nice-to-have, not a must-have flag). NOTE: This function is derived from coreos/go-systemd project's ``runningFromSystemService`` function in util/util_cgo.go. """ try: libsystemd = ctypes.cdll.LoadLibrary('libsystemd.so') except OSError: LOG.debug('unable to load libsystemd.so') return False try: sd_pid_get_owner_uid = libsystemd.sd_pid_get_owner_uid except AttributeError: LOG.debug('unable to load sd_pid_get_owner_uid') return False sd_pid_get_owner_uid.argtypes = ( ctypes.c_int, # pid_t ctypes.POINTER(ctypes.c_int), # uid_t* ) sd_pid_get_owner_uid.restype = ctypes.c_int uid = ctypes.c_int() rc = sd_pid_get_owner_uid(0, ctypes.byref(uid)) if rc >= 0: return False if -rc not in ( errno.ENOENT, # systemd < 220 errno.ENXIO, # systemd 220 - 223 errno.ENODATA, # systemd >= 234 ): return False return os.getsid(0) == os.getpid()
def unfreeze_something(): global frozen_pids global num_unfreezes global last_unfrozen_pid if frozen_pids: ## queue or stack? Seems like both approaches are problematic if num_unfreezes % unfreeze_pop_ratio: pid_to_unfreeze = frozen_pids.pop() else: ## no list.get() in python? pid_to_unfreeze = frozen_pids[0] frozen_pids = frozen_pids[1:] try: debug("going to unfreeze %s" % pid_to_unfreeze) os.kill(pid_to_unfreeze, signal.SIGCONT) ## Sometimes the parent process also gets suspended. ## TODO: we're doing some simple assumptions here: ## 1) this problem only applies to process group id or session id ## (we probably need to walk through all the parents - or maybe ## just the ppid?) ## 2) it is harmless to CONT the pgid and sid. This may not ## always be so. ## To correct this, we may need to traverse parents ## (peeking into /proc/<pid>/status recursively) prior to freezing ## the proc. ## all parents that aren't already frozen should be added to the ## unfreeze stack os.kill(os.getpgid(pid_to_unfreeze), signal.SIGCONT) os.kill(os.getsid(pid_to_unfreeze), signal.SIGCONT) except ProcessLookupError: ## ignore failure pass last_unfrozen_pid = pid_to_unfreeze log_unfrozen(pid_to_unfreeze) num_unfreezes += 1
def childproc_filialusurp(umask, chdir, umask_path, sid_path, wdir_path, pid_path): _filial_usurpation(chdir, umask) # Get our session id my_pid = os.getpid() sid = os.getsid(my_pid) # reset umask and get our set one. umask = os.umask(0) # Get our working directory. wdir = os.path.abspath(os.getcwd()) # Update parent # Write the umask to the response path with open(umask_path, 'w') as f: f.write(str(umask) + '\n') # Write the sid to the response path with open(sid_path, 'w') as f: f.write(str(sid) + '\n') # Write the working dir to the response path with open(wdir_path, 'w') as f: f.write(wdir + '\n') # Write the pid to the response path with open(pid_path, 'w') as f: f.write(str(my_pid) + '\n')
def get_data(id): try: # Verify the process exists if int(id) == getsid(int(id)): global sid global processing_status # Generate delay and track status of current process if sid != int(id): sid = int(id) processing_status = 0 if delay_process() <= 20: return "Not finished" # Return the results once the process has "finished" else: users = mongo.db.users output = [] for user in users.find(): output.append({ 'id' : user['_id'], 'createdAt' : user['createdAt'], 'services' : user['services'], 'username' : user['username'], 'emails' : user['emails'], 'slug' : user['slug'], 'updateAt' : user['updateAt'], 'MyProfile' : user['MyProfile'], 'teams' : user['teams'], 'roles' : user['roles'], 'profile' : user['profile'] }) return jsonify({ 'users' : output }) # Return a message is the id entered isn't a current process except: return "Not a current process"
def Exec(args, log_file=None): """Starts subprocess with given args and ensures its termination upon exit. This starts a subprocess with the given args. The stdout and stderr of the subprocess are piped. Note that this is a context manager, to ensure that processes (and references to them) are not leaked. Args: args: [str], The arguments to execute. The first argument is the command. log_file: optional file argument to reroute process's output. If given, will be closed when the file is terminated. Yields: process, The process handle of the subprocess that has been started. """ reroute_stdout = log_file or subprocess.PIPE if not platforms.OperatingSystem.IsWindows(): # Check if pid is session leader. if os.getsid(0) != os.getpid(): os.setpgid(0, 0) process = subprocess.Popen(args, stdout=reroute_stdout, stderr=subprocess.STDOUT) try: yield process finally: if process.poll() is None: process.terminate() process.wait()
def run(program, *args): register_signals() if fcntl.ioctl(0, termios.TIOCNOTTY) == -1: logger.warn("Unable to detach from controlling tty") else: if os.getsid(0) == os.getpid(): logger.info( "Detached from controlling tty, ignoring the first SIGHUP and SIGCONT we receive" ) IGNORED_SIGMAP[signal.SIGHUP] = 1 IGNORED_SIGMAP[signal.SIGCONT] = 1 else: logger.info("Detached from controlling tty, but was not session leader.") child_pid = os.fork() if child_pid < 0: logger.error("Unable to fork. Exiting.") return 1 elif child_pid == 0: if use_setsid: os.setsid() os.execvp(program, args) return 2 else: logger.info(f"Child spawned with PID {child_pid}.") while True: signum = signal.sigwait(set(SIGMAP.keys())) handle_signal(signum)
def posix_getsid(space, pid): """ posix_getsid - Get the current sid of the process """ try: return space.newint(os.getsid(pid)) except OSError, e: space.set_errno(e.errno) return space.newbool(False)
def close(self) -> None: if self.closed: raise channel.ChannelClosedException() sid = os.getsid(self.p.pid) self.p.terminate() os.close(self.pty_master) self.p.wait() # Wait for all processes in the session to end. Most of the time # this will return immediately, but in some cases (eg. a serial session # with picocom) we have to wait a bit until we can continue. To be as # quick as possible this is implemented as exponential backoff and will # give up after 1 second (1.27 to be exact) and emit a warning. for t in range(7): if ( subprocess.call( ["ps", "-s", str(sid)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) != 0 ): break time.sleep(2 ** t / 100) else: raise Exception("not done")
def check_lock_file(cmd, lock_file): _pid = 0 if os.path.isfile(lock_file): _file = None try: _file = open(lock_file, 'r') _pid = _file.read() except IOError: pass finally: if _file is not None: _file.close() if not _pid: _pid = -1 else: _pid = int(_pid) try: if os.getsid(_pid): print(_('Another instance of %(cmd)s is running: %(pid)d') % { 'cmd': cmd, 'pid': int(_pid) }) sys.exit(errno.EPERM) except OSError: pass else: write_file(lock_file, str(os.getpid()))
def proc_sid(proc: "Process") -> int: pid = proc.pid if pid == 0: return 0 return os.getsid(pid)
def makeThisProcessAsDaemon(): """The code, as it is, will create a new file in the root directory, when executed with superuser privileges. The file will contain the following daemon related process parameters: return code, process ID, parent process group ID, session ID, user ID, effective user ID, real group ID, and the effective group ID.""" try: retCode=0 retCode = utils.daemonProcess.create() logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename= utils.logDirectory + 'semfsDaemon.log', filemode='w') ProcParams = \ """ return code=%s \ process ID=%s \ parent process ID=%s \ process group ID=%s \ session ID=%s \ user ID=%s \ effective user ID=%s \ real group ID=%s \ effective group ID=%s """ \ % (retCode, os.getpid(), os.getppid(), os.getpgrp(), os.getsid(0), \ os.getuid(), os.geteuid(), os.getgid(), os.getegid()) logging.debug(ProcParams) os.chdir(utils.semFSInstalledDirectory) except: logging.info("Error while making the process as Daemon")
def setup_class(cls): cls.space = space cls.w_posix = space.appexec([], GET_POSIX) cls.w_path = space.wrap(str(path)) cls.w_path2 = space.wrap(str(path2)) cls.w_pdir = space.wrap(str(pdir)) try: cls.w_unicode_dir = space.wrap( str(unicode_dir).decode(sys.getfilesystemencoding())) except UnicodeDecodeError: # filesystem encoding is not good enough cls.w_unicode_dir = space.w_None if hasattr(os, 'getuid'): cls.w_getuid = space.wrap(os.getuid()) cls.w_geteuid = space.wrap(os.geteuid()) if hasattr(os, 'getgid'): cls.w_getgid = space.wrap(os.getgid()) if hasattr(os, 'getgroups'): cls.w_getgroups = space.newlist([space.wrap(e) for e in os.getgroups()]) if hasattr(os, 'getpgid'): cls.w_getpgid = space.wrap(os.getpgid(os.getpid())) if hasattr(os, 'getsid'): cls.w_getsid0 = space.wrap(os.getsid(0)) if hasattr(os, 'sysconf'): sysconf_name = os.sysconf_names.keys()[0] cls.w_sysconf_name = space.wrap(sysconf_name) cls.w_sysconf_value = space.wrap(os.sysconf_names[sysconf_name]) cls.w_sysconf_result = space.wrap(os.sysconf(sysconf_name)) cls.w_SIGABRT = space.wrap(signal.SIGABRT) cls.w_python = space.wrap(sys.executable) if hasattr(os, 'major'): cls.w_expected_major_12345 = space.wrap(os.major(12345)) cls.w_expected_minor_12345 = space.wrap(os.minor(12345)) cls.w_udir = space.wrap(str(udir))
def pid_exec(self, ev): try: proc = bsd.kinfo_getproc(self.pid) argv = list(proc.argv) command = proc.command except (LookupError, ProcessLookupError): # Exited too quickly, exit info will be catched in another event return self.logger.debug('Job did exec() into {0}'.format(argv)) if self.anonymous: # Update label for anonymous jobs self.label = 'anonymous.{0}@{1}'.format(command, self.pid) self.logger = logging.getLogger('Job:{0}'.format(self.label)) if self.state == JobState.STARTING: with self.cv: try: self.sid = os.getsid(self.pid) self.pgid = os.getpgid(self.pid) except ProcessLookupError: # Exited too quickly after exec() return if not self.supports_checkin: self.set_state(JobState.RUNNING) self.context.provide(self.provides)
def run_server(as_daemon=True): """ Optionally daemonizes the process and starts an XML-RPC server to drive the FCSH wrapper. """ if as_daemon: retCode = createDaemon() configure_server_logging() procParams = """ return code = %s process ID = %s parent process ID = %s process group ID = %s session ID = %s user ID = %s effective user ID = %s real group ID = %s effective group ID = %s """ % (retCode, os.getpid(), os.getppid(), os.getpgrp(), os.getsid(0), os.getuid(), os.geteuid(), os.getgid(), os.getegid()) logging.info(procParams + "\n") else: configure_server_logging() fcsh = FCSH() logging.debug("FCSH initialized\n") from SimpleXMLRPCServer import SimpleXMLRPCServer server = SimpleXMLRPCServer(("localhost", PORT)) server.register_introspection_functions() server.register_function(lambda cmd: fcsh.run_command(cmd), 'run_command') server.register_function(lambda: os._exit(0), 'exit') server.serve_forever()
def preexec_first(self): try: os.setsid() _logger.debug("%s: session id set to %s", self.label, os.getsid(os.getpid())) except Exception, e: _logger.error("%s: setting the process group and session id failed: %s", self.label, e) raise
def daemonize( self ): if self.args.daemon : pid = os.fork() if( pid == 0 ): # in the child # become the session leader self.isparent = True os.setsid() os.umask(0) os.chdir("/") gid = os.getsid( os.getpid() ) if gid > 0 : pid = os.fork() if pid == 0: """ for f in sys.stdout, sys.stderr: f.flush( ) si = file(sys.stdin, 'r') so = file(sys.stdout, 'a+') se = file(sys.stderr, 'a+', 0) os.dup2(si.fileno( ), sys.stdin.fileno( )) os.dup2(so.fileno( ), sys.stdout.fileno( )) os.dup2(se.fileno( ), sys.stderr.fileno( )) """ else : os._exit(0) else : os._exit(0) else: os._exit(0)
def setup_class(cls): cls.space = space cls.w_posix = space.appexec([], GET_POSIX) cls.w_path = space.wrap(str(path)) cls.w_path2 = space.wrap(str(path2)) cls.w_pdir = space.wrap(str(pdir)) try: cls.w_unicode_dir = space.wrap( str(unicode_dir).decode(sys.getfilesystemencoding())) except UnicodeDecodeError: # filesystem encoding is not good enough cls.w_unicode_dir = space.w_None if hasattr(os, 'getuid'): cls.w_getuid = space.wrap(os.getuid()) cls.w_geteuid = space.wrap(os.geteuid()) if hasattr(os, 'getgid'): cls.w_getgid = space.wrap(os.getgid()) if hasattr(os, 'getgroups'): cls.w_getgroups = space.newlist( [space.wrap(e) for e in os.getgroups()]) if hasattr(os, 'getpgid'): cls.w_getpgid = space.wrap(os.getpgid(os.getpid())) if hasattr(os, 'getsid'): cls.w_getsid0 = space.wrap(os.getsid(0)) if hasattr(os, 'sysconf'): sysconf_name = os.sysconf_names.keys()[0] cls.w_sysconf_name = space.wrap(sysconf_name) cls.w_sysconf_value = space.wrap(os.sysconf_names[sysconf_name]) cls.w_sysconf_result = space.wrap(os.sysconf(sysconf_name)) cls.w_SIGABRT = space.wrap(signal.SIGABRT) cls.w_python = space.wrap(sys.executable) if hasattr(os, 'major'): cls.w_expected_major_12345 = space.wrap(os.major(12345)) cls.w_expected_minor_12345 = space.wrap(os.minor(12345)) cls.w_udir = space.wrap(str(udir))
def test_setsid(self): args = [sys.executable, '-c', 'from __future__ import print_function;' 'import os;' 'print(os.getsid(os.getpid()))'] out = commands.run(args, setsid=True) assert int(out) != os.getsid(os.getpid())
def sid(self): """ Session ID, or None if it hasn't started yet. POSIX only. """ return os.getsid(self.pid)
def run(self): """Execute the specified script in a suprocess collecting the stdout and stderr. If a timeout was specified force exit the script completing the thread run.""" try: # print "Thread(%s) starts..." % self._node # print "Thread(%s) PID=%s PGRP=%s" % (self._node, os.getpid(), os.getpgrp()) # Run script in a unique session ID to enable process tree kill cmd = ['/usr/bin/setsid', self._script, self._node] self._subproc = subprocess.Popen(cmd, shell=False, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if self._timer: self._timer.start() subsid = os.getsid(self._subproc.pid) # print "SubProc(%s) PID=%s PGRP=%s SID=%s" % (self._node, self._subproc.pid, os.getpgid(self._subproc.pid), subsid) self._stdout, self_stderr = self._subproc.communicate() # print "InspectOUT(%s): %r" % (self._node, self._stdout) # print "InspectERR(%s): %r" % (self._node, self._stderr) # print "Thread(%s) normal end." % self._node except Exception as exc: print "Thread(%s) Exception %r %s", (self._node, exc, exc) return "ERROR" finally: if self._timer: self._timer.cancel()
def check_lock_file(cmd, lock_file): if os.path.isfile(lock_file): _file = None try: _file = open(lock_file, 'r') _pid = _file.read() except IOError: pass finally: if _file is not None: _file.close() if not _pid: _pid = -1 else: _pid = int(_pid) try: if os.getsid(_pid): print( _('Another instance of %(cmd)s is running: %(pid)d') % { 'cmd': cmd, 'pid': int(_pid) }) sys.exit(errno.EPERM) except OSError: pass else: write_file(lock_file, str(os.getpid()))
def test_ioctl(self): # If this process has been put into the background, TIOCGPGRP returns # the session ID instead of the process group id. ids = (os.getpgrp(), os.getsid(0)) with open("/dev/tty", "rb") as tty: r = fcntl.ioctl(tty, termios.TIOCGPGRP, " ") rpgrp = struct.unpack("i", r)[0] self.assertIn(rpgrp, ids)
def test_ioctl(self): # If this process has been put into the background, TIOCGPGRP returns # the session ID instead of the process group id. ids = (os.getpgrp(), os.getsid(0)) tty = open("/dev/tty", "r") r = fcntl.ioctl(tty, termios.TIOCGPGRP, " ") rpgrp = struct.unpack("i", r)[0] self.assertIn(rpgrp, ids)
def getsid(space, pid): """ getsid(pid) -> sid Call the system call getsid(). """ try: sid = os.getsid(pid) except OSError, e: raise wrap_oserror(space, e)
def test_ioctl_mutate(self): import array buf = array.array('i', [0]) ids = (os.getpgrp(), os.getsid(0)) tty = open("/dev/tty", "r") r = fcntl.ioctl(tty, termios.TIOCGPGRP, buf, 1) rpgrp = buf[0] self.assertEquals(r, 0) self.assert_(rpgrp in ids, "%s not in %s" % (rpgrp, ids))
def test_ioctl_mutate(self): import array buf = array.array('i', [0]) ids = (os.getpgrp(), os.getsid(0)) tty = open("/dev/tty", "r") r = fcntl.ioctl(tty, termios.TIOCGPGRP, buf, 1) rpgrp = buf[0] self.assertEquals(r, 0) self.assertIn(rpgrp, ids)
def test_getsid() -> None: assert psutil_extra.proc_getsid(os.getpid()) == os.getsid(os.getpid()) with psutil_extra.oneshot_proc(os.getpid()): assert psutil_extra.proc_getsid(os.getpid()) == os.getsid(os.getpid()) assert psutil_extra.proc_getsid(1) <= 1 with psutil_extra.oneshot_proc(1): assert psutil_extra.proc_getsid(1) <= 1 with psutil_extra.oneshot_proc(1): assert psutil_extra.proc_getsid(1) <= 1 with psutil_extra.oneshot_proc(1): assert psutil_extra.proc_getsid(1) <= 1 assert psutil_extra.proc_getsid(1) <= 1
def child(args, mypipe): if mypipe: os.close(mypipe[0]) wpipe = os.fdopen(mypipe[1], 'w') else: wpipe = MockPipe() for std, flags in (('stdin', os.O_RDONLY), ('stdout', os.O_WRONLY | os.O_CREAT), ('stderr', os.O_WRONLY | os.O_CREAT)): remapfd(getattr(sys, std), flags, getattr(args, std), args.daemonize) try: sid = os.setsid() except: sid = -1 pid = os.getpid() pgid = os.getpgid(pid) sid = os.getsid(pid) if pid == pgid: wpipe.write('{}\n'.format(pgid)) else: wpipe.write('Failed to setsid.\n') wpipe.close() sys.exit(1) if mypipe: try: fcntl_old = fcntl.fcntl(wpipe, fcntl.F_GETFD) fcntl.fcntl(wpipe, fcntl.F_SETFD, fcntl_old | fcntl.FD_CLOEXEC) except Exception as e: wpipe.write('Failed to set FD_CLOEXEC: {}.\n'.format(e)) wpipe.close() raise if _imdo.disable_setsid(): wpipe.write('Failed to disable setsid.\n') wpipe.close() sys.exit(1) if args.daemonize: signal.signal(signal.SIGHUP, signal.SIG_IGN) try: tty = os.open('/dev/tty', os.O_RDWR) fcntl.ioctl(tty, termios.TIOCNOTTY) except: pass wpipe.flush() try: os.execvp(args.executable, [args.executable] + args.arguments) except Exception as e: wpipe.write('Failed to execvp: {}.\n'.format(e)) wpipe.close() sys.exit(1)
async def test_process_new_session_sid() -> None: """Test that start_new_session is successfully passed to the subprocess implementation""" sid = os.getsid(os.getpid()) cmd = [sys.executable, "-c", "import os; print(os.getsid(os.getpid()))"] result = await run_process(cmd) assert result.stdout.decode().strip() == str(sid) result = await run_process(cmd, start_new_session=True) assert result.stdout.decode().strip() != str(sid)
def getsid(space, pid): """ getsid(pid) -> sid Call the system call getsid(). """ try: sid = os.getsid(pid) except OSError as e: raise wrap_oserror(space, e) return space.newint(sid)
def preexec_first(self): try: os.setsid() _logger.debug("%s: session id set to %s", self.label, os.getsid(os.getpid())) except Exception, e: _logger.error( "%s: setting the process group and session id failed: %s", self.label, e) raise
def terminate(self): if not self._running: print('pspgen is not running!', file=sys.stderr) return print('Terminating pspgen...') os.killpg(os.getsid(self._proc.pid), signal.SIGINT) exitcode = yield from self._proc.wait() self._running = False self._writer = None print('pspgen has terminated.')
def get_pid(file): try: f = open(file, "r") pid = int(f.read()) f.close() os.getsid(pid) return pid except OSError as e: if e.errno == errno.ENOENT: # no PIDFILE return 0 elif e.errno == errno.ESRCH: # no process return 0 else: raise except IOError as e: if e.errno == errno.ENOENT: # no pidfile return 0
def get_stub_sid(self, extra_stub_args=None): # Launch debugserver if extra_stub_args: self.debug_monitor_extra_args += extra_stub_args server = self.launch_debug_monitor() self.assertIsNotNone(server) self.assertTrue(lldbgdbserverutils.process_is_running(server.pid, True)) # Get the process id for the stub. return os.getsid(server.pid)
async def terminate(self): if not self._running: print('pspgen is not running!', file=sys.stderr) return print('Terminating pspgen...') os.killpg(os.getsid(self._proc.pid), signal.SIGINT) exitcode = await self._proc.wait() self._running = False if self._writer: self._writer.close() print('pspgen has terminated.')
def exec_user_shell(user, jobid, loc): '''Execute shell for user for interactive jobs. Uses the user's defined SHELL. Will also send the pgid for cray systems so that aprun will work from within the shell. Wait until termination. ''' pgid = os.getsid(0) proc = subprocess.Popen([os.environ['SHELL']], shell=True, preexec_fn=(lambda: fetch_pgid(user, jobid, loc, pgid=pgid))) os.waitpid(proc.pid, 0)
def set_new_process_group() -> None: """ Tries to set current process to a new process group That makes it easy to kill all sub-process of this at the OS-level, rather than having to iterate the child processes. If current process spawn by system call ``exec()`` than keep current process group """ if os.getpid() == os.getsid(0): # If PID = SID than process a session leader, and it is not possible to change process group return os.setpgid(0, 0)
def sub_processes(self): """ Construct the full list of process in the monitor hierarchy. """ def all_grp_processes(grp, process_list): """ Get all processes that match the given group. """ def filter_grp(pid): return grp in self.timeout_grps(pid) return filter(filter_grp, process_list) processes = self.process_list(os.getsid(self.group)) grp_processes = all_grp_processes(self.group, processes) return grp_processes
def stop(): log("stopping...") if os.path.exists(pidfile): try: pid = int(open(pidfile).read()) sid = os.getsid(pid) log("killing sid %s"%sid) os.killpg(sid, 9) log("successfully killed") except Exception, e: log("failed -- %s"%e) log("removing '%s'"%pidfile) os.unlink(pidfile)
def _on_enter(location, message_data): """ When a player spawns in a level, test whether we should create a new level handler object. If so, fork the process and do the deed. """ # TODO: Put sharding code here. if location in locations: # See whether the process has despawned. try: os.getsid(locations[location].pid) except OSError: # Explicitly tell the GC that we're done with that location # handler. del locations[location] else: return loc = EntityServlet(location, message_data) loc.start() locations[location] = loc
def get_stub_sid(self, extra_stub_args=None): # Launch debugserver if extra_stub_args: self.debug_monitor_extra_args = extra_stub_args else: self.debug_monitor_extra_args = "" server = self.launch_debug_monitor() self.assertIsNotNone(server) self.assertTrue(server.isalive()) server.expect("(debugserver|lldb-gdbserver)", timeout=10) # Get the process id for the stub. return os.getsid(server.pid)
def bitbake(*args, **kwargs): """Run bitbake, and kill the processes when the user ^C's or terminates""" bb = sh.bitbake(*args, _in='/dev/null', _bg=True, **kwargs) bitbake_sid = os.getsid(bb.pid) try: bb.wait() except BaseException: try: os.kill(bitbake_sid, signal.SIGTERM) except OSError as exc: if exc.errno == errno.ESRCH: return bb.stdout sys.stderr.write("error killing bitbake processes") raise return bb.stdout
def run(cmd, *args, **kwargs): """Run a process, and kill the processes when the user ^C's or terminates""" cmdobj = getattr(sh, cmd) process = cmdobj(*args, _in='/dev/null', _bg=True, **kwargs) sid = os.getsid(process.pid) try: process.wait() except BaseException: try: os.kill(sid, signal.SIGTERM) except OSError as exc: if exc.errno == errno.ESRCH: return process.stdout sys.stderr.write("error killing child processes") raise return process.stdout
def get_proc_info(self): pid = os.getpid() ppid = os.getppid() pgid = os.getpgid(pid) sid = os.getsid(pid) procname = setproctitle.getproctitle() # return "pid: %s; pgid: %s; sid: %s; procname: %s" % ( # pid, pgid, sid, procname) proc_info = { 'pid': pid, 'ppid': ppid, 'pgid': pgid, 'sid': sid, 'procname': procname } return proc_info
def _check_ioctl_mutate_len(self, nbytes=None): buf = array.array('i') intsize = buf.itemsize ids = (os.getpgrp(), os.getsid(0)) # A fill value unlikely to be in `ids` fill = -12345 if nbytes is not None: # Extend the buffer so that it is exactly `nbytes` bytes long buf.extend([fill] * (nbytes // intsize)) self.assertEqual(len(buf) * intsize, nbytes) # sanity check else: buf.append(fill) with open("/dev/tty", "rb") as tty: r = fcntl.ioctl(tty, termios.TIOCGPGRP, buf, 1) rpgrp = buf[0] self.assertEqual(r, 0) self.assertIn(rpgrp, ids)