如何在 C 语言中使用 getgrnam() 和 getgrent()
How to use getgrnam() with getgrent() in C
让我们先回顾一下我的代码。
#include <stdio.h>
#include <grp.h>
#include <pwd.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
int main(int argc, char** argv){
struct group *grp;
struct group *tmpGrp;
struct passwd *pw;
int n;
gid_t gid;
pw=getpwnam(argv[1]);
gid=pw->pw_gid;
printf(“%s”,pw->pw_name);
printf(“\n”);
grp = getgrgid(gid);
char *mainGrp = grp->grame;
printf(“out : %s\t”, mainGrp);
while((tmpGrp=getgrgent())!=NULL){
n=0;
printf(“in : %s\t”,mainGrp);
}
printf(“\n”);
return 0;
}
它的输出是这样的:
root
out : root in : root in : other in : bin in : sys ....
如您所见,同时使用 getgrnam() 和 getgrent() 时,组名会更改,即使是在字符串中分配的。
我想要
这样的结果
root
out : root in : root in : root in : root ....
代码例程getgrgent() 就在at assigning into string之后,但为什么会这样呢?以及如何修复它?
测试操作系统:Solaris 10
测试编译器:GCC
来自this (Linux) manual page for getgrent
:
The return value may point to a static area, and may be overwritten by subsequent calls to getgrent()
, getgrgid(3)
, or getgrnam(3)
.
因此即使使用相同的指针也会得到不同的名称,因为这些函数返回的数据是单个静态和共享缓冲区。
the POSIX getgrent
reference specification也暗示了这一点。
如果要mainGrp
不改变,需要复制实际内容。例如。制作 mainGrp
数组并使用 strcpy
.
让我们先回顾一下我的代码。
#include <stdio.h>
#include <grp.h>
#include <pwd.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
int main(int argc, char** argv){
struct group *grp;
struct group *tmpGrp;
struct passwd *pw;
int n;
gid_t gid;
pw=getpwnam(argv[1]);
gid=pw->pw_gid;
printf(“%s”,pw->pw_name);
printf(“\n”);
grp = getgrgid(gid);
char *mainGrp = grp->grame;
printf(“out : %s\t”, mainGrp);
while((tmpGrp=getgrgent())!=NULL){
n=0;
printf(“in : %s\t”,mainGrp);
}
printf(“\n”);
return 0;
}
它的输出是这样的:
root
out : root in : root in : other in : bin in : sys ....
如您所见,同时使用 getgrnam() 和 getgrent() 时,组名会更改,即使是在字符串中分配的。
我想要
这样的结果root
out : root in : root in : root in : root ....
代码例程getgrgent() 就在at assigning into string之后,但为什么会这样呢?以及如何修复它?
测试操作系统:Solaris 10
测试编译器:GCC
来自this (Linux) manual page for getgrent
:
The return value may point to a static area, and may be overwritten by subsequent calls to
getgrent()
,getgrgid(3)
, orgetgrnam(3)
.
因此即使使用相同的指针也会得到不同的名称,因为这些函数返回的数据是单个静态和共享缓冲区。
the POSIX getgrent
reference specification也暗示了这一点。
如果要mainGrp
不改变,需要复制实际内容。例如。制作 mainGrp
数组并使用 strcpy
.