获取UNIX环境中的资源值

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

C, get resource values in UNIX environment

问题

在《UNIX环境高级编程》中,第7.16节中的pr_limits函数中,以下两行代码用于显示资源限制:

lim = limit.rlim_max;
printf("%10lld", lim);

我的问题是,为什么首先将值复制到lim变量,然后再打印出来,而不直接打印呢?

英文:

In "Advanced programming in the UNIX environment", in Figure 7.16, in pr_limits function, the following two lines are written to show resource limit.

lim = limit.rlim_max;
printf("%10lld", lim);

my question is, why the value is first copied to lim variable and then it is printed, and why not directly not printed?

答案1

得分: 2

我的问题是,为什么首先将值复制到lim变量,然后再打印,而不直接打印?

可能正如评论中所指出的,中间存在类型转换的问题。Linux手册页指出:

struct rlimit {
    rlim_t rlim_cur;  /* 软限制 */
    rlim_t rlim_max;  /* 硬限制(rlim_cur的上限) */
};

rlim_t不能保证是特定类型,所以为了可移植性,你可以使用一个中间变量来进行转换(这样你可以安全地使用%10lld格式说明符),或者你可以在调用printf()时使用强制转换以确保正确的格式。无论如何,编译器在优化过程中很可能会消除这种额外的变量使用,所以你很可能不会感到任何效率损失。

这种额外的类型转换确保了代码的可移植性。

英文:

> my question is, why the value is first copied to lim variable and then it is printed, and why not directly not printed?

Probably as you have been pointed to in the comments, there's a conversion issue in the middle. The linux man page states that

struct rlimit {
    rlim_t rlim_cur;  /* Soft limit */
    rlim_t rlim_max;  /* Hard limit (ceiling for rlim_cur) */
};

and rlim_t cannot be warranted to be a specific type, so to be portable, you can either use an intermediate variable to do the conversion (so you can safely use the %10lld format specifier) or you can use a cast in the call to printf() to ensure proper formatting. Anyway, the use of an extra variable will probably be eliminated by the compiler in the optimization process, so you most probably will not sense any efficiency penalty.

This extra type conversion ensures portability of code.

huangapple
  • 本文由 发表于 2023年7月10日 16:41:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76652100.html
匿名

发表评论

匿名网友

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

确定