Mac OS X: Quickest way to kill/quit an entire process tree from within a Cocoa application

Thomas Jung picture Thomas Jung · Jun 15, 2009 · Viewed 7.7k times · Source

I know there are many questions and answers about this, but I am looking for an efficient and robust solution. I need to kill a process AND all it's child processes from within a Cocoa app. I got the process ID and what I am about to code is to execute the kill command like so

kill -- -<parent PID>

from within my app ... but that seems awfully hacky and brutal to me. Isn't there a better solution? Carbon's KillProcess()and its Process Manager friends don't seem much help unless I build a process tree representation myself. Am I missing something?

I also have some code to send the Quit Apple Event based on PID. It would be even nicer to be able to send that to each process in the tree defined by a parent process, bottom up. But that's only a nice-to-have. An answer to the first question gets the "point".

Answer

Jason Coco picture Jason Coco · Jun 15, 2009

You can just use killpg to terminate the process and everything in its group:

#include <signal.h>
#include <unistd.h>

/* ... */

killpg(getpgid(pid), SIGTERM);

Proper error checking should be done, of course, but you should get the gist. See the man pages kill(2) and killpg(2) for more info.