The code is as follows:
#include <stdio.h>
#include <signal.h>
#include <errno.h>
/*static volatile Atomic variable*/
static volatile sig_atomic_t Sigflag = 0;
/*private Signal Control handler*/
static void Turnflag (int no) {
Sigflag = (Sigflag = = 0)? 1:0;
}
/**
* Set Signal Handler
* If error return-1
* or return 0
*/
int Inithandler (int signo) {/*signal macro*/
/*using sigaction function Need this struct*/
struct Sigaction Act;
Act.sa_handler = Turnflag; /*set Signal function*/
Act.sa_flags = 0;/*meaning Sigaction is pure action*/
if ((Sigemptyset (&act.sa_mask) = = 1) | |/*get empty mask*/
(Sigaddset (&act.sa_mask,signo) = = 1) | | /*add Signo into mark*/
(Sigaction (signo,&act,null) = = 1)) /*execute function*/
return-1;
return 0;
}
/*control Signal,main method is suspeed signal and restore signal
* If error return-1,or return 0*/
int controlsig (int signo) {
/*actunblock variable mean no block mask
* Actblock variable meaning need to block mask
* Actold is original mask for restore
* */
sigset_t Actunblock,actblock,actold;
if ((Sigprocmask (sig_setmask,null,&actunblock) = = 1) | |
(Sigprocmask (sig_setmask,null,&actblock) = = 1) | |
(Sigaddset (&actblock,signo) = = 1) | |
(Sigdelset (&actunblock,signo) = = 1) | |
(Sigprocmask (sig_block,&actblock,&actold) = = 1))
return-1;
while (Sigflag!= 0)
Sigsuspend (&actunblock);
if (Sigprocmask (sig_setmask,&actold,null) = =-1)
return-1;
return 0;
}
Test run
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include "Mystring.h"
#include "file.h"
#include "Tools.h"
#include "Myerror.h"
#include "Restart.h"
#include "Passwd.h"
#include "Sig.h"
int main (int argc,char *argv[]) {
static struct stat oldsize,newsize;
const char *filepath = "Makefile";
const int SLEEPN = 2;
int signo = SIGINT;
if (stat (filepath,&oldsize) = =-1)
return-1;
for (;;) {
if (Inithandler (signo) = =-1) {
Myerror ("Init handler error");
return-1;
}
if (Controlsig (signo) = =-1) {
Myerror ("Control sig error");
return-1;
}
if (stat (filepath,&newsize) = =-1)
return-1;
if (newsize.st_size!= oldsize.st_size) {
Oldsize.st_size = newsize.st_size;
fprintf (stderr, "Check your file!%s\n", "07");
}
Sleep (SLEEPN);
}
}