What are the differences between fork
and exec
?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
The use of
fork
andexec
exemplifies the spirit of UNIX in that it provides a very simple way to start new processes.The
fork
call basically makes a duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations but the idea is to create as close a copy as possible).The new process (child) gets a different process ID (PID) and has the PID of the old process (parent) as its parent PID (PPID). Because the two processes are now running exactly the same code, they can tell which is which by the return code of
fork
- the child gets 0, the parent gets the PID of the child. This is all, of course, assuming thefork
call works - if not, no child is created and the parent gets an error code.The
exec
call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point.So,
fork
andexec
are often used in sequence to get a new program running as a child of a current process. Shells typically do this whenever you try to run a program likefind
- the shell forks, then the child loads thefind
program into memory, setting up all command line arguments, standard I/O and so forth.But they're not required to be used together. It's perfectly acceptable for a program to
fork
itself withoutexec
ing if, for example, the program contains both parent and child code (you need to be careful what you do, each implementation may have restrictions). This was used quite a lot (and still is) for daemons which simply listen on a TCP port andfork
a copy of themselves to process a specific request while the parent goes back to listening.Similarly, programs that know they're finished and just want to run another program don't need to
fork
,exec
and thenwait
for the child. They can just load the child directly into their process space.Some UNIX implementations have an optimized
fork
which uses what they call copy-on-write. This is a trick to delay the copying of the process space infork
until the program attempts to change something in that space. This is useful for those programs using onlyfork
and notexec
in that they don't have to copy an entire process space.If the
exec
is called followingfork
(and this is what happens mostly), that causes a write to the process space and it is then copied for the child process.Note that there is a whole family of
exec
calls (execl
,execle
,execve
and so on) butexec
in context here means any of them.The following diagram illustrates the typical
fork/exec
operation where thebash
shell is used to list a directory with thels
command:I think some concepts from "Advanced Unix Programming" by Marc Rochkind were helpful in understanding the different roles of
fork()
/exec()
, especially for someone used to the WindowsCreateProcess()
model:.
.
Once you understand the distinction between a program and a process, the behavior of
fork()
andexec()
function can be summarized as:fork()
creates a duplicate of the current processexec()
replaces the program in the current process with another program(this is essentially a simplified 'for dummies' version of paxdiablo's much more detailed answer)
fork()
:It creates a copy of running process. The running process is called parent process & newly created process is called child process. The way to differentiate the two is by looking at the returned value:
fork()
returns the process identifier (pid) of the child process in the parentfork()
returns 0 in the child.exec()
:It initiates a new process within a process. It loads a new program into the current process, replacing the existing one.
fork()
+exec()
:When launching a new program is to firstly
fork()
, creating a new process, and thenexec()
(i.e. load into memory and execute) the program binary it is supposed to run.fork()
splits the current process into two processes. Or in other words, your nice linear easy to think of program suddenly becomes two separate programs running one piece of code:This can kind of blow your mind. Now you have one piece of code with pretty much identical state being executed by two processes. The child process inherits all the code and memory of the process that just created it, including starting from where the
fork()
call just left off. The only difference is thefork()
return code to tell you if you are the parent or the child. If you are the parent, the return value is the id of the child.exec
is a bit easier to grasp, you just tellexec
to execute a process using the target executable and you don't have two processes running the same code or inheriting the same state. Like @Steve Hawkins says,exec
can be used after youfork
to execute in the current process the target executable.fork() creates a copy of the current process, with execution in the new child starting from just after the fork() call. After the fork(), they're identical, except for the return value of the fork() function. (RTFM for more details.) The two processes can then diverge still further, with one unable to interfere with the other, except possibly through any shared file handles.
exec() replaces the current process with a new one. It has nothing to do with fork(), except that an exec() often follows fork() when what's wanted is to launch a different child process, rather than replace the current one.
The prime example to understand the
fork()
andexec()
concept is the shell,the command interpreter program that users typically executes after logging into the system.The shell interprets the first word of command line as a command nameFor many commands,the shell forks and the child process execs the command associated with the name treating the remaining words on the command line as parameters to the command.
The shell allows three types of commands. First, a command can be an executable file that contains object code produced by compilation of source code (a C program for example). Second, a command can be an executable file that contains a sequence of shell command lines. Finally, a command can be an internal shell command.(instead of an executable file ex->cd,ls etc.)