How to check if a process is running in C++?

Saurabh Jadhav picture Saurabh Jadhav · Jul 11, 2017 · Viewed 8.8k times · Source

I have written a program in C++ to read the processes from a file into a vector and then to execute the processes line by line.

I would like to find out which processes are running and which aren't by using proc in c++

Thanks.

My code:

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <iterator>
#include <cstdlib>

using namespace std;

int main()
{   int i,j;
    std::string line_;
    std::vector<std::string> process;
    ifstream file_("process.sh");
    if(file_.is_open())
    {
        while(getline(file_,line_))
        {
            process.push_back(line_);
        }
        file_.close();
    }
    else{
        std::cout<<"failed to open"<< "\n";
    }
    for (std::vector<string>::const_iterator i = process.begin(); i != process.end(); ++i)
    {
    std::cout << *i << ' ';
    std::cout << "\n";
    }

    for (unsigned j=0; j<process.size(); ++j)
    {
    string system=("*process[j]");
    std::string temp;
    temp = process[j];
    std::system(temp.c_str());
    std::cout << " ";
    }
    std::cin.get();
    return 0;
}

Answer

metamorphling picture metamorphling · Jul 11, 2017

Taken from http://proswdev.blogspot.jp/2012/02/get-process-id-by-name-in-linux-using-c.html

Before executing your processes pass process name to this function. If getProcIdByName() returns -1 you are free to run process_name. If valid pid is returned, well, do nothing, or kill and run it from your software, depends on your needs.

#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

int getProcIdByName(string procName)
{
    int pid = -1;

    // Open the /proc directory
    DIR *dp = opendir("/proc");
    if (dp != NULL)
    {
        // Enumerate all entries in directory until process found
        struct dirent *dirp;
        while (pid < 0 && (dirp = readdir(dp)))
        {
            // Skip non-numeric entries
            int id = atoi(dirp->d_name);
            if (id > 0)
            {
                // Read contents of virtual /proc/{pid}/cmdline file
                string cmdPath = string("/proc/") + dirp->d_name + "/cmdline";
                ifstream cmdFile(cmdPath.c_str());
                string cmdLine;
                getline(cmdFile, cmdLine);
                if (!cmdLine.empty())
                {
                    // Keep first cmdline item which contains the program path
                    size_t pos = cmdLine.find('\0');
                    if (pos != string::npos)
                        cmdLine = cmdLine.substr(0, pos);
                    // Keep program name only, removing the path
                    pos = cmdLine.rfind('/');
                    if (pos != string::npos)
                        cmdLine = cmdLine.substr(pos + 1);
                    // Compare against requested process name
                    if (procName == cmdLine)
                        pid = id;
                }
            }
        }
    }

    closedir(dp);

    return pid;
}

int main(int argc, char* argv[])
{
    // Fancy command line processing skipped for brevity
    int pid = getProcIdByName(argv[1]);
    cout << "pid: " << pid << endl;
    return 0;
}