[Qt-interest] [very OT] How to create single instance app?

Jeroen De Wachter jeroen.dewachter at barco.com
Mon May 10 16:34:54 CEST 2010


Doesn't that act up if the application crashes and is unable to close 
the listen socket cleanly?
I know I've spent far too much time waiting for crashed network-enabled 
applications' stuck sockets to get cleaned up by the OS (TIME_WAIT, anyone?)
I'd hate to see that happen even with applications that don't use the 
network...

I think the lock file mentioned before is a good way to go:
- on application startup, check for the lock file
- if it doesn't exist, create it and store the id of the process that 
creates the file inside that file
- if it does exist, read the pid in the file and see if that process is 
still running
- if not, replace the lock file and store your own process id inside
- if the process is still running, return an error and quit

I think start-stop-deamon on *nix system works like this as well, btw 
(though that may only cover invocation through start-stop-daemon)?
And I'm sure Linux provides some API calls to work with lock files as well

Kind regards,

Jeroen

Bob Hood wrote:
> On 5/10/2010 8:02 AM, Konrad Rosenbaum wrote:
>   
>> ....I think we digressed a little bit from the topic of this list.
>> Didn't we?
>>     
>
> Indeed.
>
> To address the original question, I always place something like the
> following in my stand-alone apps:
>
>     class MainWindow : public QMainWindow
>     {
>         Q_OBJECT
>         ...
>     private:
>         QTcpServer          instance_lock;
>         ...
>     };
>
> and then in the constructor, I choose and hard code a random port number
> between 1024 and 65534:
>
>     if(!instance_lock.listen(QHostAddress::Any, <assigned_port_number>))
>     {
>         show_message(tr("Another instance of <application_name> seems to
> be running."));
>         exit(0);
>     }
>
> Works well so far.
>
> _______________________________________________
> Qt-interest mailing list
> Qt-interest at trolltech.com
> http://lists.trolltech.com/mailman/listinfo/qt-interest
>
>   



DISCLAIMER:
Unless indicated otherwise, the information contained in this message is privileged and confidential, and is intended only for the use of the addressee(s) named above and others who have been specifically authorized to receive it. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this message and/or attachments is strictly prohibited. The company accepts no liability for any damage caused by any virus transmitted by this email. Furthermore, the company does not warrant a proper and complete transmission of this information, nor does it accept liability for any delays. If you have received this message in error, please contact the sender and delete the message. Thank you.




More information about the Qt-interest-old mailing list