Login [Register]
Don't have an account? Register now to chat, post, use our tools, and much more.
So, I am trying to have a Python server for the future Star Trek game run on port 1701 on my raspberry pi. Things work, but I run into issues where if I end the script (Ctrl Z) the port remains bound but the service isn't running. I would (preferably) like to set this server up in such a way that I can run it using:

Code:
python3 server.py start|stop|restart

I am open to other suggestions. What is the best way to do this?

Edit: Successfully resolved this using systemd.
I was going to say, use systemd: it's much better at this than you can be without a lot of work.

Perhaps you'd care to share what you did, though?
Well, what I did was fairly simple. I have the Python script in an arbitrary directory (in this case it's in /home/trek/server). I created a unit file in /lib/systemd/system that looks like this:

Code:

[Unit]
Description=Star Trek Server
After=multi-user.target
Conflicts=getty@tty1.service

[Service]
Type=simple
ExecStart=/usr/bin/python3 /home/trek/server/setup.py
StandardInput=tty-force
PIDFile=/var/run/trekserv.pid

[Install]
WantedBy=multi-user.target


After that, you can use systemctl start|stop|status trekserv.service as root to interact with the daemon. I then realized it was still erroring, and after doing a bit more research, realized that you need a PID file, which systemd can access and remove but not create/modify, so I added this Python and then called it during the server's startup:


Code:

def writePidFile():
    pid = str(os.getpid())
    f = open('/var/run/trekserv.pid', 'w')
    f.write(pid)
    f.close()


And now I can stop/start the server using the systemd syntax.
You may also wish to not run it as root, since that's generally good practice and everything appears to already be in a user's home directory.

Code:
[Service]
...
User=trek


You can also do away with the PID file completely; it's mostly only needed for services of Type=forking (traditional daemons) because the spawned daemon in that design can't be reliably followed; when you have Type=simple, it can always identify your PID because the service process is exactly the one that systemd starts.
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are GMT - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement