Implementation principle of linux sleep()

http://www.judymax.com/archives/235

The implementation of sleep() is divided into three steps:

            1. Register a signal signal (SIGALRM, handler). Receive a signal from the kernel.

            2. Call the alarm() function.

            3.pause() suspends the process.

 

 

Example code:

 

#include <stdio.h>

#include <stdlib.h>

#include <signal.h>

#include <unistd.h>

 

 

///Clock programming alarm()

void wakeUp()

{

      printf("please wakeup!!/n");

}

int main(void) {

      printf("you have 4 s sleep!/n");

 

     signal(SIGALRM,wakeUp);

     alarm(4);

     pause();

 

     printf("good morning!/n");

 

    return EXIT_SUCCESS;

}

 

 

Analysis: I think the key is pause(). When this function is executed, the current process is suspended, and after 4 seconds of the clock alarm function, the kernel sends a SIGALRM signal. A handler that causes control to pass from the pause function to the signal. The code in the signal handler is executed, and control returns. When the signal is processed, the pause function returns and the process continues.

The execution result is:

 

you have 4 s sleep!

please wakeup!!

good morning!

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326349809&siteId=291194637