LoginSignup
37
34

More than 1 year has passed since last update.

Rustで多重起動を防ぐ

Posted at

こちらの記事にインスパイアされて、私だったらこう書くかなというのを残しておきます。

使うのは flock というシステムコールです。

Man page of FLOCK

これを使って実行可能ファイルそのものをロックファイルとして排他制御すれば簡単に多重起動を防げます。

Rustから flock を使うのは*nixのAPIをラップしたライブラリ、nixを使うと便利です。

nix - crates.io: Rust Package Registry

コードはこのようになるでしょうか。

use nix::fcntl::{flock, open, FlockArg, OFlag};
use nix::sys::stat::Mode;
use nix::Result;
use std::env;
use std::thread;
use std::time::Duration;

fn main() -> Result<()> {
    // argsの0番目に実行可能ファイルの名前が入っている
    let exe = env::args().nth(0).unwrap();
    // 適当にファイルを開く
    let fd = open(exe.as_str(), OFlag::empty(), Mode::empty())?;
    // fdに対してnon blockで排他制御をする
    match flock(fd, FlockArg::LockExclusiveNonblock) {
        Ok(()) => (),
        // 本当はEAGAINかどうかを確認した方がいいが、雑でもまあいいでしょう。
        Err(e) => {
            println!("existing process!");
            return Err(e);
        }
    }

    thread::sleep(Duration::from_secs(10));
    println!("hello");
    Ok(())
}

これをコンパイルして実行してみると以下のように、排他制御できています。

$ ./target/debug/multiboot-lock&
[1] 194747
$ ./target/debug/multiboot-lock
existing process!
Error: Sys(EAGAIN)
$
hello

[1]  + done       ./target/debug/multiboot-lock

誰かの参考になれば

37
34
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
37
34