What is the purpose of fork()?

前端 未结 15 1263
悲哀的现实
悲哀的现实 2020-12-12 11:11

In many programs and man pages of Linux, I have seen code using fork(). Why do we need to use fork() and what is its purpose?

15条回答
  •  长情又很酷
    2020-12-12 11:36

    fork() is how Unix create new processes. At the point you called fork(), your process is cloned, and two different processes continue the execution from there. One of them, the child, will have fork() return 0. The other, the parent, will have fork() return the PID (process ID) of the child.

    For example, if you type the following in a shell, the shell program will call fork(), and then execute the command you passed (telnetd, in this case) in the child, while the parent will display the prompt again, as well as a message indicating the PID of the background process.

    $ telnetd &
    

    As for the reason you create new processes, that's how your operating system can do many things at the same time. It's why you can run a program and, while it is running, switch to another window and do something else.

提交回复
热议问题