Bash: 启动并终止 child 进程

Bash: Start and kill child process

我有一个要启动的程序。假设这个程序将 运行 一个 while(true) 循环(所以它不会终止。我想写一个 bash 脚本,其中:

  1. 启动程序 (./endlessloop &)
  2. 等待 1 秒(sleep 1
  3. 杀死程序 --> 如何?

我不能使用 $!从 child 获取 pid,因为服务器正在 运行 同时处理大量实例。

您可以使用 pgrep 命令来实现同样的目的:

kill $(pgrep endlessloop)

存储 PID:

./endlessloop & endlessloop_pid=$!
sleep 1
kill "$endlessloop_pid"

你也可以查看进程是否还在运行kill -0:

if kill -0 "$endlessloop_pid"; then
  echo "Endlessloop is still running"
fi

...并将内容存储在变量中意味着它可以扩展到多个进程:

endlessloop_pids=( )                       # initialize an empty array to store PIDs
./endlessloop & endlessloop_pids+=( "$!" ) # start one in background and store its PID
./endlessloop & endlessloop_pids+=( "$!" ) # start another and store its PID also
kill "${endlessloop_pids[@]}"              # kill both endlessloop instances started above

另见 BashFAQ #68、"How do I run a command, and have it abort (timeout) after N seconds?"

Wooledge wiki 上的 ProcessManagement 页面也讨论了相关的最佳实践。