How to find the PID of any process in Mac OSX C++

天涯浪子 提交于 2020-01-01 19:06:47

问题


I need to find the PID of a certain program on Mac OSX using C++ and save it as an variable. I have been looking for the answer for this question for a while, and I can't find a detailed one, or one that works. If anyone has an idea on how to do this, please reply. Thanks!


回答1:


You can use proc_listpids in conjunction with proc_pidinfo:

#include <libproc.h>
#include <stdio.h>
#include <string.h>

void find_pids(const char *name)
{
    pid_t pids[2048];
    int bytes = proc_listpids(PROC_ALL_PIDS, 0, pids, sizeof(pids));
    int n_proc = bytes / sizeof(pids[0]);
    for (int i = 0; i < n_proc; i++) {
        struct proc_bsdinfo proc;
        int st = proc_pidinfo(pids[i], PROC_PIDTBSDINFO, 0,
                             &proc, PROC_PIDTBSDINFO_SIZE);
        if (st == PROC_PIDTBSDINFO_SIZE) {
            if (strcmp(name, proc.pbi_name) == 0) {
                /* Process PID */
                printf("%d [%s] [%s]\n", pids[i], proc.pbi_comm, proc.pbi_name);                
            }
        }       
    }
}


int main()
{
    find_pids("bash");
    return 0;
}


来源:https://stackoverflow.com/questions/49506579/how-to-find-the-pid-of-any-process-in-mac-osx-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!