systemd kills my ngrok session started from python

codeScriber asked:

I have a script i wrote that listens on mqtt.
When certain code arrives to the mqtt server then an ngrok session is started like so:

subprocess.Popen([‘/tmp/ngrok’,’http’ ,’8080′], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

the scrupt runs in a virtualenv and there for has a shell script to activate the virtual env and run it:

#!/bin/bash
. ./venv/bin/activate
python mqtt_listener.py

When running this script in my shell with & in the end the ngrok session opens and and is left open nicl untill i kill it myself.
However when running in systemd using the following system file (user file)
/home/myuser/.config/systemd/user/mqtt_listener.service

[Unit]
Description=mqtt run service
After=default.target

[Service]
Type=exec
ExecStart=/home/myuser/mqtt_listener/run_mqtt_service.sh
KillMode=process

[Install]
WantedBy=default.target

once the service gets the mqtt command i can see the the journal logs the service got my message and forked it’s ngrok process, but then i can see

the service was "succesfully deactivated" and then restarts.
the strange thing is that it always happens when i’m not logged in using ssh to the server, if i’m logged in the process will not die.
Any idea what’s i’m doing wrong ? the type=exec is due to the fact that the others just did not fit.I can’t figure out why systemd considers my python service to be done and thus kills it after a grandchild fork (first fork is the run script, which apprently i can get rid of).

My answer:


By default, user services do not run if the user is not logged in.

You can allow a user to run services while not logged in by enabling lingering for that user’s account, i.e.:

sudo loginctl enable-linger <username>

Once lingering is enabled, user services will run while the user is not logged in, and can also be enabled to start at boot time.


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.