Managing linux Shell Jobs

时间:2023-03-08 17:05:01

Managing Shell Jobs  

When moving jobs between the foreground and background, it may be useful to have an overview of all current jobs. To get such an overview, use the  jobs command. As you can see in  Table   9.2   , this command gives an overview of all jobs currently running as a background job, including the job number assigned to the job when starting it in the background. These job numbers can be used as an argument to the  fg  and  bg  commands to perform job management tasks. In  Exercise 9.1 , you learn how to perform common job management tasks from the shell.

Managing linux  Shell Jobs

Managing linux  Shell Jobs

一个很好的练习Jobs管理的实例:

Exercise 9.1 Managing jobs In this exercise, you apply the commands that you just learned about to manage jobs that have been started from the current shell.

1. Open a root shell and type the following commands:

sleep 3600 &
dd if=/dev/zero of=/dev/null &
sleep 7200

2. Because you started the last command with no & after the command, you have to wait 2 hours before you get control to the shell back. Type Ctrl+Z to stop it.

3. Type jobs . You will see the three jobs that you just started. The first two of them have the Running state, and the last job currently is in the Stopped state.

[root@rhel7 ~]# sleep  &
[]
[root@rhel7 ~]# dd if=/dev/zero of=/dev/null &
[]

 [root@rhel7 ~]# sleep 7200
 ^Z
 [3]+ Stopped sleep 7200
 [root@rhel7 ~]# jobs
  [1] Running sleep 3600 &
  [2]- Running dd if=/dev/zero of=/dev/null &
  [3]+ Stopped sleep 7200

4. Type bg 3 to continue running job 3 in the background. Notice that because it was started as the last job, you did not really have to add the number 3.

[root@rhel7 ~]# bg
[]+ sleep &
[root@rhel7 ~]# jobs
[] Running sleep &
[]- Running dd if=/dev/zero of=/dev/null &
[]+ Running sleep &
[root@rhel7 ~]#

5. Type fg 1 to move job 1 to the foreground.

6. Type Ctrl+C to cancel job number 1 and use jobs to confirm that it is now gone.

7. Use the same approach to cancel jobs 2 and 3 also.

[root@rhel7 ~]# fg
sleep
^C
[root@rhel7 ~]# jobs
[]- Running dd if=/dev/zero of=/dev/null &
[]+ Running sleep &
[root@rhel7 ~]# fg
dd if=/dev/zero of=/dev/null
^C590233206+ records in
+ records out
bytes ( GB) copied, 372.251 s, MB/s [root@rhel7 ~]# jobs
[]+ Running sleep &
[root@rhel7 ~]# fg
sleep
^C
[root@rhel7 ~]# jobs
[root@rhel7 ~]#

8. Open a second terminal on your server.

9. From that second terminal, type dd if=/dev/zero of=/dev/null & .

10. Type exit to close the second terminal.

11. From the other terminal, start top . You will see that the dd job is still running. From top, use k to kill the dd job.