Considering
C++11 §1.10/24 (in [intro.multithread])
” 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();
}
?
(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
is a normal function just like other library functions it invokes glibc fork()
wrapper rather than invoking system call directly.
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.
From man 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).