qt icon indicating copy to clipboard operation
qt copied to clipboard

Single instance best practice

Open tapir opened this issue 6 years ago • 5 comments

Is there a way to limit an app to have a single process instance as in you can only run the app only once? This is probably not a QT/Go specific thing but I wanted to ask just in case if QT has a specific way to do it.

tapir avatar May 21 '19 12:05 tapir

You can use QtSingleApplication in your projects.

apocelipes avatar May 21 '19 14:05 apocelipes

Hey

I will try to get an example for the QtSingleApplication working once I find some time.

In the meantime you could take a look here: https://rosettacode.org/wiki/Determine_if_only_one_instance_is_running#Go

A quick and dirty Go solution could look like this:

package main

import "net"

func main() {
	if _, err := net.Listen("tcp", "localhost:34567"); err != nil {
		println("another instance is already running")
		return
	}
	println("application started")

	select {}

	//NewQApplication
	//...
	//QApplication_Exec
}

therecipe avatar May 21 '19 22:05 therecipe

Thanks, I've used a global mutex for now but it only works for Windows. I'll try QtSingleApplication as well.

tapir avatar May 22 '19 07:05 tapir

Looks like QtSingleApplication is deprecated. https://forum.qt.io/topic/71778/what-happened-to-qtsingleapplication

I can't even find it in Qt5 docs: https://doc.qt.io/qt-5/index.html?search=QtSingleApplication

It is said that we should use QLocalSocket and QLocalServer. I wonder if there is simpler approach with this library, since it already talks to qtbox through rpc, and I guess that's why when you run the same application twice, the second instance crashes, and first instance freezes which you have to kill manually!

If we could just ask qtbox if app is running, or just check if qtbox process for this app is running, and exit if it is, that would solve biggest part of the problem (ideally you want to show the running instance's window when you run again).

ilius avatar Apr 11 '23 12:04 ilius

I ended up using standard Go http server and client: https://github.com/ilius/ayandict/blob/main/pkg/server/server.go https://github.com/ilius/ayandict/blob/main/pkg/application/client.go

ilius avatar Apr 17 '23 23:04 ilius