def main(): signal(SIGCHLD, SIG_IGN) db = pymysql.connect('localhost', 'root', '123456', 'dict') HOST = sys.argv[1] PORT = int(sys.argv[2]) sockfd = socket() sockfd.bind((HOST, PORT)) sockfd.listen(5) while True: try: connfd, addr = sockfd.accept() print("connect addr : ", addr) except KeyboardInterrupt: raise except: continue pid = os.fork() if pid < 0: print("create child process failed") connfd.close() continue elif pid == 0: sockfd.close() do_child(connfd, db) else: connfd.close() continue db.close() sockfd.close() sys.exit(0)
def init_sigchld_handler(): global handler_init atexit.register(cleanup_remaining_processes) prev = getsignal(SIGCHLD) master_handler = get_master_sigchld_handler(prev) signal(SIGCHLD, master_handler) handler_init = True
def run(self): """ Main execution loop """ # catch signals for proper shutdown for sig in (SIGABRT, SIGTERM, SIGINT): signal(sig, self.shutdown) # start servers self.startup() # main loop logger.debug('HAGW Server: Entering Main Loop') while True: try: time.sleep(settings.MAIN_LOOP_INTERVAL) if self.ping() == False: # cannot ping myself via RVI -> restart logger.warning('HAGW Server: ping failed -> restarting') self.cleanup() if not self.startup(): logger.warning('HAGW Server: startup failed.') continue #logger.debug('HAGW Server: Thingcontrol Status: %s', thingcontrolserver.setIVIHVAC()) except KeyboardInterrupt: print ('\n') break
def main(): s = socket() s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) s.bind(ADDR) s.listen(5) # 设置进程回收 signal(SIGCHLD, SIG_IGN) while True: try: connfd, addr = s.accept() except KeyboardInterrupt: s.close() sys.exit('服务端退出') except Exception as e: print('客户端连接失败') continue print('连接到客户端:', addr) # 创建进程 pid = os.fork() if pid == 0: s.close() do_client(connfd) else: connfd.close() continue
def main(): if len(sys.argv) < 3: print('argv error') sys.exit(1) HOST = sys.argv[1] PORT = int(sys.argv[2]) ADDR = (HOST, PORT) #创建数据报套接字 s = socket(AF_INET, SOCK_DGRAM) name = input('请输入姓名:') msg = 'L ' + name s.sendto(msg.encode(), ADDR) signal(SIGCHLD, SIG_IGN) pid = os.fork() if pid < 0: print('faild to create process') elif pid == 0: do_child(s, ADDR, name) else: do_parent(s)
def child_is_alive(): """Return True if the child process is still alive; False if not.""" try: signal(0) except: return False return True
def main(): # 创建数据库连接 db = pymysql.connect\ ("localhost",'root','123456',"dict") # 创建套接字 s = socket() s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) s.bind(("0.0.0.0",8000)) s.listen(5) # 忽略子进程信号 signal(SIGCHLD,SIG_IGN) while True: try: # 客户端连接 c,addr = s.accept() print("连接到",addr) except KeyboardInterrupt: s.close() sys.exit("服务器退出") except Exception: traceback.print_exc() continue # 创建父子进程 pid = os.fork() if pid == 0: s.close() do_child(c,db) else: c.close() continue
def single_process(): filename = os.path.abspath(sys.argv[0]) lock_file_name = filename.lstrip('/').replace('/', '_') + '.lock' lock_file_path = os.path.join( tempfile.gettempdir(), lock_file_name) fd = os.open(lock_file_path, os.O_CREAT | os.O_RDWR, 0o660) try: fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError as e: if e.errno in (errno.EACCES, errno.EAGAIN): logging.error( '%s RUNNING . QUIT' % filename ) sys.exit(0) else: raise def exit(signal, frame): os.close(fd) os.remove(lock_file_path) sys.exit(signal) for sig in (SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM, SIGQUIT): signal(sig, exit) atexit.register(lambda: exit(0, 0))
def raise_signals(signals=FATAL_SIGNALS): """Context manager to temporarily set up signal handlers to turn certain signals into exceptions. :param Sequence[signals.Signals] signals: list of signals to be handled, by default :data:`FATAL_SIGNALS`. :raise Signal: when a signal is received during execution of the context. >>> import os >>> with raise_signals(): #doctest:+IGNORE_EXCEPTION_DETAIL ... os.kill(os.getpid(), 11) ... Traceback (most recent call last): ... Signal: """ def handler(sig, frame): raise Signal(sig) old_handlers = {} for sig in signals: old_handlers[sig] = signal(sig, handler) try: yield finally: for sig, handler in old_handlers.items(): signal(sig, handler)
def main(): # 创建tcp 套接字 sockfd = socket() sockfd.bind(ADDR) sockfd.listen(5) print("等待客户端连接....") # 处理僵尸进程 signal(SIGCHLD,SIG_IGN) # 循环处理客户端连接 while True: try: connfd,addr = sockfd.accept() print("Connect from",addr) except KeyboardInterrupt: sockfd.close() db.close() # 关闭数据库 sys.exit() # 为连接的客户端创建子进程处理其请求 p = Process(target=handle,args=(connfd,)) p.daemon = True p.start()
def driver(): signal(SIGUSR1, handler) signal(SIGUSR2, handler) signal(SIGTSTP, handler) signal(SIGINT, SIG_IGN) signal(SIGQUIT, SIG_IGN) os.wait()
def main(): signal(SIGQUIT, process_quit) for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: stdout.write("percentage\t%i\n" % (i * 10)) stdout.flush() sleep(0.3)
def __init__(self): self.logger = logging.getLogger(__name__) logging.basicConfig(level=logging.ERROR) self.logger.setLevel(level=logging.DEBUG) for sig in (SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM): signal(sig, self.save_qid) self.load_qid()
def __init__(self, config, register_shutdown=False): self.config = copy.deepcopy(PHANTOMJS) self.config = merge(self.config, config) self._proc = None self._stderr_reader = None self._comms_lock = threading.RLock() self._shutdown_lock = threading.RLock() if not self._which(self.config[u'executable']): raise renderer.RenderError(''.join([ u"Can't locate PhantomJS executable: ", self.config[u'executable'] ])) if not os.path.isfile(self.config[u'script']): raise renderer.RenderError(''.join( [u"Can't locate script: ", self.config[u'script']])) self._logger = logging.getLogger(u'PhantomJSRenderer') if register_shutdown and isinstance(threading.current_thread(), threading._MainThread): for sig in (SIGABRT, SIGINT, SIGTERM): signal(sig, self._on_signal)
def get_name(): signal(SIGALRM, timeout_handler) ## from signal module alarm(5) # Request SIGALRM in 5 seconds n = sys.stdin.readline() alarm(0) # Cancel alarm return n
def main(args): global endserver, zsim_proc port = args.port tracename = args.trace hasValidation = args.validate target = int(args.target) endserver = args.endserver if args.zsimruncfg is not None: endserver = True # must quit server after simulation for sig in (SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM): signal(sig, sim_end) assert (args.zsimpath is not None) zsimbinpath = os.path.abspath(args.zsimpath) zsimrundir = os.path.dirname(args.zsimruncfg) cur_path = os.getcwd() remove_prev_portlist(args.zsimruncfg) os.chdir(zsimrundir) zsim_proc = Popen([zsimbinpath, args.zsimruncfg]) os.chdir(cur_path) # port = asyncio.run(get_mapped_port(args.zsimruncfg)) port = get_mapped_port(args.zsimruncfg) if port == -1: print("[Error] cannot get memcached mapped port") sim_end() server_addr = 'localhost:' + port client = Client(server_addr, default_noreply=True) ycsb_load(tracename + '.load', client, hasValidation) ycsb_run(tracename + '.run', client, hasValidation, target) sim_end()
def main(argv): if (len(sys.argv) != 3): print "You must provide two arguments: ip port" else: GPIO.setwarnings(False) for sig in (SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM): signal(sig, clean) setup_gpio() destination = str(sys.argv[1]) port = int(sys.argv[2]) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = (destination, port) print "server_address: ", server_address sock.connect(server_address) while True: data = sock.recv(16) motor_a_direction = data[0] motor_b_direction = data[1] print "motor A direction: ", motor_a_direction print "motor B direction: ", motor_b_direction control_motors(motor_a_direction, motor_b_direction) print "Send picture" pic = pack_image(80, 60) sock.sendall(pic) data = ""
def main(): signal(SIGINT,ctrlc_handler) #code that finds the IP subnet automatically ip_sub = str(conf.route) ip_sub = ip_sub.split('\n') ip ="" for line in ip_sub: if ("eth0" in line) or ("eth1" in line): ip = line.split()[0] ip = ip.split(".") ip_prefix = ip[0]+'.' + ip[1]+'.' + ip[2] + '.' if ip=="": sys.exit() #end of code that finds the subnet automatically print "\nARP Scanner - Scanning for Devices" print "======================================" for ip_suffix in range(1,255): ip = ip_prefix + str(ip_suffix) arpRequest = Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip, hwdst="ff:ff:ff:ff:ff:ff") #wait for 1 second before timeout and suppress the emission messages with verbose=0 arpResponse = srp1(arpRequest, timeout=1, verbose=0) if arpResponse: print ("IP: %s MAC: %s" %(arpResponse.psrc,arpResponse.hwsrc))
def run_bash(cmd, trys=1, time=10, inc=0, max_time=120): akt_count = 0 loooop = 1 out = "" class Alarm(Exception): pass def alarm_handler(signum, frame): raise Alarm while loooop and (akt_count < trys): akt_count += 1 proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if time > max_time: time = max_time signal(SIGALRM, alarm_handler) alarm(time) time += inc try: out = proc.stdout.read().strip() alarm(0) loooop = 0 except Alarm: proc.kill() return out
def run_bash_v2(cmd,trys=100,time_step=20,max_time=120,factor_max_time=4): akt_count=0 loooop=1 out="" class Alarm(Exception): pass def alarm_handler(signum, frame): raise Alarm while loooop and (akt_count<trys): akt_count+=1 proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) ###timeout does not workt with python 2.6 sorry time_max=time_step*akt_count if time_max>max_time: time_max=max_time*factor_max_time signal(SIGALRM, alarm_handler) alarm(time_max) # print proc.poll() try: out=proc.stdout.read().strip() alarm(0) loooop=0 except Alarm: #print "nochmal" proc.kill() return out #This is the stdout from the shell command
def main(): # interrupt and terminate signal handling signal(SIGINT, SIGINT_handler) signal(SIGTERM, SIGTERM_handler) # initialize pyaudio stream try: stream = init_pyaudio_stream() except: print("Unable to create audio stream.") sys.exit(1) # start the stream try: print("Starting audio stream...") stream.start_stream() if stream.is_active(): print("Audio stream is active.") except: print("Unable to start audio stream.") print("Sniffing packets...") while True: #give the processor a rest time.sleep(1 / CHUNK) read_sockets(packets) if AUDIO_BLOCKING: audify_data(packets, stream)
def main(): if len(sys.argv) < 3: print('argv error') sys.exit(1) HOST = sys.argv[1] PORT = int(sys.argv[2]) ADDR = (HOST, PORT) #创建数据报套接字 s = socket(AF_INET, SOCK_DGRAM) s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) s.bind(ADDR) #防止僵尸进程 signal(SIGCHLD, SIG_IGN) #创建新进程 pid = os.fork() if pid < 0: print('create process failed') return elif pid == 0: do_child(s) else: do_parent(s, ADDR)
def start(logger, timeinterval): # Log logger.info("TimeLaps - Start") # Load the signal for sig in (SIGABRT, SIGINT, SIGTERM): signal(sig, __signal_handler) # Load the camera capture = cv.CaptureFromCAM(0) while active: # Take picture with camera img = cv.QueryFrame(capture) # Save file current_time = time.strftime("%m.%d.%y-%H.%M.%S", time.localtime()) output_name = '/tmp/timelaps-%s.jpg' % current_time cv.SaveImage(output_name, img) # Log logger.info("TimeLaps - Take a picture") # Wait a while until next shot time.sleep(timeinterval) # Quit the camera if capture is not None: del(capture) logger.info("TimeLaps - Stop")
def mrt_open(): global recvSock, ackSock, nextAck, outPort signal(SIGINT, shutdown) try: numComms = int(argv[1]) listenPort = int(argv[2]) senderIp = socket.gethostbyname(argv[3]) senderPort = int(argv[4]) mrt_accept1(listenPort) packet, addr = recvSock.recvfrom(576) sourcePort, destPort, seqNum, ackNum, headerLength, ack, final, windowSize, contents = unpack(packet) checksum = getChecksum(packet) packetValid = checksum == 0 and nextAck == ackNum if packetValid: nextAck += 1 ackSock.connect((senderIp, senderPort)) outPort = ackSock.getsockname()[1] ackSegment = createPacket(outPort, senderPort, seqNum, ackNum, packetValid, False, 1, "") ackSock.send(ackSegment)
def ros_kill_test(): global pub rospy.init_node('ros_kill_test', anonymous=None) pub = rospy.Publisher('ros_kill_test', String, queue_size=100) # rospy.Subscriber("three_w/three_w", MultiPersons, callbackFromRecognition) rospy.Subscriber("two_w/who", MultiPersons, cb_recognition) signal(SIGINT, handler) # try: # print "Hello" # i = 0 # while True: # i += 1 # print "Iteration #%i" % i # sleep(1) # finally: # print "Goodbye" print(rospy.is_shutdown()) r = rospy.Rate(1) # 10hz while not rospy.is_shutdown(): print("running") if rospy.is_shutdown() is True: print("ttt") # print(jsonString) # print(jsonString) r.sleep()
def run(self): # get the vehicle record try: vehicle = Vehicle.objects.get(veh_name=self.vehicle_name) except: logger.error("%s: Vehicle '%s' does not exist in database. Add it first.", MY_NAME, self.vehicle_name) sys.exit(2) # start GPS polling thread self.gps_poller.start() # catch signals for proper shutdown for sig in (SIGABRT, SIGTERM, SIGINT): signal(sig, self.cleanup) # main execution loop while True: try: time.sleep(self.interval) # If we are idle too long the database server may # close the connection on us, ping the server to check if # the connection is still up. if connection.connection is not None: if connection.is_usable(): logger.debug("%s: Database connection is up.", MY_NAME) else: logger.error("%s: Database connection is down.", MY_NAME) connection.close() else: logger.error("%s: Database connection is closed.", MY_NAME) # process GPS data session = self.gps_poller.session if (session.fix.mode == MODE_NO_FIX) and not self.nofix: logger.info("%s: Waiting for GPS to fix...", MY_NAME) continue if not isnan(session.fix.time): if (session.fix.speed < 0.1) and (self.last_speed < 0.1): continue self.last_speed = session.fix.speed # if the time is valid the data record is valid location = Location() location.loc_vehicle = vehicle location.loc_time = session.utc location.loc_latitude = session.fix.latitude location.loc_longitude = session.fix.longitude if session.fix.mode == MODE_3D: location.loc_altitude = session.fix.altitude location.loc_speed = session.fix.speed location.loc_climb = session.fix.climb location.loc_track = session.fix.track location.save() logger.info("%s: Valid location: %s", MY_NAME, location) else: logger.debug("%s: Invalid location: %s", MY_NAME) except KeyboardInterrupt: print ("\n") break
def main(argv): for sig in (SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM): signal(sig, clean) # --- IP of esp esp_ip = "129.69.209.119" #placeholder broker_port = 1883 #Read other measure interval from parameter data paramArray = json.loads(argv[0]) for param in paramArray: if not ('name' in param and 'value' in param): continue elif param["name"] == "esp_ip": esp_ip = param["value"] configFileName = "connections.txt" topics = [] brokerIps = [] configExists = False configFile = os.path.join(os.getcwd(), configFileName) while (not configExists): configExists = os.path.exists(configFile) time.sleep(1) # BEGIN parsing file fileObject = open(configFile) fileLines = fileObject.readlines() fileObject.close() for line in fileLines: pars = line.split('=') topic = pars[0].strip('\n').strip() ip = pars[1].strip('\n').strip() topics.append(topic) brokerIps.append(ip) # END parsing file hostname = brokerIps[0] topic_pub = topics[0] topic_splitted = topic_pub.split('/') component = topic_splitted[0] component_id = topic_splitted[1] # --- Create ESP12e instance global esp esp = ESP12e_Push(esp_ip, hostname, broker_port, topic_pub) esp.start() # --- Create Ultrasonic sensor instance ultrasonic = Ultrasonic(hostname, broker_port, topic) while ultrasonic.getLastValue() == None: ultrasonic.updateLastValue() time.sleep(1) while True: time.sleep(1)
def run(self): """ Main execution loop """ # catch signals for proper shutdown for sig in (SIGABRT, SIGTERM, SIGINT): signal(sig, self.shutdown) # start servers self.startup() # main loop logger.debug('HAGW Server: Entering Main Loop') while True: try: time.sleep(settings.MAIN_LOOP_INTERVAL) if self.ping() == False: # cannot ping myself via RVI -> restart logger.warning('HAGW Server: ping failed -> restarting') self.cleanup() if not self.startup(): logger.warning('HAGW Server: startup failed.') continue #logger.debug('HAGW Server: Thingcontrol Status: %s', thingcontrolserver.setIVIHVAC()) except KeyboardInterrupt: print('\n') break
def __init__(self): self.port = None self.sel = selectors.DefaultSelector() self.keep_running = True self.logger = logging.getLogger(self.__class__.__name__) self.logger.setLevel(logging.DEBUG) self.send_queues = {} signal(SIGINT, self._handle_sigint)
def main(): for sig in (SIGABRT, SIGINT, SIGTERM): signal(sig, handler) print('PID: {}'.format(os.getpid())) while True: time.sleep(1)
def set_alarm_handler(timeout): def sigalarm_handler(signal, frame): print "Timeout( %sms) exceeded." % timeout if current_guid is not None: abort_transaction(current_guid) sys.exit(1) signal(SIGALRM, sigalarm_handler)
def __init__(self, host, port): self.host = host self.port = port self.logger = logging.getLogger(self.__class__.__name__) self.send_queue = queue.Queue() self.mysel = selectors.DefaultSelector() self.keep_running = True signal(SIGINT, self._handle_sigint)
def run(self): self.detector = MotionDetector(self.logger, 10) # Load the signal for sig in (SIGABRT, SIGINT, SIGTERM): signal(sig, self.signal_handler) self.detector.start()
def __init__(self, receivePort): # Split address on dot. Defaut operation msg = ( "\n\n=====================\n NEW SESSION\n=====================\n" ) makeLog(msg) self.host = "" self.listeningPort = receivePort signal(SIGPIPE, SIG_DFL)
def main(): global TAIL_FIFO global PIDFILE if len(sys.argv) < 2: print >> sys.stderr, "Usage: %s <file>" % sys.argv[0] sys.exit(1) thefile = sys.argv[1] try: f = open(thefile) except Exception as e: print >> sys.stderr, e sys.exit(1) if len(sys.argv) > 2: TAIL_FIFO = sys.argv[2] if not os.access(TAIL_FIFO, os.F_OK): try: os.mkfifo(TAIL_FIFO) except Exception as e: print >> sys.stderr, e sys.exit(1) signal(SIGINT, cleanup) signal(SIGQUIT, cleanup) signal(SIGABRT, cleanup) signal(SIGTERM, cleanup) signal(SIGHUP, cleanup) fd = os.open(PIDFILE, os.O_WRONLY | os.O_CREAT) os.write(fd, "%d" % os.getpid()) os.close(fd) ret = 0 for line in tail_file(f): line = line.strip() try: fd = os.open(TAIL_FIFO, os.O_WRONLY) if os.write(fd, line) <= 0: os.close(fd) break os.close(fd) except Exception as e: print >> sys.stderr, e ret = 1 break os.unlink(TAIL_FIFO) os.unlink(PIDFILE) sys.exit(ret)
def saler(): signal(SIGINT, saler_handler) signal(SIGQUIT, saler_handler) signal(SIGUSR1, saler_handler) signal(SIGTSTP, SIG_IGN) signal(SIGUSR2, SIG_IGN) while True: time.sleep(2) print('在路上...')
def c3(): signal(SIGTERM, stop2) signal(SIGINT, stop2) if os.path.exists(pidfile): os.kill(pid[0], SIGTERM) t[0] = time() return c4 else: pid[0] = None return stop
def main(): for sig in (SIGABRT, SIGINT, SIGTERM, SIGILL, SIGSEGV): signal(sig, cleanup) frontend = Process(target=run_server, args=[q.put_nowait]) backend = Process(target=url_listener) for proc in (frontend, backend): proc.daemon = True proc.start() pause()
def __init__(self): cwd = os.getcwd() proj = os.path.join( os.path.basename(os.path.dirname(os.path.dirname(cwd))), os.path.basename(os.path.dirname(cwd)), os.path.basename(cwd)) wx.Frame.__init__(self,None,-1,proj) self.pid = 0 signal(SIGINT,self.handler) sizer = wx.BoxSizer(wx.VERTICAL) panel = wx.Panel(self,-1) buttons = self.set_buttons(panel) panel.SetSizer(buttons) buttons.Fit(self) sizer.Add(panel,0,wx.ALL|wx.EXPAND,5) self.results = commands.getoutput("scons -s results").split() c = self.results[-1:][0] if (c < 'A' or c > 'z'): self.results.pop() # remove scons junk self.flip = {} panel = wx.Panel(self,-1) rsizer = wx.FlexGridSizer(rows=len(self.results),cols=2,vgap=5) for fig in self.results: self.flip[fig] = False title = self.get_title(fig) if title: title = '%s [%s]' % (fig,title) else: title = fig cb = wx.CheckBox(panel,-1,title) cb.Bind(wx.EVT_CHECKBOX, self.set_flip) rsizer.Add(cb,0,0) b = wx.Button(panel,-1,'show') self.Bind(wx.EVT_BUTTON,self.show(fig),b) rsizer.Add(b,0,0) panel.SetSizer(rsizer) rsizer.Fit(self) sizer.Add(panel,0,wx.ALL|wx.EXPAND,15) self.SetSizer(sizer) sizer.Fit(self)
def setSigHandler(self, signals, handler): """ Set a signal handler for the given signals (SIG*) """ # see `man signal` for valid signals # Windows has other restrictions: # https://docs.python.org/2/library/signal.html#signal.signal for sig in signals: # Some signals are not supported on Windows which raises an error. try: signal(sig, handler) except ValueError as e: continue
def __init__(self, config_path, send_user_ids_path): self.config = {} execfile(config_path, self.config) twitter_connect_info = [self.config["consumer_key"],self.config["consumer_secret"], self.config["token_key"], self.config["token_secret"]] self.tweeter_parser = TwitterParser(twitter_connect_info, REGEX, send_user_ids_path) self.email_sender = EmailSender(self.config["email_user"], self.config["email_psw"]) for sig in (SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM): signal(sig, self.exitSignalHandler) self.startParsing()
def run(self): def cleanup(*args): if self.db.cursor is not None: self.db.saveCursor() self.db.shutdown() sys.exit(0) # register the cleanup function with all signals for sig in (SIGABRT, SIGINT, SIGTERM): signal(sig, cleanup) self.db.monitor()
def do_start(self): if self.umask is not None: os.umask(self.umask) if self.rundir is not None: os.chdir(self.rundir) self.app = self.app_factory() self.add_service(self.app) self.async.init() self.async.signal(RELOAD_SIGNAL, self.reload) self.async.signal(STOP_SIGNAL, self.stop)
def __init__(self, game_filename): signal(SIGPIPE, SIG_DFL) self.game_loaded_properly = True # Verify that specified game file exists, else limit functionality if game_filename == None or not os.path.exists('textplayer/games/' + game_filename): self.game_loaded_properly = False print "Unrecognized game file or bad path" return self.game_filename = game_filename self.game_log = game_filename + '_log.txt' self.debug = False
def __init__(self): self._connectedPeers = {} self._logger = logging.getLogger(__name__) self._peerCondition = threading.Condition() self._JanusProcess = None self.videoId = 1 initialized = signal('initialized') self.peersDeadDetacher = None
def c1(): try: pid[0] = int(open(pidfile).read().strip()) except Exception as e: pass if pid[0]: print("process launched as pid %d." % pid[0]) signal(SIGINT, stop) signal(SIGTERM, stop) t[0] = time() return c2 else: if time() - t < timeout: print("waiting for process to launch...") return c1 else: print("process did not start up in %d seconds" % timeout) return stop
def run(self): """ Main execution loop """ # catch signals for proper shutdown for sig in (SIGABRT, SIGTERM, SIGINT): signal(sig, self.shutdown) # start servers self.startup() # main loop logger.info('Sensor Server: Entering Main Loop') while True: try: if settings.HEARTBEAT_ENABLE == True: logger.info('Sensor Server Heartbeat') time.sleep(settings.MAIN_LOOP_INTERVAL) except KeyboardInterrupt: print ('\n') break
def run(self): """ This function is called as a daemon. 0. Get configuration parameters 1. Create two threads, one adding period job and another adding on-demand job to queue 2. Run CRM as sub-process to consume the job queue """ logger = Logger("INFO") signal(SIGTERM, self.sigterm_handler) signal(SIGQUIT, self.sigterm_handler) try: is_valid_file, self.config_attr = ErcFileHandler().init_chmm_file(config_path, "CONFIG") if not is_valid_file: raise Exception("Invalid config file.") self.check_repo_directory() ErcTrapGenerator.init_crm_err_dictionay(self.config_attr["crm_error_dict"]) except Exception, e: Logger.error("LileeErc.run.init_chmm_file", str(e)) ErcTrapGenerator.generate_erc_trap(str(e), "") raise
def run(self, args, cwd=None, shell=False, kill_tree=True, timeout=-1, env=None): ''' Run a command with a timeout after which it will be forcibly killed. Mostly from Alex Martelli solution (probably from one of his python books) posted on stackoverflow.com ''' class Alarm(Exception): pass def alarm_handler(signum, frame): raise Alarm LOG.debug("run: args= " + str(args)) # p = Popen(args, shell = shell, cwd = cwd, stdout = PIPE, stderr = PIPE, env = env) p = Popen(args, stdout=PIPE, stderr=STDOUT) if timeout != -1: signal(SIGALRM, alarm_handler) alarm(timeout) try: stdout, stderr = p.communicate() if timeout != -1: alarm(0) except Alarm: pids = [p.pid] if kill_tree: pids.extend(self._get_process_children(p.pid)) for pid in pids: # process might have died before getting to this line # so wrap to avoid OSError: no such process try: kill(pid, SIGKILL) except OSError: pass return -9, '', '' return p.returncode, stdout, stderr
def run(self, sleep=0, mode=None, log=True, __self=None): if __self is not None: self = __self if not mode == "T": if os.name == "posix": signal(SIGHUP, self._signal) signal(SIGINT, self._signal) signal(SIGTERM, self._signal) self._running = True self.push(Started(self, mode)) try: while self.running: try: [f() for f in self._ticks.copy()] self._flush() if sleep: try: time.sleep(sleep) except: pass except (KeyboardInterrupt, SystemExit): self._running = False except: try: if log: self.push(Error(*_exc_info())) finally: self._flush() finally: try: self.push(Stopped(self)) rtime = time.time() while len(self) > 0 and (time.time() - rtime) < 3: try: [f() for f in self._ticks.copy()] self._flush() if sleep: time.sleep(sleep) rtime = time.time() except: try: if log: self.push(Error(*_exc_info())) finally: self._flush() except: pass
def _init_signals(self): def sigStop(sigNum, handler): self.sig_wrapper(sigNum, self.stop) def toggleLevel(): currentLevel = self.__get_logging_level() if currentLevel == 4: self.__set_logging_level(1) else: self.__set_logging_level(currentLevel + 1) def sigStop(sigNum, handler): self._sig_wrapper(sigNum, self.stop) def sigDebug(sigNum, handler): self.sig_wrapper(sigNum, toggleLevel) signal(SIGTERM, sigStop) signal(SIGQUIT, sigStop) signal(SIGINT, sigStop) signal(SIGUSR2, sigDebug)
def stopJanus(self): with self._janusStartStopCondition: try: if self._JanusProcess is not None: #it's possible that a new client came it while stopping the camera feed #in that case we should not try to stop it if self._JanusProcess.returncode is None: self._logger.debug('Attempting to terminate the Janus process') self._JanusProcess.terminate() attempts = 6 while self._JanusProcess.returncode is None and attempts > 0: time.sleep(0.3) self._JanusProcess.poll() attempts -= 1 if self._JanusProcess.returncode is None: #still not terminated self._logger.debug('Janus didn\'t terminate nicely, let\'s kill it') self._JanusProcess.kill() self._JanusProcess.wait() self._logger.debug('Janus Stopped') self._JanusProcess = None self.sendEventToPeers('stopConnection') self._connectedPeers = {} #STOP TIMER FOR LOST PEERS if self.peersDeadDetacher: self.peersDeadDetacher.cancel() ready = signal('manage_fatal_error_webrtc') ready.disconnect(self.closeAllSessions) return True except Exception as e: self._logger.error("Error stopping Janus. Error: %s" % e) return False
def closePeerSession(self, sessionId): with self._peerCondition: if len(self._connectedPeers.keys()) > 0: try: peer = self._connectedPeers[sessionId] except KeyError: self._logger.warning('Session [%s] for peer not found' % sessionId) peer = None if peer: peer.streamingPlugin.send_message({'request':'destroy'}) peer.close() self.sendEventToPeer(self._connectedPeers[sessionId], 'stopConnection') del self._connectedPeers[sessionId] self._logger.info("There are %d peers left.", len(self._connectedPeers)) if len(self._connectedPeers.keys()) == 0: #last session self.stopGStreamer() self.stopJanus() ready = signal('manage_fatal_error_webrtc') ready.disconnect(self.closeAllSessions)
# beercount for a user that we'll download DOWNLOAD_THRESHOLD = 1500 """ MISC """ import time from datetime import datetime, timedelta import os from signal import * # handles a ctrl-\ signal def process_quit(signum, frame): sys.exit(1) signal(SIGQUIT, process_quit) # write a line to the current line in the terminal. # @param sring String to write to the current line. def sameLine(string): sys.stdout.write("\r" + string) sys.stdout.flush() # Sleeps for a certain a specified amount of seconds, and show the countdown # @param secs Amount of seconds to sleep for. def sleepCountdown(secs): while True: try: temp = secs print "Sleeping for %d seconds." % secs print("DAYS:HOURS:MIN:SEC")
def run(self): # Execution starts here logger.info('%s: Starting...', self.__class__.__name__) # get configuration conf = get_settings() # setup gps source if conf['TRACKING_GPS_ENABLE'] == True: logger.info('%s: GPS Source enabled.', self.__class__.__name__) self.gps_source = GPSSource(conf, logger, self.queue) self.gps_source.start() # setup file source if conf['TRACKING_FILE_ENABLE'] == True: logger.info('%s: File Source enabled.', self.__class__.__name__) self.file_source = FileSources(conf, logger, self.queue) self.file_source.start() # setup municbox source if conf['TRACKING_MUNICBOX_ENABLE'] == True: logger.info('%s: Munic.Box Source enabled.', self.__class__.__name__) self.munic_source = MunicSource(conf, logger, self.queue) self.munic_source.start() # setup database sink if conf['TRACKING_DB_PUBLISH'] == True: logger.info('%s: Publishing to database enabled.', self.__class__.__name__) db_sink = DBSink(conf, logger) # setup message queue sink if conf['TRACKING_MQ_PUBLISH'] == True: logger.info('%s: Publishing to message queue enabled.', self.__class__.__name__) mq_sink = MQSink(conf, logger) # setup RVI sink if conf['TRACKING_RVI_PUBLISH'] == True: logger.info('%s: Publishing to RVI enabled.', self.__class__.__name__) rvi_sink = RVISink(conf, logger) # catch signals for proper shutdown for sig in (SIGABRT, SIGTERM, SIGINT): signal(sig, self.cleanup) # main execution loop while True: try: # get data from queue try: data = self.queue.get(True, 60) except Exception as e: if isinstance(e, KeyboardInterrupt): break else: logger.info("%s: Queue timeout", self.__class__.__name__) continue # vin is required but not all data sources may provide it if (not 'vin' in data): data[u'vin'] = conf['VIN_DEFAULT'] logger.info("%s: Got data: %s", self.__class__.__name__, data) if conf['TRACKING_DB_PUBLISH'] == True: db_sink.log(data) if conf['TRACKING_MQ_PUBLISH'] == True: mq_sink.log(data) if conf['TRACKING_RVI_PUBLISH'] == True: rvi_sink.log(data) except KeyboardInterrupt: print ('\n') break
time.sleep(0.1) return False def wait_for_process_exit(pid, tries=50): """ Wait until the entry for this process has been removed from the dict of running processes, up until the maximum number of retries. """ global running_pids cnt = 0 while pid in running_pids: cnt += 1 if cnt > tries: assert False, "Process never exited!" time.sleep(0.1) if __name__ == "__main__": def orig_chld_handler(pid, f): print "original handler" def exit_handler(pid, exitcode, rusage): print "pid: %d exited" % pid signal(SIGCHLD, orig_chld_handler) background("ls", exit_handler) time.sleep(5) # vi: noexpandtab ts=2 sts=2 sw=2