Unix Background Jobs 101
On my current project I’m working with a virtual Ubuntu machine on which Weblogic and DB2 are installed. Weblogic starts with the ./startWeblogic.sh command, and log files are written to a logfile ‘weblogic.xml’ :
./startWebLogic.sh > weblogic.log
You may go wild with opening multiple terminals and switching between them, but I hate the fact that the weblogic process is just taking up an entire window, even though it’s essentially meant to be a background process! This is where some basic unix commands kick in: run a long-lasting command or script as a background job, execute it in the background, bring it back to the foreground, see all running background jobs and (possibly) kill them. Let’s go.
Spawning a background job
This code fragment simulates a 10second command. Notice that the cursor isn’t available until the 10seconds are over.
sleep 10
Append your command with an ampersand ( & ), to run it in the background. The cursor is immediately available.
sleep 10 &
You may wonder already, ‘but how do I know the command is finished?’. See the chapter about ‘showing all background jobs’ for that.
Send the current executing command to the background and back
Suppose you forgot the & , or a command is taking longer than expected. You don’t need to quit (CTRL-C) the command, and re-execute it with the &. You can send the current executing command to the background by pressing CTRL-Z.
sander@sander-ThinkPad-T510:~$ sleep 20 ^Z [1]+ Stopped sleep 20
Notice the fact that the job was stopped (paused should be a better name). Execute the bg command to make the job continue.
sander@sander-ThinkPad-T510:~$ bg [1]+ sleep 20 & sander@sander-ThinkPad-T510:~$ fg sleep 20
To demonstrate this, you can execute thefg command to make it come back to the foreground again. You can bring back any background job to the foreground using this command. No parameters will show the most recent background job, passing %1 will show process with id 1, %2 with id 2, etc.
You can bring a background job to the foreground using fg command. When executed without arguments, it will take the most recent background job to the foreground.
Showing all background jobs
When using this technique a lot, you might send multiple commands to the background. To show all current background process, execute the jobs command.
sander@sander-ThinkPad-T510:~$ jobs [1] Running sleep 30 & [2]- Running sleep 25 & [3]+ Running sleep 20 &
Killing background jobs (OPTIONAL)
Suppose you sent a command to the background you want to kill immediatly. The kill commando can’t only kill processes, but also background jobs.
sander@sander-ThinkPad-T510:~$ sleep 25 & [1] 21153 sander@sander-ThinkPad-T510:~$ sleep 25 & [2] 21156 sander@sander-ThinkPad-T510:~$ sleep 25 & [3] 21157 sander@sander-ThinkPad-T510:~$ kill %2 sander@sander-ThinkPad-T510:~$ jobs [1] Running sleep 25 & [2]- Terminated sleep 25 [3]+ Running sleep 25 &