Reading a process and Slicing a string line

Today I had to write a quick function to read the VmSize of a linux process, in C++;
For simplicity lets define some invariants for our function:-

  • The linux process are avaialbe in /proc/
  • The PID will be passed to the function
  • VmSize is avaialbe in 'status' file

Our goal can be easily achieved by reading the 'status' file and searching for VmSize value converting it to GB.

  • Lets define the includes
    #include <iostream>
    #include <string>
    #include <vector>
    #include <fstream>
    #include <sstream>
    #include <iterator>
  • define supporiting functions
    using namespace std;
    std::string get_base(){
    return "/proc/";
    }
    std::string get_status(){
    return "/status";
    }
    void get_stream(std::string path, std::ifstream &stream)
    {
    stream.open(path, std::ifstream::in);
    if (!stream && !stream.is_open())
    {
        stream.close();
        throw std::runtime_error("non-exisitng PID");
    }
    }
  • function to read the file and slice string line
    std::string getVmSize(std::string pid)
    {
    std::ifstream process;
    get_stream(get_base() + pid + get_status(), process);
    string line;
    const std::string vm_size = "VmSize:";
    float result = 0.0;
    while (getline(process, line))
    {
        if (line.compare(0, vm_size.size(), vm_size) == 0)
        {
            std::istringstream buf(line);
            std::istream_iterator<string> beg(buf), end;
            std::vector<std::string> values(beg, end);
            result = stof(values[1]) / float(1024 * 1024);
            break;
        }
    }
    return std::to_string(result);
    }
  • make a call in main
    int main()
    {
    std::cout << getVmSize("1") << " GB" << std::endl;
    return 0;
    }
0