LoginSignup
3
3

More than 1 year has passed since last update.

[Rust]多重起動処理

Last updated at Posted at 2021-06-21

同じプログラムがいくつも起動するのを防ぐ処理を作ったりする関数。

cargo.tomlに以下を追加。

cargo.toml
[dependencies]
sysinfo = "*"

スクリプト本体

use sysinfo::{System, SystemExt, ProcessExt};
use std::env::current_exe;
/// trueの場合は、他に同じ実行ファイルが起動していることを示しています。
/// ※ ただし、デバッガを介した実行の場合、let countが0になることがあるため、注意が必要です。
/// cargo.toml
/// [dependencies]
/// sysinfo = "*"
/// if is_multiple_activation() {
///     // 多重起動しているので終了。
///     std::process::exit(1);
/// }
fn is_multiple_activation() -> bool {
    let my_path = current_exe().unwrap().display().to_string();
    let mut count = 0;
    for (_, process) in System::new_all().get_processes() {
        if my_path == process.exe().display().to_string() {
            if count > 1 { return true; };
            count += 1;
        }
    }
    return count > 1;
}

自身のファイルパスをcurrent_exe().unwrap().display().to_string()で取得し、プロセス一覧から同じものがあるかどうかを調べて同じものがあればlet mut countをインクリメントし、自身以外にも起動している状態(let mut countが1以上)の状態であればtrueを返す。

注意点

このスクリプトはデバッガーを介して使用した場合、自身をカウントせず、let mut countが0となる場合がある。

使用例

main.rs
// タイマー用
use std::thread;
use std::time::Duration;

fn main() {
    if is_multiple_activation() {
        println!("multi activation!");
        thread::sleep(Duration::from_secs(3));
        std::process::exit(1);
    }
    // 5秒後に終了するプログラム
    thread::sleep(Duration::from_secs(5));
}
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3