5

I want my (C/C++ based) program to display a numeric indicator of how many processes are currently present on the local system. The number-of-running-processes value would be queried often (e.g. 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.

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.

Ideally I'm looking for something like this, except available under Linux (getsysinfo() appears to be more of a Minix thing).

jww
  • 90,984
  • 81
  • 374
  • 818
Jeremy Friesner
  • 63,706
  • 14
  • 113
  • 212

2 Answers2

12

.... 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.

That said, if anyone knows of a MacOS/X and/or Windows equivalent to sysinfo(), I'm still interested in that.


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
}
Jeremy Friesner
  • 63,706
  • 14
  • 113
  • 212
3

opendir("/proc") and count the number of entries that are directories and have digit-only names.

Fred Foo
  • 342,876
  • 71
  • 713
  • 819