Linux command background “&” in plain language

Linux command background “&” in plain language

At the shell prompt, the command can be followed by & to run it in the background.

When heavy processing is executed in the background, it will run by itself in the background and the shell prompt will return immediately.

jobs command

You can see which jobs are running in the background.

If they are not running in the background, the jobs command will return nothing.

[ec2-user@humidai ~]$ jobs
[ec2-user@humidai ~]$

Try running the sleep command in the background, which waits for 50 seconds.

[ec2-user@humidai ~]$ jobs
[ec2-user@humidai ~]$ sleep 50 &
[1] 22586
[ec2-user@humidai ~]$ jobs
[1]+ 実行中 sleep 50 &
[ec2-user@humidai ~]$ jobs
[1]+ 終了 sleep 50
[ec2-user@humidai ~]$ jobs

After running in the background, the jobs command displayed a list of jobs running in the background.

[1] is the job number and 22586 is the process.

Running subshells in the background

Subshells can also be run in the background. Just add & after the ().

[ec2-user@humidai ~]$ (sleep 5; echo 'test') &
[1] 23753
[ec2-user@humidai ~]$ test

[1]+ 終了 ( sleep 5; echo 'test' )
[ec2-user@humidai ~]$

Job Termination

To exit the background job, press Enter.

The SLEEP command, which waits for 3 seconds, is executed in the background.

[ec2-user@humidai ~]$ sleep 3 &
[1] 23942
[ec2-user@humidai ~]$
[ec2-user@humidai ~]$
[1]+ 終了 sleep 3
[ec2-user@humidai ~]$

If you press the Enter key a few times, it will print out that the job is finished if it is finished.

However, pressing the Enter key is tedious. If you want to be notified of the end in real time, use the set command.

If you run the set -o notify(set -b) command and then run it in the background, you will be notified as soon as the job ends on its own.

[ec2-user@humidai ~]$ sleep 3 &
[1] 24693
[ec2-user@humidai ~]$ [1]+ 終了 sleep 3
[ec2-user@humidai ~]$

Difference between a job and a process

There is the idea of jobs and processes in Linux.

A process is a unit of program execution, and a job is like a unit of shell execution.

[ec2-user@humidai ~]$ (sleep 3; echo 'test') &
[1] 355

It is an image of one job with multiple processes.

コメント

タイトルとURLをコピーしました