异步bash脚本 [英] Asynchronous bash script

查看:110
本文介绍了异步bash脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了一些示例,但无法根据我的情况进行处理.

I've seen a few examples out there but not been able to work them to my situation.

我有一个脚本,该脚本调用长时间运行的命令,但是我想定期(例如每1秒一次)获取该调用的状态.例如:

I have a script that calls a long running command, but I want to periodically (say every 1s) get the status of that call. For example:

#!/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!"

是否可以通过这种方式获取子进程的状态?

Is it possible to get the status of the child process in this way?

澄清我的实际工作.实际上,这是对Elasticsearch集群的两个curl命令.长时间运行的命令将数据段合并在一起,状态"命令将获取当前的段计数.

Clarifying what I'm actually doing. It's actually two curl commands to an Elasticsearch cluster. The long running command merges data segments together, the "status" command will get the current segment count.

推荐答案

我认为最安全的方法是保存子进程的进程ID,然后定期检查它是否仍在运行:

I think that the safest way of doing this is to save the process ID of the child process and then periodically check to see if this is still running:

#!/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"

变量 $!将保存在后台启动的最后一个进程的进程ID.

The variable $! will hold the process ID of the last process started in the background.

kill -0 不会向进程发送信号,如果给定的进程ID存在且属于该进程的ID,则只会使 kill 返回且退出状态为零.用户执行 kill .

The kill -0 will not send a signal to the process, it only make kill return with a zero exit status if the given process ID exists and belongs to the user executing kill.

也可以使用 pgrep 提出一个解决方案,但是从某种意义上说,这应该更加不安全",因为必须注意不要捕获任何类似的正在运行的进程.

One could come up with a solution using pgrep too, but that will probably be a bit more "unsafe" in the sense that care must be taken not to catch any similar running processes.

这篇关于异步bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆