英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论