github.com/turingchain2020/turingchain@v1.1.21/common/limits/limits_unix.go (about)

     1  // Copyright Turing Corp. 2018 All Rights Reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Copyright (c) 2013-2014 The btcsuite developers
     6  // Copyright (c) 2015-2016 The Decred developers
     7  // Use of this source code is governed by an ISC
     8  // license that can be found in the LICENSE file.
     9  
    10  // +build !windows,!plan9
    11  
    12  // Package limits 实现设置进程打开文件资源数
    13  package limits
    14  
    15  import (
    16  	"fmt"
    17  	"syscall"
    18  )
    19  
    20  const (
    21  	fileLimitWant = 2048
    22  	fileLimitMin  = 1024
    23  )
    24  
    25  // SetLimits raises some process limits to values which allow dcrd and
    26  // associated utilities to run.
    27  func SetLimits() error {
    28  	var rLimit syscall.Rlimit
    29  
    30  	err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit)
    31  	if err != nil {
    32  		return err
    33  	}
    34  	if rLimit.Cur > fileLimitWant {
    35  		return nil
    36  	}
    37  	if rLimit.Max < fileLimitMin {
    38  		err = fmt.Errorf("need at least %v file descriptors",
    39  			fileLimitMin)
    40  		return err
    41  	}
    42  	if rLimit.Max < fileLimitWant {
    43  		rLimit.Cur = rLimit.Max
    44  	} else {
    45  		rLimit.Cur = fileLimitWant
    46  	}
    47  	err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
    48  	if err != nil {
    49  		// try min value
    50  		rLimit.Cur = fileLimitMin
    51  		err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
    52  		if err != nil {
    53  			return err
    54  		}
    55  	}
    56  
    57  	return nil
    58  }
    59  
    60  //GetLimits 获取limits
    61  func GetLimits() (syscall.Rlimit, error) {
    62  	var rLimit syscall.Rlimit
    63  	err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit)
    64  	if err != nil {
    65  		return syscall.Rlimit{}, err
    66  	}
    67  	return rLimit, nil
    68  }