Is there an easy way to get the current number of processes on Linux?

I want my (in C / C ++) program to display a numerical indicator of how many processes are currently present on the local system. The value of the number of running processes will be often requested (for example, once per second) to update my display.

Is there an easy way to get this number? Obviously, I could call "ps ax | wc -l", but I would prefer not to force the computer to start the process and analyze a few hundred lines of text to come up with one.

This program will work mainly under Linux, but it can also work under MacOS / X or Windows, so the methods related to this OS will also be useful.

Ideally, I'm looking for something like this , except for those available under Linux (getsysinfo () seems to be more suitable for Minix)

Thanks Jeremy

+5
source share
2 answers

.... and, of course, 1 minute after I submit the question, I will find out the answer: sysinfo will return (among other things) a field that indicates how many processes exist.

However, if someone knows about MacOS / X and / or Windows, equivalent to sysinfo (), I'm still interested in this.


Update: here the function finally ended.

#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
}
+12
source

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

+3

All Articles