Skip to content

Commit 2f7cf9b

Browse files
committed
feat(main): prevent multiple instances using file lock
Introduce a file lock mechanism to ensure only one instance of the application runs at a time. This prevents resource contention and duplicate updates to SketchyBar.
1 parent 468b165 commit 2f7cf9b

File tree

3 files changed

+33
-7
lines changed

3 files changed

+33
-7
lines changed

Cargo.lock

Lines changed: 16 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
[package]
22
name = "stats_provider"
3-
version = "0.8.0"
3+
version = "0.8.1"
44
description = "A simple system stats event provider for Sketchybar."
55
edition = "2021"
66
build = "build.rs"
77

88
[dependencies]
99
anyhow = "1.0.100"
1010
clap = { version = "4.5.54", features = ["derive"] }
11+
fs2 = "0.4.3"
1112
starship-battery = "0.10.3"
1213
sysinfo = { version = "0.37.2", default-features = false, features = ["component", "disk", "network", "system"] }
1314
tokio = { version = "1", features = ["full"] }
1415

1516
[build-dependencies]
16-
cc = "1.2.51"
17+
cc = "1.2.52"

src/main.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@ mod cli;
22
mod sketchybar;
33
mod stats;
44

5+
use std::fs::File;
6+
57
use anyhow::{Context, Result};
8+
use fs2::FileExt;
69
use sketchybar::Sketchybar;
710
use stats::{
811
get_battery_stats, get_cpu_stats, get_disk_stats, get_memory_stats, get_network_stats,
@@ -255,9 +258,20 @@ async fn collect_stats_commands(
255258
Ok(updated_tick)
256259
}
257260

261+
fn acquire_lock() -> Option<File> {
262+
let file = File::create("/tmp/stats_provider.lock").ok()?;
263+
file.try_lock_exclusive().ok()?;
264+
Some(file)
265+
}
266+
258267
#[cfg(target_os = "macos")]
259268
#[tokio::main]
260269
async fn main() -> Result<()> {
270+
let _lock = match acquire_lock() {
271+
Some(lock) => lock,
272+
None => return Ok(()),
273+
};
274+
261275
let cli = cli::parse_args();
262276

263277
cli::validate_cli(&cli).context("Invalid CLI arguments")?;

0 commit comments

Comments
 (0)