Skip to content

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

@expikr

Description

@expikr

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);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementSolving this issue will likely involve adding new logic or components to the codebase.proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.standard libraryThis issue involves writing Zig code for the standard library.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions