Users trying to exit Terminal sessions are often blocked by the reporting of stopped jobs. Discovering, restarting, and killing these processes are essential lessons for mac and unix users.
Susan tweeted me the following yesterday:
After I completed one of your mac tech-recipes tutorials yesterday, I was unable to logout from my terminal session in OS X. The message that “there are stopped jobs” appeared and prevented me from exiting. What did I do wrong?
You did not do anything wrong. This message is just informing you that you left a programming running in the background while working in the shell. Typically, a program is placed into the background by hitting the control-Z shortcut while the programming is running.
When this occurs the terminal will hide the program and notify you with a command like this:
[3]+ Stopped top
The [number] is the number of programs currently in the background. The plus sign shows it is the most recent to enter the background. The last word is the program that was actually stopped. In my example, I used control-Z to stop the top application.
jobs command
To view a list of all background programs, use the jobs command.
[1] Stopped top
[2] Stopped top
[3]- Stopped top
[4]+ Stopped man telnet
In my example above, you can see that I have 4 stopped applications. I have top in the background three times and man telnet once.
fg command
Through the terminal the fg command will bring the last program back to the front. This will be the application marked with the [+] via the jobs command. Once the program is back to the foreground you can exit it properly instead of stopping it. For example, one would completely exit top or man by pressing the q key. Additionally, control-c will typically kill the program compared to control-z which stops it.
Additionally, you can switch to a specific stopped program through the job number. For example, this would switch to the [2] marked program:
fg %2
kill command
You can also stop programs through the kill command. To use the kill command, we will need to access the process id numbers (PIDs) of the stopped jobs by using the jobs -l command:
[1] 833 Suspended: 18 top
[3]- 860 Suspended: 18 top
[4]+ 861 Suspended: 18 man telnet
The -l addition to our jobs command displays the PIDs. These are the numbers that are not in brackets. These are 833, 860, and 861 in our example above.
Using the kill command with a program’s PID will terminate that application. If we wanted to kill the man process in our example, we would use the following command:
kill 861
Additionally, as a shortcut you can kill all programs listed through the jobs command through the following code:
kill `jobs -p`