It' more likely a tips other than an article. Shows some ways to set timeout for a command on linux, thested on RHEL/SL/CentOS, should be ok for other linux distributions.
1. Set sleep time with the command, && condition
<command with options> & sleep 5 ; kill $!
For example, run
$ iostat 5 & sleep 2 ; kill $!
[1] 18332
Linux 2.6.32-504.3.3.el6.x86_64 03/25/2015 _x86_64_ (12 CPU)
avg-cpu: %user %nice %system %iowait %steal %idle
58.23 10.27 0.90 0.24 0.00 30.36
Device: tps Blk_read/s Blk_wrtn/s Blk_read Blk_wrtn
sdb 10.62 211.33 3830.55 634767300 11505700712
sda 11.46 222.77 3891.51 669132274 11688819718
dm-0 11.30 162.97 65.54 489518802 196862480
dm-1 953.35 260.20 7599.83 781550266 22827387016
[1]+ Terminated iostat 5
$ echo $?
0
Note: the bad part of this implementation is that if the command takes large range of time, for example, 5 sec to 1 minutes, and you set timeout to 60 sec, then this implementation always takes 60s to finish.
2. use timeout
The GNU timeout provides the timeout solution:
rpm -qf /usr/bin/timeout
coreutils-8.4-37.el6.x86_64
$timeout 5 command with options
$ timeout 2 iostat 5
Linux 2.6.32-504.3.3.el6.x86_64 03/25/2015 _x86_64_ (12 CPU)
avg-cpu: %user %nice %system %iowait %steal %idle
58.23 10.27 0.90 0.24 0.00 30.36
Device: tps Blk_read/s Blk_wrtn/s Blk_read Blk_wrtn
sdb 10.61 211.30 3830.07 634767300 11505711464
sda 11.46 222.74 3891.02 669132354 11688831830
dm-0 11.30 162.95 65.53 489518802 196865240
dm-1 953.23 260.17 7598.87 781550266 22827406144
$ echo $?
124
It returns 124 when timedout, otherwise returns the command return code.
3 Use Perl alarm
Use perl alarm feature, set alarm to 1 sec and run command sleep 10
perl -e "alarm 1; exec @ARGV" sleep 10
1427327073.25259
Alarm clock
$echo $?
142
Not, this solution doesn't work consistently with iostat I tested above, so far I have no idea about it, let me know if you find out.
4. Use expect command
Expect command on linux has timeout setting, so use it if you don't have GNU timeout on your machine
time_out=2
command="iostat 5"
$expect -c "set echo \"-noecho\"; set timeout $time_out; spawn -noecho $command; expect timeout { exit 1 } eof { exit 0 }"
Linux 2.6.32-504.3.3.el6.x86_64 03/25/2015 _x86_64_ (8 CPU)
avg-cpu: %user %nice %system %iowait %steal %idle
19.25 0.11 7.91 0.35 0.00 72.39
Device: tps Blk_read/s Blk_wrtn/s Blk_read Blk_wrtn
sda 1.11 1.33 20.49 7920768 121880814
sdb 0.81 2.19 27.40 13000458 162985856
sdc 1.99 821.91 27.57 4888989830 163979688
sdd 1.70 821.50 27.57 4886563236 163979688
dm-0 2.59 1.33 20.48 7884378 121815312
dm-1 0.00 0.00 0.01 21000 52720
md1 3.24 1.30 25.79 7713298 153425384
dm-2 3.44 2.19 27.40 12998354 162985856
$echo $?
1
Comments powered by CComment