2

In Unix/Linux you can use pipes to write output and error streams to a file. One can even write them to the same file. Is there a way to write both to the file but maintaining the order. This statement:

swipl -s jobshop.chr < CHRInput > output 2> output

indeed produces a file called "output" with both the output and error stream (normally this was the console interaction with the user). But the output stream is written before the error stream (while working with an interactive console will produce error and output streams interleaved).

5
  • Which "shell"? There's dozens. Jun 5, 2012 at 1:40
  • bin/bash. Is this relevant? I didn't knew pipes were implement different? Jun 5, 2012 at 1:47
  • Those aren't pipes. Jun 5, 2012 at 2:08
  • Then what are they? Furthermore some strange effect happen: the processes only have around 5% CPU time (since I only want to do postprocessing on the files, I wouldn't mind the system simply buffers the output until the application is finished) and a part of the output is still written on the console (with no real reason, it only happens after lets say 60 seconds). Jun 5, 2012 at 2:16
  • They're redirection. Jun 5, 2012 at 3:08

2 Answers 2

4

For bash ,

swipl -s jobshop.chr < CHRInput &> output

0
1
swipl -s jobshop.chr < CHRInput > output 2>&1

2>&1 means “redirect file descriptor 2 (standard error) to whatever file descriptor 1 (standard output) is connected to”. Note that 2>&1 has to come after the redirection of standard ouptput: 2>&1 >output would first send fd 2 to whatever fd 1 is connected to at the time (i.e. the terminal) then redirect fd 1 to the terminal.

Note that depending on how the program is written, this might not interleave the output in the same order as if it was running on a terminal. That's because many programs buffer the output on stdout, i.e. they only actually write data out when the buffer is full. But when standard output is connected to a terminal, it is line-buffered, i.e. every line is written out even if the buffer is not full. (Stderr, on the other hand, is not buffered by default.) So if the program writes full lines without taking care of flushing buffers or changning default settings and you expect that they come in order whether they were written to standard error or standard output, redirecting to a file might not work.

On reasonably recent Linux systems, if the redirected output has lines out of order, try

stdbuf -oL -oL swipl -s jobshop.chr <CHRInput >output 2>&1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .