OSX: proc_pidinfo returns 0 for other user's processes

前端 未结 2 890
轻奢々
轻奢々 2021-02-10 02:28

I need to get some information (PID, UID, GID, process name) about running processes on Mac OSX. I tried proc_pidinfo. For my own processes it works fine. However,

2条回答
  •  不要未来只要你来
    2021-02-10 03:06

    I found that macOS Mojave (version 10.14.4) had struct proc_bsdshortinfo, which is a subset of struct proc_bsdinfo. You can get other user's processes without SUID by using it instead of struct proc_bsdinfo.

    Well, I don't know from which version it is available.

    edited: It is available since at least macOS 10.10.5 (Yosemite).
    edited again: It may be available since Mac OS X 10.7 (Lion) because tmux uses struct proc_bsdshortinfo if __MAC_10_7 is defined. See here.

    Example:

    #include 
    #include 
    #include 
    
    #include 
    
    int main(int argc, char *argv[])
    {
        pid_t pid;
        struct proc_bsdshortinfo proc;
    
        if (argc == 2)
            pid = atoi(argv[1]);
        else
            pid = getpid();
    
        int st = proc_pidinfo(pid, PROC_PIDT_SHORTBSDINFO, 0,
                             &proc, PROC_PIDT_SHORTBSDINFO_SIZE);
    
        if (st != PROC_PIDT_SHORTBSDINFO_SIZE) {
            fprintf(stderr, "Cannot get process info\n");
            return 1;
        }
        printf(" pid: %d\n", (int)proc.pbsi_pid);
        printf("ppid: %d\n", (int)proc.pbsi_ppid);
        printf("comm: %s\n",      proc.pbsi_comm);
        //printf("name: %s\n",      proc.pbsi_name);
        printf(" uid: %d\n", (int)proc.pbsi_uid);
        printf(" gid: %d\n", (int)proc.pbsi_gid);
    
        return 0;
    }
    

    This program prints:

    $ ./pidinfo 
     pid: 3025
    ppid: 250
    comm: pidinfo
     uid: 501
     gid: 20
    $ ./pidinfo 1
     pid: 1
    ppid: 0
    comm: launchd
     uid: 0
     gid: 0
    

提交回复
热议问题