重击:启动并杀死子进程

今天春*_*天春天 4 bash sleep process

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

  1. 启动程序(./endlessloop &
  2. 等待1秒(sleep 1
  3. 杀死程序->怎么样?

我不能使用$!从子进程获取pid,因为服务器同时运行许多实例。

Cha*_*ffy 5

存储PID:

./endlessloop & endlessloop_pid=$!
sleep 1
kill "$endlessloop_pid"
Run Code Online (Sandbox Code Playgroud)

您还可以使用以下命令检查该进程是否仍在运行kill -0

if kill -0 "$endlessloop_pid"; then
  echo "Endlessloop is still running"
fi
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

另请参见BashFAQ#68,“如何运行命令,并在N秒后将其中止(超时)?”

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