Skip to content
Advertisement

How to reproduce “Too Many open files” error in Shell

Assume that my open file limit is 1024 per process,

Then how to reproduce Too Many open file error in shell script?

#!/bin/bash
a=0
while [ "$a" -lt 10 ]
do
   echo "Welcome $i times"
 a=`expr $a + 1`
   tail -f /dev/null > myfile$a &
done

I tried above, but it opens 10 files in 10 different processes.

Advertisement

Answer

You can use ulimit -n to set the maximum number of open files to a low number, and then open up more than that number of files using exec (Remember that file descriptors 0, 1 and 2 are already open at startup):

#!/usr/bin/env bash

ulimit -n 5
exec 3</dev/null
exec 4</dev/null
exec 5</dev/null
exec 6</dev/null

Running this produces:

foo.sh: line 6: /dev/null: Too many open files
foo.sh: line 7: /dev/null: Too many open files
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement