What is the best way to be notified when a process has been launched & exited in an kernel extension?
I know that I can use KAuth
to subscribe for a process creation (KAUTH_VNODE_EXECUTE
). How about subscribing to a process cleanup?
KAUTH_VNODE_EXECUTE isn't quite sufficient for all processes; this won't catch processes which are fork()ed without exec(). Fairly rare on OSX, but not unheard of. There is a MAC framework policy callback for fork, at least, although MAC (com.apple.kpi.dsep) is marked as unsupported by Apple, and ABI changes between major OS X versions are common.
I'm not aware of anything for shutdown, other than periodically walking through your own list of processes, looking up the proc_t for the PID in question, and checking if it's still live. Of course, if a new process with a recycled PID is detected, that also means that the previous process with the same PID has died. You may be able to infer process death from other events if you have extra information on the process in question.
There's also a way to monitor the processes when exited. you can use the kernel event notification mechanism (kevent) which is part of freeBSD and supported by OS X.
the flow begin in process startup (which you can catch using the kauth or mac framework approaches). in the callback function you need to register proper event to monitor later on. This is done by setting kevent instance using EV_SET with the following arguments :
kevent.ident = pid
kevent.filter = EVFLT_PROC
kevent.flags = EV_ADD
kevent.fflags = NOTE_EXIT
in code it should look like this :
EV_SET(&ke, pid, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
kevent(kq, &ke, 1, NULL, 0, NULL); // registration of ke to kqueue represented by kq descriptor.
Finally, you'll need another thread for listening to those events and catch them when the time is come (process exited), again using kevent command.
err = kevent(kq, NULL, 0, &ke, 1, NULL);
if (err == -1)
err(1, "error in catching the event");
if (ke.fflags & NOTE_EXIT)
printf("this is what you need ...");
for more details you may check the following doc