Problem with program's output redirection
I am supposed to put the following command in the system function argument in a C program.
$ timed-run 20 prog1 1 1>/开发者_如何学编程dev/null 2>abc.dat
timed-run
is supposed to execute prog1
up to 20 seconds and then terminate it. I want the output of prog1
to be redirected to abc.dat
. Is there any solution for this?
Thanks
When you write "1> /dev/null", you are redirecting the output of the program to the bit-bucket. (That is, you are discarding it.) If you write "1>filename" instead, the output will go to the named file.
For redirecting child process output there are several ways, Following 2 are the most importants:
- popen() (The easy one to understand and use, but popen works only with stdout of child, but you can redirect stderr to stdout as well by appending to command line string "2>&1")
- pipe fork and exec trio will help you (there are lot of info about this functions in internet)
I suspect, but can't know without seeing the prog1
source code, that prog1
is not flushing its output buffers. That is, it has code that looks like:
i = 42;
fprintf(stderr, "result: %d\n", i);
The formatted output (i.e. "result: 42\n") is being stored in stderr
's output buffer waiting for an opportune to be written. But, before that can happen, timed-run
kills prog1
with a signal.
Your choices are to either call fflush(stderr)
periodically, change the buffering type (with setbuf
or setvbuf
), or catch the signal and call fflush(stderr)
at program termination.
精彩评论