Running a shell command for a specific period of time

vodhner at cox.net vodhner at cox.net
Wed Oct 26 10:13:46 MST 2005


Erik wrote:
> I was wondering if anyone knew a way to allow a shell
> command to run for a specific period of time.  In this
> particular case, I want tcpdump to run for 23 hours,
> 59 minutes, 59 seconds.

It would be best if the process could limit itself, since anything you do in a shell script will have sloppy timing, maybe a few seconds off.  But you can do this for any process, using the following crude approach within a single script:

This script should be run with all its output redirected to a log file, so you can have a record of how it went.

Run your process (tcpdump) in the background with &

This becomes an independent process, so the next command in your script will start immediately:

date  # output goes into your log file.

sleep 86399  # Or less, since kill won't be instantaneous

date

Use a pipeline with "ps -ef" and "grep" to identify the running tcpdump process.  Extract the pid using "cut" and do a "kill".

sleep 2   # just to give kill time to take effect

ps -ef | grep ... # Did it go away?

date

exit

Details on request, but the above commands are good things to learn.  This type of ps + grep pipeline is also useful to detect if a duplicate copy of a script is running, etc.

The sleep command is only precise to within a second or two, and other system activity might delay the next command.

Vic




More information about the PLUG-discuss mailing list