You're viewing a comment by Coder.C and its responses.

Coder.C Permalink
August 28, 2012, 17:28

This is how to write alarm in bash:

function alarm() {
    timeout=$1; shift;
    bash -c "$@" &
    pid=$!
    {
      sleep $timeout
      kill $pid 2> /dev/null
    } &
    wait $pid 2> /dev/null
    return $?
  }

alarm 1 "echo >/dev/tcp/google.com/230" && echo "Y" || echo "N"

//this prints 'N' in ~1s

alarm 60 "echo >/dev/tcp/google.com/80" && echo "Y" || echo "N"

//this still returns almost immediately and prints "Y"

Comment Responses

sean Permalink
August 28, 2012, 21:23

backgrounding a job to sleep/kill a pid isn't necessarily a great idea imho. here, if the port in question is open then then you will pass the wait relatively quickly, but you still have a timer set to kill the pid. A short timer probably won't cause an issue, but the longer you wait the more likely it becomes that the kernel will assign that pid to a new process that you probably don't want killed. especially if you are launching two new pids for each possible port.

June 12, 2013, 01:14

You can't wait for a PID that isn't a child process, so the PID reuse isn't a problem. There's a lot of other good info on managing and waiting for (multiple) sub-processes here: http://stackoverflow.com/questions/356100/how-to-wait-in-bash-for-several-subprocesses-to-finish-and-return-exit-code-0

Reply To This Comment

(why do I need your e-mail?)

(Your twitter name, if you have one. (I'm @pkrumins, btw.))

Type the word "server": (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.