I do not get why Unix has fork() for creating a new process. In Win32 API we have CreateProcess() which creates a new process and loads an executable into its address space, then starts executing from the entry point. However Unix offers fork for creating a new process, and I don’t get why would I duplicate my process if I’d like to run another process.
So let me ask these two questions:
- If
fork()and thenexec()is more efficient, why isn’t there a functionforkexec(const char *newProc)since we will callexec()afterfork()almost in every case? - If it is not more efficient, why does
fork()exist at all?
The
fork()call is sufficient. It is also more flexible; it allows you to things like adjust the I/O redirection in the child process, rather than complicating the system call to create the process. With SUID or SGID programs, it allows the child to lose its elevated privileges before executing the other process.If you want a complex way to create a process, lookup the
posix_spawn()function.The difference is the
posix_spawnp()does a search on PATH for the executable.There is a whole set of other functions for handling
posix_spawn_file_actions_tandposix_spawnattr_ttypes (follow the ‘See Also’ links at the bottom of the referenced man page).This is quite a bit more like
CreateProcess()on Windows. For the most part, though, usingfork()followed shortly byexec()is simpler.Very often, the code you execute is not written by you, so you can’t modify what happens in the beginning of the child’s process. Think of a shell; if the only programs you run from the shell are those you’ve written, life is going to be very impoverished.
Quite often, the code you execute will be called from many different places. In particular, think of a shell and a program that will sometimes be executed in a pipeline and sometimes executed without pipes. The called program cannot tell what I/O redirections and fixups it should do; the calling program knows.
If the calling program is running with elevated privileges (SUID or SGID privileges), it is normal to want to turn those ‘off’ before running another program. Relying on the other program to know what to do is … foolish.