eolas/zk/Foreground_and_background_processes.md

2 KiB

tags
Linux

Use & to send a process to background

Here is a dummy process:

bash -c 'while sleep 5; do echo "Still running... $(date +%T)"; done'

If I run this normally, it will continue to print every 5 seconds and I can't use the terminal.

If I append & it will run in the background:


bash -c 'while sleep 5; do echo "Still running... $(date +%T)"; done' &
# [1] 13134

It prints the job number ([1]) and the PID of the process.

Now stdout will continue to interrupt every 5 seconds but I can do other things in the foreground, e.g:

 ~ bash -c 'while sleep 5; do echo "Still running... $(date +%T)"; done' &
[2] 13505
➜  ~ Still running... 18:20:42
echo 'i can still use terminal'
i can still use terminal
➜  ~ Still running... 18:20:47
Still running... 18:20:47

Notice now I have two processes running (the same print script, twice), so the job number has incremented to [2]

Bring a background process back to the foreground

Use %<job-number> or %<pid to bring a process back to the foreground:


fg %1
# [1]  - 13134 running    bash -c 'while sleep 5; do echo "Still running... $(date +%T)"; done'
# Still running... 18:23:22
# Still running... 18:23:22
# Still running... 18:23:27

Now it's back in the foreground and I cannot use the terminal:

Still running... 18:24:17
ls
Still running... 18:24:22
Still running... 18:24:22

Pausing a job

Ctrl+Z does not kill the process. It pauses it. This moves it to the background and pauses its execution, returning terminal control back to you.

For example I've stopped vim below:

vim minicom.log
[1]  + 14231 suspended  nvim minicom.log

Again I'm given the job number.

For it to continue in the background:

bg %1

Or the foreground:

fg %1

(This will reopen vim.)

Terminate a job

kill %1

View jobs with jobs

jobs
[1]  + suspended  nvim minicom.log
[2]  - running    bash -c 'while sleep 5; do echo "Still running... $(date +%T)"; done'