Bash save/redirect stdout and stderr when program is killed -


when programa killed external process (killed: 9), cannot redirect output (std/stderr) or save variable.

programa:

$ ./programa arg1   on stderr   on stdout   killed: 9 

failing save variable:

$ programa_output=`programa arg1` $ echo "$programa_output"  $ 

redirection file not work:

$ programa arg1 > output.txt $ cat ./output.txt $ 

any clues save / redirect output?

the immediate cause here program flushing buffers on line-by-line basis when output tty; hence, when redirected file or fifo, hasn't flushed yet when sigkill delivered -- , since sigkill can't trapped or delayed, has no opportunity perform flush @ time.

if you're on gnu platform, can use stdbuf modify behavior default:

stdbuf -o0 ./programa arg1 >output.txt 

...or...

output=$(stdbuf -o0 ./programa arg1) 

since know flushes when output tty (since output shows when run without redirection), can use unbuffer (a tool ships expect) simulate effect:

output=$(unbuffer ./programa arg1) 

however, surest thing modify source of programa explicitly perform flush operation after every write want ensure complete -- , use sigkill when absolutely required. (a common practice use sigterm, wait substantial time period, , resort sigkill).


Comments