I'm learning about fork()
and exec()
commands. It seems like fork()
and exec()
are usually called together. (fork()
creates a new child process, and exec()
replaces the current process image with a new one.) However, in what scenarios might you call each function on its own? Are there scenarios like these?
System Calls Fork and Exec – When to Use Them
execforksystem-calls
Best Answer
Sure! A common pattern in "wrapper" programs is to do various things and then replace itself with some other program with only an
exec
call (no fork)A real-life example of this is
GIT_SSH
(thoughgit(1)
does also offerGIT_SSH_COMMAND
if you do not want to do the above wrapper program method).Fork-only is used when spawning a bunch of typically worker processes (e.g. Apache
httpd
in fork mode (though fork-only better suits processes that need to burn up the CPU and not those that twiddle their thumbs waiting for network I/O to happen)) or for privilege separation used bysshd
and other programs on OpenBSD (no exec)The
root
sshd has on client connect forked off a copy of itself (28571) and then another copy (14625) for the privilege separation.