What is the purpose of fork()?

前端 未结 15 1226
悲哀的现实
悲哀的现实 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:35

    You probably don't need to use fork in day-to-day programming if you are writing applications.

    Even if you do want your program to start another program to do some task, there are other simpler interfaces which use fork behind the scenes, such as "system" in C and perl.

    For example, if you wanted your application to launch another program such as bc to do some calculation for you, you might use 'system' to run it. System does a 'fork' to create a new process, then an 'exec' to turn that process into bc. Once bc completes, system returns control to your program.

    You can also run other programs asynchronously, but I can't remember how.

    If you are writing servers, shells, viruses or operating systems, you are more likely to want to use fork.

提交回复
热议问题