lundi 4 septembre 2017

C++: best way to test output of commandline tools working together (multi threading)?

I'm trying to write unit tests for some commandline tools. In order to test the source code I need to run two other commandline tools in the background. Currently my code looks basically like this:

exec()-function to execute commands and receive output:

std::string exec(std::string const command) {
    char buffer[128];
    std::string output = "";
    FILE* pipe = popen(command.c_str(), "r");
    if (!pipe) throw std::runtime_error("popen() failed! Command could not be executed!");
    try {
        while (!feof(pipe)) {
            if (fgets(buffer, 128, pipe) != nullptr)
                output += buffer;
        }
    } catch (...) {
        pclose(pipe);
        throw;
    }
    pclose(pipe);
    return output;
}

main process:

std::thread process1(start_process1);
process1.detach();

std::thread process2(start_process2);
process2.detach();

//this is the actual commandline tool that should be tested
std::string output = exec(execute_something_in_mainprocess) 
//check output

start_process1/start_process2 are functions that call the exec-method showed above using different commands. They have to run in background otherwise the actual commandline tool can't be tested.

Is this a good way? How can i terminate the detached threads? I'm not able to change any code of the commandline tools, i can just use them and get their output.

Aucun commentaire:

Enregistrer un commentaire