简体   繁体   中英

Is it possible to implement printf() in a non blocking manner in linux terminal

I have a printf statement after sleep for 1 second. Since the printf statement takes longer than 1 second , the refresh rate is more than 2 seconds. Here is an example i am talking about :

while(1){
   printf("%s",buf);//Takes more than one second to print a table. Only few          
                    //values are updated
   sleep(1);
}

How can i have a printf to be non blocking. Is there a way in a standard linux machine ?

-Sanatan

If you only care about what shows on the screen, that is one of the problems that curses addresses. Using curses, you could update the display using reasonably optimal output (only the changed areas would be updated rather than printing the whole table each time), and with the typeahead feature, you can alleviate the problem of falling behind if the updates are too rapid.

It's more complicated than just printf . But with printf , the buffer will get full, and there is nowhere to put it except to the standard output. In some implementations, you could use setvbuf to assign a new output buffer, but POSIX frowns on that after output has started, saying :

The setvbuf() function may be used after the stream pointed to by stream is associated with an open file but before any other operation (other than an unsuccessful call to setvbuf() ) is performed on the stream.

Because of this, ncurses has treated setvbuf (and similar functions such as setbuf ) with caution. In the current release, to solve other problems, ncurses no longer uses this function. But it is still documented :

ncurses enabled buffered output during terminal initialization. This was done (as in SVr4 curses) for performance reasons. For testing purposes, both of ncurses and certain applications, this feature was made optional. Setting the NCURSES_NO_SETBUF variable disabled output buffering, leaving the output in the original (usually line buffered) mode.

The function printf is a buffered function. It only flush to stdout when the buffer is full or when you force it. If you print a \\n this will full the buffer. What you can do is to use the fflush function on stdout to force it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM