(trunk libT) possibly reduce the frequency of the "too many open files" errors

This commit is contained in:
Charles Kerr 2009-12-18 07:05:36 +00:00
parent 1457567880
commit a653d37225
1 changed files with 17 additions and 13 deletions

View File

@ -53,8 +53,8 @@
#include <sys/time.h> /* getrlimit */ #include <sys/time.h> /* getrlimit */
#include <sys/resource.h> /* getrlimit */ #include <sys/resource.h> /* getrlimit */
#endif #endif
#include <unistd.h>
#include <fcntl.h> /* O_LARGEFILE posix_fadvise */ #include <fcntl.h> /* O_LARGEFILE posix_fadvise */
#include <unistd.h>
#include <evutil.h> #include <evutil.h>
@ -77,12 +77,6 @@
*** ***
**/ **/
enum
{
NOFILE_BUFFER = 512, /* the process' number of open files is
globalMaxPeers + NOFILE_BUFFER */
};
struct tr_openfile struct tr_openfile
{ {
tr_bool isWritable; tr_bool isWritable;
@ -822,8 +816,16 @@ tr_fdGetFileLimit( const tr_session * session )
return session && session->fdInfo ? session->fdInfo->openFileLimit : -1; return session && session->fdInfo ? session->fdInfo->openFileLimit : -1;
} }
static TR_INLINE int clamp( int val, int lo, int hi )
{
if( val < lo ) val = lo;
if( val > hi ) val = hi;
return val;
}
void void
tr_fdSetPeerLimit( tr_session * session, int limit ) tr_fdSetPeerLimit( tr_session * session, int socketLimit )
{ {
struct tr_fdInfo * gFd; struct tr_fdInfo * gFd;
@ -834,18 +836,20 @@ tr_fdSetPeerLimit( tr_session * session, int limit )
#ifdef HAVE_GETRLIMIT #ifdef HAVE_GETRLIMIT
{ {
struct rlimit rlim; struct rlimit rlim;
const int NOFILE_BUFFER = 512;
const int open_max = sysconf( _SC_OPEN_MAX );
getrlimit( RLIMIT_NOFILE, &rlim ); getrlimit( RLIMIT_NOFILE, &rlim );
rlim.rlim_cur = MIN( rlim.rlim_max, (rlim_t)( limit + NOFILE_BUFFER ) ); rlim.rlim_cur = clamp( open_max, 1024, rlim.rlim_max );
setrlimit( RLIMIT_NOFILE, &rlim ); setrlimit( RLIMIT_NOFILE, &rlim );
gFd->socketLimit = rlim.rlim_cur - NOFILE_BUFFER;
tr_dbg( "setrlimit( RLIMIT_NOFILE, %d )", (int)rlim.rlim_cur ); tr_dbg( "setrlimit( RLIMIT_NOFILE, %d )", (int)rlim.rlim_cur );
gFd->socketLimit = MIN( socketLimit, (int)rlim.rlim_cur - NOFILE_BUFFER );
} }
#else #else
gFd->socketLimit = limit; gFd->socketLimit = socketLimit;
#endif #endif
gFd->publicSocketLimit = limit; gFd->publicSocketLimit = socketLimit;
tr_dbg( "%d usable file descriptors", limit ); tr_dbg( "socket limit is %d", (int)gFd->socketLimit );
} }
int int