即使应用程序崩溃也要终止NSTask

问题描述

| 如果我的应用程序崩溃,我将没有机会终止它产生的NSTasks,因此它们会浪费资源。 有什么方法可以启动一个任务,以使其在您的应用终止时终止(即使它崩溃了)?     

解决方法

        我想您需要手动处理应用程序崩溃,并以其他方式终止生成的进程。例如,您可以检查以下文章http://cocoawithlove.com/2010/05/handling-unhandled-exceptions-and.html,并在应用程序崩溃时在异常/信号处理程序中使用kill(pid向您的子进程发送终止信号(SIGKILL),但是为此,您还需要将子进程的pid(NSTask-(int)processIdentifier)放在某个地方,以从异常/信号处理程序中获取它。     ,        我实际上写了一个程序/脚本/不管做什么……这是它的基础shell脚本...该项目实际上在X代码中将其作为单个文件可执行文件来实现。海事组织,car可危。
#!/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
    ,        我过去所做的就是在父进程中创建一个管道,并将该管道的写入端传递给子进程。父级永远不会关闭读取端,而孩子会看着写入端关闭。如果写入结束,则表示父级已退出。您还需要标记管道的父管道的末端以在执行时关闭。     ,        您可以让您的任务定期检查以查看其父进程是否仍然存在。     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...