timeout是个奇妙的Linux命令,它可以控制程序运行的时间,这对于我们希望控制程序的运行时间非常有用。
timeout在CentOS6平台上,从属于软件包coreutils
#whichtimeout
/usr/bin/timeout
#rpm-qf/usr/bin/timeout
coreutils-8.4-19.el6_4.2.x86_64
timeout的原理很简单,一个简单的计时器,一个kill命令,其中-s可以跟kill的参数,具体怎么杀,就看它。
mantimeout仅仅半页,如下
TIMEOUT(1)UserCommandsTIMEOUT(1)
NAME
timeout-runacommandwithatimelimit
SYNOPSIS
timeout[OPTION]NUMBER[SUFFIX]COMMAND[ARG]...
timeout[OPTION]
DESCRIPTION
StartCOMMAND,andkillitifstillrunningafterNUMBERseconds.SUFFIXmaybe‘s’forseconds(thedefault),‘m’forminutes,‘h’
forhoursor‘d’fordays.
Mandatoryargumentstolongoptionsaremandatoryforshortoptionstoo.
-s,--signal=SIGNAL
specifythesign altobesentontimeout.SIGNALmaybeanamelike‘HUP’oranumber.See‘kill-l‘foralistofsignals
--helpdisplaythishelpandexit
--version
outputversioninformationandexit
Ifthecommandtimesout,thenexitwithstatus124.Otherwise,exitwiththestatusofCOMMAND.Ifnosignalisspecified,sendthe
TERMsignalupontimeout.TheTERMsignalkillsanyprocessthatdoesnotblockorcatchthatsignal.Forotherprocesses,itmaybe
necessarytousetheKILL(9)signal,sincethissignalcannotbecaught.
AUTHOR
WrittenbyPadraigBrady.
用法举例
1timeout120command
上面的command命令如果在120秒内完成,则平安结束,运行超过120秒后将被杀死。
脚本经常是傻乎乎的一口气跑到完,搞得我们需要写另一个脚本定期去杀它。自打有了timeout命令,腰也不疼了,腿也不酸了,跑跑歇歇更健康。
一句话,我们在脚本里或者crontab里就不用再造轮子了。