i know how create deamon listens post request. found code create deamon on link didn't know how fill it. im sending commandes android phone php server on json redirects python can communicate on serial arduino. know if there better solutions, help
here code of daemon creation:
## {{{ http://code.activestate.com/recipes/278731/ (r6) """disk , execution monitor (daemon) configurable daemon behaviors: 1.) current working directory set "/" directory. 2.) current file creation mode mask set 0. 3.) close open files (1024). 4.) redirect standard i/o streams "/dev/null". failed call fork() raises exception. references: 1) advanced programming in unix environment: w. richard stevens 2) unix programming asked questions: http://www.erlenstar.demon.co.uk/unix/faq_toc.html """ __author__ = "chad j. schroeder" __copyright__ = "copyright (c) 2005 chad j. schroeder" __revision__ = "$id$" __version__ = "0.2" # standard python modules. import os # miscellaneous os interfaces. import sys # system-specific parameters , functions. # default daemon parameters. # file mode creation mask of daemon. umask = 0 # default working directory daemon. workdir = "/" # default maximum number of available file descriptors. maxfd = 1024 # standard i/o file descriptors redirected /dev/null default. if (hasattr(os, "devnull")): redirect_to = os.devnull else: redirect_to = "/dev/null" def createdaemon(): """detach process controlling terminal , run in background daemon. """ try: # fork child process parent can exit. returns control # command-line or shell. guarantees child not # process group leader, since child receives new process id # , inherits parent's process group id. step required # insure next call os.setsid successful. pid = os.fork() except oserror, e: raise exception, "%s [%d]" % (e.strerror, e.errno) if (pid == 0): # first child. # become session leader of new session , process group # leader of new process group, call os.setsid(). process # guaranteed not have controlling terminal. os.setsid() # ignoring sighup necessary? # # it's suggested sighup signal should ignored before # second fork avoid premature termination of process. # reason when first child terminates, processes, e.g. # second child, in orphaned group sent sighup. # # "however, part of session management system, there # 2 cases sighup sent on death of process: # # 1) when process dies session leader of session # attached terminal device, sighup sent processes # in foreground process group of terminal device. # 2) when death of process causes process group become # orphaned, , 1 or more processes in orphaned group # stopped, sighup , sigcont sent members of # orphaned group." [2] # # first case can ignored since child guaranteed not have # controlling terminal. second case isn't easy dismiss. # process group orphaned when first child terminates , # posix.1 requires every stopped process in orphaned process # group sent sighup signal followed sigcont signal. since # second child not stopped though, can safely forego ignoring # sighup signal. in case, there no ill-effects if ignored. # # import signal # set handlers asynchronous events. # signal.signal(signal.sighup, signal.sig_ign) try: # fork second child , exit prevent zombies. # causes second child process orphaned, making init # process responsible cleanup. and, since first child # session leader without controlling terminal, it's possible # acquire 1 opening terminal in future (system v- # based systems). second fork guarantees child no # longer session leader, preventing daemon ever acquiring # controlling terminal. pid = os.fork() # fork second child. except oserror, e: raise exception, "%s [%d]" % (e.strerror, e.errno) if (pid == 0): # second child. # since current working directory may mounted filesystem, # avoid issue of not being able unmount filesystem @ # shutdown time changing root directory. os.chdir(workdir) # don't want file mode creation mask inherited # parent, give child complete control on permissions. os.umask(umask) else: # exit() or _exit()? see below. os._exit(0) # exit parent (the first child) of second child. else: # exit() or _exit()? # _exit exit(), doesn't call functions registered # atexit (and on_exit) or registered signal handlers. # closes open file descriptors. using exit() may cause stdio # streams flushed twice , temporary files may unexpectedly # removed. it's therefore recommended child branches of fork() # , parent branch(es) of daemon use _exit(). os._exit(0) # exit parent of first child. # close open file descriptors. prevents child keeping # open file descriptors inherited parent. there variety # of methods accomplish task. 3 listed below. # # try system configuration variable, sc_open_max, obtain maximum # number of open file descriptors close. if doesn't exists, use # default value (configurable). # # try: # maxfd = os.sysconf("sc_open_max") # except (attributeerror, valueerror): # maxfd = maxfd # # or # # if (os.sysconf_names.has_key("sc_open_max")): # maxfd = os.sysconf("sc_open_max") # else: # maxfd = maxfd # # or # # use getrlimit method retrieve maximum file descriptor number # can opened process. if there not limit on # resource, use default value. # import resource # resource usage information. maxfd = resource.getrlimit(resource.rlimit_nofile)[1] if (maxfd == resource.rlim_infinity): maxfd = maxfd # iterate through , close file descriptors. fd in range(0, maxfd): try: os.close(fd) except oserror: # error, fd wasn't open begin (ignored) pass # redirect standard i/o file descriptors specified file. since # daemon has no controlling terminal, daemons redirect stdin, # stdout, , stderr /dev/null. done prevent side-effects # reads , writes standard i/o file descriptors. # call open guaranteed return lowest file descriptor, # 0 (stdin), since closed above. os.open(redirect_to, os.o_rdwr) # standard input (0) # duplicate standard input standard output , standard error. os.dup2(0, 1) # standard output (1) os.dup2(0, 2) # standard error (2) return(0) if __name__ == "__main__": retcode = createdaemon() # code, is, create new file in root directory, when # executed superuser privileges. file contain following # daemon related process parameters: return code, process id, parent # process group id, session id, user id, effective user id, real group id, # , effective group id. notice relationship between daemon's # process id, process group id, , parent's process id. 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()) open("createdaemon.log", "w").write(procparams + "\n") sys.exit(retcode) ## end of http://code.activestate.com/recipes/278731/ }}}
if have write daemon, want use python-daemon
, it's reference implementation of pep 3143. there ton of little things have right.
if have write server, , have never done it, , don't need handle more 100 or simultaneous connections, , don't need share data between different clients, threading
far easiest solution.
an echo server daemon (which runs forever until signal
it, , doesn't attempt graceful shutdown) looks this:
import socket import threading import daemon def handle_client(sock): sock.makefile() f: sock.close() line in f: f.writeline(line) def serve_forever(): server = socket.socket() server.setsockopt(socket.sol_socket, socket.so_reuseaddr, 1) server.bind('', 12345)) server.listen(1) while true: conn, address = server.accept() thread = threading.thread(target=handle_client, args=[conn]) thread.daemon = true thread.start() daemon.daemoncontext(): serve_forever()
just put real code inside handle_client
loop.
but really, more complicated need. inetd
service lot simpler:
import sys line in sys.stdin: print(line)
and register server on port 12345, add 1 line /etc/inetd.conf
:
12345 stream tcp nowait nobody /usr/bin/python python /usr/local/bin/myscript.py
and that's it.
of course modern *nix system not using old-school inetd
, rather xinetd
, systemd
, launchd
, or other replacement, configuration little different. read appropriate docs system. still, lot simpler writing socket server daemon.
alternatively… why need write php server forward python server? there few potential answers that, if don't have one, don't need this. use python service/cgi/whatever instead of php one, , let web server handle networking, daemonizing, management, etc.
Comments
Post a Comment