Control multiple program instances - open multiple files problem

Hello. This shouldn't be an unusual problem, but I cannot find anything about it at google or at other search machine.

So, I've made an application using C++ and QtCreator. I 've made a new mime type for application's project files.
My system (ubuntu 10.10), when I right click a file and I choose "Open With 'Default Application'" the it runs

default_application path/to/the/selected/file1

So, if you select multiple files and select "Open With 'Default Application'" the system will call

default_application path/to/the/selected/file1
default_application path/to/the/selected/file2
default_application path/to/the/selected/file3

So, this is a big problem for me, because I handle the concurrent processes from inside the program, so when another instance of the program is running, a warning message is appeared. So, each application's call will recognize the others as currently running applications and so it'll show the message. I'll end up with 3 Messages saying that another process of the program is running --_--'
My application handles multiple URLs this way:

myapp path/to/the/selected/file1 path/to/the/selected/file2 path/to/the/selected/file3

How can I make my code handle all these multiple instances at the same time? Everything I've tried fails, because everything I've tried requires a check from the first instance called, which is too slow and other instances come app and all together are warning about concurrent processes of the same program :wall::wall::wall:

So, how can I fix this? is it system depended, or can I do something with the code?

Well, you'll need a way to communicate with the original process when an extra one is run, so it can check if it's first and if not, just send a message to the first and quit.

Message queues might work. They're convenient in having a property that their names are global across the system.

Have the process try to create a message queue with mq_open("/username_myapp", O_RDONLY|O_CREAT, 0600, NULL). If it succeeds in creating the message queue, it knows it's the first one, and sets up a thread to receive messages on it with mq_receive() until the program quits. (Or you could use it in nonblocking mode and poll it.) Make sure to destroy the message queue with mq_unlink when you quit, or it will continue to exist even after all your programs have quit!

If it fails to create it on the other hand, just have it open it with mq_open("/username_myapp", O_WRONLY), send a message over it, and quit.

1 Like

Thanks for the suggestion. I'll have a try with DBUS messages.

DBUS? Well there goes any and all pretense of portability...