Wednesday 25 February 2015

Sleep function in C

Welcome to Logically Proven blog.

This post demonstrates how to make your program wait for a period of time.

It is required to wait out program for a little span of time before executing some statements. For example in case waiting for Input/Output signals.

The function sleep gives a simple way to make the program wait for a short interval. If the program doesn't use signals, then you can use sleep function to wait reliably the specified interval.

Otherwise, sleep can return sooner if a signal arrives; if you want to wait for a given interval regardless of signals, use sleep.

The sleep function is declared in unistd.h

Syntax:

unsigned int sleep (unsigned int seconds)

The sleep function waits for seconds or until a signal is delivered, whichever happens first.

The sleep function returns either requested interval is over, it returns a value zero else because of deliver of a signal, it returns a non-zero (remaining time) in the sleep interval.

You can call sleep function again if the sleep returns a non zero value as long as signals arrive infrequently. If the signals are arriving in rapid - it is difficult to decide the wait time whether to shorten or lengthen the wait time.

On some systems, sleep can do strange things if your program uses SIGALRM explicitly.

On GNU systems, it is safe to use sleep function and SIGALRM in the same program, because sleep doesn't work by means of SIGALRM.

Example:

#include <time.h>
#include <stdio.h>
#include<windows.h> 
#include <conio.h>
 
int main()
{
 printf("before sleep() function\n");
 Sleep(10); //10 seconds
 printf("after 10 seconds");
 getch();
 return 0;
}

This program waits for 10 seconds before printing "after 10 seconds".


Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.


Logically Proven
Learn, Teach, Share

Ref: GNU C Library

Karthik Byggari

Author & Editor

Computer Science graduate, Techie, Founder of logicallyproven, Love to Share and Read About pprogramming related things.

0 comments:

Post a Comment

 
biz.