问题
I have already search anywhere about fork in Unix but i haven't yet understand something. For example when we are in our shell (bash) and we run a command (let's say 'ls') Are we calling fork() system call ? 'ls' is the child and the current shell is the parent?
In the book i read says exactly "A fork is produced when the current running program is copied to make a child, an exact copy of the running program". What is this means ? Exact copy of the bash? When i run ps -ef i can see and understand the PID and the PPID(parent). But why book tells that ? Exact copy isn't the same program (same process of the program)?
And I can understand the exec() system call.... Please somebody help Brothers.... THANK YOU
回答1:
You understand how a single CPU can execute multiple processes, right? It's a short leap from there to imagine that it is possible that two of these processes can be identical i.e. they execute the exact same code, and share the same resources. This is essentially what happens when the fork() system call is called.
The fork() system call was designed to be a primitive that is the first step in spawning more processes from an existing process. The fork() call basically creates a copy of the data structure(s) inside the kernel that represent the current process, and starts its execution. The new process can then overlay itself with the code for an entirely different program (using the exec() system call), and execute that instead.
Any process that needs to create another process, needs to first call fork() to create a copy of itself. The copy then executes some other program. Bash has to do this every time it needs to execute another program like "ls" or "cp" or whatever. It forks(), and then the copy process goes ahead and executes the target program.
来源:https://stackoverflow.com/questions/18760891/please-explain-fork