1. Where this code is noted:
Alarm () function is not a blocking function, the program will continue to run down after timing;
Pause () block function, which is called after the function is invoked, causing the program to hang.
2. This place is apt to be crooked; The problem was this:
Join the program after the execution of 38 lost CPU resources, then when it gets CPU resources and the signal has been issued, the program will not wake up, the answer is no.
Because, the alarm () function uses the natural timing method, when the time is up, the signal has been issued by the kernel, assuming that the program to obtain the CPU resources, initially, the kernel will first signal processing, after processing the signal, and then adjust the
Pause () function, when the signal has been sent and processed, it will not receive a signal, will not be awakened, causing the program to hang permanently.
The understanding at the time was that the processing and sending of signals was always handled by the kernel, regardless of whether the pause function was called or not;
1. Therefore, if the pause function is not called, it will not receive a signal and will not be awakened;
2. When a signal is added, the pause function is called by the system and it receives a signal and is awakened.
3.alarm function call, the program will continue to execute, do not stop, this must be understood correctly.
1#include <stdio.h>2#include <stdlib.h>3#include <unistd.h>4#include <signal.h>5#include <errno.h>6 7UnsignedintMysleep (unsignedintseconds);8 voidDo_sth (inta);9 intMainintargcChar*argv[])Ten { One if(ARGC! =2) A { -printf"./a.out string\n"); - return-1; the } - //permanent sleep, every n wonderful awakening; - while(1) - { +Mysleep ((unsignedint) Atoi (argv[1]));//sleep Time: The second parameter of the command line, after waking up, print; -printf"---------Sleep%d s late\n", Atoi (argv[1])); + } A return 0; at } - -UnsignedintMysleep (unsignedintseconds) - { - intret; -UnsignedintUnusetime; in - //Create a variable and assign it a value to structSigaction Act, oldact; +Act.sa_handler =Do_sth; -Act.sa_flags =0; theSigemptyset (&act.sa_mask); * $Sigaction (SIGALRM, &act, &oldact);//Set snapping functionsPanax Notoginseng -Alarm (seconds);//set the alarm, note that it is not a blocking function, and will continue to run down here the +ret = Pause ();//Set the Pause function, the program calls this function, falls into the block, waits for the signal to wake up, must be the capture signal. A if(ret = =-1&& errno = =eintr) the { +printf"Have catch sigalarm\n"); - } $ $Unusetime = Alarm (0);//return the remaining time - -Sigaction (SIGALRM, &oldact, NULL);//Set snapping functions the returnUnusetime; - Wuyi } the - voidDo_sth (inta) Wu { -printf"=======catch==========\n"); About}
Self-fulfilling sleep function