- Job Control
- A Practical Example
- Putting a Program into the Background
- Listing Running Processes
- Killing a Process
- A Little More About kill
- That’s It!
- Further Reading
- Job Control in Linux
- What are jobs ?
- Unique identifiers for a job
- Managing jobs in Linux
- List the running jobs
- Bring a job to the foreground
- Suspend the job
- Send a job to the background
- List only running jobs
- List only suspended jobs
- List process IDs of the jobs
- Terminate a job
- Linux: Job Control
- Example of Using Job Control
- Closing Terminal Kills My Program?
- Understanding the job control commands in Linux – bg, fg and CTRL+Z
- Whats a job in Linux
- Job Control Commands
- Running a Job in the Background
- Managing the background jobs
- 10 Linux/Unix Bash and KSH Shell Job Control Examples
- What is a job control?
- Who provides a facility to control jobs?
- Say hello to job table
- #1: Creating your first Linux/Unix job
- #2: List the current jobs
- #3: Stop or suspend running jobs
- #4: Resume suspended/stopped job in the foreground
- #5: Resume suspended/stopped job in the background
- Restart a stopped background yum process with bg
- #6: Kill a job / process
- #7 Why does shell kill off all my background jobs when I logout?
- #8 Prevent job from being killed on logout using an external command called nohup
- #9: Finding the PID of last job
- #10: Wait for job completion
Job Control
In the previous lesson, we looked at some of the implications of Linux being a multi-user operating system. In this lesson, we will examine the multitasking nature of Linux, and how it is controlled with the command line interface.
As with any multitasking operating system, Linux executes multiple, simultaneous processes. Well, they appear simultaneous, anyway. Actually, a single processor core can only execute one process at a time but the Linux kernel manages to give each process its turn at the processor and each appears to be running at the same time.
There are several commands that are used to control processes. They are:
- ps — list the processes running on the system
- kill — send a signal to one or more processes (usually to «kill» a process)
- jobs — an alternate way of listing your own processes
- bg — put a process in the background
- fg — put a process in the foreground
A Practical Example
While it may seem that this subject is rather obscure, it can be very practical for the average user who mostly works with the graphical user interface. Though it might not be apparent, most (if not all) graphical programs can be launched from the command line. Here’s an example: there is a small program supplied with the X Window system called xload which displays a graph representing system load. We can execute this program by typing the following:
Notice that the small xload window appears and begins to display the system load graph. On systems where xload is not available, try gedit instead. Notice also that our prompt did not reappear after the program launched. The shell is waiting for the program to finish before control returns. If we close the xload window, the xload program terminates and the prompt returns.
Putting a Program into the Background
Now, in order to make life a little easier, we are going to launch the xload program again, but this time we will put it in the background so that the prompt will return. To do this, we execute xload like this:
In this case, the prompt returned because the process was put in the background.
Now imagine that we forgot to use the «&» symbol to put the program into the background. There is still hope. We can type Ctrl-z and the process will be suspended. We can verify this by seeing that the program’s window is frozen. The process still exists, but is idle. To resume the process in the background, type the bg command (short for background). Here is an example:
Listing Running Processes
Now that we have a process in the background, it would be helpful to display a list of the processes we have launched. To do this, we can use either the jobs command or the more powerful ps command.
Killing a Process
Suppose that we have a program that becomes unresponsive; how do we get rid of it? We use the kill command, of course. Let’s try this out on xload . First, we need to identify the process we want to kill. We can use either jobs or ps , to do this. If we use jobs we will get back a job number. With ps , we are given a process id (PID). We will do it both ways:
A Little More About kill
While the kill command is used to «kill» processes, its real purpose is to send signals to processes. Most of the time the signal is intended to tell the process to go away, but there is more to it than that. Programs (if they are properly written) listen for signals from the operating system and respond to them, most often to allow some graceful method of terminating. For example, a text editor might listen for any signal that indicates that the user is logging off, or that the computer is shutting down. When it receives this signal, it could save the work in progress before it exits. The kill command can send a variety of signals to processes. Typing:
will print a list of the signals it supports. Many are rather obscure, but several are handy to know:
Signal # | Name | Description |
1 | SIGHUP | Hang up signal. Programs can listen for this signal and act upon it. This signal is sent to processes running in a terminal when you close the terminal. |
2 | SIGINT | Interrupt signal. This signal is given to processes to interrupt them. Programs can process this signal and act upon it. We can also issue this signal directly by typing Ctrl-c in the terminal window where the program is running. |
15 | SIGTERM | Termination signal. This signal is given to processes to terminate them. Again, programs can process this signal and act upon it. This is the default signal sent by the kill command if no signal is specified. |
9 | SIGKILL | Kill signal. This signal causes the immediate termination of the process by the Linux kernel. Programs cannot listen for this signal. |
Now let’s suppose that we have a program that is hopelessly hung and we want to get rid of it. Here’s what we do:
- Use the ps command to get the process id (PID) of the process we want to terminate.
- Issue a kill command for that PID.
- If the process refuses to terminate (i.e., it is ignoring the signal), send increasingly harsh signals until it does terminate.
In the example above we used the ps command with the x option to list all of our processes (even those not launched from the current terminal). In addition, we piped the output of the ps command into grep to list only list the program we are interested in. Next, we used kill to issue a SIGTERM signal to the troublesome program. In actual practice, it is more common to do it in the following way since the default signal sent by kill is SIGTERM and kill can also use the signal number instead of the signal name:
Then, if the process does not terminate, force it with the SIGKILL signal:
That’s It!
This concludes the «Learning the Shell» series of lessons. In the next series, «Writing Shell Scripts,» we will look at how to automate tasks with the shell.
Further Reading
- For a more in-depth treatment of the topic, see Chapter 10 in The Linux Command Line.
- 1963 Timesharing: A Solution to Computer Bottlenecks, a fascinating YouTube video from the Computer History Museum describing the first timesharing operating system and how it works. It’s basically the same method used by all modern computers.
© 2000-2021, William E. Shotts, Jr. Verbatim copying and distribution of this entire article is permitted in any medium, provided this copyright notice is preserved.
Linux® is a registered trademark of Linus Torvalds.
Источник
Job Control in Linux
This is a short tutorial on job control in Linux and Unix.
What are jobs ?
In Linux or Unix, a job is defined as a task or command that has started running but not yet finished what it is doing.
As Linux and Unix are multitasking operating systems, they allow you to run multiple commands simultaneously.
Each running command is called a job, and is assigned a unique id called the job number.
It is very easy to manage jobs in Linux.
The main commands you use for job control in Linux are as follows.
- jobs — List all the jobs that are running or suspended.
- fg — Bring the job to the foreground.
- bg — Send the job to the background.
- stop or Ctrl + z — Suspend the job.
- kill or Ctrl + c — Terminate the job.
Unique identifiers for a job
You can point out a particular job using special identifiers. They are as follows.
%n — Job whose job number / job ID is the number n.
%word — Job whose command line starts with string word.
%?word — Job whose command line contains the string word.
%+ — Current job. You can also use %% .
Managing jobs in Linux
How to manage jobs in Linux can be easily understood via an example.
Lets simultaneously run a few commands that takes some time to complete.
Here we have executed 4 sleep commands and all are started in the background as denoted by & .
List the running jobs
And the output is .
In the output above, the number within [ and ] is the job number (job ID). The job number is unique for each job.
Bring a job to the foreground
To bring job number 2 to the foreground, you run the following command.
Suspend the job
To suspend a job, you first bring the job to the foreground and then press the keys Ctrl + z .
Alternately, you can also suspend a job running in the background as follows.
Send a job to the background
To resume the suspended job 2 in the background, you can run the following command.
List only running jobs
List only suspended jobs
List process IDs of the jobs
This command will list process IDs of the jobs in addition to the normal information.
Terminate a job
To terminate a job, you first bring the running job to the foreground, and then press the keys Ctrl + c .
You can also terminate a job without bringing it in the foreground just by passing the job number to kill .
For example, to kill the 3rd job, you can do as follows.
Источник
Linux: Job Control
This is a tutorial on unix “job control”.
The following are part of bash, not separate utils, so there’s no man page for them. They are documented in man bash . [see Linux: Bash Manual in Chapters, Using Emacs for Info]
cmd & Start a program in background. For example, ruby process_log.rb & Ctrl + c Stop the current program associated with your terminal. (sending SIGINT to it) Ctrl + z Suspend the current program associated with your terminal. (sending SIGTSTP to it) jobs List background processes bg % number Run the suspended command in background. fg % number Resume a background process to foreground. disown % number Separate a job ID number from jobs table.
unix process signal is a integer send to programs to tell it something. To see a list of all signals, type man kill .
Example of Using Job Control
Here’s a common scenario of using job control:
- Start xlock with a second hand by xclock -update 1 , it’ll hog the terminal.
- Now, in terminal, press Ctrl + z to pause the program and returns you the prompt. (when the program is paused, it can’t be used. You’ll see that the second-hand stopped moving.)
- Type jobs to list all jobs and their ID in job table. Here’s a sample output: [1]+ Stopped xclock -update 1
- Type bg %1 to start the process with job ID 1 in background.
- Now, it is as if you started xclock by xclock & .
the “xlock” example above can be any shell command.
Here’s some other commands that are very useful. Note, many GUI apps these days will detach itself from terminal, even if you didn’t start it with & .
setsid command Run a program in a new session. nohup command Run a command immune to SIGHUP signal , and redirect stdout to a normal file.
Closing Terminal Kills My Program?
- Don’t close your terminal by clicking the window close. Close it by Ctrl + d . Because, when you click on close, it may kill all programs you launched from it.
- if you do emacs & , then close your GUI terminal (by clicking on the close button), it’ll also take down your emacs.
- You can use setsid emacs to launch program. It runs the program in its own session.
Источник
Understanding the job control commands in Linux – bg, fg and CTRL+Z
Whats a job in Linux
A job is a process that the shell manages. Each job is assigned a sequential job ID. Because a job is a process, each job has an associated PID. There are three types of job statuses:
1. Foreground: When you enter a command in a terminal window, the command occupies that terminal window until it completes. This is a foreground job.
2. Background: When you enter an ampersand (&) symbol at the end of a command line, the command runs without occupying the terminal window. The shell prompt is displayed immediately after you press Return. This is an example of a background job.
3. Stopped: If you press Control + Z for a foreground job, or enter the stop command for a background job, the job stops. This job is called a stopped job.
Job Control Commands
Job control commands enable you to place jobs in the foreground or background, and to start or stop jobs. The table describes the job control commands.
Option | Description |
---|---|
jobs | Lists all jobs |
bg %n | Places the current or specified job in the background, where n is the job ID |
fg %n | Brings the current or specified job into the foreground, where n is the job ID |
Control-Z | Stops the foreground job and places it in the background as a stopped job |
Running a Job in the Background
To run a job in the background, you need to enter the command that you want to run, followed by an ampersand (&) symbol at the end of the command line. For example, run the sleep command in the background.
The shell returns the job ID, in brackets, that it assigns to the command and the associated PID. With the job ID, you can use the job control commands to manage the job whereas the kernel uses PIDs to manage jobs.
When a background job is complete and you press Return, the shell displays a message indicating the job is done.
Managing the background jobs
You can use the jobs command to list the jobs that are currently running or suspended in the background.
You can use the fg command to bring a background job to the foreground.
You can use the ‘Control+Z keys and bg command to return a job to the background. The Control+Z keys suspend the job, and place it in the background as a stopped job. The bg command runs the job in the background. For example:
1. Using CTRL+Z
Источник
10 Linux/Unix Bash and KSH Shell Job Control Examples
What is a job control?
Job control is nothing but the ability to stop/suspend the execution of processes (commands) and continue/resume their execution as per your requirements. This is done using your operating system and shell such as bash/ksh or POSIX shell.
Who provides a facility to control jobs?
The Bash / Korn shell, or POSIX shell provides a facility to control jobs.
Say hello to job table
Your shell keeps a table of current jobs, called job table. When you type command the shell assigns a jobID (also known as JOB_SPEC). A jobID or JOB_SPEC is nothing but small integer numbers.
#1: Creating your first Linux/Unix job
I am going to run a command called xeyes that displays two googly eyes on screen, enter:
$ xeyes &
Sample outputs:
Fig.01: Running the xeyes command in the background
In this example, two numbers are output as follows
- [1] : The xeyes job, which was started in the background, was job number 1.
- 6891 : A process ID of job number 1.
I am going to start a few more jobs:
#2: List the current jobs
A brief description of each field is given below:
Field | Value | Description | Example(s) |
---|---|---|---|
1 | [1] | jobID or JOB_SPEC – Job number to use with the fg, bg, wait, kill and other shell commands. You must prefix the job number with a percent sign ( % ). A plus sign ( + ) identifies the default or current job. A minus sign ( — ) identifies the previous job. | %1 fg %1 kill %2 |
2 | 9379 | Process ID – An identification unique number that is automatically assigned to each process when it is created on the system. | kill 9379 |
3 | Running | state – The state of job: Running – The job is currently running and has not been suspended by a signal. Stopped – The job was suspended. | N/A |
4 | xeyes & | command – The command that was given to the shell. | script &firefox url& |
You can also use ps command to list the processes running on the system:
$ ps
#3: Stop or suspend running jobs
Hit the [Ctrl]-[Z] key or use kill command as follows:
In this example, start ping command and use the Ctrl-Z key sequence to stop the ping command job:
Animated gif 01: Suspending ping command job
#4: Resume suspended/stopped job in the foreground
Let us resume or bring stopped ping job to the foreground and make it the current job with the help of fg command. The syntax is as follows:
I can also state any job whose command line begins with the string “ping”:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
#5: Resume suspended/stopped job in the background
In this example, I am going to update all installed packages on Red Hat or CentOS Linux production server using yum command background job:
# yum -y update &>/root/patch.log &
However, due to some reason (say load issue) I decided to stop this job for 20 minutes:
# kill -s stop %yum
Sample outputs:
Restart a stopped background yum process with bg
#6: Kill a job / process
To stop/kill a yum command process, enter the following kill command whose jobID was 7:
# kill %7
OR
# kill pid
Sample outputs:
#7 Why does shell kill off all my background jobs when I logout?
In this example, I am going to start pdfwriter.py job to generate pdf files for this site in bulk:
As soon as I logout from shell, pdfwriter.py job will be killed by my shell. To overcome this problem use disown shell builting command to tell the shell not to send a HUP signal, type:
$
/scripts/www/pdfwriter.py —profile=faq . &
$ disown
$ exit
#8 Prevent job from being killed on logout using an external command called nohup
/scripts/www/pdfwriter.py —profile=faq . &
$ exit
#9: Finding the PID of last job
To find the the process ID of the most recently executed background (asynchronous) command, use bash shell special parameter $!
$ gedit foo.txt &
$ echo «PID of most recently executed background job — $!»
Sample outputs:
#10: Wait for job completion
The wait command waits for given process ID or jobID (job specification) , and reports its termination status. The syntax is as follows:
Источник