问题
The tutorials, manuals and other resources I read about fork()
usually only contain examples which could be solved much better with threads. They just communicate, do some very basic tasks, and communicate again to share or display the results. I have the feeling that unless your intention is starting a foreign program, (by having the father continuing and the child starting that foreign program), threads are always easier to handle, more flexible, and safer than forks.
Is there any other area of application when a fork()
would be superior to just using threads? Except for a virus, that is.
回答1:
You can use fork()
as a simple way to generate a snapshot from an application without stopping the original application.
Since the OS maps the process's virtual memory as copy on write, you don't really pay any cost except for data that has changed (plus OS overhead).
Edit: Added answers from comments for the sake of later viewers.
One typical example would be a web server (e.g., Apache). If a process crashes, it's easy to restart cleanly -- not so with threads. Using separate processes limits the damage you can get from a single process crashing. – Jerry Coffin
fork()
predates the various thread mechanisms by at least a decade. So, if you need portability to V7 UNIX, fork()
is a much better choice. – Robᵩ
fork()
can be used to daemonize your process while keeping the monitor process alive. – Mark B
来源:https://stackoverflow.com/questions/9949940/usefulness-of-fork-besides-executing-foreign-programs