please Explain fork()

大兔子大兔子 提交于 2019-12-25 18:18:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!