簡體   English   中英

如何在純 C++ 中將 macOS 進程限制為單個實例?

[英]How to limit macOS process to a single instance in plain C++?

我正在使用以下 Swift 代碼將 macOS 上的 GUI 應用程序限制為單個實例:

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
}

我還有一個用 C++ 編寫的控制台應用程序。 我怎樣才能在純 C++ 中做同樣的事情?

主要是如何調用與NSRunningApplicationNSWorkspace相關的任何內容?

我相信您可以使用命名互斥鎖來實現您想要的。 您創建一個具有特定名稱的互斥體。 如果 mutex 已經存在,則退出。

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

對於跨平台實現,查看https://theboostcpplibraries.com/boost.interprocess-synchronization named_mutex 是有意義的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM