---
# System prepended metadata

title: Introduction to Linux Daemon
tags: [Linux, "SysV\_", systemctl, systemd, Daemon]

---

# Introduction to Linux Daemon
* Background Processes in Linux
* Linux Init Systems: systemd vs. System V
* Command `systemctl`: Managing System Services in Linux

## What is a Linux Daemon?
* **Definition**: A daemon is a background process that runs continuously and performs specific tasks or waits to perform specific tasks.
* **Origin**: The term "daemon" comes from Greek mythology, meaning a benevolent or benign nature spirit.
* Run in the background without user intervention.
* Often started at boot time and run continuously until the system is shut down.
* Do not have a controlling terminal.
* Perform system-level tasks such as logging, printing, and networking.

## How Daemons Work
* Examples
    * `sshd`: Secure Shell Daemon, handles SSH connections.
    * `httpd`: HTTP Daemon, serves web pages.
    * `crond`: Daemon that executes scheduled tasks.
    * `syslogd`: System logging daemon.
* Lifecycle:
    * **Initialization**: Daemon is started, often during system boot.
    * **Operation**: Daemon runs in the background, waiting for tasks or performing continuous operations.
    * **Termination**: Daemon stops when the system shuts down or when manually stopped.

## Introduction to Init Systems
* Init systems are responsible for initializing the system during the boot process and managing services.
* They determine the startup and shutdown sequence of services and daemons in a Unix-like operating system.
* System V (SysV) v.s. systemd

## System V (SysV) Init
* Overview: 
    * One of the oldest init systems used in Unix-like operating systems.
* Characteristics:
    * Based on runlevel scripts located in `/etc/init.d/` directory.
    * Uses symbolic links in `/etc/rc*.d/` directories to start and stop services.
    * Sequential execution of startup scripts.
* Pros:
    * Simplicity and predictability in its approach.
    * Easy to understand and configure manually.
* Cons:
    * Can lead to longer boot times due to sequential execution.
    * Relatively more challenging to manage complex dependencies between services.

## systemd
* Overview: 
    * Modern init system introduced as a replacement for System V init.
* Characteristics:
    * Implements parallelization for service startup.
    * Uses **unit files** for service configuration.
    * **Units** are resources that systemd manages, including services, sockets, devices, etc.
        * Service units: Represent system services.
        * Socket units: Represent inter-process communication sockets.
        * Target units: Represent system states or synchronization points.
    * Offers features like service activation on demand, dependency management, logging, and monitoring.
* Pros:
    * Faster boot times due to parallelization.
    * Advanced dependency management.
    * Built-in logging and monitoring capabilities.
* Cons:
    * Some users find its complexity overwhelming, especially those accustomed to traditional Unix-like systems.
    * Requires learning new concepts and commands.

## SysV Init vs. systemd
* Linux init systems play a crucial role in the boot process and service management.
* System V init and systemd are two prominent init systems with distinct approaches and features.
* Choice between them depends on factors like system requirements, familiarity, and distribution support.

|  | SysV | systemd |
| -------- | -------- | -------- |
| Startup Time | Sequential | Parallel |
| Configuration | Scripts | Unit Files |
| Dependency Management | Manual | Automated |
|Logging and Monitoring| Externeal tools | Built-in |
|Adoption| Legacy systems | Modern distribution |

## What is systemctl?
* systemctl is a command-line utility for controlling the systemd system and service manager.
* It is used to manage system services, units, targets, sockets, and other objects controlled by systemd.
* systemctl can handle service dependencies automatically.
* When starting or stopping a service, systemctl ensures that dependent services are started or stopped accordingly.

## `systemctl` syntax
```
systemctl [OPTIONS] [COMMAND] [UNIT]
```
E.g., start a service: `sudo systemctl start {service-name}`

* Common Commands:
    * `start`: start a service
    * `stop`: stop a service
    * `restart`: restart a service
    * `reload`: reload configuration
    * `enable`: enable a service to start on boot
    * `disable`: disable a service from starting  on boot
    * `status`: show the status of a service

## Creating a Simple Daemon
* Write the daemon code (e.g., in C, Python, Bash).
* Ensure the code runs in the background.
* Handle signals (e.g., start, stop, reload).
* Implement logging for monitoring.
    * Place the unit file in `/etc/systemd/system/`
    * Enable the service `sudo systemctl enable mydaemon`
    * Start the service `sudo systemctl start mydaemon`
    * Check status `sudo systemctl status mydaemon`

## Creating a Simple Daemon - Backup Service (Bash)
* Run the service one time
* Service dependency: atd.service

**/backups/backup.sh**
```
#!/bin/bash
source="/etc /home /root /var/lib /var/spool/{cron,at,mail}"
target="/backups/backup-system-$(date +%Y-%m-%d).tar.gz"
[ ! -d /backups ] && mkdir /backups
tar -zcvf ${target} ${source} &> /backups/backup.log
```
**/etc/systemd/system/backup.service**
```
[Unit]
Description=backup my server
Requires=atd.service

[Service]
Type=simple
ExecStart=/bin/bash -c " echo /backups/backup.sh | at now"

[Install]
WantedBy=multi-user.target
```
**terminal**
```
[root@study ~]# chmod a+x /backups/backup.sh
[root@study ~]# systemctl daemon-reload
[root@study ~]# systemctl start backup.service
[root@study ~]# systemctl status backup.service
backup.service - backup my server
   Loaded: loaded (/etc/systemd/system/backup.service; disabled)
   Active: inactive (dead)

Aug 13 07:50:31 study systemd[1]: Starting backup my server...
Aug 13 07:50:31 study bash[20490]: job 8 at Thu Aug 13 07:50:00 2015
Aug 13 07:50:31 study systemd[1]: Started backup my server.

```

## Creating a Simple Daemon - Timestamp service (Python)
* Keep running in background

**/home/u/timestamp/timestamp.py**
```
#!/usr/bin/env python3
import time
import datetime

def main():
    while True:
        file1 = open("datedata.txt", "a")
        file1.write(str(datetime.datetime.now())+" example \n")
        print(str(datetime.datetime.now())+" example \n")
        file1.close()
        time.sleep(30)
if __name__ == "__main__":
    main()
```
**/etc/systemd/system/timestamp.service**
```
[Unit]
Description="recording timestamp"

[Service]
Restart=always
WorkingDirectory=/home/u/timestamp
ExecStart=/usr/bin/python3 timestamp.py

[Install]
WantedBy=multi-user.target
```

## Reference
https://linux.vbird.org/linux_basic/centos7/0560daemons.php#systemd_cfg_custom
https://medium.com/@guemandeuhassler96/run-your-python-script-as-a-linux-daemon-9a82ed427c1a

