您的位置:首页 > 其它

检测创建文件或删除文件会报告:信号处理机制

2016-06-27 14:18 330 查看
#include<stdio.h>
#define _GNU_SOURC
#include<fcntl.h>
#include<stdlib.h>
#include<signal.h>
#include<unistd.h>
static void handler_d(int sig,siginfo_t *s,void* data)
{
int even_fd,even_pid;
even_fd=s->si_fd;
even_pid=s->si_pid;
printf("process:%d,has deleted something from fd:%d\n",even_pid,even_fd);
}
static void handler_m(int sig,siginfo_t *s,void* data)
{
int even_fd,even_pid;
even_fd=s->si_fd;
even_pid=s->si_pid;
printf("process:%d,has motified something from fd:%d\n",even_pid,even_fd);
}
int main()
{
struct sigaction act_d,act_m;
int fd1,fd2;
pid_t pid;
pid=fork();
if(pid<0)
{
printf("error\n");
exit(1);
}
else if(pid==0)
{//child
fd1=open("/home/xiaozhi",O_RDONLY);
if(fd1==-1)
{
printf("open /home/xiaozhi fail\n");
}

fd2=open("/home/rz",O_RDONLY);
if(fd2==-1)
{
printf("open /home/rz fail\n");
}
act_m.sa_sigaction=handler_m;
sigemptyset(&act_m.sa_mask);
act_m.sa_flags=SA_SIGINFO;

sigaction(SIGRTMIN+2,&act_m,NULL);

fcntl(fd1,F_SETSIG,SIGRTMIN+2);
fcntl(fd1,F_NOTIFY,DN_MODIFY|DN_MULTISHOT);

fcntl(fd2,F_SETSIG,SIGRTMIN+2);
fcntl(fd2,F_NOTIFY,DN_MODIFY|DN_MULTISHOT);

while(1)
{
pause();
}

}
else
{
//father
fd1=open("/home/xiaozhi",O_RDONLY);
if(fd1==-1)
{
printf("open /home/xiaozhi fail\n");
}

fd2=open("/home/rz",O_RDONLY);
if(fd2==-1)
{
printf("open /home/rz fail\n");
}
act_d.sa_sigaction=handler_d;
sigemptyset(&act_d.sa_mask);
act_d.sa_flags=SA_SIGINFO;

sigaction(SIGRTMIN+1,&act_d,NULL);
fcntl(fd1,F_SETSIG,SIGRTMIN+1);
fcntl(fd1,F_NOTIFY,DN_MODIFY|DN_MULTISHOT);

fcntl(fd2,F_SETSIG,SIGRTMIN+1);
fcntl(fd2,F_NOTIFY,DN_MODIFY|DN_MULTISHOT);
while(1)
{
pause();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  信号