diff --git a/zk/Foreground_and_background_processes.md b/zk/Foreground_and_background_processes.md new file mode 100644 index 0000000..391274c --- /dev/null +++ b/zk/Foreground_and_background_processes.md @@ -0,0 +1,105 @@ +--- +tags: + - Linux +--- + +## Use `&` to send a process to background + +Here is a dummy [process](./Processes.md): + +```sh +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: + +```sh + +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 `%` or `%