Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

std.process: add function to enforce single-instance #20278

Open
expikr opened this issue Jun 13, 2024 · 0 comments
Open

std.process: add function to enforce single-instance #20278

expikr opened this issue Jun 13, 2024 · 0 comments

Comments

@expikr
Copy link
Contributor

expikr commented Jun 13, 2024

Some apps assume they only ever have one instance of themselves running on a given system.

It might make sense to provide this functionality under the std.process namespace if the interface can be cleanly mapped to platform-specific equivalents.

Windows provides CreateMutex for a global lock that can be checked against, proof of concept:

const std = @import("std");
const win = std.os.windows;

extern "kernel32" fn CreateMutexA(?*const win.SECURITY_ATTRIBUTES, win.BOOL, win.LPCSTR) callconv(win.WINAPI) ?win.HANDLE;
extern "user32" fn MessageBoxA(?win.HANDLE, ?win.LPCSTR, ?win.LPCSTR, win.UINT) callconv(win.WINAPI) i32;

fn win32_singleton(name: win.LPCSTR) error{ Unexpected, AlreadyExists }!win.HANDLE {
    const m = CreateMutexA(null, 1, name);
    const e = win.kernel32.GetLastError();
    if (m) |h| {
        if (e == .SUCCESS) return h;
        if (e == .ALREADY_EXISTS) {
            win.CloseHandle(h);
            return error.AlreadyExists;
        }
    }
    return win.unexpectedError(e);
}

pub fn main() !void {
    _ = try win32_singleton("Hello World Program");
    _ = MessageBoxA(null, "world", "hello", 0);
}
@expikr expikr changed the title std: utility to check single instance process std: function to check for and guarantee only one running instance of the program Jun 14, 2024
@expikr expikr changed the title std: function to check for and guarantee only one running instance of the program std.process: add function to enforce single-instance Jun 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant