Golang的Getrlimit函数返回的值与ulimit命令返回的值不同。

huangapple go评论73阅读模式
英文:

Golang Getrlimit returns the different value from ulimit

问题

我尝试使用Golang的Getrlimit函数获取当前的“打开文件描述符”限制。以下是我的代码:

package main

import (
    "fmt"
    "syscall"
)

func main() {
    lim := syscall.Rlimit{}

    err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &lim)
    if err != nil {
        panic(err)
    }
    fmt.Println("soft:", lim.Cur)
    fmt.Println("hard:", lim.Max)
}

运行这段代码会输出:

$ go run main.go
soft: 1048576
hard: 1048576

你可以看到软限制(soft)的值是"1048576",然而,使用ulimit -Sn命令输出的值是"1024"。我还尝试了使用以下C代码:

#include <sys/resource.h>
#include <stdio.h>

int main() {
    struct rlimit rlim;
    if (getrlimit(RLIMIT_NOFILE, &rlim) == -1) {
        return -1;
    }
    printf("soft: %lld \n", (long long) rlim.rlim_cur);
    printf("hard: %lld \n", (long long) rlim.rlim_max);
    return 0;
}

编译并运行这段代码也会输出:

soft: 1024
hard: 1048576

所以,Golang打印出的"rlim_max"(硬限制)的值是正确的,但"rlim_cur"(软限制)的值是不正确的,它应该是"1024"。正如你所看到的,C代码和ulimit -Sn命令都输出了"1024"。

这是我的测试环境:

  • 操作系统:Ubuntu 22.04 LTS x86_64
  • Golang 1.19.1 for amd64

我想知道是否有人遇到了相同的问题,以及为什么会出现这种情况?谢谢!

英文:

I tried to use Golang to get current "open fd" limit with the Getrlimit function, here is my code:

package main

import (
    &quot;fmt&quot;
    &quot;syscall&quot;
)

func main() {
    lim := syscall.Rlimit{}

    err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &amp;lim)
    if err != nil {
        panic(err)
    }
    fmt.Println(&quot;soft:&quot;, lim.Cur)
    fmt.Println(&quot;hard:&quot;, lim.Max)
}

Run this will print:

$ go run main.go
soft: 1048576
hard: 1048576

Here you can see the soft number is "1048576", however, the ulimit -Sn prints it as "1024". I also tried this with C code:

#include &lt;sys/resource.h&gt;
#include &lt;stdio.h&gt;

int main() {
    struct rlimit rlim;
    if (getrlimit(RLIMIT_NOFILE, &amp;rlim) == -1) {
        return -1;
    }
    printf(&quot;soft: %lld \n&quot;, (long long) rlim.rlim_cur);
    printf(&quot;hard: %lld \n&quot;, (long long) rlim.rlim_max);
    return 0;
}

Compile and run it will also print:

soft: 1024
hard: 1048576

So the number Golang printed out for the "rlim_max" (hard) is correct, but "rlim_cur" (soft) is incorrect, it's supposed to be "1024"? As you can see both the C code and ulimit -Sn command printed "1024".

Here is my testing environment:

  • Operating system: Ubuntu 22.04 LTS x86_64
  • Golang 1.19.1 for amd64

I am wondering if anyone experienced the same problem and why it happened like this? Thank you!

答案1

得分: 0

这是根据1.19版本的设计,详细讨论请参考https://github.com/golang/go/issues/46279。

英文:

This is per design since 1.19, see https://github.com/golang/go/issues/46279 for the whole discussion.

huangapple
  • 本文由 发表于 2022年9月8日 04:05:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/73640931.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定