How to use fork() in unix? Why not something of the form fork(pointerToFunctionToRun)?

前端 未结 8 2136
盖世英雄少女心
盖世英雄少女心 2021-02-06 05:01

I am having some trouble understanding how to use Unix\'s fork(). I am used to, when in need of parallelization, spawining threads in my application. It\'s always s

8条回答
  •  臣服心动
    2021-02-06 05:30

    History aside, there are some fundamental differences with respect to ownership of resource and life time between processes and threads.

    When you fork, the new process occupies a completely separate memory space. That's a very important distinction from creating a new thread. In multi-threaded applications you have to consider how you access and manipulate shared resources. Processed that have been forked have to explicitly share resources using inter-process means such as shared memory, pipes, remote procedure calls, semaphores, etc.

    Another difference is that fork()'ed children can outlive their parent, where as all threads die when the process terminates.

    In a client-server architecture where very, very long uptime is expected, using fork() rather than creating threads could be a valid strategy to combat memory leaks. Rather than worrying about cleaning up memory leaks in your threads, you just fork off a new child process to process each client request, then kill the child when it's done. The only source of memory leaks would then be the parent process that dispatches events.

    An analogy: You can think of spawning threads as opening tabs inside a single browser window, while forking is like opening separate browser windows.

提交回复
热议问题