我已经看到了一些例子,但是没能将它们用于我的情况.
我有一个调用长时间运行命令的脚本,但我想定期(比如说每1个)获得该调用的状态.例如:
#!/bin/bash
curl localhost:9200/my_index/_forcemerge?max_num_segments=2 &
while [ command is running ]; do
curl -XGET localhost:9200/_cat/shards/my_index?v&h=index,shard,prirep,segments.count
sleep 1
done
echo "finished!"
Run Code Online (Sandbox Code Playgroud)
是否有可能以这种方式获得子进程的状态?
编辑:澄清我实际在做什么.它实际上是Elasticsearch集群的两个curl命令.长时间运行命令将数据段合并在一起,"status"命令将获得当前段计数.
我认为最安全的方法是保存子进程的进程ID,然后定期检查它是否仍在运行:
#!/bin/bash
mycommand &
child_pid=$!
while kill -0 $child_pid >/dev/null 2>&1; do
echo "Child process is still running"
sleep 1
done
echo "Child process has finished"
Run Code Online (Sandbox Code Playgroud)
该变量$!将保存在后台启动的最后一个进程的进程ID.
该kill -0不会发出信号的过程,它不仅使kill如果给定的进程ID存在且属于执行用户以零退出状态返回kill.
人们也可以提出一个解决方案pgrep,但从某种意义上讲,这可能会更加"不安全",必须注意不要抓住任何类似的运行流程.