Linux: Job Control
What is Job Control
Job Control means managing which process runs in foreground, which runs in background.
- Foreground Job → means the process is tied to the shell.
- Background Job → means the process is detached from the shell.
- Job Number → jobs are numbered starting from 1 in the order they are backgrounded or stopped.
Job Control Commands
cmd &
-
Start a program in background. e.g.
python process_log.py &
- Ctrl+c
- Stop the current program tied to the terminal. (sending SIGINT to it)
- Ctrl+z
- Suspend the current program tied to the 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?
Tips:
- 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.
To run a server, you can do: nohup myserver > out.txt 2> err.txt < /dev/null &
.
This will set stdout to out.txt, and stderr to err.txt, and stdin from /dev/null
, and not receive signal SIGHUP signal, and remove this process from jobs table.