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).
Type the ps aux to see all running process in Linux. Alternatively, you can issue the top command or htop command to view running process in Linux.
You can list running processes using the ps command (ps means process status). The ps command displays your currently running processes in real-time. This will display the process for the current shell with four columns: PID returns the unique process ID.
To list processes in Linux, use one of the three commands: ps, top or htop. Ps command provides static snapshot of all processes, while top and htop sorts by CPU usage.
You can use the ps command to list all background process in Linux. Other Linux commands to obtain what processes are running in the background on Linux. top command – Display your Linux server's resource usage and see the processes that are eating up most system resources such as memory, CPU, disk and more.
.... 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
}
opendir("/proc")
and count the number of entries that are directories and have digit-only names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With