Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill process after a given time bash?

Tags:

bash

kill

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 
like image 921
krizzo Avatar asked Oct 21 '11 15:10

krizzo


People also ask

How do you kill a specific time process?

You can use a cron job to terminate the process in specific date and time.

What does kill 9 mean?

“ 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.

Can we kill Bash process?

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 .


1 Answers

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 
like image 175
Itay Perl Avatar answered Sep 25 '22 00:09

Itay Perl