print number of active process in linux

Hi I am making a c++ code with fork() creating childs.


How can I print the total amount of processes running on my linux operating system?
I don't need the list of the process, I only want the total

I use a Geany IDE an Ubuntu 14.

Thanks a Lot
Christian.
Thanks But I need to print from a C++ Code, not in linux console.
std::system("ps -eo pid | wc -l"); ?

Somewhat more seriously, see the manual for proc(5) and sysinfo(2).
sysinfo, in particular, obtains the number of processes.
Last edited on
ps is the only portable way.
I wonder if this is what you are after?

https://linux.die.net/man/3/popen

One can use this run a shell command, so you could use it to run ps

Regards :+)
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#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;
}
Last edited on
Topic archived. No new replies allowed.