Course outline · 0% complete

0/29 lessons0%

Course overview →

Processes: ps, kill, and the background

lesson 6-2 · ~10 min · 17/29

Programs become processes

The day this lesson matters: a program freezes your terminal, or something on a server is stuck eating 100% CPU, or a port is "already in use" and you need to find the program holding it. Process tools let you see and stop running programs without rebooting the machine.

A process is a running program. Open three terminals and run bash in each: one program, three processes. The OS gives every process a PID (process ID number).

The inspection tools:

  • ps: list your processes. ps aux lists everything running on the machine, one process per line (great for piping into grep).
  • kill PID: politely ask a process to quit (it sends a signal named TERM).
  • kill -9 PID: force-quit, no questions (signal KILL). Last resort.

And the keyboard shortcuts you'll use daily in a real terminal: Ctrl+C stops the program currently hogging your prompt, and Ctrl+Z pauses it and drops it into the background.

Foreground and background

Normally the shell waits for each command to finish before giving you the prompt back: the command runs in the foreground. End a command with & and it runs in the background instead, so you keep working while it churns:

sleep 60 &

The shell tracks these as jobs: jobs lists them, fg brings one back to the foreground, and wait pauses the script until background jobs finish. Inside a script, the special variable $! holds the PID of the most recent background job, which is exactly what you need to kill it later.

Code exercise · bash

Run it. sleep runs in the background (thanks to &), the echo proves the shell didn't wait, and wait blocks until the job wraps up.

Code exercise · bash

Kill a process on purpose: a 30-second sleep starts in the background, $! remembers its PID, and kill ends it instantly. The script finishes in well under a second.

Quiz

A script is running in your terminal and you want to stop it RIGHT NOW. What do you press?

A stuck program called musicd is eating your CPU. Hunt it down and stop it (simulated).

Step 1/3: Find musicd in the full process list: pipe ps aux through grep.

$ 

Problem

Fill in the command: to list every process running on the machine (the version usually piped into grep), you type ps ___ (three letters).