๐ Extended Subprocesses and Subshells
Understanding process creation, subshells, and job control is essential for writing efficient shell scripts.
๐งญ Process Creation Basics
When you run a command, the shell:
- Forks โ Creates a copy of itself (child process)
- Execs โ Replaces child's memory with the command
- Waits โ Parent waits for child to complete (unless backgrounded)
1 2 3 4 5 | |
๐งช Subshells
A subshell is a child process that inherits the parent's environment but runs independently.
Creating Subshells
1 2 3 4 5 6 | |
1 2 | |
1 2 | |
๐ง Subshell vs Background Job
| Aspect | Subshell (...) |
Background & |
|---|---|---|
| Runs concurrently | โ | โ |
| Inherits vars | โ | โ |
| Modifies parent | โ | โ |
| Waits for finish | โ (implicit) | โ (must use wait) |
| Can be piped | โ | โ |
๐งช Grouping Commands
Use subshells to group operations:
1 2 3 4 5 6 | |
All output redirected together. Changes inside don't affect parent.
๐ง Background Jobs
Launch tasks in background:
1 2 3 4 5 6 7 8 9 10 | |
List background jobs:
1 2 3 | |
Bring to foreground:
1 | |
Send signal to background job:
1 | |
๐งช Process Substitution (Advanced)
Treat command output as a file:
1 | |
Works like:
1 | |
Also for input:
1 2 3 | |
โ ๏ธ Bash/Zsh feature โ not POSIX.
๐ง Managing Parallel Jobs
Limit concurrent background jobs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
๐งช Daemonizing a Process
Convert script to background daemon:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
๐งพ Portability Notes
| Feature | POSIX | Bash | Zsh |
|---|---|---|---|
Subshells (...) |
โ | โ | โ |
Background & |
โ | โ | โ |
$! (last PID) |
โ | โ | โ |
jobs, fg, bg |
โ | โ | โ |
| Process substitution | โ | โ | โ |
disown |
โ | โ | โ |
๐งพ Summary
- Subshells isolate side effects โ use
(...)for grouping. - Background jobs (
&) enable concurrency โ manage withwait. - Process substitution is powerful but not portable.
- Use double-fork pattern for proper daemonization.
- Limit parallel jobs to avoid resource exhaustion.
๐ Continue to: Pipelines and Process Substitution