-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: don't allow to run multiple instances of the app
- Loading branch information
Showing
4 changed files
with
94 additions
and
6 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
extern crate nix; | ||
|
||
pub use self::inner::*; | ||
|
||
mod inner { | ||
use nix::sys::socket::{self, UnixAddr}; | ||
use nix::unistd; | ||
use nix::Result; | ||
use std::os::unix::prelude::RawFd; | ||
|
||
/// A struct representing one running instance. | ||
pub struct SingleInstance { | ||
maybe_sock: Option<RawFd>, | ||
} | ||
|
||
impl SingleInstance { | ||
/// Returns a new SingleInstance object. | ||
pub fn new(name: &str) -> Result<Self> { | ||
let addr = UnixAddr::new_abstract(name.as_bytes())?; | ||
let sock = socket::socket( | ||
socket::AddressFamily::Unix, | ||
socket::SockType::Stream, | ||
socket::SockFlag::empty(), | ||
None, | ||
)?; | ||
|
||
let maybe_sock = match socket::bind(sock, &socket::SockAddr::Unix(addr)) { | ||
Ok(()) => Some(sock), | ||
Err(nix::errno::Errno::EADDRINUSE) => None, | ||
Err(e) => return Err(e.into()), | ||
}; | ||
|
||
Ok(Self { maybe_sock }) | ||
} | ||
|
||
/// Returns whether this instance is single. | ||
pub fn is_single(&self) -> bool { | ||
self.maybe_sock.is_some() | ||
} | ||
} | ||
|
||
impl Drop for SingleInstance { | ||
fn drop(&mut self) { | ||
if let Some(sock) = self.maybe_sock { | ||
// Intentionally discard any close errors. | ||
let _ = unistd::close(sock); | ||
} | ||
} | ||
} | ||
} |