gpt4 book ai didi

c - 如何使用 getpwuid_r() 正确设置缓冲区和 bufsize?

转载 作者:太空狗 更新时间:2023-10-29 11:49:18 26 4
gpt4 key购买 nike

背景信息

我正在尝试获取用户用户名的字符串,唯一提供的有关该用户的信息是他们的 uid 号码。由于先前调用 fstat,我有 uid(并且 uid 存储在 struct stat).

我需要以线程安全的方式获取用户名,因此我尝试使用 getpwuid_r()。根据getpwuid(3) man page :

int getpwuid_r(uid_t uid, struct passwd *pwd, char *buffer,
size_t bufsize, struct passwd **result);

The getpwuid_r() function shall update the passwd structure pointed to by pwd and store a pointer to that structure at the location pointed to by result. The structure shall contain an entry from the user database with a matching uid. Storage referenced by the structure is allocated from the memory provided with the buffer parameter, which is bufsize bytes in size. A call to sysconf(_SC_GETPW_R_SIZE_MAX) returns either −1 without changing errno or an initial value suggested for the size of this buffer. A null pointer shall be returned at the location pointed to by result on error or if the requested entry is not found.

If successful, the getpwuid_r() function shall return zero; otherwise, an error number shall be returned to indicate the error.



问题陈述

阅读下面的手册页示例后,我很困惑为什么他们需要迭代,同时增加缓冲区的大小,直到缓冲区可以容纳其信息。

我假设缓冲区包含 struct passwd pwd - 考虑到这一点,为什么我们不能设置 buffer = (void *) malloc(getsize(struct passwd) )bufsize = sizeof(struct passwd)

long int initlen = sysconf(_SC_GETPW_R_SIZE_MAX);
size_t len;
if (initlen == −1)
/* Default initial length. */
len = 1024;
else
len = (size_t) initlen;
struct passwd result;
struct passwd *resultp;
char *buffer = malloc(len);
if (buffer == NULL)
...handle error...
int e;
while ((e = getpwuid_r(42, &result, buffer, len, &resultp)) == ERANGE)
{
size_t newlen = 2 * len;
if (newlen < len)
...handle error...
len = newlen;
char *newbuffer = realloc(buffer, len);
if (newbuffer == NULL)
...handle error...
buffer = newbuffer;
}
if (e != 0)
...handle error...
free (buffer);

关于此函数如何在 pwd 中设置数据,我有什么不明白的地方吗?可能我没有完全理解我们设置的struct passwd和buffer space有什么关系。

最佳答案

passwd 结构由 standard 定义至少包含这些成员:

char    *pw_name   // User's login name. 
uid_t pw_uid // Numerical user ID.
gid_t pw_gid // Numerical group ID.
char *pw_dir // Initial working directory.
char *pw_shell // Program to use as shell.

注意三个 char * 成员;他们指向位于结构之外的其他地方的存储。许多实现将有两个以上的 char * 成员:pw_passwdpw_gecos

getpwuidgetpwuid_r的区别在于前者可能使用静态缓冲区来存储name、passwd、dir、gecos和shell字符串1 - 以及 passwd 结构本身 - 而后者,因为它是可重入的,需要用户提供一个缓冲区来保存 struct passwd 和另一个缓冲区来保存保存字符串。

在实践中,这两个函数共享很多 common code .

I am confused as to why they need to iterate, while increasing the size of the buffer, until the buffer can hold its information.

如果对 sysconf(_SC_GETPW_R_SIZE_MAX) 的调用失败,您只需要猜测字符串的缓冲区应该有多大,并不断增加其大小直到足够大。

1V7 ,当所有信息都在 /etc/passwd 中时,这个静态缓冲区只是/etc/passwd 相应行的副本,在五个字符串字段的每个末尾插入一个 NUL。

关于c - 如何使用 getpwuid_r() 正确设置缓冲区和 bufsize?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47462890/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com