I want to get a Linux command's output string as well as command output status in a C++ program. I am executing Linux commands in my application.
for example: Command:
rmdir abcd
Command output string:
rmdir: failed to remove `abcd': No such file or directory
Command Status:
1 (Which means command has been failed)
I tried using Linux function system()
which gives the output status, and function popen()
which gives me output string of a command, but neither function gives me both
the output string and output status of a Linux command.
printf command is used to output a given string, number or any other format specifier. The command operates the same way as printf in C, C++, and Java programming languages.
After one page of output is displayed, the “more” program waits for you to press the spacebar before displaying the next page. If you want to quit out of the paging process, simply press the 'Q' key.
The system() function is a part of the C/C++ standard library. It is used to pass the commands that can be executed in the command processor or the terminal of the operating system, and finally returns the command after it has been completed. <stdlib. h> or <cstdlib> should be included to call this function.
The output string is in standard output or standard error descriptor (1 or 2, respectively).
You have to redirect these streams (take a look at dup
and dup2
function) to a place, where you can read them (for example - a POSIX pipe
).
In C I'd do something like this:
int pd[2];
int retValue;
char buffer[MAXBUF] = {0};
pipe(pd);
dup2(pd[1],1);
retValue = system("your command");
read(pd[0], buffer, MAXBUF);
Now, you have (a part of) your output in buffer and the return code in retValue.
Alternatively, you can use a function from exec
(i.e. execve
) and get the return value with wait
or waitpid
.
Update: this will redirect only standard output. To redirect standard error, use dup2(pd[1],1)
.
The simplest solution is to use system
, and to redirect standard out and standard error to a temporarly file, which you can delete later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With