Skip to content
Advertisement

Why doesn’t Linux prevent spawning infinite number of processes and crashing?

With the very simple code below, my system (Ubuntu Linux 14.04) simply crashes not even letting my mouse respond. I had to force quit with the power button. I thought Linux is a stable OS tolerable of handling such basic program errors. Did I miss something?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>

void check(int isOkay){
  if(!isOkay){
    printf("errorn");
    abort();
  }
}

int main(void){
  #define n 1000000
  int array[n];
  sem_t blocker;
  int i;

  while(1){
    if(!fork()){
      for(i = 0; i < n; ++i){
        array[i] = rand();
      }
      check(sem_init(&blocker, 0, 0) == 0);
      check(sem_wait(&blocker) == 0);
    }
  }
  return 0;
}

Advertisement

Answer

Congratulations, you’ve discovered the fork bomb. There are shell one-liners that can wreak the same sort of havic with a lot less typing on your part.

It is in fact possible to limit the number of processes that a user can spawn using ulimit — see the bottom of the linked wikipedia articles for details.

A desktop install of Ubuntu is not exactly a hardened server, though. It’s designed for usability first and foremost. If you need a locked down system that can’t crash, there are better options.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement