1

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;
}
Saurabh Jadhav
  • 11
  • 1
  • 1
  • 7
  • There is no library call that gives you an easy answer to whether or not a process is running. You would need to handle it manually. Something like: call `system("ps aux &> processes.txt")` and the analyse the `processes.txt` file looking for the process name etc. – Griffin Jul 11 '17 at 14:22
  • You may need to write some code like `ps aux | grep program_name` to see if there exists any instances of `program_name` running. – duong_dajgja Jul 11 '17 at 14:25
  • @duong_dajgja Yes but I wanted to include that in my code, to know which processes are running. – Saurabh Jadhav Jul 11 '17 at 14:28
  • @SaurabhJadhav: Check this: https://stackoverflow.com/questions/939778/linux-api-to-list-running-processes – duong_dajgja Jul 11 '17 at 14:29
  • 1
    Heresy by some since some take the position C and C++ are completely unrelated: [Determine programmatically if a program is running](https://stackoverflow.com/q/6898337/608639) and [How to find if a process is running in C?](https://stackoverflow.com/q/11785936/608639) – jww Jul 11 '17 at 14:34
  • @duong_dajgja I checked the post, actually I am a learner and I don't know how to use proc in my program. – Saurabh Jadhav Jul 11 '17 at 14:49

3 Answers3

3

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;
}
metamorphling
  • 369
  • 3
  • 9
  • Well after running the processes I wanted to know which of the initiated processes are running and which failed. @metamorphling – Saurabh Jadhav Jul 11 '17 at 14:40
3

Use kill(pid, sig) but check for the errno status. If you're running as a different user and you have no access to the process it will fail with EPERM but the process is still alive. You should be checking for ESRCH which means No such process.

If you're running a child process kill will succeed until waitpid is called that forces the clean up of any defunct processes as well.

Here's a function that returns true whether the process is still running and handles cleans up defunct processes as well.

bool IsProcessAlive(int ProcessId)
{
    // Wait for child process, this should clean up defunct processes
    waitpid(ProcessId, nullptr, WNOHANG);
    // kill failed let's see why..
    if (kill(ProcessId, 0) == -1)
    {
        // First of all kill may fail with EPERM if we run as a different user and we have no access, so let's make sure the errno is ESRCH (Process not found!)
        if (errno != ESRCH)
        {
            return true;
        }
        return false;
    }
    // If kill didn't fail the process is still running
    return true;
}
Playdome.io
  • 3,137
  • 2
  • 17
  • 34
2

In C, I use kill(pid_t pid, int sig) to send a blank signal (0) to a specific pid, therefore checking if it's active with the return of this function.

I don't know if you have a similar function in C++ but because you're using linux as well, it might be worth checking signals.

MadStark
  • 465
  • 4
  • 17