[Mono-dev] Problem handling more the 1024 file handle

Torello Querci tquerci at gmail.com
Fri Nov 4 03:19:27 EDT 2011

Hi al,

trying to handle more that 1024 handle file I got an exception even if
I increase the max number of file limit using "setrlimit". The example
source code below.
Of course mono have the right pcap permission.

Using strace on both this code and no setrlimit version code I have
some differences.
On the no setrlimit version I have this syscall:

open("file1021.out", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = -1
EMFILE (Too many open files)

and this seems to be correct.
On the setrlimit version code I have this syscalls:

open("file1021.out", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 1024
close(1024)                             = 0

so seems that mono close the file because open  return value is 1024.

Is this a bug, a feature, or something else?

using System;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;

namespace TestFiles
	struct rlimit {
		public IntPtr rlimit_cur;
		public IntPtr rlimit_max;

	class MainClass
		public static unsafe void Main (string[] args)
			FileStream[] streams;
			string path;
			if (args.Length == 0) {
				Console.WriteLine ("You need to specify the number of files that
needs to be created.");
			int nFiles = Int32.Parse (args[0]);
			streams = new FileStream[nFiles];

			rlimit data = new rlimit ();
			data.rlimit_cur = (IntPtr) 20000;
			data.rlimit_max = (IntPtr) 20000;

			int result = setrlimit (RLIMIT_NOFILE, &data);
			if (result != 0) {
				throw new Exception ("Cannot change limit on open files");

			for (int i=0; i<nFiles; ++i) {
				path = string.Format ("file{0}.out", i);
				try {
					streams[i] = File.Open(path, FileMode.Create, FileAccess.Write,
				} catch (Exception ex) {
					Console.WriteLine ("Unable to write file {0}", path);
					Console.WriteLine (ex.Message);
					Console.WriteLine (ex.StackTrace);					
		const int RLIMIT_NOFILE = 7;
		[DllImport ("libc", SetLastError = true)]
		unsafe extern static int setrlimit(int resource, rlimit* rlim);

More information about the Mono-devel-list mailing list