如果我的应用程序崩溃,我没有机会终止它产生的NSTasks,所以他们留下来吃掉资源。
有没有办法启动任务,以便在您的应用终止时终止(即使崩溃)?
答案 0 :(得分:3)
我认为您需要手动处理应用程序崩溃,并以不同的方式终止生成的进程。例如,您可以检查以下文章http://cocoawithlove.com/2010/05/handling-unhandled-exceptions-and.html和异常/信号处理程序,当应用程序崩溃时使用kill(pid,SIGKILL)向您的子进程发送终止信号,但为此您还需要保留子进程的pid进程(NSTask - (int)processIdentifier)从异常/信号处理程序获取它。
答案 1 :(得分:2)
我实际上是wrote a program / script / whatever that does just this ...这是作为它的基础的shell脚本......项目实际上在X代码中将它作为单个文件可执行文件实现..奇怪的是,苹果使得它如此不稳定,IMO。
#!/bin/bash
echo "arg1 is the SubProcess: $1, arg2 is sleepytime: $2, and arg3 is ParentPID, aka $$: $3"
CHILD=$1 && SLEEPYTIME=$2 || SLEEPYTIME=10; PARENTPID=$3 || PARENTPID=$$
GoSubProcess () { # define functions, start script at very end.
$1 arguments & # "&" puts SubP in background subshell
CHILDPID=$! # what all the fuss is about.
if kill -0 $CHILDPID; then # rock the cradle to make sure it aint dead
echo "Child is alive at $!" # glory be to god
else echo "couldnt start child. dying."; exit 2; fi
babyRISEfromtheGRAVE # keep an eye on child process
}
babyRISEfromtheGRAVE () {
echo "PARENT is $PARENTPID"; # remember where you came from, like j.lo
while kill -0 $PARENTPID; do # is that fount of life, nstask parent alive?
echo "Parent is alive, $PARENTPID is it's PID"
sleep $SLEEPTIME # you lazy boozehound
if kill -0 $CHILDPID; then # check on baby.
echo "Child is $CHILDPID and is alive."
sleep $SLEEPTIME # naptime!
else echo "Baby, pid $CHILDPID died! Respawn!"
GoSubProcess; fi # restart daemon if it dies
done # if this while loop ends, the parent PID crashed.
logger "My Parent Process, aka $PARENTPID died!"
logger "I'm killing my baby, $CHILDPID, and myself."
kill -9 $CHILDPID; exit 1 # process table cleaned. nothing is left. all three tasks are dead. long live nstask.
}
GoSubProcess # this is where we start the script.
exit 0 # this is where we never get to
答案 2 :(得分:1)
我过去所做的是在父进程中创建一个管道,并将该管道的写入端传递给子进程。父节点从不关闭读取结束,并且子节点监视写入结束。如果写入结束,则表示父项已退出。您还需要将管道的父管道末端标记为在exec上关闭。
答案 3 :(得分:0)
您可以定期检查您的任务,看看他们的父进程是否仍然存在。