Linux Fork and Exec – Understanding the Confusion

debianexecforklinux

As when we do fork on current process, our process as parent process generates child process with same characteristics but different process IDs. So after that, when we do exec() in our child process, process stops execution, and our program which was executing in our stoppped child process, now has his own process.

Isn't that the same as when we run our applications in particular after which every application has his own process and PID?

Best Answer

Yes, because that's how it's done in UNIX.

There is no "run application" system call; it's always done by fork/exec pairs.

Incidentally, exec does not generate a new PID. exec replaces the contents of the process -- the memory is discarded, and a whole new executable is loaded -- but the kernel state remains the same (open files, environment variables, working directory, user, etc.), and the PID remains the same.


Further reading, if you're interested:

  • vfork is like fork except that it must always be paired with exec, and is useful when fork can't work, as in ucLinux.

  • clone is the new fork (today's fork function uses clone behind the scenes) but does a lot more, including creating new processes that share the same memory (rather than duplicate it, like fork) and we call those threads.