How to kill a child process after a given timeout in Bash?

前端 未结 8 1949
青春惊慌失措
青春惊慌失措 2020-11-22 15:24

I have a bash script that launches a child process that crashes (actually, hangs) from time to time and with no apparent reason (closed source, so there isn\'t much I can do

8条回答
  •  清歌不尽
    2020-11-22 15:39

    (As seen in: BASH FAQ entry #68: "How do I run a command, and have it abort (timeout) after N seconds?")

    If you don't mind downloading something, use timeout (sudo apt-get install timeout) and use it like: (most Systems have it already installed otherwise use sudo apt-get install coreutils)

    timeout 10 ping www.goooooogle.com
    

    If you don't want to download something, do what timeout does internally:

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

    In case that you want to do a timeout for longer bash code, use the second option as such:

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

提交回复
热议问题