Skip to content

Commit

Permalink
feat: lockfile to prevent overlapping locks
Browse files Browse the repository at this point in the history
  • Loading branch information
imgurbot12 committed May 23, 2024
1 parent 39a97e1 commit 142fd44
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 4 deletions.
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand Down
9 changes: 5 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ mod config;
mod event;
mod graphics;
mod lock;
mod pid;

use crate::config::{Config, Settings};

Expand Down Expand Up @@ -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()?;
Expand Down
33 changes: 33 additions & 0 deletions src/pid.rs
Original file line number Diff line number Diff line change
@@ -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<Self> {
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");
}
}

0 comments on commit 142fd44

Please sign in to comment.