我让我的守护进程使用 fanotify API 来控制对文件的访问。这是工作线程:
void * threadProc( void * data )
{
if( data == NULL ) return 0;
RealTimeDrvrImp & _this = *( ( RealTimeDrvrImp * )data );
const unsigned int fi_flags = FAN_CLOEXEC | FAN_CLASS_CONTENT | FAN_NONBLOCK;
const unsigned int fi_event_f_flags = O_RDONLY | O_LARGEFILE;
_this.m_fa_fd = fanotify_init( fi_flags, fi_event_f_flags );
if (-1 == _this.m_fa_fd )
return NULL;
const unsigned int fm_flags = FAN_MARK_ADD | FAN_MARK_MOUNT;
const uint64_t fm_event_f_flags = FAN_OPEN_PERM /*| FAN_ACCESS_PERM*/ /*| FAN_CLOSE_WRITE*/;
if (-1 == fanotify_mark( _this.m_fa_fd, fm_flags, fm_event_f_flags, 0, "/" ) )
{
close( _this.m_fa_fd );
return NULL;
}
char buf[4096];
int len = 0;
struct timespec tmsp = { 0, 1000000 };//500 miliseconds
pid_t self_pid = getpid();
while( _this.m_DoAvRealtimeScanThread )
{
if(-1 == ( len = read(_this.m_fa_fd, (void *) &buf, sizeof (buf))) )
{
if( EAGAIN == errno )
{
nanosleep( & tmsp, NULL );
continue;
}
else
break;
}
const struct fanotify_event_metadata *metadata
= (struct fanotify_event_metadata *) buf;
while (FAN_EVENT_OK(metadata, len)) {
if (metadata->fd != FAN_NOFD ) {
if (metadata->fd >= 0)
{
bool bCloseFdNow = true;
if( metadata->mask & FAN_OPEN_PERM ||
metadata->mask & FAN_ACCESS_PERM )
{
bool bWriteNow = true;
struct fanotify_response response = {0,0};
response.fd = metadata->fd;
response.response = FAN_ALLOW;
if( metadata->pid == self_pid )
{//this process event, always allow
}
else if( _this.IsReplyReadyNow( response ) )
{//response.response is set in IsReplyReadyNow();
}
else //else event is added to a queue,
//will be handled and closed later in another thread
{
bCloseFdNow = false;
bWriteNow = false;
}
if( bWriteNow )
{
pthread_mutex_lock( & _this.m_faWriteMtx );
write( _this.m_fa_fd, &response, sizeof (struct fanotify_response ) );
pthread_mutex_unlock( & _this.m_faWriteMtx );
}
}
if( bCloseFdNow )
close( metadata->fd );
}
}
metadata = FAN_EVENT_NEXT(metadata, len);
}
}
close( _this.m_fa_fd );
_this.m_fa_fd = -1;
return NULL;
}
它工作正常。如果我在重新启动或关闭之前停止守护进程,一切正常。但是,如果我试图在守护进程运行的情况下重新启动系统或关机,系统就会冻结。
我认为系统可能会在重新启动/关闭时将 SIGSTOP 发送到它的守护进程,对吗?如果是这样,守护进程不允许访问任何文件并锁定系统?
请帮忙。
我正在使用带有内核 3.11.0 的 Ubuntu 12.04 64 位。