如何在Mac OSX C ++中查找任何进程的PID [英] How to find the PID of any process in Mac OSX C++

查看:556
本文介绍了如何在Mac OSX C ++中查找任何进程的PID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用C ++在Mac OSX上找到某个程序的PID,并将其保存为变量.我一直在寻找这个问题的答案,但是找不到详细的答案或可行的答案.如果有人对如何执行此操作有任何想法,请回复. 谢谢!

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!

推荐答案

您可以将proc_listpidsproc_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;
}

这篇关于如何在Mac OSX C ++中查找任何进程的PID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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