Archive for the ‘Code’ Category

Determining if an app is running in 64-bit mode

Wednesday, February 6th, 2008

OK, time for more geek-talk. I’ve spent a couple of late nights fussing with fat binaries, bundles, and mach-o architecture API’s to try and find a way to determine if an app is running in 64 bit mode. Surprisingly, I couldn’t just Google it and get an easy solution.

Looking at the darwin source, I found there’s a sysctl() token to get this information. This code will return the processor type (including the 64-bit flag). Note that it uses the sysctlbyname_with_pid() function in Apple’s Universal Binary Programming Guidelines:

cpu_type_t GetProcessArchitecture(pid_t pid)
{
    cpu_type_t cputype;
    size_t cpusz = sizeof(cputype);    

    // Default values
#if __i386__
    cputype = CPU_TYPE_X86;
#else
    cputype = CPU_TYPE_POWERPC;
#endif

    if (sysctlbyname_with_pid("sysctl.proc_cputype", pid,
                              &cputype, &cpusz, NULL, 0) == -1)
    {
        fprintf(stderr, "proc_cputype: sysctlbyname_with_pid failed:"
                "%s\n", strerror(errno));
    }
    return cputype;
}
[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Getting the owner of a process

Thursday, December 6th, 2007

I was a little surprised that I couldn’t find this online anywhere, so for others that may need it, here’s a function that gets the effective owner of a Mac OS X process, given the process pid:

uid_t OwnerForPID(int pid)
{
    struct kinfo_proc info;
    size_t length = sizeof(struct kinfo_proc);
    int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
    if (sysctl(mib, 4, &info, &length, NULL, 0) < 0)
        return kProcessValueUnknown;
    if (length == 0)
        return kProcessValueUnknown;
    return info.kp_eproc.e_ucred.cr_uid;
}

And of course, you know you can get your own process ID with getpid() and use the Process Manager’s GetProcessPID() function to get a pid if you know another process’ ProcessSerialNumber.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]