144

Question: Can I kick off a process with systemd and assign that process a working directory of my choosing?

I have a service that I want to start with systemd. When that service is being started, I want to be able to assign it a current working directory. I know how to do this if I was using init, but I'm having trouble with systemd.

Here's what I've been trying to get working.

My Service

I created a simple utility ("listdir"), written in Python, and placed in /opt/bin/listdir:

#! /usr/bin/python

import os

print 'Current working directory: %s' % (os.getcwd())

My Configuration File

I then created a listdir.service file for systemd and placed it here: /lib/systemd/system/listdir.service:

[Unit]
Description=Test of listing CWD.

[Service]
ExecStartPre=chdir /usr/local
ExecStart=/opt/bin/listdir
StandardOutput=syslog
StandardError=syslog

[Install]
WantedBy=multi-user.target

Problem

When I run systemctl start listdir my system log records the root directory ("/") as the current working directory. Of course, I expected /usr/local as the current directory, since I thought ExecStartPre would change directories before starting the process.

Obviously, I'm imagining that systemd would work something like a shell script (even though I know it isn't a shell script). Can someone give me an idea of what I should be doing? Is it even possible to set a working directory using systemd? Thanks!


Edit: My system log is reporting an error. (I just noticed.)

Executable path is not absolute, ignoring: chdir /usr/local 

So, chdir is a shell command, and not an executable itself. Okay. But is there still some way for me to change directories using systemd?

260

On systemd >= 227 you should be able to use:

[Service]
WorkingDirectory=/usr/local

to get your script to execute there.

(DOCS)

  • 4
    How did you find this? It's not mentioned anywhere in the documentation! – jameshfisher Oct 17 '16 at 15:33
  • 2
    @jameshfisher it's in this part of the documentation – Eric Renouf Oct 17 '16 at 15:36
  • 3
    @EricRenouf aha, they should just duplicate those shared options in the service documentation – jameshfisher Oct 18 '16 at 10:52
  • 3
    So just for clarity, would this go in the [Service] section? – dthor Dec 20 '16 at 1:32
  • 4
    Answering myself, it worked on latest CentOS 7, despite of the version. – BrunoJCM Aug 29 '17 at 20:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.