获取当前进程在MacOS上派生的活动线程数



在过去的3个小时里,我一直在网上和系统标题中搜索,但在C/C++中找不到我在MacOS上尝试做什么的机制。

我正在寻找一种方法来检索当前运行的进程的活动/活动线程总数。我承认,如果我计算我自己生成的线程,这将是微不足道的,但事实并非如此。我正在处理的代码库使用了几个线程库,出于调试目的,我需要这些基本信息。

在linux上,我只能访问/proc/self/stat/,其中第20个元素是活动线程的总数,但这在MacOS上不可用。如果有帮助,这必须在MacOS12.0+上工作

有人有什么想法吗?

通过谷歌搜索,在我看来,在从task_for_pid():获得正确的马赫端口后,您应该能够使用task_threads()获得这些信息

int pid = 123; // PID you want to inspect
mach_port_t me = mach_task_self();
mach_port_t task;
kern_return_t res;
thread_array_t threads;
mach_msg_type_number_t n_threads;
res = task_for_pid(me, pid, &task);
if (res != KERN_SUCCESS) {
// Handle error...
}
res = task_threads(task, &threads, &n_threads);
if (res != KERN_SUCCESS) {
// Handle error...
}
// You now have `n_threads` as well as the `threads` array
// You can use these to extract info about each thread
res = vm_deallocate(me, (vm_address_t)threads, n_threads * sizeof(*threads));
if (res != KERN_SUCCESS) {
// Handle error...
}

然而,请注意,task_for_pid()的使用可能会受到限制。我不太了解权限在macOS上是如何工作的,但你可以查看其他帖子:

  • task_for_pid停止在OS X 10.11上工作
  • 让task_for_pid((在El Capitan中工作
  • 这个GitHub Gist包含一个带有注释.plist的示例

最新更新