简体   繁体   English

是否有一种轻量级的方法来获取Linux中当前的进程数?

[英]Is there a lightweight way to obtain the current number of Processes in Linux?

I want my (C/C++ based) program to display a numeric indicator of how many processes are currently present on the local system. 我希望我的(基于C / C ++)程序显示当前系统当前存在多少进程的数字指示器。 The number-of-running-processes value would be queried often (eg once per second) to update my display. 将经常查询运行进程数值(例如每秒一次)以更新我的显示。

Is there a lightweight way to get that number? 有没有轻量级的方法来获得这个数字? Obviously I could call "ps ax | wc -l", but I'd prefer not to force the computer to spawn a process and parse several hundred lines of text just to come up with a single integer. 显然我可以调用“ps ax | wc -l”,但我不想强迫计算机生成一个进程并解析数百行文本只是为了得到一个整数。

This program will be running primarily under Linux, but it might also run under MacOS/X or Windows also, so techniques relevant to those OS's would be helpful also. 该程序将主要在Linux下运行,但也可能在MacOS / X或Windows下运行,因此与这些操作系统相关的技术也会有所帮助。

Ideally I'm looking for something like this , except available under Linux (getsysinfo() appears to be more of a Minix thing). 理想的情况是我在寻找像这样在Linux下,除了可用(getsysinfo()似乎更多的是Minix的东西)。

.... and of course 1 minute after I post the question, I figure out the answer: sysinfo will return (amongst other things) a field that indicates how many processes there are. ....当然,我发布问题后1分钟,我找到了答案: sysinfo将返回(除其他外)一个字段,指示有多少进程。

That said, if anyone knows of a MacOS/X and/or Windows equivalent to sysinfo(), I'm still interested in that. 也就是说,如果有人知道MacOS / X和/或Windows等同于sysinfo(),我仍然对此感兴趣。


Update: Here's the function I finally ended up with. 更新:这是我最终结束的功能。

#ifdef __linux__
# include <sys/sysinfo.h>
#elif defined(__APPLE__)
# include <sys/sysctl.h>
#elif defined(WIN32)
# include <Psapi.h>
#endif

int GetTotalNumProcesses()
{
#if defined(__linux__)
   struct sysinfo si;
   return (sysinfo(&si) == 0) ? (int)si.procs : (int)-1;
#elif defined(__APPLE__)
   size_t length = 0;
   static const int names[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
   return (sysctl((int *)names, ((sizeof(names)/sizeof(names[0]))-1, NULL, &length, NULL, 0) == 0) ? (int)(length/sizeof(kinfo_proc)) : (int)-1;
#elif defined(WIN32)
   DWORD aProcesses[1024], cbNeeded;
   return EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded) ? (cbNeeded/sizeof(DWORD)) : -1;
#else
   return -1;
#endif
}

opendir("/proc")并计算目录条目数并具有仅数字名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM