Every time I run my project in Qt Creator, it spins up another instance of my app. I have to manually quit the app or else my Dock gets full pretty fast. What a pain. Is there a way around this? It would make a lot more sense if when I run the app again, I could just terminate the already running version. Can this be done?
Share
you can use shared memory to solve your problem. I have used this approach to not start another instance of my program while there is already a running instance. Actually I have implemented this to achieve so called single instance application.
However your case is a bit different from mine, you need to somehow send a signal from 2nd application to the first one to make it close. I think you can achieve this behaviour still using
QSharedMemory.What I’ve done to achive single instance app is to create a shared memory with a universally unique id(UUID) as key and every time my program starts put a lock on it, so if it is already locked my program understands there is already a running instance and closes automatically.
You need to improve this implementation to adapt your requirement. In theory what you need to do is to put a function pointer(or a qt signal) to the shared memory and when another instance come up make your (second) instance fire that function which forces to exit the first instance. Unfortunately I don’t know how to implement this but I hope this would give you an opinion…
The flow should be somewhat like follows:
To give you a slight hint, my code for single instance is like follows
good luck and don’t forget to share your solution here 😉
EDIT:
If putting a function pointer or Qt signal and then fire it is impossible(I hope not) you can put a variable to shared memory to lets say hold the number of running instances and in your app periodically(in a thread) check it and if it is greater than 1 close the application.
Watch out for race conditions here! You can avoid race conditions by putting a pair of a random number generated by each instance and start time. so before closing, your app ensures that it is the elder one. Ex:
QPair<int, QDateTime>