如何使用 C++ 以编程方式从 osx 中的 pid 获取 uid? [英] How to programatically get uid from pid in osx using c++?

查看:16
本文介绍了如何使用 C++ 以编程方式从 osx 中的 pid 获取 uid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个pid,我想找到进程的所有者(作为uid).有没有办法使用 C++ 在 osx(或任何 unix)中获得它?

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++?

谷歌没有帮助.'ps' 能够做到;所以我认为应该有办法以编程方式获取它.

Google didn't help. 'ps' is able to do it; so I assume there should be a way to get it programatically.

推荐答案

终于找到了一种无需解析 'ps' 输出即可以编程方式执行此操作的方法

Finally found a way to programatically do this without parsing the output of 'ps'

uint getUidUsingSysctl(uint pid)
{
    struct kinfo_proc *sProcesses = NULL, *sNewProcesses;
    int    aiNames[4];
    size_t iNamesLength;
    int    i, iRetCode, iNumProcs;
    size_t iSize;

    iSize = 0;
    aiNames[0] = CTL_KERN;
    aiNames[1] = KERN_PROC;
    aiNames[2] = KERN_PROC_ALL;
    aiNames[3] = 0;
    iNamesLength = 3;

    iRetCode = sysctl(aiNames, iNamesLength, NULL, &iSize, NULL, 0);

    /* allocate memory and populate info in the  processes structure */
    do
    {
        iSize += iSize / 10;
        sNewProcesses = (kinfo_proc *)realloc(sProcesses, iSize);

        if (sNewProcesses == 0)
        {
            if (sProcesses)
                free(sProcesses);
            /* could not realloc memory, just return */
            return -1;
        }
        sProcesses = sNewProcesses;
        iRetCode = sysctl(aiNames, iNamesLength, sProcesses, &iSize, NULL, 0);
    } while (iRetCode == -1 && errno == ENOMEM);

    iNumProcs = iSize / sizeof(struct kinfo_proc);

    for (i = 0; i < iNumProcs; i++)
    {
        if (sProcesses[i].kp_proc.p_pid == pid) 
        {
            return sProcesses[i].kp_eproc.e_ucred.cr_uid;
        }

    }

    /* clean up and return to the caller */
    free(sProcesses);

    return -1;
}

注意:可能有更好的方法来获取 'kinfo_proc' 而不是遍历所有进程.

Note: There might be a better way to get 'kinfo_proc' instead of iterating through all process.

这篇关于如何使用 C++ 以编程方式从 osx 中的 pid 获取 uid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆