GNU/Linux >> Linux Esercitazione >  >> Linux

Come uccidere un processo figlio dopo un determinato timeout in Bash?

# Spawn a child process:
(dosmth) & pid=$!
# in the background, sleep for 10 secs then kill that process
(sleep 10 && kill -9 $pid) &

o per ottenere anche i codici di uscita:

# Spawn a child process:
(dosmth) & pid=$!
# in the background, sleep for 10 secs then kill that process
(sleep 10 && kill -9 $pid) & waiter=$!
# wait on our worker process and return the exitcode
exitcode=$(wait $pid && echo $?)
# kill the waiter subshell, if it still runs
kill -9 $waiter 2>/dev/null
# 0 if we killed the waiter, cause that means the process finished before the waiter
finished_gracefully=$?

(Come visto in:BASH FAQ entry #68:"Come posso eseguire un comando e farlo interrompere (timeout) dopo N secondi?")

Se non ti dispiace scaricare qualcosa, usa timeout (sudo apt-get install timeout ) e usalo come:(la maggior parte dei sistemi lo ha già installato altrimenti usa sudo apt-get install coreutils )

timeout 10 ping www.goooooogle.com

Se non vuoi scaricare qualcosa, fai ciò che timeout fa internamente:

( cmdpid=$BASHPID; (sleep 10; kill $cmdpid) & exec ping www.goooooogle.com )

Nel caso in cui desideri eseguire un timeout per un codice bash più lungo, usa la seconda opzione come tale:

( cmdpid=$BASHPID; 
    (sleep 10; kill $cmdpid) \
   & while ! ping -w 1 www.goooooogle.com 
     do 
         echo crap; 
     done )

Linux
  1. Come far morire il processo figlio dopo che il genitore è uscito?

  2. Perché il processo figlio è ancora vivo dopo che il processo genitore è stato ucciso in Linux?

  3. Come uccidere il processo di zombi

  4. come usare kill SIGUSR2 in bash?

  5. Come mettere in pausa/riprendere un processo in Linux

Come uccidere un processo in Linux? Comandi per terminare

Come uccidere un processo in Linux

Come uccidere i processi Zombie in Linux

Come eliminare l'esecuzione del processo Linux su una porta particolare

Come KILL un processo su Linux

Come uccidere i processi zombi in Ubuntu