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;
}
6
  • 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. Commented Jul 11, 2017 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. Commented Jul 11, 2017 at 14:25
  • @duong_dajgja Yes but I wanted to include that in my code, to know which processes are running. Commented Jul 11, 2017 at 14:28
  • @SaurabhJadhav: Check this: stackoverflow.com/questions/939778/… Commented Jul 11, 2017 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 and How to find if a process is running in C? Commented Jul 11, 2017 at 14:34

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Well after running the processes I wanted to know which of the initiated processes are running and which failed. @metamorphling
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;
}

2 Comments

this doesn't handle recycled pids. can you please show how to resolve it?
You need to store the information about the process when it was initially created. Comparing start_time should be sufficient, You can parse /proc/<pid>/stat to get information about the process. Since this is beyond the topic of this question, so i won't include a full solution for that in my answer.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.