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?

14th Jun 2021, 4:08 PM
Shweta Gare
Shweta Gare - avatar
5 Réponses
+ 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.
14th Jun 2021, 4:31 PM
Arsenic
Arsenic - avatar
+ 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>
14th Jun 2021, 4:27 PM
Shweta Gare
Shweta Gare - avatar
+ 2
Thank you for your quick response! Much appreciated!
14th Jun 2021, 4:33 PM
Shweta Gare
Shweta Gare - avatar
+ 2
Ok ✌
14th Jun 2021, 4:59 PM
MikkyTech
MikkyTech - avatar
+ 1
You need to flush output buffer This normally happens in Linux OS. Use fflush(stdout) after printing first string
15th Jun 2021, 5:27 AM
🌀 Shail Murtaza شعیل مرتضیٰ
🌀 Shail Murtaza شعیل مرتضیٰ - avatar