github.com/palcoin-project/palcd@v1.0.0/limits/limits_unix.go (about)

     1  // Copyright (c) 2013-2014 The btcsuite developers
     2  // Use of this source code is governed by an ISC
     3  // license that can be found in the LICENSE file.
     4  
     5  // +build !windows,!plan9
     6  
     7  package limits
     8  
     9  import (
    10  	"fmt"
    11  	"syscall"
    12  )
    13  
    14  const (
    15  	fileLimitWant = 2048
    16  	fileLimitMin  = 1024
    17  )
    18  
    19  // SetLimits raises some process limits to values which allow btcd and
    20  // associated utilities to run.
    21  func SetLimits() error {
    22  	var rLimit syscall.Rlimit
    23  
    24  	err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit)
    25  	if err != nil {
    26  		return err
    27  	}
    28  	if rLimit.Cur > fileLimitWant {
    29  		return nil
    30  	}
    31  	if rLimit.Max < fileLimitMin {
    32  		err = fmt.Errorf("need at least %v file descriptors",
    33  			fileLimitMin)
    34  		return err
    35  	}
    36  	if rLimit.Max < fileLimitWant {
    37  		rLimit.Cur = rLimit.Max
    38  	} else {
    39  		rLimit.Cur = fileLimitWant
    40  	}
    41  	err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
    42  	if err != nil {
    43  		// try min value
    44  		rLimit.Cur = fileLimitMin
    45  		err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
    46  		if err != nil {
    47  			return err
    48  		}
    49  	}
    50  
    51  	return nil
    52  }