总是在函数中返回根信息

总是在函数中返回根信息

本文介绍了为什么 getpwnam() 总是在函数中返回根信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简单的程序,它对用户名调用 getpwnam(),将该用户名传递给一个函数,然后再次调用 getpwnam().出于某种原因,我总是在函数内部获取 root 的密码信息.

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?

提前致谢!

推荐答案

http://pubs.opengroup.org/onlinepubs/9699919799/functions/getpwnam.html

特别是读/写的顺序没有保证,所以将getpwnam返回的数据传回getpwnam是不安全的.

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.

你真的不应该使用getpwnam;改用 getpwnam_r.

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

这篇关于为什么 getpwnam() 总是在函数中返回根信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 03:20