spiralofhope logo
spiralofhope logo

S
piral of Hope
Better software is possible.
Styles
Table of Contents

Programming > Shell scripting >


Wait for a program to exit

\Xdialog --yesno 'test' 5 40 &
checkpid=$!
\wait $checkpid &> /dev/null
\echo "Xdialog has ended."

Is a program running?

Problem:

The basic solution is kill -0 $pid to see if a pid would be killable. To be killable it has to exist. This can be implemented like so:

timeout=10

timeout_run(){
  \Xdialog --yesno 'test' 5 40 &
  checkpid=$!
}

timeout_running(){
  \echo "It's still running\!"
}

timeout_not_running(){
  \echo "It's no longer running."
}

timeout_run
\sleep $timeout
\kill -0 $checkpid &> /dev/null
if [ $? -eq 0 ]; then
  timeout_running
else
  timeout_not_running
fi

Is a program hung?

This was originally designed as a way for the script to learn if an application was hung.

I leverage xkill, which is almost universally installed and is very easy to interact with. I could communicate with my script by right-clicking to have xkill do nothing and exit gracefully, or I could simply left-click with xkill to kill the misbehaving application.

timeout=10

timeout_run(){
  \Xdialog --yesno 'test' 5 40 &
}

timeout_program() {
  \xkill > /dev/null &
  checkpid=$!
}

timeout_running(){
  \echo "It's still running\!"
}

timeout_not_running(){
  \echo "It's no longer running."
}

timeout_run
timeout_program
\sleep $timeout
\kill -0 $checkpid &> /dev/null
if [ $? -eq 0 ]; then
  timeout_running
else
  timeout_not_running
fi