0
sleep() function does not work as expected
I have written a simple code to understand the working of sleep() function in c. Code: int main() { FILE *fp; fp=fopen("ass1q1.txt","r"); printf("before sleep"); sleep(5); printf("\nafter"); } O/p: $ ./a.out before sleep after It sleeps for 5 secs & later displays before & after msg together. Can anyone explain how can I make it work?
5 ответов
+ 4
Your sleep function is working perfectly. It's just that the output is flushed to screen at the end of the program.
Here's how things are happening :-
1) put "before sleep" string in output buffer
2) sleep for 5 seconds
3) put "\nafter" string in output buffer.
The output buffer is then flushed to stdout after the program execution ( or before if it fills completely )
Try using "fflush(stdout)" after first print statement to flush the output buffer before and see the difference.
+ 2
I am running it on Ubuntu (via VMware)
Headers used are:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
+ 2
Thank you for your quick response!
Much appreciated!
+ 2
Ok ✌
+ 1
You need to flush output buffer
This normally happens in Linux OS.
Use fflush(stdout) after printing first string