Red Hat – Background and Foreground Processes

Here’s another one that I really hadn’t heard of before.  In the command shell, there’s the idea of background and foreground processes. 

The example they used in class involved the sleep command, which is sort of lame, but it works.  So if we tell the console to sleep for 60 seconds we’d do something like this…

[root@CentosBox ~]# sleep 60

Now most of us probably know that we can terminate that process (running the foreground) by issuing a CTRL-C command.  If we do that, we get our normal console prompt back and the process dies.  However, if we issue a CTRL-Z we can pause the process…

[root@CentosBox ~]# sleep 60

[1]+  Stopped                 sleep 60
[root@CentosBox ~]#

Now at this point, I can tell the job to run int the background by issuing a ‘bg’ command.  If there were more than one job running I could specify the number.  So in this case it would be ‘bg 1’…

[root@CentosBox ~]# bg 1
[1]+ sleep 60 &
[root@CentosBox ~]# jobs
[1]+  Running                 sleep 60 &
[root@CentosBox ~]#

Then by entering the ‘jobs’ command, we can see that it’s now running again, but I have my console back.  So if you have a big script running, force it into the background so you can keep doing stuff.  Then just check to see when it’s done.  Better yet, you can just tell the command to run in the background to start with by issuing the ‘&’ after the command.  For instance…

[root@CentosBox ~]# sleep 6000 &
[2] 19080
[1]   Done                    sleep 60
[root@CentosBox ~]# sleep 7000 &
[3] 19081
[root@CentosBox ~]# jobs
[2]-  Running                 sleep 6000 &
[3]+  Running                 sleep 7000 &

You can also, kill the jobs if they are running for too long.  Here I show a couple examples of how to kill jobs…

[root@CentosBox ~]# jobs
[2]-  Running                 sleep 6000 &
[3]+  Running                 sleep 7000 &
[root@CentosBox ~]# jobs
[2]-  Running                 sleep 6000 &
[3]+  Running                 sleep 7000 &
[root@CentosBox ~]# kill %2
[root@CentosBox ~]# jobs
[2]-  Terminated              sleep 6000
[3]+  Running                 sleep 7000 &
[root@CentosBox ~]# jobs -l
[3]+ 19081 Running                 sleep 7000 &
[root@CentosBox ~]# kill 19081
[root@CentosBox ~]# jobs
[3]+  Terminated              sleep 7000
[root@CentosBox ~]#

In the first instance, I used the job number (1) and the ‘kill %’ command.  In the second instance, I found the PID by doing a ‘job -l’ and used that with the kill command.

Pretty powerful stuff if you get acquainted with managing processes effectively. 

Leave a Reply

Your email address will not be published. Required fields are marked *