为什么一个`fork()`调用没有在无限循环中优化? [英] Why is a `fork()` call not optimized away in an infinite loop?

查看:343
本文介绍了为什么一个`fork()`调用没有在无限循环中优化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑


< / strong> 实现可以假设任何线程将最终执行以下操作之一:

- terminate,

- make调用库I / O函数,

- 访问或修改volatile对象,或

- 执行同步操作或原子操作。

[注意:这是为了允许编译器转换,如删除空循环,即使
终止不能被证明。 -end note]

The implementation may assume that any thread will eventually do one of the following:
— terminate,
— make a call to a library I/O function,
— access or modify a volatile object, or
— perform a synchronization operation or an atomic operation.
[Note: This is intended to allow compiler transformations such as removal of empty loops, even when termination cannot be proven. —end note ]

…是编译器允许优化以下循环:

… is the compiler allowed to optimize away the following loop:

int main(int argc, char* argv[]) {
    while ( true )
        fork();
}

(之前有一些讨论(优化while(1);在C ++ 0x 中),但它似乎不回应在循环中 fork 调用的情况。)

(There is some earlier discussion at (Optimizing away a "while(1);" in C++0x), but it does not seem to answer the case of a fork call in the loop.)

推荐答案

fork 是一个正常函数,就像其他库函数一样调用 glibc fork () wrapper而不是直接调用系统调用。

fork is a normal function just like other library functions it invokes glibc fork() wrapper rather than invoking system call directly.

编译器无法确定此函数包含什么,避免优化此循环,这会导致 fork bomb 在某条评论中提及。

A compiler has no way to determine what does this function contain and a conformant compiler should always avoid optimizing this loop away and this would result in fork bomb as referred in one of the comment.

为了避免后果,应该避免用户可以拥有的最大进程数。

To avoid the consequences, one should avoid the maximum number of processes a user can own.

从man fork


从版本2.3.3开始,而不是调用内核的fork()系统调用,glibc fork()包装器作为
NPTL线程实现调用带有标志
的clone(2),提供与传统系统调用相同的效果。 glibc包装器使用pthread_atfork(3)调用已建立
的任何fork处理程序。

Since version 2.3.3, rather than invoking the kernel's fork() system call, the glibc fork() wrapper that is provided as part of the NPTL threading implementation invokes clone(2) with flags that provide the same effect as the traditional system call. The glibc wrapper invokes any fork handlers that have been established using pthread_atfork(3).

这篇关于为什么一个`fork()`调用没有在无限循环中优化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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