0

What I want to do is have a command that will return when a program closes. So for example, say I have opened chromium-browser using the window manager or another console window, I'd like to have a command I could issue that will only return when chromium-browser is shut down so I can take appropriate action.

Any ideas?

1 Answer 1

3

I'm doing something similar on my home server where I want a quick-and-dirty queuing system for quantum chemical computations. The following is a chunk from the middle of my queuing script:

# If second argument passed, treat as PID to check for
#  completion before proceeding
if [ -n "$2" ]
then
  while [ `ps aux | grep orca | sed -r 's/[a-z0-9]+[ ]+([0-9]+).*/\1/' | grep "^$2\$" | wc -l` -gt 0 ]
  do
    sleep 1m
  done
fi

The commands inside the back-ticks perform the following:

  1. Call ps aux to get the process list
  2. grep the name of the executable ("orca" here) to protect against the rare case where the process of interest has run long enough that the PID usage has wrapped back around and the PID of interest has been assigned to an unrelated process
  3. sed each remaining process listing, using extended Regex, to leave only the PID number on each line
  4. grep to check if any of the PIDs found are a match for the target PID
  5. wc -l provides an easy way to count the number of matching PIDs (the count should only ever be one or zero, but the -gt 0 implementation should be robust against unusual circumstances)

The script then sleeps for one minute (easily customizeable) and repeats the PID check. At whatever point the PID of interest is no longer found, the script moves on. In my case, the downstream commands execute the appropriate computation; you can adapt to perform whatever action(s) you wish.

5
  • 1
    I used your start and made it into a single command instead of a script file: bash -c 'while true; do if [ "$(ps -ef | grep chromium-browser | grep -v grep)" == "" ]; then exit 1; else sleep 1; fi done'.
    – Brian
    Mar 20, 2015 at 18:57
  • You can probably convert this into an alias, too.
    – hBy2Py
    Mar 20, 2015 at 18:59
  • This looks like it will only trigger when the last instance of chromium is terminated - is that what you want?
    – hBy2Py
    Mar 20, 2015 at 20:09
  • well, my actual command will be smarter than that. I'll put all the specific flags in the grep that I start chromium with that only occur with the instance I'm concerned with.
    – Brian
    Mar 23, 2015 at 14:37
  • Ahh, gotcha, your comment was just a template. Cool!
    – hBy2Py
    Mar 23, 2015 at 15:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .