Command Line Intermediate: Text, Processes and Users
Processes and Jobs
In this lesson you will
- List and inspect processes
- Stop a process with the right signal
- Run and manage background jobs
Introduction
Every running program is a process. Each has an ID number (PID), an owner and a state. Knowing how to see and control processes is vital when something hangs or uses too much memory.
Seeing processes
Terminal
ps # processes in your current terminal
ps aux # every process, with owner, CPU and memory
ps aux | grep node # find a particular program
top # live view, press q to quitIn ps aux, useful columns are USER, PID, %CPU, %MEM and the COMMAND. Many systems also offer htop, a friendlier version of top.
To find a process ID by name:
Terminal
pgrep -l firefoxStopping processes
kill does not always "kill". It sends a signal.
Terminal
kill 1234 # polite request to stop (SIGTERM)
kill -9 1234 # forceful stop (SIGKILL)
pkill firefox # by nameAlways try the normal kill first. It lets the program clean up files and save data. Use kill -9 only when it will not stop, because the program gets no chance to tidy up.
Quick quiz
Which should you try first when stopping a frozen program?
Foreground, background and jobs
A command that takes a long time blocks your terminal. Add & to run it in the background:
Terminal
sleep 300 &
jobs # list background jobs in this shell
fg %1 # bring job 1 to the foregroundTo pause a running command, press Ctrl+Z. Then continue it in the background with bg, or bring it back with fg. Ctrl+C interrupts and stops it.
Closing the terminal normally ends its jobs. To keep a program running after you log out, use nohup:
Terminal
nohup ./long-task.sh > output.log 2>&1 &2>&1 sends error messages to the same place as normal output. For serious long-lived work, tools such as tmux or a system service are better.
Exit codes
When a command finishes, it returns a number. 0 means success, anything else means a problem. Check the last one with:
Terminal
ls /nowhere
echo $?On most Linux systems the output of echo $? is 2 here, because the folder does not exist. Scripts depend on exit codes, as you will see in the advanced course.
Chaining commands
Terminal
mkdir backup && cp notes.txt backup/ # second runs only if the first succeeded
command1 || command2 # second runs only if the first failed
command1 ; command2 # run both regardlessTry it yourself
Start sleep 300 &, find it with ps aux | grep sleep, then stop it with kill and its PID. Check with jobs that it is gone.
Summary
ps,topandpgrepshow processes, and each has a PID.killsends signals. Try the polite one first, and-9as a last resort.&,jobs,fg,bgandnohupmanage background work, and exit code 0 means success.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading