Linux for backend engineers

Processes, file descriptors, memory, ports, logs, systemd, and the commands that answer "what is this machine doing".

12 min read🔁 CI/CD, Linux and Nginx

The service runs on Linux, and the JVM lessons stopped at the boundary where the kernel takes over: the process that ended with no Java log, the Too many open files that stopped accepting connections, the port that was already in use after a restart. This lesson is the kernel's side of those boundaries — enough to read what the system is telling you, and the commands that show it.

Processes and signals

A running JVM is a process: a PID, a parent, a user, an environment, open files, and a set of threads the kernel schedules (ps -T -p <pid> lists them; the thread-dump lesson's nid is the kernel's thread id in hex). ps aux, top and htop show them; /proc/<pid>/ is the truth they read from — status for memory and threads, fd/ for open files, environ for the environment, limits for the caps.

The kernel talks to a process with signals, and a service must handle three:

SignalSent byThe process should
SIGTERM (15)systemctl stop, the orchestrator, Dockerfinish in-flight work and exit: Java runs shutdown hooks; Spring Boot's graceful shutdown drains
SIGKILL (9)the kernel's OOM killer, the orchestrator after the grace periodnothing — it cannot be caught; the process is gone mid-write
SIGHUP (1)a terminal closing, some daemons for "reload config"for a JVM, usually exit; nohup ignores it

The rule from the Docker course applies here too: the signal reaches the JVM only if the JVM is the process it was sent to. A sh -c "java ..." wrapper receives the SIGTERM and does not forward it, so the JVM sees nothing until the SIGKILL arrives. exec java ... in a script, or the exec-form entrypoint, makes Java the process. Exit codes tell the story afterwards: 0 clean, 1 a Java exception or System.exit(1), 137 ended by signal 9 (128 + 9), 143 terminated by signal 15.

File descriptors

Every open file, socket, pipe and epoll instance is a file descriptor: an integer in the process's table. The table has a limit, set by ulimit -n in a shell, LimitNOFILE= in a systemd unit, or the container runtime's default.

The default of 1024 on some systems is a number a Java service reaches in minutes. Every accepted connection is a descriptor, and so is every outbound HTTP call, every open log file, and every jar on the classpath while it is being read. The failure is java.io.IOException: Too many open files. It stops accepting connections as well as opening files, so a leak of file handles becomes an outage of the whole listener.

ls /proc/<pid>/fd | wc -l is the count, and lsof -p <pid> says what they are. A leak shows as the same file or the same remote address repeated hundreds of times. Typical causes are the Files.lines without a try from the I/O course, or an HTTP client created per request instead of once. Set the limit high (65536 is common) and find the leak. Raising the limit alone moves the outage to next week.

Memory, and the OOM killer

The memory-areas lesson measured what a JVM uses; the kernel sees only the total, the process's resident set size (RSS, in ps and top), and enforces a limit through the cgroup the container or the systemd unit sets (MemoryMax=1G on this repository's API unit). When the limit is hit — or, on a host without limits, when the whole machine runs out — the OOM killer picks a process, by a score that favours the largest, and sends SIGKILL. The evidence is not in the application's log; it is in the kernel's: dmesg -T | grep -i 'killed process' or journalctl -k, with the process name, its RSS, and the cgroup.

Two things to know when reading it.

  • free -m shows memory "used" by the page cache as available, which it is, because the kernel drops cache under pressure. So a host at 95% "used" may be fine, while a container at 95% of its limit is not.
  • Swap on a JVM host is a latency disaster rather than a safety net. A heap page swapped out turns a 10 ms GC pause into seconds. Most JVM hosts run with swap off (vm.swappiness=0 or none configured) and a limit that ends the process instead.

Ports and sockets

A service listens on a port. ss -tlnp (the modern netstat -tlnp) lists who is listening on what, with the PID. It is the first command when the answer to "is it up" is unclear.

ss -tnp | grep :5432 shows the connections to the database, and their states:

  • ESTABLISHED is a live connection.
  • TIME_WAIT is a closed one the kernel holds for a minute (thousands of them after a load test is normal).
  • CLOSE_WAIT in large numbers is your process not closing what the other side closed. That is a client leak, and the Too many open files above is where it ends.

Ports below 1024 need root or the CAP_NET_BIND_SERVICE capability, which is why a service listens on 8080 and nginx on 443. Address already in use after a restart is the old process still holding the port, or a socket in TIME_WAIT without SO_REUSEADDR, which Java's server sockets set by default. And a service that should not be reachable from outside binds 127.0.0.1, as this repository's API does on 8082 — the firewall is a second layer, not the first.

systemd and journald

On a virtual machine the service is a unit: a file that says what to run, as whom, with what environment and limits, and what to do when it dies.

orders-api.service, the parts that matterplaintext
[Service]
User=orders
EnvironmentFile=/etc/orders-api.env
ExecStart=/usr/lib/jvm/java-25-openjdk-amd64/bin/java -Xms128m -Xmx384m -XX:MaxMetaspaceSize=160m -jar /srv/orders/current/orders-api.jar
Restart=always
RestartSec=5
MemoryMax=1G
LimitNOFILE=65536

Restart=always is the supervisor; EnvironmentFile keeps credentials out of the unit (which anyone who can run systemctl cat would otherwise see — the file's own comment says so); MemoryMax is the cgroup limit; User is the non-root rule. systemctl status, start, stop, restart, enable (start at boot) and daemon-reload after editing the file are the whole interface.

Its logs go to journald, which is where you read them: journalctl -u orders-api -f follows, --since "1 hour ago" bounds, -p err filters by priority, -k is the kernel log where the OOM killer writes. The observability course's structured logging still applies — the JSON goes into the journal as the message — and a log shipper reads the journal to send it onward.

Under the hood: what "handling" a signal actually involves, and who is really tracking the process tree

A signal is not a message queued somewhere for the process to read when convenient. It is the kernel interrupting the process's normal execution, at the next opportunity, to run a handler: a piece of code the process registered in advance. If it registered none, the kernel's own default action applies, which for SIGTERM is to terminate the process.

Between the kernel deciding to deliver a signal and the process actually running the handler, the signal is pending. A process can also block a signal (mask it), so it stays pending without running its handler until unblocked. This is how a critical section can defer a SIGTERM for a moment without losing it. But SIGKILL and SIGSTOP cannot be blocked, caught or ignored by any process, which is exactly why SIGKILL is the kernel's and the OOM killer's tool of last resort.

There is a sharp constraint on what a handler is allowed to do while it runs. Only a small set of async-signal-safe functions may be called from inside it, because the signal can interrupt the process at literally any instruction, including in the middle of another library call that was not written to be reentrant.

This is why the JVM's shutdown-hook mechanism (Runtime.getRuntime().addShutdownHook()) does not run your cleanup code inside the OS-level signal handler at all. The JVM's own native signal handler does the minimal safe thing: it records that a shutdown was requested. Then it starts your registered shutdown-hook threads through the normal JVM thread machinery, safely outside the signal-handling context.

That two-step is also why a shutdown hook that hangs genuinely blocks JVM exit, whether it is waiting forever to drain a queue or blocked on a socket that will never respond. It is ordinary Java code running on an ordinary thread. The OS will not forcibly interrupt it for you, the way it interrupted the process to deliver SIGTERM in the first place.

systemd's role goes beyond just sending the signal. It tracks a service's entire cgroup: every process the service started, however deep the fork tree goes, rather than only the one PID it launched. So systemctl stop can send SIGTERM to the whole tree. After TimeoutStopSec (15 seconds for this repository's own code10x.service) it escalates to SIGKILL for anything still alive in that cgroup, including a grandchild process the original one spawned and forgot about.

A plain shell script backgrounding a process with & has no equivalent. A child that double-forks or is reparented can escape the shell's own knowledge entirely and keep running after the parent is gone. That is one of the reasons a supervised unit is worth more than "start it and hope."

Try it yourself

Why sh -c "java -jar app.jar" can leave the JVM running after systemctl stop

A unit's ExecStart is set to /bin/sh -c "java -jar app.jar" instead of java -jar app.jar directly (or exec java -jar app.jar inside a wrapper script). systemctl stop is run, and the JVM does not shut down gracefully — it lingers until TimeoutStopSec expires and systemd escalates to SIGKILL.

Using what the signal-delivery mechanics above say about which process actually receives a signal, and what you know from the Docker course's version of this same rule, reason about what systemctl stop actually signalled and why the JVM's shutdown hooks never ran.

Where the SIGTERM actually went

sh -c "java -jar app.jar" makes sh the process systemd started and tracks as the unit's main PID (or, at minimum, the direct parent in the cgroup). sh in turn forks java as a child process to run the command.

SIGTERM from systemctl stop is delivered to the PID systemd is tracking as the service, which is sh, not automatically to every descendant. sh's default handling of SIGTERM is to terminate itself. Depending on the shell and how the command was launched, that does not necessarily propagate the signal to the still-running java child at all. The JVM's own SIGTERM handler (the one that triggers shutdown hooks) never fires, because the JVM process was never sent a SIGTERM. Only its parent shell was.

The JVM keeps running, orphaned or reparented, until systemd's cgroup tracking enforces TimeoutStopSec and escalates to SIGKILL for everything left in the cgroup. (The cgroup tracking does see the JVM, even though it was not the direct signal target.)

exec java -jar app.jar fixes it by replacing the shell process image with the JVM's in place: same PID, no child. The signal systemd sends the tracked PID lands on the JVM directly, and its shutdown hooks actually run.

Misconceptions

  • "A signal handler runs the cleanup code directly." Only code written to be async-signal-safe may run inside the actual signal-handling context. The JVM's shutdown hooks run as ordinary Java threads started in response to the signal, not inside it. That is also why a hung shutdown hook is not something the OS will interrupt for you.
  • "systemctl stop signals every process the service started." It signals the tracked PID (or, more precisely, everything systemd's cgroup accounting knows belongs to the service). But a signal sent to a parent is not automatically forwarded to a child the parent spawned. A sh -c wrapper without exec can absorb the SIGTERM and leave the real process running until the kill timeout.

Sources

  • man 7 signal — signal disposition, blocking and pending state, and which signals cannot be caught or ignored.
  • man 2 sigaction and the async-signal-safety list (man 7 signal-safety) — what a handler may safely call.
  • systemd.kill(5) — how systemd tracks a unit's cgroup and escalates from SIGTERM to SIGKILL after TimeoutStopSec.
Progress is saved on this device and to your account when signed in.