[英]Safe way to use the result of getpwnam()/getpwuid()?
I'm working on Linux and FreeBSD. 我正在Linux和FreeBSD上工作。 When I use
getpwnam()
or getpwuid()
, I get a pointer to a passwd
struct. 当我使用
getpwnam()
或getpwuid()
,我得到了一个指向passwd
结构的指针。 What's the safe way to use the char*
members of that passwd
struct? 使用该
passwd
结构的char*
成员的安全方法是什么?
The man page says this struct is a static object but will be overwritten by subsequent calls, so I guess the safe way is to use strdup()
to get a copy of the char*
members and then no longer uses the passwd
struct. 手册页中说此结构是一个静态对象,但以后的调用会覆盖它,因此我猜比较安全的方法是使用
strdup()
获取char*
成员的副本,然后不再使用passwd
结构。
Is my understanding correct? 我的理解正确吗?
The safest way is not to use them at all, but instead use getpwnam_r
and getpwuid_r
, which store the results in a caller-provided buffer. 最安全的方法是根本不使用它们,而是使用
getpwnam_r
和getpwuid_r
,它们将结果存储在调用者提供的缓冲区中。 This not only avoids the issue you're asking about, but also makes your code safe for use in a multi-threaded process. 这不仅避免了您要问的问题,而且还使您的代码可以安全地在多线程进程中使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.