#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("%s %s\n", getpwnam("steve")->pw_name, getpwnam("root")->pw_name);
printf("%d %d\n", getpwnam("steve")->pw_uid, getpwnam("root")->pw_uid);
return EXIT_SUCCESS;
}
$ gcc main.c && ./a.out
steve steve
1000 0
在 8
行中,我们尝试打印用户名 steve 和 root,但它打印了两次 steve
。在 9
行,我们尝试打印 steve 和 root 的 UID,它成功打印了它们。
我想确定 8
行中那个奇怪行为的根本原因。
我知道getpwnam
返回的指针指向静态分配的内存,pw_name/pw_passwd/pw_gecos/pw_dir/pw_shell
等字段指向的内存也是静态的,这意味着这些值可以被后续调用覆盖。但对这个奇怪的结果还是一头雾水。
This is exercise 8-1 of The Linux Programming Interface. Add this so that someone like me could find this through the search engine in the future:). And the question in the book is wrong, go here to see the revised version.
最佳答案
代码连续调用 getpwnam()
返回一个指向同一地址的指针,并将同一指针传递给 printf()
两次。编译器决定进行调用的顺序将决定它是显示“steve”还是“root”。
通过调用 getpwnam_r()
分配两个缓冲区空间并在对 printf()
的调用中分别使用一个缓冲区空间相反。
关于c - getpwnam 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73452740/