How to increase the limit of “maximum open files” in C on Mac OS X

后端 未结 6 2052
刺人心
刺人心 2020-12-15 13:04

The default limit for the max open files on Mac OS X is 256 (ulimit -n) and my application needs about 400 file handlers.

I tried to change the limit with setrlimit(

6条回答
  •  既然无缘
    2020-12-15 13:45

    For some reason (perhaps binary compatibility), you have to define _DARWIN_UNLIMITED_STREAMS before including :

    #define _DARWIN_UNLIMITED_STREAMS
    
    #include 
    #include 
    
    main()
    {
      struct rlimit rlp;
    
      FILE *fp[10000];
      int i;
    
      getrlimit(RLIMIT_NOFILE, &rlp);
      printf("before %d %d\n", rlp.rlim_cur, rlp.rlim_max);
    
      rlp.rlim_cur = 10000;
      setrlimit(RLIMIT_NOFILE, &rlp);
    
      getrlimit(RLIMIT_NOFILE, &rlp);
      printf("after %d %d\n", rlp.rlim_cur, rlp.rlim_max);
    
      for(i=0;i<10000;i++) {
        fp[i] = fopen("a.out", "r");
        if(fp[i]==0) { printf("failed after %d\n", i); break; }
      }
    
    }
    

    prints

    before 256 -1
    after 10000 -1
    failed after 9997
    

    This feature appears to have been introduced in Mac OS X 10.6.

提交回复
热议问题