Search code examples
cmacosunixmacos-carbonfreebsd

How to check if pid belongs to current user session?


I can get the list of running process from the this source code on mac.

Now, I want to filter these processes for different users or at least for current user session.


Solution

  • You can just extend your code like this..

        kinfo_proc *mylist;
        size_t mycount = 0;
        mylist = (kinfo_proc *)malloc(sizeof(kinfo_proc));
        GetBSDProcessList(&mylist, &mycount);
    
        char *user  = getenv("USER");
    
        for (int i = 0; i < mycount; i++) 
        {       
            uid_t uid = mylist[i].kp_eproc.e_pcred.p_ruid;
            struct passwd * pwd = getpwuid(uid);
            char    * username = pwd->pw_name;
    
            if(strcmp(username, user) == 0)
            {
                printf(" %d - %s \n", mylist[i].kp_proc.p_pid, mylist[i].kp_proc.p_comm);
            }
        }