How to move SimpleSocket server into a background process

时光总嘲笑我的痴心妄想 提交于 2019-12-17 21:13:43

问题


I have a simple socketServer that works perfectly on the main thread.

#Server PORT
PORT = 8020
#reassign variables
Handler = Server #this is a SimpleHTTPHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

httpd.serve_forever()

I need to have this run in the background and have the ability to stop the process at will. What is the proper way to do this?

EDIT

Sorry I was unclear. I need to have the server running non stop and I can only access the system from SSH so I can't just start it and walk away.


回答1:


Assuming you are running your script on a POSIX operating system and your script is named socket_server.py, you can use nohup like this:

$ nohup python socket_server.py >> /dev/null 2>&1 &

That will put your script in the background, make it immune to hangups, and you can exit your SSH session. The shell will print out the job number and PID:

$ [1] 1234

You can stop it later by getting sending a SIGTERM using kill:

$ kill -SIGTERM 1234



回答2:


You might need threading/_thread

def server():
    ....

import _thread
_thread.start_new_thread(server, ())

This basically starts the server function on a different thread.

EDIT: In this case in your def server(): you a global variable threadIsRunning, if this is valued to True it should continue, but if it is valued to False run thread.exit() this should all be in some sort of loop.



来源:https://stackoverflow.com/questions/41334729/how-to-move-simplesocket-server-into-a-background-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!