2

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!

4
  • 1
    Try ps -aef in the Terminal. Then chose one process and try finding that, e.g. pgrep coreaudiod or pgrep USBAgent. Then maybe think about using popen() to do the same from your program in C++. stackoverflow.com/q/44610978/2836621 Commented Mar 27, 2018 at 7:28
  • @MarkSetchell I don't think this applies. I am using this to modify, not output. Honestly, I just want to know how to find the PID using C++ before I get into anymore things. Commented Mar 27, 2018 at 7:51
  • 1
    How can it not apply? If you want to find the processid of process "fred", you run pgrep fred in the Terminal and it prints the processid, surely? In your C++ program, you do exactly the same, then read that number using popen("/usr/bin/pgrep fred"). Commented Mar 27, 2018 at 8:54
  • I am using popen to find the process ID and in some rare occasions on MacOS Big Sur and Catalina, I found that it's stuck for ~10 minutes on that. Why might that happen? Is there any way to avoid that or add some timeout value to that? Commented Feb 17, 2021 at 19:10

1 Answer 1

11

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; } 
Sign up to request clarification or add additional context in comments.

1 Comment

This code can also be easily modified to return a boolean if the program is running. I used this code to check whether a program was running or not.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.