-1

I run a subprocess with:

tmux new-session -d command

How do I wait for it to complete, preferably with a timeout set?

sshilovsky
  • 958
  • 2
  • 9
  • 22

1 Answers1

2

POSIX advisory locking is a suitable tool for the job. Here, I'm using the tool flock -- particularly, the version at https://github.com/discoteq/flock (as opposed to the less-portable version that ships with util-linux; hence the relatively awkward usage).

#!/usr/bin/env bash
#              ^^^^- MUST be run with bash 4.3 or newer; not sh, not bash 3.x

demoLock() {
  lockFile=${1:-tmux.lock} bgTime=${2:-5} waitTime=${3:-3}
  flock "$lockFile" tmux new-session -d sleep "$bgTime"
  exec {lockFd}<>"$lockFile" # open lockFile and assign a dynamic fd
  if flock -w "$waitTime" "$lockFd"; then # lock that fd; success -> tmux exited
    echo "Background session finished successfully" >&2
  else
    echo "Background session ran out of time; proceeding without it" >&2
  fi
  exec {lockFd}>&- # close our manually-opened file descriptor
}

# Demonstrate with a lock held for five seconds while waiting for up to 3
demoLock tmux.lock 5 3 # "Background session ran out of time; proceeding without it"

# Demonstrate with a lock held for three seconds while waiting for up to 5
demoLock tmux.lock 3 5 # "Background session finished successfully"

If instead of continuing without waiting when the background process exceeds its timeout you want to kill it, see BashFAQ #68, Timeout a command in bash without unnecessary delay, or Command line command to auto-kill a command after a certain amount of time.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441