shell控制超时

Eg.

# detect timeout control
function detect_timeout()
{
    wait_time=8

    # start conmand  bg
    ( $* ) & command_pid=$!

    # start time_out process bg
    ( sleep ${wait_time} ; kill -HUP ${command_pid} ) 2> /dev/null & sleep_pid=$!
    
    wait $command_pid 2> /dev/null;
    command_status=$?

    pkill -HUP -P ${sleep_pid}
    wait ${sleep_pid}

    return ${command_status};
}

备注

  • 使用“()”括起来的内容是在子shell中执行的
  • 使用“&”可以使得命令在后台执行
  • “$!”可以获取到上一个后台进程的PID
  • wait指定的进程执行完毕
  • kill -HUP发送SIGHUP信号给指定的进程
  • pkill -HUP -P 给父进程发送SIGHUP信号

参考文章

【1】shell控制超时时间,自动退出

posted @ 2020-08-04 09:12  delta1037  阅读(337)  评论(0编辑  收藏  举报