pidof systemd
2733
If this return a number then your system supports systemd. Most Linux distributions in 2017 support systemd.
Since systemd starts the process then all processes will be children of systemd
pstree -p
The result should be a tree list of all the currently running processes.
This simple script (hello-world.sh) just outputs hello world every 30 seconds.
#!/bin/bash
while $(sleep 30);
do
echo "hello world"
done
Make the file executable
chmod a+x hello-world-service.sh
This command can now be run from the command line but it is not yet running as a service.
Create the service file hello-word.service in /etc/systemd/system/.
sudo /etc/systemd/system/hello-word.service
Put he following into the .service file.
[Unit]
Description=Hello World Service
After=systend-user-sessions.service
[Service]
Type=simple
ExecStart=/home/leo/Projects/test/hello-world.sh
The service file is typically divided into two parts.
The Unit section defines the basic information about the service such as the description and when to run the service. In this case the After line tells systemd that it should wait for the user sessions to start but it could be started before that too if required.
The Service section tells that the type is simple and the command to run. You could also set the type=forking for services which handle their own daemonization. Basically if you run the command and it keeps sending output to the screen then it is a simple type whereas if it runs in the background then it is a forking type. Note: You must use an absolute path for the location of the command. You cannot use ~/Projects/test/hello-world.sh.
Once the .system file has been created in the /etc/systemd/system directory, you can start the service using:
sudo systemctl start hello-world.service
systemctl status hello-world.service
journalctl -u hello-world -e
The -u flag tells which service and the -e flag tells it to start at the end of the file and work back.
Jun 24 13:27:23 leo-500-136ea hello-world.sh[27611]: hello world
Jun 24 13:27:53 leo-500-136ea hello-world.sh[27611]: hello world
Jun 24 13:28:23 leo-500-136ea hello-world.sh[27611]: hello world
You can also add the following line the Service section of to replace the hello-world.sh with a more descriptive tag in the log files. For example you could do:
SyslogIdentifier=HelloWorldService
So the resulting file would look like:
[Unit]
Description=Hello World Service
After=systend-user-sessions.service
[Service]
Type=simple
ExecStart=/home/leo/Projects/test/hello-world.sh
SyslogIdentifier=HelloWorldService
So the log file now looks like:
Jun 24 13:39:56 leo-500-136ea HelloWorldService[28037]: hello world