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

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.


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


最简单的解决方案是使用system ,并将标准输出和标准错误重定向到临时文件,稍后您可以删除该文件。


Unfortunately there's no easy and simple way in C on Linux to do this. Here's an example how to read/write stdout/stderr/stdin of child process correctly.

And when you want to receive exit code you have to use waitpid (complete example is provided on the bottom of the provided page):

endID = waitpid(childID, &status, WNOHANG|WUNTRACED);

Now you just have to join those two together :)

There's also a great free book named Advanced Linux Programming (ALP) containing detailed information about these kinds of problem available here.

链接地址: http://www.djcxy.com/p/74852.html

上一篇: D的语法真的是上下文吗?

下一篇: 如何在c ++中获得linux命令的输出字符串和输出状态