I have a script that tries to make a DB connection using another program and the timeout(2.5min) of the program is to long. I want to add this functionality to the script.
If it takes longer then 5 seconds to connect, kill the process
Else kill the sleep/kill process.
The issue I'm having is how bash reports when a process is killed, that's because the processes are in the same shell just the background. Is there a better way to do this or how can I silence the shell for the kill commands?
DB_CONNECTION_PROGRAM > $CONNECTFILE & pid=$! (sleep 5; kill $pid) & sleep_pid=$! wait $pid # If the DB failed to connect after 5 seconds and was killed status=$? #Kill returns 128+n (fatal error) if [ $status -gt 128 ]; then no_connection="ERROR: Timeout while trying to connect to $dbserver" else # If it connected kill the sleep and any errors collect kill $sleep_pid no_connection=`sed -n '/^ERROR:/,$p' $CONNECTFILE` fi
You can use a cron job to terminate the process in specific date and time.
“ kill -9” command sends a kill signal to terminate any process immediately when attached with a PID or a processname. It is a forceful way to kill/terminate a or set of processes. “ kill -9 <pid> / <processname>” sends SIGKILL (9) — Kill signal. This signal cannot be handled (caught), ignored or blocked.
To interrupt it, you can try pressing ctrl c to send a SIGINT. If it doesn't stop it, you may try to kill it using kill -9 <pid> , which sends a SIGKILL. The latter can't be ignored/intercepted by the process itself (the one being killed). To move the active process to background, you can press ctrl z .
There's a GNU coreutils utility called timeout: http://www.gnu.org/s/coreutils/manual/html_node/timeout-invocation.html
If you have it on your platform, you could do:
timeout 5 CONNECT_TO_DB if [ $? -eq 124 ]; then # Timeout occurred else # No hang fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With