Why is getpwnam() always returning root information in a function?

◇◆丶佛笑我妖孽 提交于 2019-12-08 04:23:55

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/12664456/why-is-getpwnam-always-returning-root-information-in-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!