I wrote a simple program that calls getpwnam()
on a username, passes that username to a function, and then calls getpwnam()
again. For some reason, I always get the passwd information for root inside the function.
#include <sys/types.h>
#include <pwd.h>
#include <stdio.h>
void printuser(char *username) {
printf("USERNAME2: %s\n", username);
struct passwd *user_info = getpwnam(username);
printf("USERNAME3: %s\n", username);
printf("USERNAME4: %s\n", user_info->pw_name);
}
int main(int argc, char *argv[]) {
struct passwd *user_info = getpwnam(argv[1]);
printf("USERNAME1: %s\n", user_info->pw_name);
printuser(user_info->pw_name);
printf("USERNAME5: %s\n", user_info->pw_name);
}
The program always produces the following output:
$ ./test_getpwnam chenxiaolong
USERNAME1: chenxiaolong
USERNAME2: chenxiaolong
USERNAME3: root
USERNAME4: root
USERNAME5: root
I can't find anything in the man page related to this. Is there something I'm doing wrong?
Thanks in advance!
http://pubs.opengroup.org/onlinepubs/9699919799/functions/getpwnam.html
In particular, there is no guarantee about the ordering of reads/writes, so it is not safe to pass data returned from
getpwnam
back togetpwnam
.You really should not use
getpwnam
at all; usegetpwnam_r
instead.