fork()的作用除了执行外部程序外 [英] Usefulness of fork() besides executing foreign programs

查看:94
本文介绍了fork()的作用除了执行外部程序外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读的有关fork()的教程,手册和其他资源通常仅包含示例,这些示例可以通过线程更好地解决.他们只是交流,执行一些非常基本的任务,然后再次交流以共享或显示结果.我的感觉是,除非您打算启动一个外部程序(通过父亲继续执行,而孩子启动该外部程序),则线程总是比派生更容易处理,更灵活和更安全.

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.

fork()优于仅使用线程时,是否还有其他应用领域?除了病毒,就是这样.

Is there any other area of application when a fork() would be superior to just using threads? Except for a virus, that is.

推荐答案

您可以使用fork()作为从应用程序生成快照的简单方法,而无需停止原始应用程序.

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).

编辑:为以后的观看者添加了评论中的答案.

Added answers from comments for the sake of later viewers.

一个典型的示例是Web服务器(例如Apache).如果进程崩溃,则很容易干净地重新启动,而线程则不然.使用单独的进程可以限制单个进程崩溃所造成的损害. –杰里·科芬

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()比各种线程机制至少早十年.因此,如果您需要移植到V7 UNIX,fork()是一个更好的选择. –Robᵩ

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()可用于守护进程,同时使监视进程保持活动状态. –马克B

fork() can be used to daemonize your process while keeping the monitor process alive. – Mark B

这篇关于fork()的作用除了执行外部程序外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆