How to run a C++ program in another C++ program? - c++

I have a simple C++ program that takes in inputs and outputs some string. Like this:
$ ./game
$ what kind of game? type r for regular, s for special.
$ r
$ choose a number from 1 - 10
$ 1
$ no try again
$ 2
$ no try again
$ 5
$ yes you WIN!
Now I want to write a c++ program can runs this c++ program and plays the game automatically without user input and then outputs it to a file or standard output.
Running it would look like this:
./program game r > outputfile
game is the game program, r for playing regular style.
How should I do this? The main reason I need this program is that I want to do automatic testing for a much bigger program.

You could use std::system from <cstdlib>:
std::system("game r > outputfile");
The return value is ./program's, the sole argument must be of type char const *.
There is no standard way to run a program and feed it standard input, though. Judging by your command line, you're on some Unix variant where popen from <stdio.h> should work:
FILE *sub = popen("game r > outputfile", "w");
then write to sub with the stdio functions and read outputfile afterwards.
(But for simple testing, I'd recommend implementing the core logic of your program as a set of functions/classes that can be run by a custom main function in a loop; or pick your favorite scripting language to handle this kind of thing.)

I'd be more efficient to add a caller function to your main source and have it control looping, logging, and feeding input. It would also not require system calls or other magic to pull off. Being a game programmer, we have our games play themselves as much as possible to help with debugging, and almost always this is done via internal code, not through external scripting or system calls. It makes it easier to feed viable input as well.

This scenario cries out for a "script", IMHO.
Bash, Perl, Python - you name it.
SIMPLEST CASE:
Just write a bash script to call ./program game r > outputfile.
Or ./program game r < test_input.txt > test_output.txt
For more advanced scenarios, you might want to look at "expect".
You might also want to look at "STAF", which might be a great way to "automate your automated tests":
http://staf.sourceforge.net/current/STAFFAQ.htm

Related

Execute a C++ program and copy the cmd output using Perl

I am trying to code a perl script which would compile a C++ program and then execute it by passing in the required values. After the execution, I need whatever is printed on the cmd for comparison with a sample code.
Right now my code compiles the cpp code perfectly and correctly executes it, but completes without passing in the values.
All I am doing right now is use system commands
system("cl E:\\checker\\Perl\\temp.cpp");
system("temp.exe");
system("10");
system("20");
system("30");
system("40");
system("50");
The C++ Code is something like this
cin >> a;
cin >> b;
cin >> c;
cin >> d;
cin >> e;
The code correctly compiles and exectues, but the following values (which are inputs to the C++ code which is using cin) doesn't seem to work
Please note I am using the Visual Studio compiler. Also can someone tell me how I can extract the information outputted by the C++ code into maybe a perl array for comparison.
You can use IPC::Open2 to establish bidirectional communication between your Perl script and the other program, e.g.
use IPC::Open2;
use autodie;
my ($chld_out, $chld_in);
my $pid = open2(
$chld_out,
$chld_in,
q(bc -lq)
);
$chld_in->print("1+1\n");
my $answer = <$chld_out>;
print $answer;
kill 'SIGINT', $pid; # I don't believe waitpid() works on Win32. Possibly with Cygwin.
Unfortunately, buffering can make this approach a lot harder than one would hope. You'll also have to manually wait and reap the child process. An alternative would be to use a module like IO::Pty or Expect to create a pseudo-tty environment to simulate user interaction (but I believe these two only work in a Cygwin environment on Windows). There's also IPC::Run, a more fully-featured alternative to IPC::Open2/3.
See also: perlipc and perlfaq8.
The correct syntax for system is either
system('command', 'arg1', 'arg2', ... , 'argn');
Or all as a single string, which allows shell interpretation (which you may not want):
system('command arg1 arg2');
system does not capture output. Instead, use the backticks operator:
my $command_output = `command args`;
or its generic form qx. (If you assign to an array, the output will be split on $/ and pushed onto the array one line at a time).
There is also the pipe form of open (open my $pipeh, '-|', 'command', 'arg1', ..., 'argn') or die $!;) and the readpipe function.

Is it possible to execute another program using C++?

What I'd like to do is have my C++ code open up Mplus (statistical program that I've downloaded on my computer) and run it. Is it possible?
You may be able to do what you want with std::system() calls like:
std::system("program -e input_commands.txt"); // Assuming it accepts some sort of command line args
std::system("program < input_commands.txt"); // Assuming it responds to stdin
It depends on the program if this approach will work.

Calling Mathematica from OCaml program

I am writing OCaml code. In part of it, I want to examine whether two arithmetic expression are equal (like x+2+y == x+2*y-y+2). Implemeting this in mathematica is straightforward, so all I want some help on executing Mathematica and get the result back in OCaml. My OS platform is Linux.
Cheers,
Z.
You may be able to use something along the lines of this:
let channel_to_mathematica, channel_from_mathematica = open_process "mathematica"
in
Printf.fprintf channel_to_mathematica "Tell me if this is equal ...\n";
let answer_from_mathematica = Scanf.fscanf channel_from_mathematica ...
in
...
Documentation of open_process here
Documentation of module Scanf here
A very general answer is to write a command-line Mathematica script that takes 2 expressions (either on the command line or stdin) and outputs whether they are equal.
Then in OCaml simply call that program with a system call.
As for writing such a command-line Mathematica script, I recommend MASH (disclosure: I made MASH):
Call a Mathematica program from the command line, with command-line args, stdin, stdout, and stderr

Communicating between a ruby script and a running c++ program

I have a c++ program which performs one function. It loads a large data-file into an array, receives an array of integers and performs a lookup in that array, returning a single integer. I am currently calling the program with each integer as an argument, like so:
$ ./myprogram 1 2 3 4 5 6 7
I also have a ruby script, and I would like this script to utilize the c++ program.
Currently, I am doing this like so.
Ruby Code:
arguments = "1 2 3 4 5 6 7"
an_integer = %x{ ./myprogram #{arguemnts} }
puts "The program returned #{an_integer}" #=> The program returned 2283
This is all working properly, but my problem is that each time ruby makes this call, the c++ program has to reload the data-file (which is over 100mb) - very slow, and very inefficient.
How can I rewrite my c++ program load the file only once, allowing me to make many lookups via a ruby script without reloading the file each time. Would using sockets be a sensible approach? Writing the c++ program as a ruby extension?
Obviously I am not an experienced c++ programmer, so thanks for your help.
A possible approach is to modify your C++ program so that it takes its input from the standard input stream (std::cin) instead of from the command line parameters, and returns its result through the standard ouput (std::cout) instead of as main's return value. Your Ruby script would then use popen to launch the C++ program.
Assuming the C++ program currently looks like:
// *pseudo* code
int main(int argc, char* argv[])
{
large_data_file = expensive_operation();
std::vector<int> input = as_ints(argc, argv);
int result = make_the_computation(large_data_file, input);
return result;
}
It would be transformed into something like:
// *pseudo* code
int main(int argc, char* argv[])
{
large_data_file = expensive_operation();
std::string input_line;
// Read a line from standard input
while(std:::getline(std::cin, input_line)){
std::vector<int> input = tokenize_as_ints(input_line);
int result = make_the_computation(large_data_file, input);
//Write result on standard output
std::cout << result << std::endl;
}
return 0;
}
And the Ruby script would look like
io = IO.popen("./myprogram", "rw")
while i_have_stuff_to_compute
arguments = get_arguments()
# Write arguments on the program's input stream
IO.puts(arguments)
# Read reply from the program's output stream
result = IO.readline().to_i();
end
io.close()
Well,
You could go about this a number of different ways.
1) A simple, potentially ugly way to do this is to have your c++ run and intermittently check for a file, have your ruby script produce said file containing your arguments. Your C++ program would then use the contained arguments returning it's result to a result file which you could wait on within your ruby script... This is obviously HACK TASTIC but it's uber simple to implement and would work.
2) Expose your c++ code as a c extension to ruby. This is not as hard as it's sounds especially if you use RICE and would provide significantly less hackie solution.
3) If your c++ can be exposed through a c header file then it's almost trivial to construct a bridge using FFI. Jeremy Hinegardner gave a good lecture on constructing FFI interfaces at rubyconf heres the screencast
4) D-Bus provides an application communication bus, you could alter your C++ app to take advantage of said event bus and pass messages from your ruby using ruby-dbus
There are of course a thousand other routes... Maybe one or the other of these could prove viable :)
Cheers!

Embedded console tools functionality in application

I'm currently developing an application that happens to require some file preprocessing before actually reading the data.
Doing it externally was not a possibility so I came up with a fork & execve of "cut options filename | sort | uniq -c" etc... and I execute it like that.
However I thought that maybe there was already another option to reuse all those ancient and good working tools directly in my code and not having to invoke them through a shell.
I am currently looking at busybox to see if there is an easy way of statically link and programatically call those utils but no luck yet.
Arkaitz, the answer no, because of how you've phrased the question.
You ask for "another option to reuse all those ancient and good working tools directly in my code and not having to invoke them through a shell"
The problem with that is, the proper and accepted way of reusing all those ancient and good working tools is exactly what you're saying you want to avoid - invoking them via a shell (or at least, firing them up as child processes via popen for example) - and it's definitely not recommend to try to subsume, copy, or duplicate these tools into your code.
The UNIX (and Linux) model for data manipulation is robust and proven - why would you want to avoid it?
The 'ancient' tools were built for use by the shell, not to be built/linked into an executable. There are, however, more recent tools that kinda do lot of what you showed on your command line preprocessor: iostreams with extractors (to replace cut), std::sort and std::unique to replace the respective programs...
struct S { string col1, col3;
bool operator<( const S& s ) { return col1 < s.col1; }
};
vector<S> v;
while( cin ) {
S s;
string dummy;
cin >> s.col1 >> dummy >> col3 >> dummy;
v.push_back( s );
}
sort(v.begin(), v.end(), S::smaller );
unique( v.begin(), v.end() );
Not too complicated, I think.
Try popen().
char buffer [ BUFFER_SIZE ];
FILE * f = popen( "cut options filename | sort | uniq -c", "r" );
while( /*NOT*/! feof(f) )
fgets( buffer, BUFFER_SIZE, f );
pclose( f );
Reference: How to execute a command and get output of command within C++ using POSIX?
You have to do it through the shell, but it's easier to use "system" call.
while(something) {
int ret = system("foo");
if (WIFSIGNALED(ret) &&
(WTERMSIG(ret) == SIGINT || WTERMSIG(ret) == SIGQUIT))
break;
}
Just write another useful 'ancient and good' tool ;) and read all data from stdin and return it to stdout.
cat *.txt | grep 'blabla' | sort | my_new_tool | tee -o res_file
The nice way to do it is:
Create 2 pipes
Fork a new process
Replace stdin and stdout for child process with pipes using dup2 function
exec a command you'd like
Write and read from parent process using pipes
busybox was my first thought as well, although you might also want to consider embedding a scripting engine like Python and doing these kind of manipulations in Python scripts.
I would definitely not try to strip this kind of functionality out of GNU command line tools since they have grown significantly since the early UNIX days and sprouted an awful lot of options.
If the busybox code seems too hard to adapt, then the next place I would look would be Minix source code. Look under Previous Versions and pick one of the version 1 or 2 Minixes because those were written as teaching code so they tend to be clearer and simpler.
If you do not want to call external commands (whether by exec, popen or system etc) but do not want to modify the source of these utilities and compile them into your code (relatively easy, just change 'main' to 'main_cut' etc), then the only remaining option I see is to embed the utilities inside your code and either extract them at runtime or dynamically create a filing system by pointing at the data inside your code (eg using a floppy or cd image and writing a FUSE module that picks up the disk image data from a ram address). All of which seems like a lot of work just to make this look like a single neatly-packaged utility.
Personally, if i really had to do this, I'd get the source of all those utils and compile them in as external calls. Of course you'd no longer have pipes easily available, you'd either have to use temp files for preprocessing, or something more complicated involving co-routines. Or maybe sockets. Lots of work and messy whatever you do!