How to programatically get uid from pid in osx using c++?

前端 未结 5 1992
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 14:01

Given a pid, I want to find the owner of the process (as uid). Is there a way to get this in osx (or any unix) using C++?

Google didn\'t help. \'ps\' is able to do i

5条回答
  •  盖世英雄少女心
    2020-12-09 14:45

    The source for the ps command, reveals that there is a function called get_proc_stats defined in proc/readproc.h that (among other things) returns the real user name(UID) & Effective user name(EUID) for a given pid.

    You need to do install libproc-dev to get this function. and then you can do:

    #include 
    void printppid(pid_t pid) 
    {
        proc_t process_info;
        get_proc_stats(pid, &process_info);
        printf("Real user of the process[%d] is [%s]\n", pid, process_info.ruser);
    }
    

    compile it with gcc the-file.c -lproc.

    Once you have the real user name you can use getpwnam() and getgrnam() functions to get the uid.

提交回复
热议问题