Linux run command with timeout

How to Run a Command with Time Limit (Timeout) In Linux

Linux comes with a bounty of commands, each command unique and used in specific cases. The goal of Linux is to help you be as fast and efficient as possible. One property of a Linux command is the time limit. You can set a time limit for any command you want. If the time expires, the command stops executing.

In this short tutorial, you are going to learn two methods on how you can use a time limit in your commands.

On this page:

Run Linux Commands Using the timeout Tool

Linux has a command-line utility called a timeout, which enables you to execute a command with a time limit.

Its syntax is as follows.

To use the command, you specify a timeout value (in seconds) with the command you want to run. For instance, to timeout a ping command after 5 seconds, you can run the following command.

You do not have to specify the (s) after number 5. The command below is the same and will still work.

Timeout Ping Command in Linux

Other suffixes include:

  • m representing minutes
  • h representing hours
  • d representing days

Sometimes commands may continue to run even after timeout sends the initial signal. In such instances, you can use the —kill-after option.

Here’s the syntax.

You need to specify a duration to let timeout know after how much time the kill signal is to be sent.

For example, the command shown is going to be terminated after 8 seconds.

Set Time Limit to Linux Commands

Run Linux Commands Using Timelimit Program

The Timelimit program runs a given command then terminates the process after a specified time using a given signal. It initially passes a warning signal, and then after a timeout, it sends the kill signal.

Unlike the timeout option, Timelimit has more options such as killsig, warnsig, killtime, and warntime.

Timelimit can be found in the repositories of Debian-based systems and to install it, use the following command.

For Arch-based systems, you can install it using AUR helper programs e.g., Pacaur Pacman, and Packer.

Other Linux distributions, you can download timelimit source and manually install it.

After installation, run the following command and specify the time. In this example, you can use 10 seconds.

Note that if you don’t specify arguments, Timelimit uses the default values: warntime=3600 seconds, warnsig=15, killtime=120, and killsig=9.

Conclusion

In this guide, you have learned how to run commands with a time limit in Linux. In review, you can use the Timeout command or the Timelimit utility.

The Timeout command is easy to use, but the Timelimit utility is a bit complicated but has more options. You can choose the most suitable option depending on your needs.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

Читайте также:  Как обновить приложение линукс

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Команда Linux timeout объяснение для начинающих (с примерами)

Иногда, когда вы выполняете команду в Linux, вам может потребоваться запустить ее в течение определенного периода времени.

Существует утилита командной строки – timeout – которая специально разработана для этой цели.

В этой статье мы обсудим основы этой команды на нескольких простых для понимания примерах.

Но прежде чем сделать это, стоит упомянуть, что все примеры в этом руководстве были протестированы на машине с Ubuntu 18.04 LTS.

Команда timeout Linux

Как следует из названия, команда timeout в Linux позволяет вам выполнять команду с ограничением по времени.

Ниже приводится ее синтаксис:

Ниже приведены примеры в стиле вопрос / ответ, которые должны дать вам лучшее представление о том, как работает этот инструмент.

Вопрос 1. Как использовать команду timeout?

Основное использование довольно просто – просто запустите ‘timeout’, указав во входных данных значение времени ожидания (в секундах), а также команду, которую вы хотите выполнить.

Например, если вы хотите тайм-аут команды ping через 5 секунд, вот как вы можете использовать тайм-аут в этом случае.

Вопрос 2. Как получить статус вывода команды?

По умолчанию, если команда timeout успешна, она возвращает 124 в качестве состояния выхода. Ниже приведен пример:

В первом случае я позволил команде timeout успешно работать, и, как вы можете видеть, статус вывода был 124.

Однако во время второго запуска я принудительно убил команду, используя Ctrl + C, и в этом случае, статус выхода был 0.

Но в случае, если вы хотите, чтобы тайм-аут возвратил статус входной команды, даже если тайм-аут прошел успешно, вам придется использовать параметр командной строки –preserve-status.

Вопрос 3. Как изменить время ожидания сигнала?

Нет смысла гадать, что тайм-аут работает, посылая сигнал входной команде, чтобы последняя прекратила выполнение к приближающемуся сроку.

По умолчанию SIGTERM используется командой.

Однако, если вы хотите, вы можете изменить сигнал, отправляемый по таймауту.

Для этого вам нужно будет использовать параметр командной строки -s и указать в качестве входного сигнала сигнал, который вы хотите отправить по таймауту.

Чтобы получить список доступных сигналов, которые вы можете отправить, выполните следующую команду:

Вопрос 4. Как сделать так, чтобы тайм-аут автоматически отправлял сигнал KILL?

Иногда вы можете встретить входную команду, которая продолжает выполняться даже после того, как тайм-аут отправляет начальный сигнал.

Для подобных случаев timeout предлагает опцию –kill-after.

Вот как man-страница объясняет это:

Итак, как вы можете видеть, вам нужно указать продолжительность, чтобы сообщить тайм-ауту, через сколько времени должен быть отправлен этот сигнал.

Заключение

В зависимости от того, какую работу вы выполняете, команда timeout может оказаться весьма удобным инструментом.

Здесь, в этом руководстве, мы обсудили большинство вариантов, предлагаемых этой утилитой.

Как только вы закончите практиковать их, вы можете узнать больше о тайм-ауте, перейдя на его справочную страницу.

Источник

Put a Timer on Your Running Commands With Timeout Command in Linux

With the timeout command you can set a time limit on running other commands and programs. If the program runs longer than the set limit, timeout kills it.

Sounds good, right? Let’s see how to use this command.

Using timeout command in Linux

Here’s the syntax for the timeout command:

As you can see, the time is always set in seconds here.

Let’s take an example with the sleep command. The sleep command basically ‘sleeps’ till the allotted time. Which means it just waits for that many seconds.

So if I use sleep 10, the shell waits for 10 seconds. But if I put a timeout of 4 seconds, the sleep command that was supposed to run for 10 seconds, ends in just 4 seconds.

Читайте также:  Популярные оболочки для linux

By default, the timeout command sends SIGTERM to politely kill the running program. You may send some other signal using the -s option.

You can see all the kill signals in Linux with kill -l command. Let’s say you want to send the SIGKILL signal (kill -9) instead of the default, SIGTERM. You can use something like this:

You could also use KILL or 9 (the number for SIGKILL as listed in kill -l) instead of SIGKILL.

Hard killing a program is not a nice thing to do. But a program can ignore the SIGTERM.

A better way to handle is to send the kill signal only when your initial termination request is ignored by the running program.

So, let’s say you want to run a program not more than 5 seconds. But if the running program refuses to stop, you send the kill signal 3 seconds after sending the default SIGTERM. Here’s what you can use:

This means your program won’t run more than 8 seconds. You can use the time command to check how long did the program actually run.

Is there a practical use of timeout command?

It sounds like one of those obscure Linux commands that you might not use every day. It could, however, be useful in some special situations.

For example, if you started playing a terminal game to fresh your mood for a bit but you lost track of the time and kept on playing far more than the desired time.

The timeout command is helpful in such cases.

Stay tuned to learn more Linux commands. Do subscribe to the newsletter to receive regular tips and tricks.

Источник

Linux run a command with a time limit (timeout)

How to run a command with a time limit on Linux

Our goal is to run a command named “ ping www.cyberciti.biz ” with a time limit of 30 seconds:

  1. Open the terminal application
  2. Run ping command have it abort after 30 seconds: timeout 30s ping www.cyberciti.biz
  3. One can combine sleep and other shell commands: ping www.cyberciti.biz & sleep 30s; kill $!

Let us see all timeout commands, syntax and examples in Linux operating systems.

Linux time limit command

The syntax is as follows for timeout command:
timeout DURATION COMMAND
timeout DURATION COMMAND arg1 arg2
timeout 1m ping google.com
timeout 30s tracepath www.cyberciti.biz
timeout [options] DURATION COMMAND arg1 arg2
DURATION is a floating point number with an optional suffix as follows:

  • s for seconds (the default).
  • m for minutes.
  • h for hours.
  • d for days.

How to run ping command for 8 seconds and abort it

Try:
date
timeout 8s ping www.cyberciti.biz
timeout 8s ping 192.168.2.254
date

Linux timeout command for ssh

Say you want to start ssh session just for fire mintues for running command/app1 and die after 5 minutes, run:
timeout 5m monitor@server1.cyberciti.biz — /path/to/app1 —save —force —update

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Specify the signal to be sent on timeout

The syntax is:
timeout -s 9 YourCommandHere
timeout —signal=9 YourCommandHere
timeout -s 15 30s tracepath google.com
timeout -s 9 2m tail -F /var/log/secure
## send SIGTERM as terminate signal ##
timeout -s SIGTERM 5m ping google.com
To get a list of signals, run the following kill command:
kill -l
Sample outputs:

Читайте также:  Нет строки windows installer

How to set grace period

Pass the -k or —kill-after=DURATION options to the timeout command. For example, send a KILL signal if COMMAND is still running this long after the initial signal was sent:
timeout -k=5 2m command1 arg1
timeout -k=5 -s SIGKILL 2m /path/to/my-app arg1 arg2

Other options:

The —preserve-status option allows timeout to exit with the same status as COMMAND, even when the command times out.
timeout —preserve-status 10s command1
The —foreground option when not running timeout directly from a shell prompt, allow COMMAND to read from the TTY and get TTY signals; in this mode, children of COMMAND will not be timed out:
timeout —foreground 1m command2
## Login to remote server. Run htop and die after 30seconds ##
timeout —foreground 30s ssh -t vivek@server1.cyberciti.biz htop
timeout —foreground 20s ssh -t vivek@centos7 top

Bash solution

The syntax is pretty simple with the help of read command and kill command:
MyCoolCommand Arg1 & read -t TIMEOUT_VALUE || kill $!
command arg1 & read -t 30 || kill $!
tail -F /var/log/secure & read -t 60 || kill $!
ping 192.168.2.254 & read -t 10 || kill $!

The $! contains the process ID (PID) of the most recently executed background pipeline. In this example ping was the most recently executed background job.

A note about Perl one liner for Unix/macOS/BSD oses

Try the following combination of Perl and shell function when don’t have or don’t want one of the above programs, you can use a perl one-liner to set an ALRM and then exec the program you want to run under a time limit. In any case, you must understand what your program does with SIGALRM; programs with periodic updates usually use ALRM for that purpose and update rather than dying when they receive that signal.

Источник

Unix / Linux: Run Command with Timeout

Objective: Execute / Run a command and kill it if it’s still running after a specified duration on Unix / Linux.

On Linux, the timeout utility can be used to run a command with a time limit. The timeout command will kill the process once the specified duration has elapsed. The duration is a number with an optional suffix: ‘s’ for seconds (the default), ‘m’ for minutes, ‘h’ for hours or ‘d’ for days.

To kill a slow process after 1 minute, you can use the following syntax.

The duration can also be specified in minutes using the following syntax.

The arguments “arg1” and “arg2” are passed as input to slow-command and not to the timeout utility. After 1 minute, the timeout sends a SIGTERM signal to the process. Some process will not terminate when a SIGTERM signal is sent. In such cases, we will need to send a SIGKILL signal to the process instead.

There are two ways to send a SIGKILL signal to the process from the timeout utility. The first way is by specifying the default signal to be sent using the following syntax.

The second way is to first send the SIGTERM after the initial timeout. Then, wait for another timeout and send a SIGKILL to the process if it’s still running. This can be done using the following syntax.

The process is sent a SIGTERM signal after 60 seconds. If it is still running, then a SIGKILL signal is sent after another 30 seconds.

In the event that the timeout utility is not available, the below 1-liner can be used as an alternative.

The slow-command is started as a background process. The sleep command will then pause till the timeout duration. In our case, it will sleep for 60 seconds. Once 60 seconds has elapsed, the kill command will send a SIGTERM signal to the slow-command process. The ‘ $! ‘ shell variable will give the PID of the last background job.

Источник

Оцените статью