Home > Mobile >  How do I detect if I'm a first instance or send a IPC message to previous instance of same app?
How do I detect if I'm a first instance or send a IPC message to previous instance of same app?

Time:10-01

My app is suppose to run long term (usually idling). If I try to open a second app (or trigger the app via global hotkey) I'd like my existing instance to receive some kind of IPC message and bring itself to the front. How do I do this on linux? The problem I've been running into is if I hold a global lock it doesn't automatically free when the instance close (usually I unlock it but an app can crash). If I try to use mkfifo I have no idea if I'm the first instance or not and every solution I can think of seems to require a lot of code and usually that's a sign to me I might be doing something wrong

CodePudding user response:

There are many IPC primitives, all possible to use.

A simple one is using a named pipe: If the pipe doesn't exist then the program creates it and starts as usual. Then it polls the pipe at regular intervals to see if something can be received on the pipe, in which case the program receives it (and discards it) and puts itself to the "front".

If, on the other hand, the named pipe exists, then the program sends a simple dummy message through it, and exits.

CodePudding user response:

I would use a flag file, e.g. /run/service-name/pid with PID of the first running instance. A new instance would check this file, if it does not exists, create it, if it does, send a SIGUSR1 to the PID in the file.

@Some programmer dude's answer above provides a bit more of flexibility.

  • Related