I’m looking for a solution to writing a piece of program in C++ on Linux that parses a file which contains programs with a set arguments, then runs those programs with their arguments arguments.
Each program (line) is executed one at a time and then the parent process waits for each child to exit and inspects it’s exit status (i’m only interested if it is 0).
Example of text to be parsed:
prog1 -a arg1 -m arg2 -c arg3
prog2 arg1 arg2 arg3 arg4
….
I believe it is best to store everything in a vector of strings, eg:
vector <std::string> p_vector;
while (getline(file, line))
p_vector.push_back(line);
then, for each element i from 0 to p_vector.size() I need to do something like the example I found on the net:
if(fork() = 0) //? shouldn't here be == ?
{
execv(fullpath,argv);//does full path mean my p_vector[i]? or the child process and then argv is a list of space delimited arguments?
exit(1);
}
else
{
int *status;
wait(status);
if(*status == 0)
printf("%s exited correctly", fullpath);//fullpath, right?
else
//other printf error
}
or, should I better use for this
string command = p_vector[i]; // eg: ls -l -a -l folder_one , put more arguments because I do not know the exact number of them for each parsed line
int exitCode = system(command.c_str());
If anyone has also an idea of how to do this using a script, that would be welcome too, although the scope of my question is C++!
I could have used Qt’s QProcess as I know how to use that one but that might raise some legal issues of which I’m now aware right now (there’s no problem with sharing the code however, the company I work for may not allow that)
Thanks and looking forward to getting some answers from you!
I agree with Ignacio. But if you have to do it , then I would prefer you using System/popen command.
BUT MAKE SURE YOU ARE NOT RUNNING ANY COMMAND THAT WOULD LAND YOU TO TROUBLE.. like ” rm -rf * “.
This is very likely to happen if you are going to read from a file which cannot be trusted with.
And no need to copy it to new string you can do “system(p_vector[i].c_str());”