linux 脚本 wait,shell脚本使用 timeout + wait 完成: 超时退出执行,等待执行完毕并处理执行结果 - yanbin's Blog...

具体需求是:

1.从文件中读取 seq, 使用 pub 程序将 seq 推送给定阅读了 cmd topic 的 peer client.

client 将处理结果(message)推送到 cmdresp topic. 这个过程是经过 server 的,可以不考虑。

pub 成功后记录 seq.

2. sub 程序订阅 cmdresp topic, 简单处理接收到的消息,并且记录到文件。

3. 对比 pub 成功的 seq 记录与接收到的 message, 获得一个 pub/sub 成功率。

问题是:

1. pub 和 sub 分别使用两个不同的管道,pub cmd 成功后并不等待 cmdresp.

甚至可以说: pub 程序并不知道 cmdresp 的存在,甚至不知道 sub 的存在.

2. sub 是阻塞的:没有任何消息也不退出。

3. pub message 到 peer client 到 cmdresp 返回之间的时间是不确定的。

消息在两个管道都有可能出现延迟。

4. sub 程序本身没有超时退出选项。

伪代码是:

timeout time sub cmdresp_topic > cmdresp_record

while seq in read seqs:

seq = parse_seq(seq)

message = create_message(seq)

pub cmd_topic message

record(message, msg_record)

// do something, maybe sleep 1s

wait sub

parse(cmdresp_record, msg_record)

shell 代码是:

tmp_file="$(mktemp)

rm -f $tmp_file

mkfifo $tmp_file

# terminate $MOSQUITTO while $TIMEOUT period

timeout $TIMEOUT \

$MOSQUITTO_SUB -t $topic_resp --cafile $CA --cert $CERT --key $KEY > $tmp_file &

cat $tmp_file | cut -d',' -f1 | cut -d':' -f2 | sed -n 's/\"//gp' >> $SUB_LOG &

N=0

for line in $(cat $SNS_FILE)

do

sn="$(echo "$line" | cut -d'&' -f1)"

seq="$($LOOKUP_TOPIC $sn)"

name="$(printf "%s%.4d" $sn $seq)"

topic="router/$name/cmd"

N=$((N+1))

mid="$(date +%Y%m%d%H%M%S)-$N"

message=makemsg $mid

$MOSQUITTO_PUB -t $topic --cafile $CA --cert $CERT --key $KEY -m "$message"

sw="$(echo "$line" | cut -d'&' -f2)"

record="$(date +%Y%m%d:%H),$sn,$sw,1"

[ $? -eq 0 ] && echo "$record" >> $PUB_LOG

[ $((N % 10)) -eq 0 ] && sleep $SLEEP_TIME

done

wait # wait $MOSQUITTO_SUB and cat $tmpfile terminaation

rm -f $tmp_file

if [ -f $SUB_LOG -a -f $PUB_LOG ]; then

tmp_file="$(mktemp -p $RECORD_DIR)"

for line in $(cat $SUB_LOG)

do

sed "s/\(.*$line.*\),1/\1,0/g" $PUB_LOG > $tmp_file

cp $tmp_file $PUB_LOG

done

rm -f $tmp_file

fi

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值