// Oldham, Jeffrey D. // 2000Feb01 // CS3352 // CS3352 Monte Carlo Repeater Program // This program runs another program P a specified number n of times. // It collects the one integer output of P, printing the output. // To run the program, type // repeater number-of-trials P [P's command line arguments] // where // "number-of-trials" is an integer indicating how many times program // P should be run // "P" is the name of the program that generates one trial // It should print one number to the standard output. // command-line arguments for P can be specified #include #include // has EXIT_SUCCESS #include #include #include // has ULONG_MAX // Run a specified program. // input <- argv[0] (for printing error messages) // command line to run program // output-> integer returned by the program int runP(const char cmd[], const string & commandLine) { FILE * output; // Start up the program P. if ((output = popen(commandLine.c_str(), "r")) == static_cast(NULL)) { cerr << cmd << ": failed to run " << commandLine << "\n"; throw "failed to run"; } int response; if (fscanf(output, "%i", &response) != 1) { cerr << cmd << ": failed to read response from " << commandLine << "\n"; throw "failed to read from program"; } if (pclose(output) != EXIT_SUCCESS) { cerr << cmd << ": " << commandLine << " failed execution\n"; throw "program failed to run"; } return response; } int main(int argc, char *argv[]) { if (argc < 3) { cerr << argv[0] << ": number-of-trials program-to-run [command-line-arguments]\n"; throw "illegal command line arguments"; } unsigned long nuTrials = strtoul(argv[1], static_cast(0), 0); if (nuTrials == ULONG_MAX) { cerr << argv[0] << ": number-of-trials out of range\n"; throw "illegal number of trials"; } // Construct P's command line. string commandLine = argv[2]; // command line to run P for (int argCounter = 3; argCounter < argc; ++argCounter) { commandLine += " "; commandLine += argv[argCounter]; } // Run the program P. for (; nuTrials > 0; --nuTrials) cout << runP(argv[0], commandLine) << endl; return EXIT_SUCCESS; }