I searched online and posted here to understand how to use systemd to auto start a c++ application, now I want it to automatically restart that application if it crashes.
I know the correct course of action is to make the application not crash, but it is not my program to change
Here is what I gathered so far from here:
and here:Writing a systemd script that starts 2 applications in linux
Create the file in /etc/systemd/system/app1.service with:
[Unit]
Description=app1 systemd service.
[Service]
Type=simple
ExecStart=/home/pi/app1
RemainAfterExit=no
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=multi-user.targetThen execute to enable service
sudo systemctl enable app1.service
The service starts up initially, but when I execute
sudo kill xx where xx is the pid of the app, it does not restart itself
How can I fix this init.d script to automatically restart the app if it crashes?
Or is it not going to work if I kill it though sudo kill? In this case how can I test that it works without waiting for it to crash?
thanks
2 Answers
This is what Restart=on-failure does [emphasis mine]:
Restart=Configures whether the service shall be restarted when the service process exits, is killed, or a timeout is reached. […]
Takes one of
no,on-success,on-failure,on-abnormal,on-watchdog,on-abort, oralways. […] In this context, a clean exit means an exit code of0, or one of the signalsSIGHUP,SIGINT,SIGTERMorSIGPIPE, and additionally, exit statuses and signals specified inSuccessExitStatus=. If set toon-failure, the service will be restarted when the process exits with a non-zero exit code, is terminated by a signal (including on core dump, but excluding the aforementioned four signals), when an operation (such as service reload) times out, and when the configured watchdog timeout is triggered.
(source)
kill sends SIGTERM by default. That's why the service does not restart itself after you kill it.
How can I fix this script to automatically restart the app if it crashes?
If the app returns non-zero exit status in such situation then there's nothing to fix. The service will be restarted.
how can I test that it works without waiting for it to crash?
Kill it with
SIGQUITorSIGKILL:kill -s SIGQUIT $pidOr you can use
RestartForceExitStatus=SIGTERMto make the service restart itself afterSIGTERM. But notekill $pidwill then test ifRestartForceExitStatus=works, not exactlyRestart=.Or you can (temporarily) modify
/home/pi/app1so it exits with a non-zero exit status after receivingSIGUSR1or after few seconds. SendSIGUSR1to the process or just wait, then pollsystemctl status app1.serviceto see what happens.
Easy fix
It needed the forking type and the pid file,
this will work with the sudo kill command
Thanks,
[Unit]
Description=app1 systemd service.
[Service]
Type=simple
ExecStart=/home/pi/fbcp-ili9341
RemainAfterExit=no
Restart=always
RestartSec=5s
[Install]
WantedBy=multi-user.target 2