0

Currently, I have a c++ program to call an external program, wait for it to finish, and return the string that was supposed to print on the screen by the external program;

string result_now=exec("./CCLS_to_akmaxsat "+softer_filename);

std::string exec(std::string command) {
    //cout << "\n\nEvaluating command: " << command << "\n\n" << endl;
    const char* cmd = command.c_str();
    FILE* pipe = popen(cmd, "r");
    if (!pipe) return "ERROR";
    char buffer[256];
    std::string result = "";
    while(!feof(pipe)) {
        if(fgets(buffer, 256, pipe) != NULL)
            result += buffer;
    }
    pclose(pipe);
    return result;
}

And here is the output:

c This is the CCLS_to_akmaxsat solver, Version: MAXSAT EVALUATION 2014 (2014.03.28)
c Many thanks to the akmaxsat team!
c start CCLS
c stop CCLS
c start akmaxsat
c initialized bestCost to 924115047
o 924115047
c first lower bound: 850209662
c 3406 branches 129 propagates
c total generalized unit propagation = 6941, success = 49.07%
s OPTIMUM FOUND
c Optimal Solution = 924115047
v -60 -58 -56 -54 52 50 48 46 44 42 40 38 36 34 32 30 28 -26 -24 -22 -20 -18 -16 -14 -12 -10 -8 -6 -4 -2 21 23 -25 -27 -29 -31 -33 -35 -37 -39 -41 -43 -45 -47 -49 -51 -53 -55 -57 59 19 17 15 13 11 9 7 5 3 1
c stop akmaxsat

However, if I see that the lower bound is larger than some value. I no longer want to spend time waiting for the program to finish, rather I would terminate the program and provide some information back to my main c++ solver. How do I achieve this? Or if you have some very related tutorials, please don't hesitate to tell me. Thank you.

user40780
  • 1,540
  • 6
  • 22
  • 41
  • 1
    Don't do `while(!feof(...))`, it will not work as you expect it to. The reason is because the `EOF` flag is not set until *after* you attempt to read from beyond the end of the file. That means you loop will iterate once to many. Instead do `while(fgets(...) != NULL)`. Although it will work in your specific case sice you check the result of the `fgets` call, but in the general case don't do it. – Some programmer dude Dec 03 '14 at 19:15
  • To expand on @JoachimPileborg's comment. Though you're using the c-style functions to access your input, I think the same reasonings apply as stated in this Q&A: [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – πάντα ῥεῖ Dec 03 '14 at 19:25

0 Answers0