Under some situation, we want to start some long jobs and then return to the shell to continue our work. We can do this by starting a job in the background. The shell such as bash will keep a list of background jobs and their status. But only one foreground job is allowed. Job control is one of the functions of all the modern shells. In this post, we are using bash.
Start a background job and return to the shell:
The “&” symbol tells the shell to run this “command” in background. The use are return to the shell prompt immediately without waiting for the job to end. If the “&” symbol is not used, the user must wait for the command to end to get the shell prompt.
Another situation is that the user forget to start a long job with a “&” in the end and so the job is running in the foreground. The job can also be changed to the background by two steps:
First, suspend the foreground job:
Ctrl + Z
Second, continue the job in background:
List the background jobs and their status:
The background jobs and their status can be queried by the build-in command jobs
The result is a list of lines. Each line starts with a number. This number can be used to control the jobs.
Bring a job to foreground and background:
Bring a suspended job to background has been introduced before, the format is:
n is the number of the job that can be got from the job command.
Bring a background job the foreground:
Kill a background job:
We can use the format “kill pid” to kill a process. But we can also use the job number to kill the background jobs like this:
n is the job number.