From 142fd44af0411a90c414cf40797f3bbb6a430e07 Mon Sep 17 00:00:00 2001 From: imgurbot12 Date: Thu, 23 May 2024 00:04:24 -0700 Subject: [PATCH] feat: lockfile to prevent overlapping locks --- Cargo.lock | 10 ++++++++++ Cargo.toml | 1 + src/main.rs | 9 +++++---- src/pid.rs | 33 +++++++++++++++++++++++++++++++++ 4 files changed, 49 insertions(+), 4 deletions(-) create mode 100644 src/pid.rs diff --git a/Cargo.lock b/Cargo.lock index 0aa1d63..fbff816 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -660,6 +660,7 @@ dependencies = [ "chrono", "clap", "env_logger", + "filelock-rs", "futures-intrusive", "iced_runtime", "iced_wgpu", @@ -785,6 +786,15 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "filelock-rs" +version = "0.1.0-beta.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6427c04067bba5e8ceb9a2826fe30568c7d615ff560b4a6fec7a626b528057b" +dependencies = [ + "libc", +] + [[package]] name = "fixedbitset" version = "0.4.2" diff --git a/Cargo.toml b/Cargo.toml index 3d25393..f4c91bf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ calloop = { version = "0.13.0" } chrono = "0.4.38" clap = { version = "4.5.4", features = ["derive"] } env_logger = "0.11.2" +filelock-rs = "0.1.0-beta.2" futures-intrusive = "0.5.0" iced_runtime = "0.12.1" iced_wgpu = { version = "0.12.1", features = ["image"] } diff --git a/src/main.rs b/src/main.rs index 2016b7f..8474212 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,6 +9,7 @@ mod config; mod event; mod graphics; mod lock; +mod pid; use crate::config::{Config, Settings}; @@ -112,12 +113,12 @@ impl Cli { } fn main() -> Result<()> { - // enable log and set default level - if std::env::var("RUST_LOG").is_err() { - std::env::set_var("RUST_LOG", "info"); - } env_logger::init(); + // ensure only one lock instance runs at a time + println!("making lock?"); + let _lock = pid::PidLock::new()?; + // parse cli and run lockscreen let cli = Cli::parse(); let settings = cli.settings()?; diff --git a/src/pid.rs b/src/pid.rs new file mode 100644 index 0000000..4aba257 --- /dev/null +++ b/src/pid.rs @@ -0,0 +1,33 @@ +//! PidLock Implementation + +use std::fs::{remove_file, File}; +use std::path::PathBuf; + +use anyhow::{Context, Result}; +use filelock_rs::FdLock; + +pub struct PidLock { + path: PathBuf, + lock: File, +} + +impl PidLock { + pub fn new() -> Result { + let path = xdg::BaseDirectories::new() + .context("failed to read xdg base-dirs")? + .get_runtime_file("dynlock.lock") + .context("failed to locate lockfile")?; + println!("path {path:?}"); + let lock = File::create(&path).context("failed to create lockfile")?; + lock.try_lock_exclusive() + .context("failed to lock lockfile")?; + Ok(Self { path, lock }) + } +} + +impl Drop for PidLock { + fn drop(&mut self) { + self.lock.unlock().expect("failed to unlock lockfile"); + remove_file(&self.path).expect("failed to remove lockfile"); + } +}