systemd and unit files
When Linux boots, the kernel starts one program first, as process 1. On Debian, Ubuntu, Fedora and most other distributions that is systemd. It starts the services, programs that run in the background, and watches them. ps -p 1 shows it.
You describe a service in a small text file, a unit file. Ours is /etc/systemd/system/hello.service. ExecStart is the command to run: python3 with our script. Restart=on-failure means: if it crashes, start it again.
systemd does not notice new or changed unit files on its own. sudo systemctl daemon-reload tells it to read them all again. systemctl is the command for talking to systemd; sudo runs it as root, the administrator.
Running a service
sudo systemctl start hello: systemd asks the kernel to run the ExecStart command as a new process, a child of systemd. The kernel gives it a number, PID 1234. Now hello.py runs in the background.
systemctl status hello asks systemd how the service is doing. Loaded: it found the unit file. Active: active (running). Main PID: 1234, the process it watches. Reading the status needs no sudo.
hello.py prints hello every 5 seconds, but a service has no terminal. systemd sends its output to the journal, the system log. sudo journalctl -u hello shows only this unit's lines, tagged python3[1234].
Crashes, boot and stop
Let's crash it: sudo kill -9 1234. Signal 9, SIGKILL, makes the kernel end a process at once, with no chance to clean up. Only do this to a test service like ours. The process is gone.
systemd notices its child died from a signal. With Restart=on-failure that counts as a failure, so after 100 ms, the default RestartSec, it runs ExecStart again. The new process gets a new PID, 1240, and logs on.
start runs a service now; enable makes it start at boot. sudo systemctl enable hello reads [Install]: WantedBy=multi-user.target. It puts a link to our file in multi-user.target.wants, which systemd follows at every boot.
sudo systemctl stop hello sends SIGTERM, a polite request to end. If the process were still running after 90 seconds, the default timeout, systemd would send SIGKILL. A stop you asked for is not a failure, so nothing restarts.
What happens
;; step 1/10 · pid1
kernel boots, then starts /sbin/init as process 1 (PID 1)
on systemd systems /sbin/init is systemd
systemd the service manager: starts, watches and stops
services (programs with no window, in the background)
$ ps -p 1 -o comm=
systemd
The PIDs 1234 and 1240 are examples. Your machine picks its own numbers, and the journal lines start with the date and the computer's name, cut to "…" here. kill -9 is a last resort: the process cannot save its work or tidy up. To restart a service on purpose, use sudo systemctl restart hello instead.