Kill process after it's been allowed to run for some time

I want to limit the time a grep process command is allowed to run or be alive.

For example. I want to perform the following:

grep -qsRw -m1 "parameter" /var

But before running the grep command I want to limit how long the grep process is to live, say no longer than 30 seconds.

How do I do this?

And if it can, how do I return or reset to have no time limit afterwards.


Solution 1:

You can use timelimit, it is available in the default ubuntu or you could compile it yourself.

timelimit executes a command and terminates the spawned process after a given time with a given signal. A “warning” signal is sent first, then, after a timeout, a “kill” signal, similar to the way init(8) operates on shutdown.

Solution 2:

Here's some slightly hackish bash for that:

grep -qsRw -m1 "parameter" /var &

GREPPID=$!

( sleep 30; kill $GREPPID ) &

fg $GREPPID

Basically, it starts the search in the background, then starts a subshell that waits 30 seconds and then kills the search process. If the search takes <30s, the process will already be dead. It's not a great idea to kill a process that's already dead since there's a very small chance something else will reuse the pid, but for something like this it's generally okay. Lastly, the search is put back in the foreground and will run until it finishes or is killed.