On Windows you can you the WMIC command to get this information;
C:\WMIC PROCESS get Caption,Commandline,Processid
And by calling that from
C++ you can parse the output and read the information you want.
Something like this might work for you;
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <string>
#include <vector>
#include <istream>
#include <ostream>
#include <sstream>
#include <stdio.h>
using namespace std;
class process_info {
public:
const string name;
const int id;
const string command_line;
process_info(const string& name, const int id, const string command_line)
: name(name), id(id), command_line(command_line) {
}
};
int to_int(const string& value) {
int i;
istringstream ss(value);
ss >> i;
return i;
}
string trim(const string& str, const char trim_char) {
string::size_type start = str.find_first_not_of(trim_char);
string::size_type end = str.find_last_not_of(trim_char);
if (start == end)
return "";
string temp = str.substr(0, end + 1);
return temp.substr(start, temp.size());
}
string trim_whitespace(const string& str) {
return trim(trim(trim(trim(str, ' '), '\t'), '\r'), '\n');
}
string run_command(const char* cmd) {
FILE* pipe = _popen(cmd, "r");
if (!pipe)
return "ERROR";
static const int buffer_size = 2048;
char buffer[buffer_size];
string result = "";
while(!feof(pipe)) {
if(fgets(buffer, buffer_size, pipe) != NULL)
result += buffer;
}
_pclose(pipe);
return result;
}
int main(int argc, char* argv[]) {
const string result = run_command("WMIC PROCESS get Caption,Commandline,Processid");
stringstream str(result);
string line;
vector<process_info> processes;
if (getline(str, line, '\r')) {
const string::size_type cl_pos = line.find("CommandLine", 0);
const string::size_type pid_pos = line.find("ProcessId", 0);
while(getline(str, line, '\r')) {
if (line.find_first_not_of('\n') != string::npos) {
if (line.size() > 0) {
const string name = trim_whitespace(line.substr(0, cl_pos));
const string command_line = trim_whitespace(line.substr(cl_pos, pid_pos-cl_pos));
const string pid = trim_whitespace(line.substr(pid_pos, line.size() - pid_pos));
if (pid.size() > 0) {
const process_info info(name, to_int(pid), command_line);
processes.push_back(info);
}
}
}
}
}
cout << "Dumping list of processes: " << endl;
for(string::size_type i = 0; i < processes.size(); ++i) {
cout << "[" << processes[i].id << "] " << processes[i].name << "; command line={" << processes[i].command_line << "}" << endl;
}
return 0;
}
(apologies for the "manual" string parsing, I am assuming you'll use
boost or something like that for your final version).
Hope this helps,
Fredrik Bornander