tags:

views:

91

answers:

3

Using my c++ program how can I find out what group the current user running my program belongs to? So my program need to figure out a couple of things :

  1. The current username of the user
  2. The group the user belongs to

How can do the above 2 using c++ on a RedHat / Linux machine?

+5  A: 

With getuid(2) and getgid(2). See credentials(7) for more information.

Use getpwuid(3) and getgrgid(3) for the names.

Ignacio Vazquez-Abrams
thanks for your answer... getgid returns the first group id, what happens if the user belongs to multiple groups? How can i find a list of all groups he belongs to?
ace
You'll have to use `getgroups(2)` as given in the other answer.
Ignacio Vazquez-Abrams
Ok i figured it out....getgrnam() will return a structure with a member called gr_mem which is an array of all the usernames in the particular group.Thanks.
ace
+2  A: 

You use getuid(2) and getgid(2) to get the numeric user and group ids, then use getpwuid(3) and getgrgid(3) to look up those ids in the user/group databases and turn them into text names.

Chris Dodd
+2  A: 

You can find some of the information via getgid() (real GID) and getegid() (effective GID). For the other auxilliary groups, you need to use getgroups().

In practice, the real and effective GID are normally the same, but it is the effective GID that is used when creating a file. Usually, the group list returned by getgroups() includes the real group - though it is not clear that it actually has to do so.

Jonathan Leffler