Systemd oneshot, ExecStop and RemainAfterExit

July 14, 2015 by
Filed under: Development, Linux 

I wanted to create a systemd service file that just ran 3 small commands today in a sequence on ExecStart and another set of reverse commands on ExecStop. My initial idea was to use bash syntax with ; between the commands (I keep forgetting that Systemd is not bash…), and the service file was set to being a oneshot file, which meant the ; was actually interpreted correctly, but all the ExecStop commands where also run directly when running systemctl start service.

So I read up a little on Systemd and ExecStart, this is what the http://www.freedesktop.org/software/systemd/man/systemd.service.html#ExecStart= page has to say:

When Type is not oneshot, only one command may and must be given. When Type=oneshot is used, zero or more commands may be specified. This can be specified by providing multiple command lines in the same directive, or alternatively, this directive may be specified more than once with the same effect.

So… that means the ; syntax will only work with oneshot apparently. Also, oneshot means that ExecStop runs directly after ExecStart. Further reading the documentation seems to indicate that RemainAfterExit=yes will make the service stay around according to systemd, so it will only try to execute the first time you run systemctl start, but not the second one. I don’t think this fixes that it runs ExecStop on start however, but I’m not sure.

Comments

One Comment on Systemd oneshot, ExecStop and RemainAfterExit

  1. Chris Morin on Wed, 10th Feb 2016 21:54
  2. If you have RemainAfterExit=yes, ExecStop won’t run until after the service is stopped.

    Also, if you want to run multiple commands on start when something isn’t a “oneshot”, you can always use ExecStartPre=.
    Alternatively, you can do something like this:
    ExecStart=/bin/bash -c “cmd1; cmd2; cmd3”

    Though since it’s not a oneshot, you’d want the last one to be long running.

    For what you described, I think that a oneshot with a RemainAfterExit=yes would be the best way to go.

Tell me what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!