notifier_linux.rs56.67%
1
// Copyright 2025 Google LLC2
//3
// Licensed under the Apache License, Version 2.0 (the "License");4
// you may not use this file except in compliance with the License.5
// You may obtain a copy of the License at6
//7
// https://www.apache.org/licenses/LICENSE-2.08
//9
// Unless required by applicable law or agreed to in writing, software10
// distributed under the License is distributed on an "AS IS" BASIS,11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12
// See the License for the specific language governing permissions and13
// limitations under the License.14
15
use std::fs::File;16
use std::io::{ErrorKind, Read, Result, Write};17
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd};18
19
use libc::{EFD_CLOEXEC, EFD_NONBLOCK, eventfd};20
use mio::event::Source;21
use mio::unix::SourceFd;22
use mio::{Interest, Registry, Token};23
24
use crate::ffi;25
26
#[derive(Debug)]27
pub struct Notifier {28
fd: File,29
}30
31
impl Notifier {32
pub fn new() -> Result<Self> {48x33
let fd = ffi!(unsafe { eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK) })?;48x34
Ok(Notifier {48x35
fd: unsafe { File::from_raw_fd(fd) },48x36
})48x37
}48x38
39
pub fn notify(&self) -> Result<()> {58x40
let mut fd = &self.fd;58x41
let Err(e) = fd.write(&1u64.to_ne_bytes()) else {58x42
return Ok(());58x43
};44
if e.kind() != ErrorKind::WouldBlock {45
return Err(e);46
};47
let mut buf = [0u8; 8];48
let _ = fd.read(&mut buf)?;49
let _ = fd.write(&1u64.to_ne_bytes())?;50
Ok(())51
}58x52
}53
54
impl Source for Notifier {55
fn register(&mut self, registry: &Registry, token: Token, interests: Interest) -> Result<()> {48x56
registry.register(&mut SourceFd(&self.fd.as_raw_fd()), token, interests)48x57
}48x58
59
fn reregister(&mut self, registry: &Registry, token: Token, interests: Interest) -> Result<()> {60
registry.reregister(&mut SourceFd(&self.fd.as_raw_fd()), token, interests)61
}62
63
fn deregister(&mut self, registry: &Registry) -> std::io::Result<()> {4x64
registry.deregister(&mut SourceFd(&self.fd.as_raw_fd()))4x65
}4x66
}67
68
impl AsFd for Notifier {69
fn as_fd(&self) -> BorrowedFd<'_> {70
self.fd.as_fd()71
}72
}73