How Can I Ensure Only One Instance of My Go Application Runs on Windows?

Mary-Kate Olsen
Release: 2024-11-28 02:12:14
Original
820 people have browsed it

How Can I Ensure Only One Instance of My Go Application Runs on Windows?

Achieving a Single Instance Executable with Golang on Windows

Running multiple instances of an executable can lead to unexpected behaviors and resource contention. To prevent this, you may wish to restrict your Golang application to a single active instance.

Using Global Mutex for Instance Control

A common approach to enforce single instance execution is through the use of a global mutex. A mutex, or mutual exclusion object, allows only one process to gain exclusive access to a shared resource at any given time. In this case, our shared resource is the running executable.

Implementation on Windows

To create a global mutex in Golang for Windows, you can utilize the CreateMutexW function provided by the kernel32.dll. This function takes several arguments, including the name of the mutex. For cross-user session compatibility, it's recommended to prefix the mutex name with "Global".

In the provided code snippet, a function called CreateMutex is defined that abstracts the CreateMutexW function. You can use this function to create a global mutex by passing a unique name, such as "SomeMutexName".

Here's the modified code snippet:

import (
    "syscall"
    "unsafe"
)

var (
    kernel32        = syscall.NewLazyDLL("kernel32.dll")
    procCreateMutex = kernel32.NewProc("CreateMutexW")
)

func CreateMutex(name string) (uintptr, error) {
    ret, _, err := procCreateMutex.Call(
        0,
        0,
        uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(name))),
    )
    switch int(err.(syscall.Errno)) {
    case 0:
        return ret, nil
    default:
        return ret, err
    }
}

// mutexName starting with "Global\" will work across all user sessions
_, err := CreateMutex("SomeMutexName")
Copy after login

By creating and setting a global mutex, your Golang application can ensure that only one instance is running at a time. If another instance attempts to execute, it will be blocked until the initial instance terminates, effectively restricting the executable to a single active instance.

The above is the detailed content of How Can I Ensure Only One Instance of My Go Application Runs on Windows?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template