プロセスの一覧を取得する

前に書いたOS X用のプログラムがiOSでも普通に動いたわ。
さすがUNIXマシン。

#include <sys/sysctl.h>
#include <pwd.h>

#define MIB_NAMELEN 4
void
show_processes()
{
    int mibname[MIB_NAMELEN] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0}; // all processes
    struct kinfo_proc *procs;
    size_t buffersize = 0;
    int index, count;
    
    // get required buffer size for procs 
    if (sysctl(mibname, MIB_NAMELEN, NULL, &buffersize, NULL, 0) < 0) {
        // failure calling sysctl()
        return;
    }
    procs = (struct kinfo_proc *)malloc(buffersize);
    // get procs info.
    if (sysctl(mibname, MIB_NAMELEN, procs, &buffersize, NULL, 0) < 0) {
        // failure calling sysctl()
        free(procs);
        return;
    }

    count = buffersize/sizeof(struct kinfo_proc);
    printf("UID      PID   COMMAND\n");
    for (index = 0; index < count; index++) {
        uid_t p_uid = procs[index].kp_eproc.e_pcred.p_ruid;
        char *username = user_from_uid(p_uid, 0);
        pid_t p_pid = procs[index].kp_proc.p_pid;
        char *p_comm = procs[index].kp_proc.p_comm;
        printf("%-8s %5d %s\n", username, p_pid, p_comm);
    }
    free(procs);
    return;
}

iPadで出力

UID      PID   COMMAND
root      7415 amfid
mobile    7414 True3DMaze4i
mobile    7413 debugserver
mobile    7409 lsd
mobile    7405 installd
root      7402 lockbot
_securityd  7401 securityd
mobile    7074 atc
mobile    7063 springboardservi
mobile    7032 notification_pro
mobile    7026 syslog_relay
mobile    7024 notification_pro
mobile    7021 notification_pro
mobile    7017 afcd
mobile    7012 ptpd
mobile    6662 iBooks
mobile    6640 MobileSafari
mobile    6635 ubd
root      6634 filecoordination
mobile    5744 MobileMail
mobile    5579 MobileSlideShow
mobile    5394 MobileStore
mobile    5390 AppStore
root       502 SCHelper
mobile     488 Preferences
mobile     321 assetsd
mobile     145 MobilePhone
mobile     141 absinthed.K93
mobile      82 dataaccessd
mobile      81 aosnotifyd
root        70 networkd
mobile      67 SpringBoard
mobile      63 BTServer
mobile      58 aggregated
mobile      57 apsd
mobile      52 fairplayd.K93
root        51 fseventsd
mobile      49 iapd
mobile      48 imagent
root        46 locationd
_mdnsresponder    45 mDNSResponder
mobile      44 mediaremoted
mobile      43 mediaserverd
root        27 wifid
root        23 powerd
root        21 lockdownd
_wireless    19 CommCenterClassi
root        16 syslogd
root        14 configd
root        13 notifyd
root        12 UserEventAgent
root         1 launchd
root         0 kernel_task

cf: http://opensource.apple.com/source/adv_cmds/adv_cmds-46/ps.tproj/
もうちょっと詳しい情報はtask_info()とかで取れるっぽい。

と思ったらtask_for_pid()がobsoleteになってた……。


[追記:2012/3/4] 引数も取れた