Home > OS >  How to limit macOS process to a single instance in plain C ?
How to limit macOS process to a single instance in plain C ?

Time:12-25

I'm using the following Swift code to limit my GUI app on macOS to a single instance:

func IsAnotherInstanceRunning() -> Bool
{
    let thisApp = NSRunningApplication.current
    let thisBundleID = thisApp.bundleIdentifier
    let thisPID = thisApp.processIdentifier
    
    let workspace = NSWorkspace.shared
    
    let apps = workspace.runningApplications.filter { (app) -> Bool in
        
        if(app.bundleIdentifier == thisBundleID &&
           app.processIdentifier != thisPID)
        {
            return true;
        }
        
        return false;
    };
    
    //Found any?
    if(apps.count > 0)
    {
        return true
    }
    
    return false
}

I also have a console application written in C . How can I do the same in pure C ?

Mainly how do I call anything related to NSRunningApplication and NSWorkspace?

CodePudding user response:

I believe you can use named mutexes to achieve what you want. You create a mutex with a specific name. If mutex already exists you quit.

https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_mutexattr_getpshared.html

For crossplatform implementation make sense to take a look on https://theboostcpplibraries.com/boost.interprocess-synchronization named_mutex.

  • Related