To find the current GUI user if you are not the one

Your unix process may be running as root or some other user. But, for some weird reason, you need to know the current user logged in (via GUI).
void GetSessionHomeDir(char *home, int len)
{
CFDictionaryRef sessionInfoDict = CGSessionCopyCurrentDictionary();
if (sessionInfoDict == NULL) {
// printf("Unable to get session dictionary.");
return;
}
CFNumberRef userUID = CFDictionaryGetValue(sessionInfoDict, kCGSessionUserIDKey);
int uid;
CFNumberGetValue(userUID, kCFNumberSInt32Type, &uid);
struct passwd *paswd;
paswd = getpwuid(uid);
printf("name:%s uid:%d home:%s\n", paswd->pw_name, paswd->pw_uid, paswd->pw_dir);
strncpy(home, paswd->pw_dir, len);
}
struct passwd definition found in the include file :


struct passwd {
char *pw_name; /* user name */
char *pw_passwd; /* encrypted password */
uid_t pw_uid; /* user uid */
gid_t pw_gid; /* user gid */
time_t pw_change; /* password change time */
char *pw_class; /* user access class */
char *pw_gecos; /* Honeywell login info */
char *pw_dir; /* home directory */
char *pw_shell; /* default shell */
time_t pw_expire; /* account expiration */
int pw_fields; /* internal: fields filled in */
};

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: