Why is getpwnam() always returning root informatio

2019-06-07 01:09发布

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!

标签: c root getpwnam
1条回答
不美不萌又怎样
2楼-- · 2019-06-07 01:43

The return value may point to a static area which is overwritten by a subsequent call to getpwent(), getpwnam(), or getpwuid().

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 to getpwnam.

You really should not use getpwnam at all; use getpwnam_r instead.

查看更多
登录 后发表回答