'How to run program in Bash script for as long as other program runs in parallel?

I have two programs server and client. server terminates after an unknown duration. I want to run client in parallel to server (both from the same Bash script) and terminate client automatically a few seconds after the server has terminated (on its own).

How can achieve this?

I can run multiple programs in parallel from a bash script and timeout a command in Bash without unnecessary delay, but I don’t know the execution duration of server beforehand so I can’t simply define a timeout for client. The script should continue running so exiting the script to kill the child processes is not an option.

Edits

This question only addresses waiting for both processes to terminate naturally, not how to kill the client process once the server process has terminated.

@tripleee pointed to this question on Unix SE in the comments, which works especially if the order of termination is irrelevant.



Solution 1:[1]

#!/bin/bash

execProgram(){
  case $1 in
        server)
                sleep 5 &  # <-- change "sleep 5" to your server command.
                           # use "&" for background process    
                SERVER_PID=$!
                echo "server started with pid $SERVER_PID"
                ;;
        client)
                sleep 18 &  # <-- change "sleep 18" to your client command
                            # use "&" for background process
                CLIENT_PID=$!
                echo "client started with pid $CLIENT_PID"
                ;;
  esac
}

waitForServer(){
        echo "waiting for server"
        wait $SERVER_PID
        echo "server prog is done"

}

terminateClient(){
        echo "killing client pid $CLIENT_PID after 5 seconds"
        sleep 5
        kill -15 $CLIENT_PID >/dev/null 2>&1
        wait $CLIENT_PID >/dev/null 2>&1
        echo "client terminated"
}

execProgram server && execProgram client
waitForServer && terminateClient

Solution 2:[2]

With GNU Parallel you can do:

server() {
   sleep 3
   echo exit
}
client() {
   forever echo client running
}
export -f server client
# Keep client running for 5000 ms more
# then send TERM and wait 1000 ms
# then send KILL
parallel -u --termseq 0,5000,TERM,1000,KILL,1 --halt now,success=1 ::: server client

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ole Tange