Created
March 7, 2016 20:46
-
-
Save khanzf/a0f27469142b6afaa6c2 to your computer and use it in GitHub Desktop.
Fork-Based Daemon Process
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Basic skeleton of Daemon Fork-based daemon service | |
# | |
# It will accept a new socket connection, then trigger execute_cmd(). You | |
# can create a global variable to keep track of the child processes if you | |
# need to. This approach is sub-optimal, it should use select/poll on the | |
# accept() function, but this is python not C with a Posix interface. I am | |
# having the child process just do a simple "/bin/ls" as a proof of concept. | |
# | |
# Farhan Khan ([email protected]) | |
import sys, os, socket, signal | |
def execute_cmd(): | |
pid = os.fork() | |
if pid == 0: # This is the child process | |
devnull = os.open('/dev/null', os.O_WRONLY) | |
# Uncommented these two to make output go away | |
# os.dup2(devnull, 1) # Overwrite stdout | |
# os.dup2(devnull, 2) # Overwrite stderr | |
os.execv('/bin/ls', ['ls', '/etc/']) | |
else: | |
pass | |
def signalHandler(signum, _): | |
if signum == signal.SIGCHLD: | |
dead_pid, status = os.wait() | |
print("The child process %d died"%dead_pid) | |
def build_socket(): | |
# Binding on IPv6, w00t w00t! | |
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) | |
# Binding on port 10000 | |
sock.bind(('', 10000)) | |
sock.listen(10) | |
return sock | |
def main(): | |
sock = build_socket() | |
signal.signal(signal.SIGCHLD, signalHandler) | |
while True: | |
try: | |
connection, client_address = sock.accept() | |
print "Got a connection, do something" | |
connection.send("Send me 10 characters, I'll send you them back and execute the command\r\n") | |
data = connection.recv(10) | |
connection.send(data) | |
connection.close() | |
execute_cmd() | |
except socket.error, msg: | |
continue # This will happen because of the signal interrupt | |
# Interrupt the accept(2) syscall | |
print "Server dying, the end" | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment