Using a T-piece with a continuous output of the C program

It should be really easy, but I can't catch it.

This is a trivial C entry to stdout:

root@oceanLondon:~/tst# cat tst.c
#include <stdio.h>
#include <unistd.h>

int
main(int argc, char **argv)
{
        for (; ;) {
                printf("Hello world!\n");
                sleep(1);
        }
        return 0;
}

      

Now if I want to write the output to my screen and file:

root@oceanLondon:~/tst# ./tst |tee file

      

it just doesn't work, i have blank screen and blank file.

If I execute the program that exits, then it works fine, eg.

root@oceanLondon:~/tst# ls |tee file
Makefile
file
qq
tst
tst.c
tst.o
root@oceanLondon:~/tst# cat file
Makefile
file
qq
tst
tst.c
tst.o
root@oceanLondon:~/tst#

      

Is this some kind of buffering problem? And can anyone help me make a triple in the continuation program please?

+3


source to share


2 answers


The standard output stream is line buffered if the stream can be specified to refer to an interactive device (like a terminal), otherwise it is fully buffered, so there are times when it printf

doesn't flush even if it has a new line to print. for example, with channel or redirected output;

> tst | tee file
> tst > file

      

Calling fflush(stdout)

after printf()

will solve the problem.



The linked text from the section C99

7.19.3

states that:

When the stream is unbuffered, characters should appear from the source or destination as soon as possible. Otherwise, characters can accumulate and be transmitted to or from the host environment as a block.

When a stream is fully buffered, characters must be transferred to or from the host environment as a block when the buffer is full.

When a stream is line-buffered, characters must be transferred to or from the host environment as a block when a newline character is encountered.

As originally discovered, standard error is not fully buffered; standard input and standard output streams are fully buffered if and only if the stream can be defined not to refer to an interactive device.

+2


source


Your problem seems to be stdout

buffered and not displayed after the newline. You can make it display it by dumping it after the printf statement:

fflush(stdout); 

      

Alternatively, you can turn off buffering with:



setbuf(stdout, NULL);

      

Also note that it is stderr

not buffered and you can check if the problem is buffered by printing on stderr

instead stdout

.

As you noticed, you can also use stdbuf

(more on this in this answer ).

0


source







All Articles