Is there any Carbon/Cocoa/C API available on Macs that I can use to enumerate processes? I\'m looking for something like EnumProcesses
on Windows.
My go
Late to the party, but if you really need a robust solution that can check whether any process is running (including BSD processes), you can do the following:
#include
#include
#include
#include
#include
int main(int argc, const char* argv[]) {
pid_t pid = atoi(argv[2]);
// This MIB array will get passed to sysctl()
// See man 3 sysctl for details
int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
struct kinfo_proc result;
size_t oldp_len = sizeof(result);
// sysctl() refuses to fill the buffer if the PID does not exist,
// so the only way to detect failure is to set all fields to 0 upfront
memset(&result, 0, sizeof(struct kinfo_proc));
if (sysctl(name, 4, &result, &oldp_len, NULL, 0) < 0) {
perror("sysctl");
return 1;
}
// SZOMB means a zombie process, one that is still visible but is not running anymore
if (result.kp_proc.p_pid > 0 && result.kp_proc.p_stat != SZOMB) {
printf("Process is running.\n");
} else {
printf("Process is NOT running.\n");
}
return 0;
}
Note that the above code is a modified version of one of my private libraries and is untested. However, it should make clear how the API is used, and works successfully on macOS 10.14.5.