Home > Mobile >  How to run program in Bash script for as long as other program runs in parallel?
How to run program in Bash script for as long as other program runs in parallel?

Time:05-07

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.

CodePudding user response:

#!/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
  • Related