def SvcDoRun(self): import servicemanager # log a service started message servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, ' (%s)' % self._svc_display_name_)) while 1: self.thread_event = Event() self.thread_event.set() try: self.bottle_srv = BottleWsgiServer(self.thread_event) self.bottle_srv.start() except Exception, info: errmsg = getTrace() servicemanager.LogErrorMsg(errmsg) self.SvcStop() rc = win32event.WaitForMultipleObjects((self.hWaitStop, ), 0, win32event.INFINITE) if rc == win32event.WAIT_OBJECT_0: # user sent a stop service request self.SvcStop() break
def relay(self, msg_type, x, y, text): if self.shmem_c2p is None: self.shmem_c2p = self._create_shmem('c2p', mmap.ACCESS_WRITE) lst_event = [self.event_c2p_data_empty, self.event_c2p_data_ready] rc = win32event.WaitForMultipleObjects(lst_event, 0, win32event.INFINITE) event_num = rc - win32event.WAIT_OBJECT_0 if event_num == 0: self.shmem_c2p_bytes_in_use = 0 # write guaranteed to work if empty, otherwise failure possible new_bytes_in_use = shmem_write_text(self.shmem_c2p, self.shmem_c2p_bytes_in_use, 'iii', ( msg_type, x, y, ), text) if new_bytes_in_use == self.shmem_c2p_bytes_in_use: # write could not be completed - shmem full. wait for empty win32event.SetEvent(self.event_c2p_data_ready) rc = win32event.WaitForSingleObject(self.event_c2p_data_empty, win32event.INFINITE) self.shmem_c2p_bytes_in_use = shmem_write_text( self.shmem_c2p, 0, 'iii', ( msg_type, x, y, ), text) else: self.shmem_c2p_bytes_in_use = new_bytes_in_use win32event.SetEvent(self.event_c2p_data_ready)
def CollectorThread(stopEvent, file): win32trace.InitRead() handle = win32trace.GetHandle() # Run this thread at a lower priority to the main message-loop (and printing output) # thread can keep up import win32process win32process.SetThreadPriority( win32api.GetCurrentThread(), win32process.THREAD_PRIORITY_BELOW_NORMAL ) try: while 1: rc = win32event.WaitForMultipleObjects( (handle, stopEvent), 0, win32event.INFINITE ) if rc == win32event.WAIT_OBJECT_0: # About the only char we can't live with is \0! file.write(win32trace.read().replace("\0", "<null>")) else: # Stop event break finally: win32trace.TermRead() print("Thread dieing")
def __target(timeout=60): if platform.uname()[0].lower() == "windows": import win32con import win32event self.running = True kill = win32event.CreateEvent(None, 1, 0, None) pulse = win32event.CreateWaitableTimer(None, 0, None) win32event.SetWaitableTimer(pulse, 0, timeout * 1000, None, None, False) while (self.running): try: result = win32event.WaitForMultipleObjects( [kill, pulse], False, 1000) # if kill signal received, break loop if (result == win32con.WAIT_OBJECT_0): break # elif timeout has passed, generate a pulse elif (result == win32con.WAIT_OBJECT_0 + 1): self['event']() except: self.notifyOfError( "Pacemaker shutdown. Heartbeats will not be generated." ) win32event.SetEvent(kill) elif self.options['Verbose']: print "Pacemaker only supported in Windows at this time. "
def Nui_ProcessThread(self, *args): print "Nui_ProcessThread started:", args # http://stackoverflow.com/questions/100624/python-on-windows-how-to-wait-for-multiple-child-processes abort = 0 while not abort: nEventIdx = win32event.WaitForMultipleObjects(hEvents, False, 100) if nEventIdx == 0: print "m_hEvNuiProcessStop event occurred:", hEvents[nEventIdx] abort = 1 elif nEventIdx == 1: print "m_hNextDepthFrameEvent event occurred:", hEvents[ nEventIdx] elif nEventIdx == 2: print "m_hNextVideoFrameEvent event occurred:", hEvents[ nEventIdx] self.Nui_GotVideoAlert() elif nEventIdx == 3: print "m_hNextSkeletonEvent event occurred:", hEvents[ nEventIdx] self.Nui_GotVideoAlert() else: print "unknown nEventIdx:", nEventIdx #finished = handles[nEventIdx] #exitcode = GetExitCodeProcess(finished) #procname = hEvents.pop(finished) #finished.close() #print "Subprocess %s finished with exit code %d" % (procname, exitcode) time.sleep(0.3) print "Nui_ProcessThread ended"
def Run(self): while 1: handles = [self.stopEvent, self.adminEvent] if self.watchEvent is not None: handles.append(self.watchEvent) rc = win32event.WaitForMultipleObjects(handles, 0, win32event.INFINITE) if rc == win32event.WAIT_OBJECT_0: break elif rc == win32event.WAIT_OBJECT_0 + 1: self.RefreshEvent() else: win32api.PostMessage(self.hwnd, MSG_CHECK_EXTERNAL_FILE, 0, 0) try: # If the directory has been removed underneath us, we get this error. win32api.FindNextChangeNotification(self.watchEvent) except win32api.error as exc: print( "Can not watch file", self.doc.GetPathName(), "for changes -", exc.strerror, ) break # close a circular reference self.doc = None if self.watchEvent: win32api.FindCloseChangeNotification(self.watchEvent)
def SvcDoRun(self): # Log a "started" message to the event log. servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) ProcETL().SendSms('ProcJob开始运行') #如果系统日期不是2007年,将时间调整为2007 (y, m, d, h, mi, s) = time.localtime()[0:6] if y != 2007: setdate = '%04d-%02d-%02d' % (2007, m, d) os.system('date %s' % setdate) win32event.SetWaitableTimer(self.timerForProcess, 0, 1000 * 60 * 1, None, None, 0) win32event.SetWaitableTimer(self.timerForPrepare, 0, 1000 * 60 * 2, None, None, 0) while 1: timeout = win32event.INFINITE waitHandles = self.hWaitStop, self.timerForProcess, self.timerForPrepare rc = win32event.WaitForMultipleObjects(waitHandles, 0, timeout) if rc == win32event.WAIT_OBJECT_0: # Stop event break elif rc == win32event.WAIT_OBJECT_0 + 1: ProcETL().ETLProcess() elif rc == win32event.WAIT_OBJECT_0 + 2: ProcETL().ETLPrepare() win32event.CancelWaitableTimer(self.timerForProcess) win32event.CancelWaitableTimer(self.timerForPrepare) servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED, (self._svc_name_, ''))
def __wait_for_child(self): # kick off threads to read from stdout and stderr of the child process threading.Thread(target=self.__do_read, args=(self.__child_stdout, )).start() threading.Thread(target=self.__do_read, args=(self.__child_stderr, )).start() while True: # block waiting for the process to finish or the interrupt to happen handles = (self.wake_up_event, self.h_process) val = win32event.WaitForMultipleObjects(handles, 0, win32event.INFINITE) if val >= win32event.WAIT_OBJECT_0 and val < win32event.WAIT_OBJECT_0 + len( handles): handle = handles[val - win32event.WAIT_OBJECT_0] if handle == self.wake_up_event: win32api.TerminateProcess(self.h_process, 1) win32event.ResetEvent(self.wake_up_event) return False elif handle == self.h_process: # the process has ended naturally return True else: assert False, "Unknown handle fired" else: assert False, "Unexpected return from WaitForMultipleObjects"
def run(self): """Monitor the daemon process. Returns True if the service should continue running and False if the service process should exit. On True return, the process exited unexpectedly and the caller should restart it. """ keep_running = True rc = win32event.WaitForMultipleObjects([self.hWaitStop, self.hZope], 0, # bWaitAll win32event.INFINITE) if rc == win32event.WAIT_OBJECT_0: # a stop service request was recieved keep_running = False elif rc == win32event.WAIT_OBJECT_0 + 1: # the process died; this may be an error condition status = win32process.GetExitCodeProcess(self.hZope) # exit status 0 means a clean shutdown, # presumably via the web interface. keep_running = status != 0 if keep_running: # Any other status is an error so we write it and # any output to the event log self.warning("Process terminated with exit code %d.\n%s" \ % (status, self.getCapturedOutput())) else: # No other valid return codes. assert 0, rc return keep_running
def SvcDoRun(self): if hasattr(sys, "frozen"): this_dir = os.path.dirname(win32api.GetModuleFileName(None)) else: this_dir = os.path.dirname(os.path.abspath(__file__)) # TODO: maybe it is better to run this in a job object too with open(os.path.join(this_dir, 'npm.log'), 'w') as npm_log: subprocess.check_call('npm install', cwd=this_dir, shell=True, stdin=None, stdout=npm_log, stderr=subprocess.STDOUT) security_attributes = win32security.SECURITY_ATTRIBUTES() security_attributes.bInheritHandle = True startup = win32process.STARTUPINFO() startup.dwFlags |= win32process.STARTF_USESTDHANDLES startup.hStdInput = None startup.hStdOutput = win32file.CreateFile( os.path.join(this_dir, "service_stderr.log"), win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ, security_attributes, win32file.CREATE_ALWAYS, 0, None) startup.hStdError = win32file.CreateFile( os.path.join(this_dir, "service_stdout.log"), win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ, security_attributes, win32file.CREATE_ALWAYS, 0, None) (hProcess, hThread, processId, threadId) = win32process.CreateProcess( None, r'"C:\Program Files\nodejs\node.exe" node_worker.js', None, None, True, win32process.CREATE_SUSPENDED | win32process.CREATE_BREAKAWAY_FROM_JOB, None, this_dir, startup) assert not win32job.IsProcessInJob(hProcess, None) self.hJob = win32job.CreateJobObject(None, "") extended_info = win32job.QueryInformationJobObject( self.hJob, win32job.JobObjectExtendedLimitInformation) extended_info['BasicLimitInformation'][ 'LimitFlags'] = win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | win32job.JOB_OBJECT_LIMIT_BREAKAWAY_OK win32job.SetInformationJobObject( self.hJob, win32job.JobObjectExtendedLimitInformation, extended_info) win32job.AssignProcessToJobObject(self.hJob, hProcess) win32process.ResumeThread(hThread) win32api.CloseHandle(hThread) signalled = win32event.WaitForMultipleObjects( [self.hWaitStop, hProcess], False, win32event.INFINITE) if signalled == win32event.WAIT_OBJECT_0 + 1 and win32process.GetExitCodeProcess( hProcess) != 0: servicemanager.LogErrorMsg( self._svc_name_ + " process exited with non-zero status " + str(win32process.GetExitCodeProcess(hProcess))) win32api.CloseHandle(hProcess) win32api.CloseHandle(self.hJob) win32api.CloseHandle(self.hWaitStop) win32api.CloseHandle(startup.hStdOutput) win32api.CloseHandle(startup.hStdError)
def wait(self, state, interval=0.1, channel=None): if isinstance(state, (tuple, list)): if self.state not in state: events = tuple([self._get_state_event(s) for s in state]) win32event.WaitForMultipleObjects(events, 0, win32event.INFINITE) elif self.state != state: event = self._get_state_event(state) win32event.WaitForSingleObject(event, win32event.INFINITE)
def run (self): """Until the stop event is fired, perform the action whenever the action event fires""" self.finished = 0 events = self.events.keys () while not self.finished: result = win32event.WaitForMultipleObjects (events, 0, win32event.INFINITE) if win32event.WAIT_OBJECT_0 <= result <= win32event.WAIT_OBJECT_0 + len (events) - 1: self.events[events[result - win32event.WAIT_OBJECT_0]]()
def run(self): self.__is_running = True self.__change_handles = None self.__dirs = {} try: while self.__is_running: self.__refresh_requests() if self.__change_handles is None: for monitor in self.__dirs.values(): # Newly added if monitor.get_change_handle() is None: monitor.set_change_handle( win32file.FindFirstChangeNotification( monitor.get_dir(), 0, win32con.FILE_NOTIFY_CHANGE_FILE_NAME)) # Refresh change handlers cache print "Refreshing change-handles cache" self.__change_handles = {} for monitor in [ monitor for monitor in self.__dirs.values() if monitor.get_change_handle() ]: self.__change_handles[ monitor.get_change_handle()] = monitor print self.__change_handles #old_path_contents = os.listdir (self.path_to_watch) if len(self.__change_handles) > 0: result = win32event.WaitForMultipleObjects( self.__change_handles.keys(), False, 500) else: result = win32con.WAIT_FAILED if (result >= win32con.WAIT_OBJECT_0) and ( result <= win32con.WAIT_OBJECT_0 + len(self.__change_handles) - 1): changed_handle = self.__change_handles.keys()[result] #print changed_handle monitor = self.__change_handles[changed_handle] #print monitor.get_dir() #print monitor.get_handlers() added, deleted, modified = monitor.reload_file_changes() if len(added) > 0 or len(deleted) > 0 or len(modified) > 0: logging.info(monitor.get_handlers()) self.__serve_handlers(monitor, added, deleted, modified) win32file.FindNextChangeNotification(changed_handle) finally: for monitor in self.__dirs.values(): if monitor.get_change_handle(): win32file.FindCloseChangeNotification( monitor.get_change_handle()) monitor.set_change_handle(None) self.__success = True logging.info("Directory watcher finished")
def RunEm(): handles = [] # First get the screen size to calculate layout. screenX = win32api.GetSystemMetrics(win32con.SM_CXSCREEN) screenY = win32api.GetSystemMetrics(win32con.SM_CYSCREEN) # First instance will be on the left hand side of the screen. rect = -150, -150, 50, 50 #handle = CreateMyProcess("C:\\Program Files\\Mozilla Firefox\\firefox.exe ", rect) #handles.append(handle) # Second instance of notepad will be on the right hand side. #rect = screenX/2+1, 0, screenX/2, screenY rect = 0, 0, screenX / 10, screenY / 4 #handle = CreateMyProcess(r"C:\Program Files\Mozilla Firefox\firefox.exe", rect) handle = CreateMyProcess("notepad", rect) handles.append(handle) # Now we have the processes, wait for them both # to terminate. # Rather than waiting the whole time, we loop 10 times, # waiting for one second each time, printing a message # each time around the loop countdown = range(1, 100000) countdown.reverse() for i in countdown: print "Waiting %d seconds for apps to close" % i rc = win32event.WaitForMultipleObjects( handles, # Objects to wait for. 1, # Wait for them all 1000) # timeout in milli-seconds. if rc == win32event.WAIT_OBJECT_0: # Our processes closed! print "Our processes closed in time." break # else just continue around the loop. else: # We didn't break out of the for loop! print "Giving up waiting - killing processes" for handle in handles: try: win32process.TerminateProcess(handle, 0) except win32process.error: # This one may have already stopped. pass
def SvcDoRun(self): # We create our named pipe. pipeName = "\\\\.\\pipe\\PyPipeService" openMode = win32pipe.PIPE_ACCESS_DUPLEX | win32file.FILE_FLAG_OVERLAPPED pipeMode = win32pipe.PIPE_TYPE_MESSAGE # When running as a service, we must use special security for the pipe sa = pywintypes.SECURITY_ATTRIBUTES() # Say we do have a DACL, and it is empty # (ie, allow full access!) sa.SetSecurityDescriptorDacl(1, None, 0) pipeHandle = win32pipe.CreateNamedPipe( pipeName, openMode, pipeMode, win32pipe.PIPE_UNLIMITED_INSTANCES, 0, 0, 6000, # default buffers, and 6 second timeout. sa) # Loop accepting and processing connections while 1: try: hr = win32pipe.ConnectNamedPipe(pipeHandle, self.overlapped) except error, details: print "Error connecting pipe!", details pipeHandle.Close() break if hr == winerror.ERROR_PIPE_CONNECTED: # Client is fast, and already connected - signal event win32event.SetEvent(self.overlapped.hEvent) # Wait for either a connection, or a service stop request. timeout = win32event.INFINITE waitHandles = self.hWaitStop, self.overlapped.hEvent rc = win32event.WaitForMultipleObjects(waitHandles, 0, timeout) if rc == win32event.WAIT_OBJECT_0: # Stop event break else: # Pipe event - read the data, and write it back. # (We only handle a max of 255 characters for this sample) try: hr, data = win32file.ReadFile(pipeHandle, 256) win32file.WriteFile(pipeHandle, "You sent me:" + data) # And disconnect from the client. win32pipe.DisconnectNamedPipe(pipeHandle) except win32file.error: # Client disconnected without sending data # or before reading the response. # Thats OK - just get the next connection continue
def wait(self, timeout1, timeout2=0): import win32event timeout = int(timeout1 + timeout2) * 1000 result = win32event.WaitForMultipleObjects([self._heventStop, self._heventHeartbeat], False, timeout) if ( win32event.WAIT_OBJECT_0 != result and win32event.WAIT_OBJECT_0 + 1 != result and win32event.WAIT_TIMEOUT != result): raise FatalException(-1, "Error waiting for stop/heartbeat events: " + str(result)) if (win32event.WAIT_TIMEOUT == result): return -1 return result # 0 -> stop, 1 -> heartbeat
def start(self): '''Connects pipes''' self.log.info('Blocked') self.running = True overlapped = pywintypes.OVERLAPPED() for pipe in self.pipes: win32pipe.ConnectNamedPipe(pipe, overlapped) while True: code = win32event.WaitForMultipleObjects(self.pipes, True, self.CONNECTION_TIMEOUT) if code != win32event.WAIT_TIMEOUT: break self.log.info('Unblocked')
def run(self): # # FindFirstChangeNotification sets up a handle for watching # file changes. The first parameter is the path to be # watched; the second is a boolean indicating whether the # directories underneath the one specified are to be watched; # the third is a list of flags as to what kind of changes to # watch for. We're just looking at file additions / deletions. # change_handle = win32file.FindFirstChangeNotification( self.latus_folder, 0, win32con.FILE_NOTIFY_CHANGE_FILE_NAME) # This order is important. If multiple events are triggered, only the lowest index is # indicated. So, the exit event must be the lowest index or else we could miss # the exit event if it happens as the same time as a file system change. wait_objects = [change_handle] if self.exit_event_handle is not None: wait_objects.insert(0, self.exit_event_handle) # prepend # # Loop forever, listing any file changes. The WaitFor... will # time out every half a second allowing for keyboard interrupts # to terminate the loop. # exit_flag = False try: old_path_contents = self.local_folder_contents() while not exit_flag: result = win32event.WaitForMultipleObjects( wait_objects, 0, 10 * 1000) print('WaitForMultipleObjects', result) # # If the WaitFor... returned because of a notification (as # opposed to timing out or some error) then look for the # changes in the directory contents. # if result == win32con.WAIT_OBJECT_0: exit_flag = True elif result == win32con.WAIT_OBJECT_0 + 1: new_path_contents = self.local_folder_contents() added = [ f for f in new_path_contents if not f in old_path_contents ] deleted = [ f for f in old_path_contents if not f in new_path_contents ] self.sync(added, deleted) old_path_contents = new_path_contents win32file.FindNextChangeNotification(change_handle) finally: win32file.FindCloseChangeNotification(change_handle)
def worker_run(keepalive=None): """ The main loop of the worker """ ## It is an error to fork with db connections ## established... they can not be shared: if DB.db_connections > 0: ## We try to fix it by making the child get new ## handlers. Note that the child still needs to hold the ## handles or they will get closed on the parent as well ## - this seems like a hack DB.DBO.DBH_old = DB.DBO.DBH DB.DBO.DBH = Store.Store(max_size=10) DB.db_connections = 0 ## These are all the methods we support jobs = [] my_pid = os.getpid() ## This is the last broadcast message we handled. We will ## only handle broadcasts newer than this. broadcast_id = 0 try: dbh = DB.DBO() dbh.execute("select max(id) as max from jobs") row = dbh.fetch() broadcast_id = row['max'] or 0 except: pass while 1: ## Ping the parent try: if keepalive: os.write(keepalive, "Checking") except Exception, e: print e pyflaglog.log(pyflaglog.WARNING, "Our nanny died - quitting") os._exit(1) ## Check for memory usage check_mem(os._exit, 0) ## Check for new tasks: if not jobs: try: r = win32event.WaitForMultipleObjects( [SyncEvent, TerminateEvent], False, 10000) if r == 1: ## TerminateEvent signaled sys.exit(0) except (NameError, AttributeError), e: time.sleep(config.JOB_QUEUE_POLL)
def _StopOrWaitForChildProcessToFinish(self, childProcess): #Wait for the child process to finish or for the stop event to be signaled if(win32event.WAIT_OBJECT_0 == win32event.WaitForMultipleObjects([WinService._heventSvcStop, childProcess._handle], False, win32event.INFINITE)): # The OS only detaches the child process when the master process exits. # We must kill it manually. try: #Sending signal.CTRL_BREAK_EVENT doesn't work. It only detaches the child process from the master. # Must brutally terminate the child process. Sorry Java. childProcess.terminate() except OSError, e: print_info_msg("Unable to stop Ambari Server - " + str(e)) return False
def wait(self, state, interval = 0.1, channel = None): """Wait for the given state(s), KeyboardInterrupt or SystemExit. Since this class uses native win32event objects, the interval argument is ignored. """ if isinstance(state, (tuple, list)): if self.state not in state: events = tuple([ self._get_state_event(s) for s in state ]) win32event.WaitForMultipleObjects(events, 0, win32event.INFINITE) elif self.state != state: event = self._get_state_event(state) win32event.WaitForSingleObject(event, win32event.INFINITE)
def run(self): hDir = win32file.CreateFileW( self._watch_path, FILE_LIST_DIRECTORY, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS | win32con.FILE_FLAG_OVERLAPPED, None ) while self._windows_sucks_flag: buf = win32file.AllocateReadBuffer(1024) win32file.ReadDirectoryChangesW( hDir, buf, True, win32con.FILE_NOTIFY_CHANGE_FILE_NAME | win32con.FILE_NOTIFY_CHANGE_DIR_NAME | win32con.FILE_NOTIFY_CHANGE_SIZE | win32con.FILE_NOTIFY_CHANGE_LAST_WRITE, self._overlapped ) result_stack = {} rc = win32event.WaitForMultipleObjects((self._wait_stop, self._overlapped.hEvent), 0, win32event.INFINITE) if rc == win32event.WAIT_OBJECT_0: # Stop event break data = win32file.GetOverlappedResult(hDir, self._overlapped, True) # lets read the data and store it in the results results = win32file.FILE_NOTIFY_INFORMATION(buf, data) for action, afile in results: if action in ACTIONS: full_filename = os.path.join(self._watch_path, afile) result_stack.setdefault(full_filename, []).append(ACTIONS.get(action)) keys = list(result_stack.keys()) while len(keys): key = keys.pop(0) event = result_stack.pop(key) if (ADDED in event) and (DELETED in event): event = [e for e in event if e not in (ADDED, DELETED)] noticed = [] for each_event in event: if each_event not in noticed: self._callback(each_event, full_filename) noticed.append(each_event)
def start_process(self): global should_ignore_ctrl_c global createProcess_cmdline assert self.hProcess is None assert self.hThread is None assert self.pid is None assert self.is_starting == False self.is_starting = True # use main process stdout and stderr startup_info = win32process.STARTUPINFO() startup_info.hStdOutput = win32file._get_osfhandle(sys.stdout.fileno()) startup_info.hStdError = win32file._get_osfhandle(sys.stderr.fileno()) startup_info.hStdInput = win32file._get_osfhandle(sys.stdin.fileno()) startup_info.dwFlags = win32process.STARTF_USESTDHANDLES self.hProcess, self.hThread, self.pid, self.dwThreadId = t = win32process.CreateProcess( None, createProcess_cmdline, None, None, 1, 0, None, workingDirectory, startup_info) try: hRemoteThread, remoteThreadId = win32process.CreateRemoteThread(self.hProcess, None, 0, exitThread, -1, 0) logger.info("hRemote: %s %s" % (hRemoteThread, remoteThreadId)) except pywintypes.error as e: print(e) if e.winerror == 5: # (5, 'CreateRemoteThread', 'Access is denied.') # if process exists before we make to create remote thread self.is_starting = False return else: raise logger.debug("### wait #123") ret = win32event.WaitForMultipleObjects( [hRemoteThread, self.hProcess], False, win32event.INFINITE ) event_i = ret - win32event.WAIT_OBJECT_0 if event_i == 0: logger.debug("### hRemoteThread was executed") pass elif event_i == 1: # process terminated (unexpectedly) logger.debug("### WAIT OVER: process terminated (unexpectedly)") self.post_terminate() else: raise Exception("unexpected ret or event_id", ret, event_i) self.is_starting = False
def waitForPendingRequests(self): """ Wait for any pending requests to finish/close... This only does anything useful if a mixin similar to TCPServerService.SvcTrackingThreadingMixin is in the class definition. """ while self.thread_handles: # The 5000 says, SCM, I think I'm going to finish shutting down in 5s. self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING, 5000) #print "Waiting for %d threads to finish..." % (len(self.thread_handles)) # Actually wait for 3s just to be paranoid. rc = win32event.WaitForMultipleObjects(self.thread_handles, 1, 3000)
def close(self): if self.file: self.file.close() self.file = None if sys.platform == "win32": win32event.WaitForMultipleObjects(self.wait_for, 1, win32event.INFINITE) return win32process.GetExitCodeProcess(self.child_pid) else: if self.thread: self.thread.join() if type(self.child_pid) == type([]): for pid in self.child_pid: exit = os.waitpid(pid, 0)[1] return exit else: return os.waitpid(self.child_pid, 0)[1] return None
def SvcDoRun(self): self.is_running = True logging.info("[SERVICE] let's start") while self.is_running: rc = win32event.WaitForMultipleObjects(self.haltEvent, self._timeout) if rc == win32event.WAIT_OBJECT_0: logging.info("[SERVICE] Stop Signal") break else: try: logging.info("[SERVICE] RUN function.") #수행 method 실행 except: logging.warning("[SERVICE] %s" % traceback.format_exc()) logging.warning("[SERVICE] RETURN of function is : %s")
def SvcDoRun(self): self.ReportServiceStatus(win32service.SERVICE_START_PENDING) log('starting') self.ReportServiceStatus(win32service.SERVICE_RUNNING) self.modification_handle = get_config_modification_handle( self._base_path) self.configuration_mtime = os.stat( os.path.join(self._base_path, self._config_filename)).st_mtime keep_running = True do_start = True while keep_running: # do the actual start if do_start: self.start() log('Started. Waiting for stop') index = win32event.WaitForMultipleObjects( [self.stop_event, self.modification_handle], False, win32event.INFINITE) if index == 0: # The stop event has been signaled. Stop execution. keep_running = False else: # re-initialise handle win32file.FindNextChangeNotification(self.modification_handle) new_mtime = os.stat( os.path.join(self._base_path, self._config_filename)).st_mtime if new_mtime != self.configuration_mtime: self.configuration_mtime = new_mtime do_start = True log('Restarting child processes as the configuration has changed' ) self.stop() self.config = read_config(self._base_path, self._config_filename) else: do_start = False win32file.FindCloseChangeNotification(self.modification_handle)
def handleWindowsEvents(self, timeout): '''Handle windows service events, timeout in milliseconds Returns timeout flag''' rc = win32event.WaitForMultipleObjects(self.__events, False, timeout) if rc == win32event.WAIT_OBJECT_0: self.handleStop() elif rc == win32event.WAIT_OBJECT_0+1: self.reload() return False elif rc == win32event.WAIT_OBJECT_0+2: self.handlePause() return False elif rc == win32event.WAIT_OBJECT_0+3: self.handleResume() return False elif rc == win32event.WAIT_TIMEOUT: return True raise WindowsError()
def signalCheckerThread(self): while not self.shutdown_requested: handles = [self.admin_event_handle] signums = [None] for signum, handle in self.event_handles.items(): signums.append(signum) handles.append(handle) rc = win32event.WaitForMultipleObjects(handles, False, win32event.INFINITE) logger.debug("signalCheckerThread awake with %s" % rc) signum = signums[rc - win32event.WAIT_OBJECT_0] if signum is None: # Admin event - either shutdown, or new event object created. pass else: logger.debug("signalCheckerThread calling %s" % signum) self.signalHandler(signum, None) logger.debug("signalCheckerThread back") logger.debug("signalCheckerThread stopped")
def eof(self): ### should be calling file.eof() here instead of file.close(), there ### may be data in the pipe or buffer after the process exits if sys.platform == "win32": r = win32event.WaitForMultipleObjects(self.wait_for, 1, 0) if r == win32event.WAIT_OBJECT_0: self.file.close() self.file = None return win32process.GetExitCodeProcess(self.child_pid) return None if self.thread and self.thread.isAlive(): return None pid, status = os.waitpid(self.child_pid, os.WNOHANG) if pid: self.file.close() self.file = None return status return None