How to pause between functions in a program in C with GCC? - c

So my problem is my program runs too fast that I can't see how it behaves. It's supposed to make the text crawl along the edges of the terminal. I tried to use sleep() to make a short pause betweenprintf(...)s so that it I can see where the text us going while it prints.
This is what it looks like:
http://i.imgur.com/B6FFbNp.gif
So I put sleep() function after the printfs so that it will pause before starting the loop again and make the text move slowly. But what happens is it pauses the programs indefinitely before it even starts. This also happens with usleep and system("pause 1"). This is what it looks like:
http://i.imgur.com/krGW3lB.gif
==================================================================================
EDIT:
Okay, I figured it out on my own. It seems that sleep() only works if I put \n in my strings. I don't know why. I didn't even read this in the damn manuals.
So if you have
printf("HELLO\n");
sleep(3);
printf("HELLO\n");
sleep(3);
printf("HELLO\n");
It will result in:
HELLO
[pause for 3 seconds]
HELLO
[pause for 3 seconds]
HELLO
but if you remove the newline characters it will:
[pause for 9 seconds]
HELLO HELLO HELLO
I don't know why this happens but it just does
==================================================================================
EDIT:
This is how I wanted my program to work:
http://i.imgur.com/DXv7E60.gif
Thank you for your answers

Your observations do not due to sleep() not working, but to the fact that printf() uses stdout, which is line buffered. "line buffered" means, that what has been written to stdoutis buffered until the end of the line is reached before the buffer's content it is flushed out.
So after the first printf("HELLO"); the output does not go to the screen but stays in the buffer, then sleep(1); is executed and makes you wait. Then for the next printf("HELLO"); the output still does not go to the screen, but the following sleep(1); again makes you wait for 1 second ... and so on until a line end if reached by your program printing a '\n' or by the program's end, which implicitly flushes the output buffer to the console.
You can avoid the behaviour by flushing stdout's output buffer explicitly after every printf():
#include <stdio.h>
#include <unistd.h>
int main(void)
{
printf("HELLO");
fflush(stdout);
sleep(3);
printf("HELLO");
fflush(stdout);
sleep(3);
printf("HELLO");
/* fflush(stdout); */ /* not needed as buffers are implicitly flushed on the program's end */
return 0;
}

A quick hack I usually do is make some buffer array (eg. char buf[10]) and place an fgets() in between iterations, which forces the program to wait for a newline from the user. So, for example, if we had:
.
.
.
for(i = 0; i < 1000000; ++i)
printf("%d\n", i);
we could then do
.
.
.
char buf[10];
for(i = 0; i < 1000000; ++i){
printf("%d\n", i);
fgets(buf, 10, stdin);
}
and control the iterations with the enter key.
We could also stop every nth iteration by using a modulus. Using the above example, we will now stop every 100 iterations:
.
.
.
char buf[10];
for(i = 0; i < 1000000; ++i){
printf("%d\n", i);
if(i % 100 == 0)
fgets(buf, 10, stdin);
}
A more time consuming but effecient way is to use a dedicated debugger like GDB.

Related

Print number for each second

#include <stdio.h>
#include <wiringPi.h>
#include <softPwm.h>
int main(void)
{
wiringPiSetupGpio();
for(int i = 0 ; i <50; i++)
{
if ( i%10 == 1)
{
printf("\n");
}
printf("%d ", i);
delay(1000);
}
return 0;
}
I'm working in rasberry pi environment.
I want to print a number for each 1 second. But this code did not print a number one by one but
print 10 numbers for each 10 seconds. This code gives 10 numbers in line at once. What's the problem??
The stdout channel is line buffered by default. This means that data sent to stdout won't necessarily appear until a newline character is printed.
If you call fflush(stdout), any buffered output will be immediately printed.
printf("%d ", i);
fflush(stdout);
in order to print the values at the running time using printf you need to add \n so try this may work.
#include <stdio.h>
#include <wiringPi.h>
#include <softPwm.h>
int main(void)
{
wiringPiSetupGpio();
for(int i = 0 ; i <50; i++)
{
if ( i%10 == 1)
{
printf("\n");
}
// a `\n` added at the end of the string!
printf("%d \n", i);
delay(1000);
}
return 0;
}
for more info read this question's answer
The problem is probably that the output stream is not being flushed. I suggest that you call fflush( stdout ); before the delay(1000); function call. This will ensure that all printed data actually becomes observable, before the program enters a wait state.
Normally, it is not necessary to explicitly flush an output stream, because the output will become visible sooner or later. For example, the output buffer will usually get implicitly flushed whenever you read input or when the program ends. Also, if your program is writing output to the user's screen (in contrast to, for example, writing output to a file), then the output stream is probably line-buffered, which means that the output stream will get implicitly flushed whenever a newline character is written.
However, in this case, it appears that the implicit flushing mentioned above is not sufficient. Therefore, you will have to revert to explicit flushing using the function fflush, as mentioned above.

I use sleep function in ubuntu ,but printf function run very slowly in while loop. why?

I use ubuntu 14.04 version system for below code.
I use below code : (below code is infinite Loop)
#include <stdio.h>
#include <unistd.h>
int flag=0;
int main(void){
printf("program start.\n");
printf("PID=%d\n",getpid());
printf("flag=%d\n",flag);
//-----------I feel weired below do...while... sentences----------//
do{
printf("loop_");
sleep(1);
}while(flag==0);
printf("program exit.\n");
return 0;
}
in the beginning below print result :
root#ubuntu:~/Desktop/my_test_code# ./issue
program start.
PID=3113
flag=0
...........//start waiting here,and don't print "loop_"
then after I waited for long time this program prints a lot of "loop_".
I find it very strange, and should print a string "loop_" and then, wait a second, then print a "loop_" again, and so on, why me waiting for a long time, do it start to print a lot of "loop_" ?
anybody has any idea for my issue . thank you in advance.
printf bufferizes its output (until a given size or \n), so you don't see the output until it flushes it.
changing your loop to
printf("loop_");
fflush(stdout);
sleep(1);
should solve your issue.
Root cause:
Usually stdout's buffer are getting flushed by \n so here loop goes on and stdout did not get chance to buffered its data properly.
Solution:
There are three way here
1) Use \n at the end of printf
printf("loop_\n");
2) call fflush(stdout): after printf in loop.
3) Disabled the buffering for stdout stream using below call in your program
setvbuf(stdout, NULL, _IONBF, 0);

Printf and sleep inside for loop? [duplicate]

This question already has answers here:
Why does printf not flush after the call unless a newline is in the format string?
(10 answers)
Closed 6 years ago.
I can't understand why following code works like this..I mean: instead of printing "hello" after each one second delay...it wait 5 second and display hellohellohellohellohello at once.
#include <stdio.h>
int i;
for(i=0; i<5; i++) {
printf("hello");
sleep(1);
}
The output of printf() (stdout) is line buffered by default if the output is going to a tty. You need one of
printf("hello\n");
or
printf("hello");
fflush(stdout);
The latter will explicitly flush the output each iteration.
printf do not print immediatly, instead it cache it line per line.
Add "\n" (newline) add the end of your string printf("hello\n"); or use write function instead write(STDOUT_FILENO, "hello", sizeof("hello"));.
You are writing to standard output (stdout), which is buffered. If you want the content to be immediately printed, you may flush the output or insert a newline.
You can add a \n to the end of your string so as to print the newline -- change your printf line to:
printf("hello\n");
For flushing the stdout buffer call fflush on it, after the printf:
#include <stdio.h>
int main() {
int i;
for(i=0; i<5; i++) {
printf("hello");
fflush(stdout);
sleep(1);
}
}
In general the output can be buffered. That means the implementation collects several bytes before actually writing to the console. You can explicitly write the buffer by fflush(stdout). This is true for all file descriptors, one of which is stdout, the terminal output. You can disable the buffering with setbuff(stdout, NULL), but this is almost never a good idea performance wise.
Try this:
int i;
for(i=0;i<5;i++){
printf("hello\n");
i=0;
sleep(1);
}

Strange Behaviour because of sleep()

I was just getting familiar with sleep(), i found that
#include<stdio.h>
int main()
{
int i=0;
printf("*********Testing Sleep***********\n");
for(i=0;i<10;i++)
{
printf("%d",i);
sleep(1);
}
return 0;
}
this does not print number per iteration rather dumps all numbers when gets out of loop....
but when i modify printf...
#include<stdio.h>
int main()
{
int i=0;
printf("*********Testing Sleep***********\n");
for(i=0;i<10;i++)
{
printf("%d\n",i);
sleep(1);
}
return 0;
}
and now as i've added '\n' new line it works as expected... why it is behaving strangely in former one...
This is because the output buffer isn't being flushed (in other words, actually committed to the terminal). When you write a newline, the output buffer is more likely to be (but still not always, in some cases) flushed. Many terminal implementations do this to improve performance. To force the behaviour you want, you need to call fflush(stdout); after each printf call, like this:
#include<stdio.h>
int main()
{
int i=0;
printf("*********Testing Sleep***********\n");
for(i=0;i<10;i++)
{
printf("%d",i);
fflush(stdout);
sleep(1);
}
return 0;
}
What you are looking at is line buffered output. Actually writing to output is an expensive operation, so I/O streams are usually buffered. Actually writing the buffer is deferred until a specific event is encountered. In standard C, you have three types of buffering:
fully buffered - the buffer is written when full.
line buffered - the buffer is written when a newline is encountered (your case).
unbuffered - the buffer is written whenever an I/O function is executed. (Good for error logging.)
Writing the buffer is called flushing. That's why there is a stdio function called fflush(). You might also want to check out setvbuf() and its parameter constants, _IOFBF, _IOLBF and _IONBF. I am sure you can figure out what they mean without looking them up. ;-)
Edit: This program delivers as you originally expected:
#include <stdio.h>
// This is the header where sleep() is declared. Don't go without it.
#include <unistd.h>
int main()
{
int i=0;
// setvbuf() can be called on a stream only BEFORE
// you do any I/O on it!
setvbuf( stdout, NULL, _IONBF, 0 );
printf( "*********Testing Sleep***********\n" );
for ( i = 0; i < 10; ++i )
{
printf( "%d", i );
sleep( 1 );
}
return 0;
}
standard output for terminals is line buffered, output is not written unless there is a newline or you manually flush it.
Output is buffered, so that that the OS has an opportunity to optimize output speed. To make sure they are flushed immediately, do fflush (stdout);, but usually, you don't.
This is because printf() uses buffered output for better performance. Buffer is flushed to the console once \n is printed.
Printf is buffered.
You can force printf to 'flush' its buffer using the fflush call.
Or
Simply push the buffer to stdout using \n as in your case .
More detailed discussion is here

Why does printf() not print anything before sleep()?

I'm just learning C with Kernighan and Ritchie's book; I'm in the basics of the fourth chapter ("Functions and Program Structure"). The other day I became curious about the sleep() function, so tried to use it like this:
#include <stdio.h>
#include <unistd.h>
int main(void)
{
printf(" I like cows.");
sleep(5);
return 0;
}
The problem is the output of the program, it looks like it does the sleep() first and then the printf(), in other words, it waits five seconds and then prints the string. So I thought, maybe the program gets to sleep() so fast that it doesn't let printf() have his work done like I want, that is print the string and then sleep.
How can I show the string and then put the program to sleep?
The compiler is GCC 3.3.5 (propolice) in OpenBSD 4.3.
printf() writes to stdout (the default output stream) which is usually line buffered. The buffer isn't flushed by the time sleep is called so nothing is displayed, when the program exits all streams are automatically flushed which is why it prints right before exiting. Printing a newline will usually cause the stream to be flushed, alternatively you could use the fflush function:
int main(void)
{
printf(" I like cows.\n");
sleep(5);
return 0;
}
or:
int main(void)
{
printf(" I like cows.");
fflush(stdout);
sleep(5);
return 0;
}
If you are printing to a stream that is not line buffered, as may be the case if stdout is redirected or you are writing to a file, simply printing a newline probably won't work. In such cases you should use fflush if you want the data written immediately.
Your problem is that printf (and anything else that uses the stdio library to write to stdout (standard output)) is buffered - line buffered if it goes to the console, and size buffered if it goes to a file. If you do a fflush(stdout); after the printf, it will do what you want. You could try just adding a newline ('\n') to your string, and that would do the right thing as long as you don't redirect standard output to a file.
I'm not 100% sure, but I think stderr isn't buffered, which can cause confusion because you might see output you made to stderr before output you previously made to stdout.
Buffering means that all the output is stored in a place (called buffer) and is output after a certain amount of data is present in it. This is done for efficiency reasons.
Some (most?) implementations clear the buffer after a newline when writing to the console, so you can also try
printf(" I like cows.\n");
instead of the call to fflush()
I implemented time encounter as following;
for (int i = 1; i <= 60; i++) {
printf("%02d", i);
fflush(stdout);
sleep(1);
printf("\b\b");
}

Resources