2011-05-31 6 views
6

Si mi aplicación falla, no tengo la oportunidad de finalizar las NSTasks que generó, por lo que se quedan consumiendo recursos.Finalizar NSTask incluso si la aplicación falla

¿Hay alguna forma de iniciar una tarea que finaliza cuando la aplicación finaliza (incluso si se bloquea)?

+0

Sí, evite que su aplicación falle ;-) –

Respuesta

3

Supongo que debe manejar los bloqueos de aplicaciones manualmente y de forma diferente para finalizar los procesos generados. Por ejemplo, puede consultar el siguiente artículo http://cocoawithlove.com/2010/05/handling-unhandled-exceptions-and.html y en el controlador de excepción/señal cuando la aplicación bloquea la señal de finalización de envío a los procesos secundarios usando kill (pid, SIGKILL), pero para esto también necesita mantener los procesos pid de hijo (NSTask - (int) processIdentifier) ​​en algún lugar para obtenerlo del manejador de excepción/señal.

+0

Gracias, parece que funciona bien. – Enchilada

0

Puede hacer que sus tareas revisen periódicamente para ver si su proceso primario aún existe.

+0

No tengo el control de la aplicación de tareas en sí. Estoy ejecutando otro programa ya existente, como "tar" o "cd". – Enchilada

1

Lo que he hecho en el pasado es crear un conducto en el proceso principal y pasar el extremo de escritura de ese conducto en el elemento secundario. El padre nunca cierra el final de lectura, y el niño observa el final de escritura para cerrar. Si el final de escritura se cierra alguna vez, significa que el padre salió. También deberá marcar el final del conducto de los padres para cerrar en el ejecutivo.

+0

¿Tiene algún código de muestra? Los documentos/guías de NSTask/NSPipe/NSFileHandler no son muy completos y tienen poco código de muestra. – Enchilada

2

De hecho, wrote a program/script/whatever that does just this ... Aquí está el script de shell que fue la base de ello ... El proyecto en realidad lo implementa dentro del código X como un solo archivo ejecutable ... raro que la manzana lo haga tan precario, 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 
Cuestiones relacionadas