Перейти к основному содержимому
Linux Processes, Signals & systemd Services
Урок 4 из 10

Linux Processes, Signals & systemd Services

Inspect running Linux processes and listening network sockets, control execution safely with signals, and manage persistent background services using systemd.

Средний 22 мин Linux и Windows
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.
Только в разрешённой среде — Описанные здесь приёмы применяются только в учебных лабораториях и в системах, которые принадлежат вам или на которые есть письменное разрешение.

Цели обучения

  • Inspect running processes, parent-child relationships, and resource ownership with ps
  • Send appropriate POSIX signals to reload, interrupt, or terminate processes safely
  • Control and audit systemd services across current runtime and boot persistence
  • Map listening TCP and UDP ports back to their owning processes and unit files

Рекомендуется заранее: Терминал Linux и структура каталогов FHSВладение файлами и права доступа rwx в LinuxLinux Users, Groups & Sudo Basics

#Why this matters

Files and permissions on disk only describe what could run; live security work depends on knowing what is running right now. Every web server, database, scheduled task, or unexpected backdoor on a Linux host runs in memory as one or more processes.

To diagnose a hung daemon, reduce attack surface, or triage a suspicious connection, you must trace three things together: the running process, its owner account, and the network socket or systemd unit behind it.

#Inspecting running processes

When the Linux kernel boots, it starts the init system as PID 1 (on modern distributions this is systemd), which spawns system services and user sessions. Every process has a numeric Process ID (PID), a Parent PID (PPID), an owner UID, and a state such as R (running or runnable), S (sleeping), or Z (zombie, finished but not yet reaped by its parent).

The ps command reads live kernel process tables exposed under /proc and prints a snapshot. Two classic flag styles appear everywhere:

  • ps aux shows all users' processes with CPU, memory, state (STAT), start time, and command line.
  • ps -ef shows UID, PID, PPID, and full command, making parent-child chains easy to follow.
Inspecting processes on a lab host
$ ps -eo pid,ppid,user:12,stat,cmd --sort=-%cpu | head -n 6
    PID    PPID USER         STAT CMD
   1842    1801 www-data     S    python3 -m http.server 8088
    914       1 root         Ss   sshd: /usr/sbin/sshd -D
    880       1 postgres     Ss   /usr/lib/postgresql/15/bin/postgres
    612       1 root         Ss   /lib/systemd/systemd-journald

Notice how sshd and postgres have PPID 1 because systemd launched them directly, while python3 has PPID 1801 and runs as www-data. Checking the parent process (ps -fp 1801) tells you whether a shell, cron job, or compromised web worker started it.

#Sending signals cleanly

A signal is a lightweight software notification delivered to a process. Administrators use kill (which sends a signal despite its name) to ask a daemon to reload its config or shut down gracefully before forcing termination.

Signal Number Default action Common use
SIGHUP 1 Terminate (often caught to reload) Reload daemon configuration without dropping connections
SIGINT 2 Terminate Interrupt from keyboard (Ctrl+C)
SIGKILL 9 Force terminate immediately Last resort when a process ignores SIGTERM
SIGTERM 15 Terminate gracefully Default signal sent by kill <pid>

Always try SIGTERM (kill 1842 or kill -15 1842) before SIGKILL (kill -9 1842). Applications can catch SIGTERM to flush buffers, close files, and remove lock files. The kernel handles SIGKILL directly, so a process cannot catch it, risking corrupted state.

#Managing services with systemd

Long-running background processes (daemons) are normally defined as .service unit files in /lib/systemd/system/ (or /usr/lib/systemd/system/) with local overrides in /etc/systemd/system/. You manage them with systemctl.

Keep runtime state separate from boot persistence:

  • sudo systemctl start nginx / stop nginx: starts or stops the service right now.
  • sudo systemctl restart nginx: stops and starts it; reload asks it to re-read configuration if supported.
  • sudo systemctl enable nginx / disable nginx: creates or removes symlinks so the service does or does not launch automatically at boot.
  • systemctl status nginx: shows whether the unit is active, its main PID, recent log lines, and whether it is enabled.
  1. List socketssudo ss -tulpn
  2. Trace PIDps -fp PID
  3. Check unitsystemctl status UNIT
  4. Act safelystop/disable or reload

#Mapping processes to listening ports

A process listening on a network port expands the host's attack surface. Use ss (socket statistics) with -tulpn to audit open listeners:

  • -t / -u: show TCP and UDP sockets.
  • -l: show only listening sockets.
  • -p: display the owning process name and PID (requires sudo to see processes owned by other users).
  • -n: show numeric IP addresses and ports instead of resolving names.
Auditing listening ports on lab.local
$ sudo ss -tulpn
Netid State  Recv-Q Send-Q Local Address:Port Peer Address:Port Process
tcp   LISTEN 0      128        127.0.0.1:5432      0.0.0.0:*     users:(("postgres",pid=880,fd=5))
tcp   LISTEN 0      128          0.0.0.0:22        0.0.0.0:*     users:(("sshd",pid=914,fd=3))
tcp   LISTEN 0      5            0.0.0.0:8088      0.0.0.0:*     users:(("python3",pid=1842,fd=3))

Compare the local addresses: postgres binds to 127.0.0.1:5432 (reachable only from the machine itself), whereas python3 binds to 0.0.0.0:8088 (reachable on every network interface).

#Common mistakes

  • Jumping straight to kill -9: Using SIGKILL first skips graceful cleanup and can corrupt active writes or leave stale PID files.
  • Stopping without disabling: Running systemctl stop leaves an unwanted service configured to return after the next reboot unless you also run systemctl disable.
  • Omitting sudo with ss -tulpn: Without elevated privileges, ss still lists ports, but the Process column stays blank for other users' daemons.
  • Ignoring bind addresses: Assuming a port is internal when it actually listens on 0.0.0.0 exposes internal tools to the wider network.

#Summary

Every running program on Linux is a process with a PID, parent PID, and owner, inspected with ps and controlled through signals such as SIGTERM (graceful) and SIGKILL (forced). Persistent daemons are managed as systemd units via systemctl, where runtime state (start/stop) is distinct from boot persistence (enable/disable). Combining sudo ss -tulpn with ps and systemctl status lets you connect any open port back to its owning process and account.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему

Практика: проверьте свои знания