Kill a program and its child processes?

Mac OSX specific forum
User avatar
kenmo
Addict
Addict
Posts: 2081
Joined: Tue Dec 23, 2003 3:54 am

Kill a program and its child processes?

Post by kenmo »

(Question about Mac OS X)

If I run an external program via RunProgram(), I know I can kill it using KillProgram().

However, if the external program has started its own children processes, is there a way to kill all of them?

I am reading the OS X man pages, and I seem to need a combination of the following:

Code: Select all

pid = ProgramID(Program)
kill(pid, sig)
killpg(pgrp, sig)
SIGTERM (15)
SIGKILL (9)
???
but I have not figured out any method that works (kills the children processes). Any ideas? :?:
User avatar
kenmo
Addict
Addict
Posts: 2081
Joined: Tue Dec 23, 2003 3:54 am

Re: Kill a program and its child processes?

Post by kenmo »

Here is an example (run it and click "Launch Program" then "Kill"):

(The launched program will re-launch a child copy of itself.)

You can see in the comments that I have 3 methods to kill the run program which DON'T kill the child process, and 1 method which kills the run program AND child AND parent program AND even the PureBasic IDE (all same process group?)

Any method to just kill the specified program and its children?

Code: Select all

ImportC ""
  kill(*pid, sig.i)
  killpg(*pgrp, sig.i)
  getpgid(*pid)
EndImport
#SIGTERM = 15
#SIGKILL = 9

ExamineDesktops()
If (CountProgramParameters() = 0)

  OpenWindow(0, DesktopWidth(0)/4, DesktopHeight(0)/3, 200, 200, "Main", #PB_Window_SystemMenu)
  ButtonGadget(0, 10, 10, 180, 30, "Launch Program")
  Prog.i = #Null
  Repeat
    E = WaitWindowEvent()
    If (E = #PB_Event_Gadget)
      If (Prog)
        
        ; Kills program, but not children
        ;kill(PID, #SIGTERM)
        
        ; Kills program, but not children
        ;kill(PID, #SIGKILL)
        
        ; Kills program, children, this parent program, AND PureBasic IDE!
        ;killpg(getpgid(PID), #SIGTERM)
        
        ; Kills program, but not children
        KillProgram(Prog)
        
        CloseProgram(Prog)
        Prog = #Null
      Else
        Prog = RunProgram(ProgramFilename(), "1", GetCurrentDirectory(), #PB_Program_Open)
        PID = ProgramID(Prog)
      EndIf
      If (Prog)
        SetGadgetText(0, "Kill")
      Else
        SetGadgetText(0, "Launch Program")
      EndIf
      Delay(50)
    EndIf
  Until E = #PB_Event_CloseWindow
  
ElseIf (CountProgramParameters() > 0)
  
  If (CountProgramParameters() = 1)
    OpenWindow(0, DesktopWidth(0)/2, DesktopHeight(0)/3, 150, 150, "Sub #1", #PB_Window_SystemMenu)
    Delay(250)
    RunProgram(ProgramFilename(), "1 2", GetCurrentDirectory())
    ;End
  Else
    OpenWindow(0, DesktopWidth(0)*3/4, DesktopHeight(0)/3, 150, 150, "Sub #2", #PB_Window_SystemMenu)
  EndIf
  Repeat : Until WaitWindowEvent() = #PB_Event_CloseWindow

EndIf
Post Reply