I'm not that acquainted to C programming and would like to know how to obtain the internal Unix userid of a user (I'm on HP UX) and stro it in a variable.
I found the getuid() fonction returns the current user's internal ID. But I would like to find it for a different user. I was hoping something like this would work, but it doesn't: UserID = getuid("jsmith").
getuid is a kernel call which returns a number the process already had -- every process has a user. Looking up other users means opening /etc/passwd, which means using a library call like getpname, which searches the name, or getpwent, which loops over the entire /etc/passwd file.
Note that some of the fields in the structure it returns are obsolete -- especially password, which is now stored elsewhere.
Code:
#include <sys/types.h>
#include <pwd.h>
#include <stdio.h>
int main(void) {
const char *user="user";
struct passwd *p=getpname(user);
if(p != NULL)
printf("name %s UID %d GID %d\n", (int)p->pw_name, p->pw_uid, (int)p->pw_gid);
else fprintf(stderr, "No such user '%s'\n", user);
}
Thank you Cororona688. I tried compiling your code snipit but I get errors. My C compiler (ie: I'm running HP-UX) is probably incompatible.
How about this:
- I know the Unix command to obtain a user's internal userid on HP-UX is: id -u <userid> . This command returns an integer representing the internal userid.
- I know the C system() function allows running OS commands.
- I don't know how to run the system() function and save the output in a variable. I wish I could just do this: UserId = system("id -u jsmith");
- Can someone show me the correct C syntax for storing the output of this Unix command into a variable in my C program?
Thanks
"Has errors" is not really a useful thing to say. What errors it had would've been much more helpful. If you'd posted those errors, someone else could tell I'd misspelled some function names -- not to mention some other errors in my code, which was written in a real hurry. Sorry about that, this one actually compiles:
Try this:
Code:
#include <sys/types.h>
#include <pwd.h>
#include <stdio.h>
int main(void) {
const char *user="user";
struct passwd *p=getpwnam(user);
if(p != NULL)
printf("name %s UID %d GID %d\n", user, (int)p->pw_name, p->pw_uid, (int)p->pw_gid);
else fprintf(stderr, "No such user '%s'\n", user);
}
Last edited by Corona688; 03-21-2014 at 04:21 PM..
Coronna688 - Sorry for not posting the errors. This actually works now!
The GID is the value I was looking for.
Thanks a bunch :-)
MadeInGermany - I didn't know how to read Unix environment variables. Now I do. Thanks!
Let me push my luck on that last question I had:
What's a simple way to run a Unix command and save the echoed value in a variable inside my C program ?