Wednesday, August 22, 2018

Background processes and Job control

In a Bash shell, when we enter any command or start any program, it starts running in foreground. In such a situation, we cannot run more than one command in the foreground. We need to create many terminal windows for starting many processes. If we need to start many processes or programs from the same terminal, then we will need to start them as background processes.

If we want to start a process in the background, then we need to append the command in the Bash shell by &.

Example: to start program Hello as the background process
Hello &

 Sleep: This process sleeps for the duration, which is mentioned in the integer value next to
the sleep command
Ex: sleep 10000
sleep for 10000 seconds
Now, you can press the Ctrl + C key combination to terminate the process created by the sleep command.

Now, use the following command: sleep 10000 &

 This time, it will start running in the background.Therefore, we will be able to enter the next command in the Bash terminal

Since the newly created process is running in the background, we can enter new commands very easily in the newly created terminal:
$ sleep 20000 &
$ sleep 30000 &
$ sleep 40000 &

To check the presence of all the processes, enter the following command:
$ jobs

The jobs command lists all the processes running in terminal, including foreground and background processes. You can clearly see their status as running, suspended, or stopped. The numbers in [] show the job ID.
The + sign indicates which command will receive fg and bg commands by default.

To make any existing background process to run in the foreground,
fg 3
The preceding command will make the job number 3 to run in the foreground instead of the background.

If we want to make the process to stop executing and get it suspended, then press Ctrl + Z. This key combination makes the foreground process to stop executing. Please note that the process has stopped but not terminated
To make the stopped process continue running in background, use the following command:
$ bg job_number
$ bg 3

If you wish to terminate the process, you can use the job ID or process ID as follows:
$ jobs –l // This will list jobs with pid
$ kill pid or
$ kill %job_id // This will kill job
$ kill %3


No comments:

Post a Comment