Isn't this a job for the Pid library ?
Just thinking out loud, I know PIDs are extremely tricky to work with