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

前端 未结 8 1892
青春惊慌失措
青春惊慌失措 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:43

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

    or to get the exit codes as well:

    # 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=$?
    

提交回复
热议问题