diff options
| author | Sean Kurtz <seankurtz75@gmail.com> | 2026-11-19 17:37:25 -0600 |
|---|---|---|
| committer | Sean Kurtz <seankurtz75@gmail.com> | 2026-11-19 17:37:25 -0600 |
| commit | f5f5683fc23876e66bdf31ba72ce6df3d430fc1b (patch) | |
| tree | 5dbf20af2cb8f74a3d61c2fc8dfe4653a0b6f904 /src/exec.c | |
| parent | b0c99064d0a3eb344fd07a6220f3fd4422bfab7f (diff) | |
| download | zash-f5f5683fc23876e66bdf31ba72ce6df3d430fc1b.tar.gz | |
exec: run a subshell in process when its body cannot change anything
A `fork()` copies the address space on z/OS, where a `spawn()` can share
it. The subshell row measured 4.7 ms a turn there against 0.3 ms for an
external command, and ksh88 does not fork for `( : )` at all.
The pipeline stage check already answered the safety question with
is_pure(), so a subshell whose body is one output-only builtin with no
redirections and no assignments reuses the answer and runs in the shell.
Expansion of the arguments is wrapped in the same capture scope a
pipeline stage uses, so ${x=1} no longer escapes.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'src/exec.c')
| -rw-r--r-- | src/exec.c | 35 |
1 files changed, 35 insertions, 0 deletions
@@ -1215,6 +1215,26 @@ static int run_pure(simple_cmd *sc, output *o) { return status; } +/** + * @brief Can a subshell run without a process of its own? + * + * Its body has to be one command whose name is written literally, that + * name has to be a builtin which only writes output, and neither the + * subshell nor the command may redirect or assign. Then nothing the + * parent can see can change. A `fork()` copies the address space on + * z/OS, 4.7 ms against 0.3 ms for a `spawn()`, and ksh88 does not pay it + * for `( : )` either. + */ +static bool subshell_in_process(const node *n) { + const node *b = n->u.body; + if (n->redirs || !b || b->kind != N_SIMPLE || b->redirs || + b->u.simple.assigns || !b->u.simple.args || !b->u.simple.args->plain) + return false; + cmdinfo ci; + find_command(b->u.simple.args->plain, &ci, 0); + return ci.kind == C_BUILTIN && (ci.bi->flags & BI_PURE); +} + /* ---- pipelines ------------------------------------------------------- */ /** @@ -1805,6 +1825,21 @@ static int eval_case(node *n, unsigned flags) { */ static int eval_subshell(node *n, unsigned flags) { if (!(flags & EV_EXIT) || trap_has_exit()) { + if (!job_launching && !opt.errexit && subshell_in_process(n)) { + simple_cmd sc; + varscope vs; + /* Expansion may assign (${x=1}), so undo it on the way out. */ + scope_push(&vs, true, false); + bool ok = guarded_prep(n->u.body, &sc); + if (ok && is_pure(&sc)) { + int status = run_pure(&sc, &out1); + scope_pop(); + return status; + } + scope_pop(); + if (!ok) + return exitstatus; + } job *jb = jc_active() && !job_launching ? job_begin(n, true) : NULL; pid_t pid = fork_shell(); if (pid) { |
