Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get linux command output string and output status in c++

Tags:

c++

linux

command

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.

like image 848
SwapG Avatar asked Apr 02 '13 12:04

SwapG


People also ask

Which command is used to output string in Linux?

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.

How do I display the output page on Linux?

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.

What is system () in C?

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.


2 Answers

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).

like image 200
Piotr Zierhoffer Avatar answered Oct 08 '22 04:10

Piotr Zierhoffer


The simplest solution is to use system, and to redirect standard out and standard error to a temporarly file, which you can delete later.

like image 36
James Kanze Avatar answered Oct 08 '22 04:10

James Kanze