将stdout和stderr重定向到linux下

时间:2015-05-23 09:37:47

标签: linux shell io sandbox rhel

我有Test.cppsandbox下运行(RHEL7):

Test.cpp内容:

#include<stdio>
 int main(void) {
  int a = 1/0;
  return 0;
 }

使用gcc(4.8)Test.cpp编译它,生成a.out 现在运行a.out在控制台上打印floating pointing exception

现在我认为如果我将stderr重定向到文件,我希望错误打印在文件中。 但事实并非如此,它仍然继续在控制台中打印。 谷歌搜索显示,在这种例外情况下,程序立即终止,如果你捕获了bash的stderr,那么它应该重定向。 所以我跑

su -c ./a.out 2>err 

在错误文件中打印宾果错误。

现在主要游戏开始了 我想在沙箱下运行它 所以我跑:

su -c 'sandbox ./a.out 1>out 2>err'

但是在err文件或控制台中没有打印任何内容。

如何在这种情况下捕获stdout和stderr?

2 个答案:

答案 0 :(得分:1)

To be clear (you mention it in passing): The error you want is printed by bash. It's not printed as the dying gasp of your program. So what matters is where the shell itself is redirected.

When you did:

su -c ./a.out 2>err 

The redirection is part of the shell you executed in. The 2>err opens err as stderr for su. su creates a shell which inherits stderr and eventually prints the error.

In this version:

su -c 'sandbox ./a.out 1>out 2>err'

You've quoted the redirection '... 2>err' so the stderr of the su is not affected. The sandbox command is redirected. However, the sandbox command may or may not use a shell to run the command, or it may use exec cmd.... Either way, there is no shell waiting for your crash to print the message.

You could try:

su -c 'sandbox bash -c ./a.out 1>out 2>err'

That should ensure that there's a bash with the desired stderr around to print your result.

You can also catch this result yourself (and avoid having the shell print anything) with something like:

#!/bin/sh

./a.out &
wait $!
echo $?

Invoking it in the background will prevent the usual output. Then waiting for it (with explicit PID) will return an error code in $?. If a process exits with a signal, the error code will be 128 + signum (get the list from kill -l)

答案 1 :(得分:0)

sandbox ./a.out > pr 2> err

在你的例子中,你将stdout重定向到管道,而猫的stderr会错误。