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

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.

Related

how to pass on some output from a c++ program to the shell so that it can be used in the shell

Is there any good way i can make some data created by my c++ program available to the shell after exiting the program?
I have a c++ program, inside which i have a string containing a path:
std::string path = "/home/some/path"
I want this path to be available after the c++ program exits main and i am returned to the shell, so that i can use that path (e.g. cd to that path).
I have considered/tried the following approaches:
I tried making an environment variable in c++ program using setenv(). However the environment variable only exists while in the c++ program, and it is apparently not possible to make those changes visible in the shell after exiting the program.
(considered) writing the path to a temporary file, so that a bash script could later access the details of the path from it. However i have read many suggestions to not do that due to security vulnerabilities.
I tried calling the bash script from within the c++ program, using system(). This does not work if i try to cd to that directory (exiting the program will keep me in the same directory as before).
I figure that if i am desperate, i could have my program cout the path, and use the solutions as described here:
$ ./program | tee output.txt
Then the path is stored inside the file. This works technically, but has the undesirable effect of creating a file and printing the path to the screen, and is basically creating a temporary file.
another option to, again, cout in my program, and use command substitution. running in the shell
$ var=$(./program)
storing the path in var. This didnt work because my program does many things including requiring user input before calling
std::cout<< path << std::endl;.
Particularly, i have observed this approach to not display a curses window, which is required for the program.
the only solution that has worked is piping the output to tee.
Environment variables are only an input, they cannot be used to return any information from a program.
You are already using std::cin and std::cout for user input, and std::cerr should be reserved for error messages. However, you can have the shell open more filedescriptors, and have your program write to those. However, doing this with pure C++ is not possible. But if you don't mind using POSIX C functions:
#include <cstdio>
int main() {
FILE *f = fdopen(3, "w");
fprintf(f, "some path\n");
}
And then use it like so:
./program 3> output.txt
This of course creates an undesirable file. I don't think there is any way to store the output from an extra filedescriptor directly to a variable in bash. However, you could create a temporary file inside /dev/shm, so it will never be written to disk, or create a FIFO object and redirect the output from the program to the FIFO, and then read it back. For some examples of how to do this, see this question.
You could write the output that you want the user to see to stderr instead of stdout. Only output what you need your shell script to see to stdout:
#include <iostream>
int main() {
std::clog << "Enter data: "; // clog prints to stderr like cerr
std::string line;
std::getline(std::cin, line);
std::cout << line << '\n';
}
Then this will work:
var=$(./program)

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.

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

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

C++: How to escape user input for safe system calls?

On a Linux platform, I have C++ code that goes like this:
// ...
std::string myDir;
myDir = argv[1]; // myDir is initialized using user input from the command line.
std::string command;
command = "mkdir " + myDir;
if (system(command.c_str()) != 0) {
return 1;
}
// continue....
Is passing user input to a system() call safe at all?
Should the user input be escaped / sanitized?
How?
How could the above code be exploited for malicious purposes?
Thanks.
Just don't use system. Prefer execl.
execl ("/bin/mkdir", "mkdir", myDir, (char *)0);
That way, myDir is always passed as a single argument to mkdir, and the shell isn't involved. Note that you need to fork if you use this method.
But if this is not just an example, you should use the mkdir C function:
mkdir(myDir, someMode);
Using system() call with command line parameters without sanitizing the input can be highly insecure.
The potential security threat could be a user passing the following as directory name
somedir ; rm -rf /
To prevent this , use a mixture of the following
use getopt to ensure your input is
sanitized
sanitize the input
use execl instead of system to execute
the command
The best option would be to use all three
Further to Matthew's answer, don't spawn a shell process unless you absolutely need it. If you use a fork/execl combination, individual parameters will never be parsed so don't need to be escaped. Beware of null characters however which will still prematurely terminate the parameter (this is not a security problem in some cases).
I assume mkdir is just an example, as mkdir can trivially be called from C++ much more easily than these subprocess suggestions.
Reviving this ancient question as I ran into the same problem and the top answers, based on fork() + execl(), weren't working for me. (They create a separate process, whereas I wanted to use async to launch the command in a thread and have the system call stay in-process to share state more easily.) So I'll give an alternative solution.
It's not usually safe to pass user input as-is, especially if the utility is designed to be sudo'd; in order to sanitize it, instead of composing the string to be executed yourself, use environment variables, which the shell has built-in escape mechanisms for.
For your example:
// ...
std::string myDir;
myDir = argv[1]; // myDir is initialized using user input from the command line.
setenv("MY_DIR", myDir, 1);
if (system("mkdir \"${MY_DIR}\"") != 0) {
return 1;
}
// continue....

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!