如何在 Bash 脚本中 运行 编程与其他程序 运行 并行?

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

我有两个程序 serverclientserver 在未知持续时间后终止。我想 运行 clientserver 并行(都来自同一个 Bash 脚本)并在 server 几秒后自动终止 client ] 已终止(自行终止)。

如何实现?

我可以 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 杀死子进程不是一个选项。

编辑

This question 仅解决等待两个进程自然终止的问题,而不是如何在 server 进程终止后终止 client 进程。

@tripleee 在评论中指出 this question on Unix SE,这有效 尤其是在终止顺序无关紧要的情况下。

#!/bin/bash

execProgram(){
  case  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

使用 GNU Parallel,您可以:

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