代碼如下:
測試運行
#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;
}
#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);
}
}