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

February 22, 2008
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 */
};