python實現守護程序的方法
阿新 • • 發佈:2018-12-16
#!/usr/bin/python2.7 #coding=utf-8 import socket import os import sys import Constants from io import BytesIO as StringIO def socket_server(): f = StringIO() server_address = Constants.SOCKET_FILE # Make sure the socket does not already exist try: os.unlink(server_address) except OSError: if os.path.exists(server_address): raise # Create a UDS socket sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # Bind the socket to the address print('starting up on {}'.format(server_address)) sock.bind(server_address) # Listen for incoming connections sock.listen(1) while True: # Wait for a connection print('waiting for a connection') connection, client_address = sock.accept() try: print('connection from', client_address) # Receive the data in small chunks and retransmit it while True: data = connection.recv(16) print('received {!r}'.format(data)) if data: print('sending data back to the client') if data == "get": connection.sendall(read_from_memory(f)) else: write_into_memory(f,data) else: print('no data from', client_address) break finally: # Clean up the connection connection.close() def write_into_memory(string_io,info): """ 狀態的寫入分別包含: nodeId int // 1 | 2 redisState int // 0: unknown, 1: master, 2: slave, [3, ]: down remoteOpState int // 0: unknown, 1: active masterId int // 1 | 2, master node ID :return: """ string_io.write(info) return def read_from_memory(string_io): return string_io.read() if __name__ == "__main__": # do the UNIX double-fork magic, see Stevens' "Advanced # Programming in the UNIX Environment" for details (ISBN 0201563177) try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError, e: print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) # decouple from parent environment os.chdir("/") os.setsid() os.umask(0) # do second fork try: pid = os.fork() if pid > 0: # exit from second parent, print eventual PID before print "Daemon PID %d" % pid sys.exit(0) except OSError, e: print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) # start the daemon main loop socket_server()