红联Linux门户
Linux帮助

Linux:shell脚本反复运行同一个程序

发布时间:2017-02-14 09:20:29来源:linux网站作者:cfqcfqcfqcfqcfq
描述:写了一个检测脚本运行ffmpeg程序,当程序运行结束后继续运行该ffmpeg程序。 
 
思路:起初想要持续检测正在运行的进程,如果进程正在进行就什么也不做,该进程结束就重启该进程。写的脚本如下:
 
#!/bin/bash
#sh kill.sh  
input=$1  
output=$2  
i=1  
#check output exist or not  
while true  
do  
{  
# test whether or not runing a ffmpeg     
taskNum=`ps -ef|grep ffmpeg_loft-libdt | wc -l`  
if [ $taskNum -ge 2 ];then  
echo -e "taskNum:$taskNum"  
continue      
fi  
sh kill.sh #clean background program  
ls $output && rm -r $output  
ls $output || mkdir $output  
#must running in backgroung  
for j in `seq 1 4`  
do  
./transcoder/transcoder/client -vv -q 6.8 -c ~/DT/guangxing/udp2file/result_iudp_oudp_hevc_ch01_baseport36$((i-1))00/cool9-8client.ini   > ${output}/client1-$j.log 2>&1 &  
done  
./ffmpeg_loft-libdt/ffmpeg -re -i $input -c:a libfaac -b:a 64k -ac 2 -ar 44.1k -rd 3 -r 25 -gop_size 32 -c:v libDT265 -b:v 3936k -realtime_mode 1 -static_schedule 1 -ini ~/DT/guangxing/udp2file/resul    t_iudp_oudp_hevc_ch01_baseport36$((i-1))00/cool9-8client.ini -license dev.dtlicense -client_num 4 -f mpegts -max_interleave_delta 1000M $output/output${i}.ts > $output/res${i}.log 2>&1 
sleep 10  
}  
done
 
注:
1、通过反引号`将命令的结果返回到一个变量中
2、如果有两个以上该进程就跳过循环。进程个数为2而不是1是因为wc -l会多统计一行。
3、-ge 用作整数比较 表示第一个参数大于等于第二个参数
 
实际运行发现循环体会阻塞在ffmpeg程序上。当ffmpeg程序执行完才会继续循环。所以前面的检测进程步骤就可以删掉。依然可以实现相同的效果。
 
#!/bin/bash
input=$1  
output=$2  
i=1  
#check output exist or not  
while true  
do  
{  
sh kill.sh #clean background program  
ls $output && rm -r $output  
ls $output || mkdir $output  
#must running in backgroung  
for j in `seq 1 4`  
do  
./transcoder/transcoder/client -vv -q 6.8 -c ~/DT/guangxing/udp2file/result_iudp_oudp_hevc_ch01_baseport36$((i-1))00/cool9-8client.ini   > ${output}/client1-$j.log 2>&1 &  
done  
./ffmpeg_loft-libdt/ffmpeg -re -i $input -c:a libfaac -b:a 64k -ac 2 -ar 44.1k -rd 3 -r 25 -gop_size 32 -c:v libDT265 -b:v 3936k -realtime_mode 1 -static_schedule 1 -ini ~/DT/guangxing/udp2file/resul    t_iudp_oudp_hevc_ch01_baseport36$((i-1))00/cool9-8client.ini -license dev.dtlicense -client_num 4 -f mpegts -max_interleave_delta 1000M $output/output${i}.ts > $output/res${i}.log 2>&1  
}  
done
 
最后该脚本是一个死循环 为了运行时候不让其占用终端。我们把它放在后台运行
nohup ./run3.sh 4k-3_10M_H265.sid832.tsid51.ts 4K_rd3 > /dev/null &  
nohup command & : 后台运行,你关掉终端也会继续运行。
 
脚本后台运行的相关内容见参考文献1
 
参考文献:
1&命令后天运行
Linux:shell脚本反复运行同一个程序
 
本文永久更新地址:http://www.linuxdiyf.com/linux/28383.html