One way you could do this is by counting the number of directories under proc that have numbers for names because /proc creates a subdirectory named after the process number of every running process.
#include <algorithm>
#include <stdexcept>
#include <cerrno>
#include <cstring>
#include <dirent.h>
// ...
std::size_t number_of_processes()
{
DIR* dir;
if(!(dir = opendir("/proc")))
throw std::runtime_error(std::strerror(errno));
std::size_t count = 0;
while(dirent* dirp = readdir(dir))
{
// is this a directory?
if(dirp->d_type != DT_DIR)
continue;
// is every character of the name a digit?
if(!std::all_of(dirp->d_name, dirp->d_name + std::strlen(dirp->d_name),
[](char c){ return std::isdigit(c); }))
continue;
// digit only named directory, must be a process
++count;
}
if(closedir(dir))
throw std::runtime_error(std::strerror(errno));
return count;
}