0

I have an Test.cpp which is run under sandbox(RHEL7):

Test.cpp content:

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

compile it using gcc(4.8) Test.cpp which produces the a.out Now running a.out prints floating pointing exception on console

Now i thought that if i redirect stderr to a file, i expect the error to be printed in file. But that is not the case it still continue to print in console. Googling reveal that under such exception the program is terminated immediately and if you capture the stderr of bash then it should redirect. So i run

su -c ./a.out 2>err 

Bingo error get printed in err file.

Now the MAIN GAME STARTS i want to run it under sandbox so i run:

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

But there is nothing printed in err file or in console.

How to capture stdout and stderr under such situation ?

Bhuvan
  • 4,028
  • 6
  • 42
  • 84

2 Answers2

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)

Ben Jackson
  • 90,079
  • 9
  • 98
  • 150
0
sandbox ./a.out > pr 2> err

In your example you're redirecting stdout to the pipe, and cat's stderr to err.

izabera
  • 659
  • 5
  • 11