Putting jobs in background

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Multiple commandsHomePipes →
  • Linux supports executing multiple processes in parallel or in series.
  • You always begin your first session (login session) on the Linux system with a single process running bash as shell.
  • Most Linux commands such as editing files, displacing current date & time, logged in users etc can be done with various Linux commands.
  • You type all commands at a shell prompt one by one. These program always take control of your screen and when done you will get back the shell prompt to type a new set of commands.
  • However, sometime you need to carry out tasks in background and use the terminal for other purpose. For example, find all mp3 files stored on a disk while writing a c program.

Job Control

  • The bash shell allows you to run tasks (or commands) in the background using the facility called job control.
  • Job control refers to the ability to selectively stop, suspend the execution of processes and continue (resume) their execution at a later point.
  • A user typically employs this facility via an interactive interface supplied jointly by the system’s terminal driver and bash.

Jobs

  • Processes under the influence of a job control facility are referred to as jobs.
  • Each job has a unique id called job number.
  • You can use the following command to control the job:
    • fg - Place job in the foreground.
    • bg - Place job in the background.
    • jobs - Lists the active jobs on screen.

Background process

  • A command that has been scheduled nonsequentially is called background process.
  • You can not see the background processes on screen. For example, Apache httpd server runs in background to serve web pages. You can put your shell script or any command in background.

Foreground process

  • A command that you can see the command on screen is called the foreground process.

How do I put commands in background?

The syntax is as follows for putting jobs in background:

command &
command arg1 arg2 &
command1 | command2 arg1 &
command1 | command2 arg1 > output &
  • The & operator puts command in the background and free up your terminal.
  • The command which runs in background is called a job.
  • You can type other command while background command is running.

Example

For example, if you type:

find /nas -name "*.mp3" > /tmp/filelist.txt &

Sample outputs:

[1] 1307

The find command is now running in background. When bash starts a job in the background, it prints a line showing a job number ([1]) and a process identification number (PID - 1307). A job sends a message to the terminal upon completion as follows identifying the job by its number and showing that it has completed:

[1]+  Done                    find /share/ -name "*.mp3" > /tmp/filelist
← Multiple commandsHomePipes →