Invoke another exe and get value - c++

How to invoke another .exe and then get the returned value?
Here's the code that I tried and failed:
int main() {
int ret = (int) system("Test.exe");
}
In this code ret holds Zero value but it's should be able to container Test.exe's value.

system returns OS return code, not the console output. There is no portable way to get the output of the program you run (#Rapptz correction, system calls are implementation-defined).
Much easier (at least for some basic usage) would be to redirect output of said .exe to a file, and then read that file.

Related

Running the command line dot program from a Qt application generates no output, what is wrong?

I have an app that generates a dependencies.dot file which I then want to convert to an SVG image.
When I do that from a simple application like so:
int main(int argc, char * argv[])
{
system("dot -Tsvg ../BUILD/dependencies.dot > ../BUILD/dependencies.svg");
return 0;
}
It works great. The SVG image is present and working.
When I instead run it from my Qt application, the SVG file is created (by the shell), but it remains empty.
Any idea what could prevent dot from outputting data to its stdout?
Just in case, I also tried a cat to send the input through stdin instead of a filename:
system("cat ../BUILD/dependencies.dot | dot -Tsvg > ../BUILD/dependencies.svg");
And that didn't make any differences.
Also using the full path (/usr/bin/dot) did not help either.
Another test, I tried to use popen() and the first fread() immediately returns 0 (i.e. the mark of EOF).
It may not be Qt, but something is interacting with dot's ability to do anything. Any pointers on why that is would be wonderful.
Maybe an important note? I start my app. from a console, so stdin, stdout and stderr should all work as expected. I actually can see debug logs appearing there and other apps seem to work just as expected (i.e. My Qt app. can successfully run make, for example).
Here is an example of the resulting SVG (when I don't run it from within my Qt app):
For reference, the source code can be found on github. This is part of the snapbuilder. A tool that I use to run a build on launchpad. It's still incomplete, but it's getting there.
https://github.com/m2osw/snapcpp/tree/master/snapbuilder
The specific function to look for: project::generate_svg().
I still have no clue what side effect Qt has on system() that the dot command would fail. However, if using my own fork() + execve(), then it works.
I wanted a new process class for my environment, so I implemented that. This newer version is using FIFOs or directly opening closing files that it passes to the process.
...
// write the script in `std::stringstream dot` then:
//
std::string script(dot.str());
g_dot_process = std::make_shared<cppprocess::process>("dependencies");
g_dot_process->set_command("/usr/bin/dot");
g_dot_process->add_argument("-Tsvg");
g_dot_process->add_input(cppprocess::buffer_t(script.data(),
script.data() + script.length()));
g_dot_process->set_capture_output();
g_dot_process->set_output_capture_done(output_captured);
g_dot_process->start(); // TODO: check return value for errors
...
// and in output_captured()
//
void snap_builder::svg_ready(std::string const & svg)
{
std::string const svg_filename(...);
{
std::ofstream out;
out.open(svg_filename);
if(!out.is_open())
{
std::cerr << "error: \n";
return;
}
out.write(svg.c_str(), svg.size());
}
dependency_tree->load(QString::fromUtf8(svg_filename.c_str()));
}
Now the dot file is generated and displayed as expected.
This is rather strange since most everything else I've done with a simple system() call works as expected. There must be something about stdin or stdout that makes dot not do its work.

strange behavior with system command in c++

I have written a code in that at some point calls an external executable using the system command.
Here is how I do this:
First remove the output files of the external code.
boost::filesystem::remove("Results/CVground.bin");
boost::filesystem::remove("Results/CVground.BUD");
then write input files for the external code. The code is too long to paste here. It just writes few ascii files.
Then run the model. To make things even worse as you can see I'm calling a windows executable under linux using wine.
std::string sim_command = "/opt/wine-stable/bin/wine ";
sim_command.append(cvd.simulationExe()).append(" CVsimAqua.in >/dev/null");
int sys = system(sim_command.c_str());
Essentially the command I'm calling under system is the following
int sys = system("/opt/wine-stable/bin/wine Simulation3.02.exe CVsimAqua.in >/dev/null");
UPDATE:
Based on the suggestion I modified the above command so that it prints to a file as such
int sys = system("/opt/wine-stable/bin/wine Simulation3.02.exe CVsimAqua.in > log.dat");
This is usually takes a couple of minutes to complete.
Then I'm doing a check that the output files actually exists as follows:
if (!boost::filesystem::exists("Results/CVground.bin")) {
std::cout << "\t\tSys output from rank " << rank << " is " << sys << std::endl;
fun.clear();
fun.push_back(10000000);
fun.push_back(10000000);
boost::filesystem::current_path(main_dir);
return;
}
I have found that in some cases I do get the following print in my log file. The rank number is different in each run.
Sys output from rank 78 is 32512
What I don't understand is that the output of system is positive, which I believe it means that the system command was successful. Is there any way to capture more information from the system command?
UPDATE
After I changed the from /dev/null to log.dat I realized that when the system fails it doesn't even create the log.dat file, however I always check with system(NULL) that system is available before calling the system.
I have found extremely difficult to debug this because these errors occur only when I run the code on the cluster.
Is it possible that the system command returns before the execution code finishes? I have seen a definite NO answer to that question but I was wondering if things are getting trickier since I'm calling via wine.
Thank you
The system function returns the exit code from the command you run. By convention, processes return 0 on success and non-zero on failure. What a non-zero exit code means, depends on the application, wine in this case. If may be easier to debug if you don't redirect its output to /dev/null
There are some specific return values for when the system call itself fails: -1 is a process could not be created, and 127 if a shell could not be executed. See man 3 system for the details on those cases.

Turbo C++ system function running an executable

How to run any exe file from turbo c++? I know that I should stop using turbo c++ and move one to Dev or Code::Blocks, but my school doesn't agree so I gotta wing it.
I just want to know how to run a file with or without the system() function.
Any kind of advice is welcome
Here's what I have tried so far:
1
#include<process.h>
int main()
{
system("tnfsv13.exe"); //tnfsv being a 16-bit application(The need for slowness v 13)
return 0;
}
2
#include<process.h>
int main()
{
system("tnfsv13.bat");
return 0;
}
tnfsv13.bat:
start "c:\TurboC3\BIN\" tnfsv13.exe
NOTE: Just a doubt, you guys: system() is not working in windows XP. I tried it using dosbox in windows 7 and it works well, but in XP it does absolutely nothing. Not even the system("dir") command seems to work but system(NULL) returns 1. Any guesses why?
Thanks.
You can also use Turbo C++'s execl() function. execl() loads and runs C:\\TC\\BIN\\tnfsv13.exe. NULL means there are no arguments to send to tnfsv13.exe. If an error occurs, execl() returns -1 into int c .
#include<stdio.h>
#include<process.h>
int main()
{
int c = execl("C:\\TC\\BIN\\tnfsv13.exe", NULL);
return 0;
}
Explanation:
execl() loads and executes a new child process. Because the child
process is placed in the memory currently occupied by the calling
process, there must be sufficient memory to load and execute it.
'pathname' specifies the file name of the child process. If
'pathname' has a file name extension, then only that file is searched
for. If 'pathname' ends with a period (.), then 'pathname' without an
extension is searched for. If that filename is not found, then
".EXE" is appended and execl() searches again. If 'pathname' has no
extension and does not end with a period, then execl() searches for
'pathname' and, if it is not found, appends ".COM" and searches
again. If that is not found, it appends ".EXE" and searches again.
'arg0', 'arg1',...'argn' are passed to the child process as command-
line parameters. A NULL pointer must follow 'argn' to terminate the
list of arguments. 'arg0' must not be NULL, and is usually set to
'pathname'.
The combined length of all the strings forming the argument list
passed to the child process must not exceed 128 bytes. This includes
"n" (for 0-n arguments) space characters (required to separate the
arguments) but does not include the null ('\0') terminating
character.
Returns: If execl() is successful, it does not return to the
calling process. (See the spawn...() routines for a
similar function that can return to the calling
process). If an error occurs, execl() returns -1 to
the calling process. On error, 'errno' (defined in
<errno.h>) is set to one of the following values
(defined in <errno.h>):
E2BIG Argument list or environment list too big.
(List > 128 bytes, or environment > 32k)
EACCES Locking or sharing violation on file.
(MS-DOS 3.0 and later)
EMFILE Too many files open.
ENOENT File or path not found.
ENOEXEC File not executable.
ENOMEM Not enough memory.
Notes: Any file open when an exec call is made remains open
in the child process. This includes
'stdin','stdout', 'stderr', 'stdaux', and 'stdprn'.
The child process acquires the environment of the
calling process.
execl() does not preserve the translation modes of
open files. Use setmode() in the child process to
set the desired translation modes.
See the spawn...() routines for similar though more
flexible functions that can return to the calling
program.
Caution: The file pointers to open buffered files are not
always preserved correctly. The information in the
buffer may be lost.
Signal settings are not preserved. They are reset to
the default in the child process.
-------------------------------- Example ---------------------------------
The following statements transfer execution to the child process
"child.exe" and pass it the three arguments "child", "arg1",
and"arg2":
#include <process.h> /* for 'execl' */
#include <stdio.h> /* for 'printf' and 'NULL' */
#include <errno.h> /* for 'errno', 'ENOENT' and 'ENOMEM' */
main()
{
execl("child.exe", "child", "arg1", "arg2", NULL);
/* only get here on an exec error */
if (errno == ENOENT)
printf("child.exe not found in current directory\n");
else if (errno == ENOMEM)
printf("not enough memory to execute child.exe\n");
else
printf(" error #%d trying to exec child.exe\n", errno);
}
system() works fine, though it may not work exactly the way you expect: it does the same thing as typing a command at a MSDOS (or Win32) command prompt including input and output being connected to the console.
If you just want to run a program, pass parameters, and not return from it, use a convenient form from the exec() family of functions. See this for one example.

detecting if program is installed on machine

Say I have an application I write, that relies for some task on an externat app (lets call it "tool") that is installed on my machine. In my program, I call it with system( "tool myarguments" ); , works fine.
Now, I want to distribute my app. Of course, the end-user might not have "tool" installed on his machine, so I would like my app to check this, and printout a message for the user. So my question is:
Is there a portable way to check for the existence of an app on the machine? (assuming we know its name and it is accessible through the machine's shell).
Additional information: First idea was to check the existence of the binary file, but:
This is platform dependent,
depending on how it has been installed (build from sources, installed through package,...), it might not always be in the same place, although it can be accessed through local path.
My first opinion on this question is "No", but maybe somebody has an idea ?
Reference: system()
Related: stackoverflow.com/questions/7045879
If you use the Qt toolkit, QProcess may help you.
Edit: and look for QProcess::error() return value: if it is QProcess::FailedToStart , then either it is not installed, or you have insufficient permissions.
If running the tool without argument has no side-effect, and is expected to return an exit code of 0, you can use system("tool") to check tool's existence.
You can check whether the command has been found by checking system's return value like this:
int ret = system("tool");
if (ret != 0) {
std::cout << "tool is not here, move along\n";
}
It is portable in the sense that system is expected to return 0 if all goes well and the command return status is 0 too.
For example, on Linux, running system("non_existing_command") returns 0x7F00 (same type of value as returned by wait()).
On Windows, it returns 1 instead.

c++ was a system call executed properly

I have written a small c++ program that takes some input files and runs some ffmpeg processes on them (via the 'system()' function). I would like to add to that program some code to delete the original files but I need to be sure that the ffmpeg commands executed properly and with no errors. How can I get my c++ program to check if the system() function it used executed properly?
According to the documentation for system
If command is not a null pointer, the value returned depends on the
system and library implementations, but it is generally expected to be
the status code returned by the called command, if supported.
In other words:
if(system("mycommand") != 0)
{
cout << "mycommand failed..." << endl;
}
or something like that. [Obviously assuming that "mycommand" is defined to give a result code of 0 if successfull - most things do, but there are exceptions].