Monday, July 13, 2015

Background and Foreground Jobs in Linux

Linux/Unix lets you control how you interface with jobs quite conveniently. Here is a cheat-sheet I keep for my own use:

Send Foreground to Background

  • Start foreground job in terminal
  • Press Ctrl+Z to suspend job
  • Type "bg" to send it to background
  • Check background jobs with jobs, top, or ps commands

Example:

$ sleep 1000    # job running in foreground
^Z
[1]+  Stopped                 sleep 1000

$ bg
[1]+ sleep 1000 &

$ jobs
[1]+  Running                 sleep 1000 &

Send Background to Foreground

  • Suppose you have multiple background jobs running 
  • Use jobs command to list them
  • "fg" brings last background job into foreground
  • fg %1 brings job #1 listed in output of the jobs command


Example:

$ sleep 200&   # submit job#1
[1] 9074

$ sleep 100&  # submit job #2
[2] 9075

$ fg       # bring job #2 to foreground
sleep 100

^Z       # suspend it 
[2]+  Stopped                 sleep 100

$ bg   # put it back into background
[2]+ sleep 100 &

$ jobs   # check if both jobs running
[1]-  Running                 sleep 200 &
[2]+  Running                 sleep 100 &

$ fg %1  # bring job #1 to foreground
sleep 200

^C  # kill it using Ctrl+C

$ jobs  # check to see if job#2 is still running
[2]+  Running                 sleep 100 &


No comments: