Page 1 of 1

Check if another instance is running

Posted: Tue Feb 12, 2013 6:26 pm
by spacebuddy
Under Windows we can use a mutex to check if another instance of our program
is running, how is this accomplished on the Mac?

Re: Check if another instance is running

Posted: Tue Feb 12, 2013 9:37 pm
by uwekel
Hi spacebuddy,

i did something similar in my newsreader project for Linux. Maybe you can port this to Mac. It contains only three very small methods. Here is the code with sample use below:

Code: Select all

DisableDebugger
InitNetwork()
EnableDebugger

Global _InstancePort

Procedure InstanceInit(Port)
  ;keep communication port
  _InstancePort = Port
  ;creates a new server listening at the given port
  If CreateNetworkServer(#PB_Any, Port)
    ProcedureReturn #True
  EndIf
EndProcedure
Procedure InstanceSend(Text.s)
  ;send's a message to a server and return #True on success
  Protected id = OpenNetworkConnection("localhost", _InstancePort)
  If id
    SendNetworkString(id, Text)
    CloseNetworkConnection(id)
    ProcedureReturn #True
  EndIf
EndProcedure
Procedure.s InstanceReceive()
  ;receives a message from a connected client
  If NetworkServerEvent() = #PB_NetworkEvent_Data
    *b = AllocateMemory(256)
    ReceiveNetworkData(EventClient(), *b, 256)
    s.s = PeekS(*b)
    FreeMemory(*b)
    ProcedureReturn s
  EndIf
EndProcedure

CompilerIf #PB_Compiler_IsMainFile
  If OpenWindow(0, 0, 0, 400, 300, "Test", #PB_Window_SystemMenu | #PB_Window_ScreenCentered | #PB_Window_SizeGadget)
    ButtonGadget(0, 8, 8, 100, 36, "Send")
    If InstanceInit(7531)
      Repeat
        Select WaitWindowEvent(100)
        Case #PB_Event_Gadget
          If EventGadget() = 0
            InstanceSend("Cool!")
          EndIf
        Case #PB_Event_CloseWindow
          Break
        EndSelect
        ;look for event
        s.s = InstanceReceive()
        If s
          Debug s
        EndIf
      ForEver
    EndIf
  EndIf
CompilerEndIf
First you have to call InstanceInit() from your main program with a port number of your choice. If the method returns #True, the initialisation was successfully done and it was the first instance of your program. If the method returns #False, the initialisation failed because your program runs already. If you like, you can now send a message string to your first program by calling the InstanceSend() method. In the event loop of your program, you have to check InstanceReceive() method to get this message string. That's it. I guess it does even run on Windows so it is a multi-platform solution.

Best regards
Uwe

Re: Check if another instance is running

Posted: Wed Feb 13, 2013 6:13 am
by wilbert
I don't know if OS X supports running multiple instances of an application at all.