Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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".

like image 934
Thomas Jung Avatar asked Jan 24 '23 12:01

Thomas Jung


1 Answers

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.

like image 162
Jason Coco Avatar answered Jan 26 '23 01:01

Jason Coco