Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: timing builtins etc.

On Nov 23, 11:16am, Richard Coleman wrote:
} Subject: Re: timing builtins etc.
} In execpline2, there is the comment
} /* if we are doing "foo | bar" where foo is a current *
}  * shell command, do foo in a subshell and do the     *
}  * rest of the pipeline in the current shell.         */
} Does anyone know why this special case was added?

It's not really a special case for pipelines; pipelines always fork
off the left side and then process the rest of the pipeline in the
current shell.  It's a special case for builtins and shell functions
only because they are not normally forked off at all.

You have to fork one side of the pipeline or the other in order to
set up the pipe between the processes.  You could do the builtin in
the current shell and fork a subshell for the right side, but it's
more logical to fork the left side first because it's the producer
on which the right side consumer depends.  Besides, a builtin
or shell function might appear somewhere in the right side, too.

} Because of this, if you try to do something like
} jobs | wc -l
} it doesn't do what people expect.  Since `jobs' runs in a subshell,
} there are no jobs to report, so the above line always returns 0.

Csh has this restriction, too.

You're surely aware that the reason that there are no jobs to report
has nothing to do with the actual process tree.  Any subshell could
print out the jobs list as easily as the parent could.  It's just
that the jobs list gets thrown away when a subshell is entered, so
there's nothing to print.

Zsh does the left side in a subshell because executing in a subshell
sets up all the correct entry and exit conditions (true fork rather
than vfork, etc.), so that e.g. the child won't mess up the "real"
shell's tty and so forth.  Ideally, the notion of being a forked copy
of the current shell would be separate from the notion of being a
lexical subshell, so that entry and exit conditions would be separate
from clearing the job table and other subshell requirements.  This
must be what bash is doing.

} I checked bash and it returns the correct answer.

What does bash do if you put "fg" on the left side of a pipe?  Note
that "jobs" and "fg" have traditionally been the same builtin at the
C code level in zsh, and for "fg" the process tree really does make
a difference.  And what does bash do with

    ( jobs ) | wc -l


Bart Schaefer                     Vice President, Technology, Z-Code Software
schaefer@xxxxxxxxxx                  Division of NCD Software Corporation

Messages sorted by: Reverse Date, Date, Thread, Author