Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Linux timeout command

Linux timeout command

Linux Command Reference Linux Command Reference


timeout is a utility command in Linux systems used to terminate a running command after a specified time. This command is especially useful in the following scenarios:

The timeout command is part of the GNU coreutils package and is preinstalled on most Linux distributions.


Command syntax

The basic syntax of the timeout command is as follows:

timeout [选项] 持续时间 命令 [参数...]

Parameter Description

  1. Duration:

  2. can be a plain number (default unit is seconds)
  3. You can also specify a unit:10s(10 seconds),5m(5 minutes),1h(1 hour)
  4. Decimal values are supported:0.5s(500 milliseconds),1.5m(1 minute 30 seconds)
  5. - can be a plain number (default unit is seconds) - you can also specify units: `10s` (10 seconds), `5m` (5 minutes), `1h` (1 hour) - decimals are supported: `0.5s` (500 milliseconds), `1.5m` (1 minute 30 seconds)
    1. Command:

    2. The command or program to execute
    3. can be a built-in command or an external program
    4. - The command or program to execute - can be a built-in command or an external program
      1. Parameters:

      2. Arguments passed to the command
      3. - Arguments passed to the command

        Common options

        Option Description Example
        -s or --signal Specify the signal to send after timeout (default is TERM) timeout -s KILL 5s command
        -k or --kill-after If the initial signal is ineffective, send a KILL signal after a specified time timeout -k 5s 10s command
        --preserve-status Return the exit status of the terminated command timeout --preserve-status 5s command
        --foreground Run the command in the foreground (by default in the background) timeout --foreground 5s command
        -v or --verbose Display verbose output timeout -v 5s command

        Usage examples

        Basic Usage

        Example

        Terminate the ping command after 5 seconds

        timeout 5s

        ping

        example.com

        Terminate script execution after 1 minute

        timeout 1m .

        /

        long_script.sh

        Specify the signal type

        Example

        Send an INT signal after 3 seconds (equivalent to Ctrl+C)

        timeout

        -s

        INT 3s

        command

        Send a KILL signal after 10 seconds (forced termination)

        timeout

        -s

        KILL 10s

        command

        Compositional use

        Example

        Send a TERM signal first, then a KILL signal after 5 seconds

        timeout

        -k

        5s 10s

        command

        Get the exit status

        Example

        Preserve the exit status of the terminated command

        timeout

        --preserve-status

        5s

        command

        echo

        $?

         

        Check the exit status code


        Practical Application Scenarios

        1. Prevent scripts from running indefinitely

        Example

        Limit a database backup script to at most 2 hours

        timeout 2h .

        /

        backup_database.sh

        2. Timeout control in automated testing

        Example

        Limit test cases to at most 30 seconds

        timeout 30s .

        /

        run_test_case.sh

        3. Network operation timeout

        Example

        Limit file downloads to at most 1 minute

        timeout 1m

        wget

        http:

        //

        example.com

        /

        large_file.zip

        4. Timeout handling for interactive programs

        Example

        Give the user at most 10 seconds to enter a choice

        timeout 10s

        read

        -p

        "Please enter your choice: "

        choice


        Notes

        1. Signal Processing:

        2. Some programs may catch and ignore the TERM signal, in which case the KILL signal is needed
        3. Use the KILL signal with caution during critical data operations, as it may cause data corruption
        4. - Some programs may catch and ignore the TERM signal, in which case the KILL signal is needed - use the KILL signal with caution during critical data operations, as it may cause data corruption
          1. Child process handling:

          2. By default, timeout only terminates the directly launched process and may not terminate all child processes
          3. To terminate the entire process tree, you can consider combining with kill Command
          4. - By default, timeout only terminates the directly launched process and may not terminate all child processes - to terminate the entire process tree, you can consider combining with the `kill` command
            1. Time precision:

            2. Linux kernel time precision is usually at the millisecond level
            3. Very short times (such as 0.001s) may not be controlled precisely
            4. - Linux kernel time precision is usually at the millisecond level - very short times (such as 0.001s) may not be controlled precisely
              1. Return Value:

              2. If the command completes before the timeout, return the command's exit status
              3. If terminated due to timeout, return 124
              4. If timeout itself encounters an error, return 125-128
              5. - If the command completes before the timeout, return the command's exit status - if terminated due to timeout, return 124 - if timeout itself encounters an error, return 125-128

                Advanced techniques

                1. Use in combination with other commands

                Example

                Perform cleanup operations after a timeout

                timeout 30s

                command

                ||

                echo

                "Command timed out, performing cleanup..."

                2. Use in scripts

                Example

                #!/bin/bash

                if

                timeout 10s

                command

                ;

                then

                   

                echo

                "Command completed successfully"

                else

                   

                echo

                "Command timed out or failed"

                fi

                3. Monitor resource usage

                Example

                Limit CPU time (requires combining with ulimit)

                (

                ulimit

                -t

                10

                ; timeout 20s

                command

                )


                Frequently Asked Questions

                Q1: What is the difference between timeout and sleep?

                A: sleep simply waits for a specified time, while timeout limits the execution time of another command.

                Q2: How do I terminate all child processes started by timeout?

                A: You can use the process group approach:

                timeout --foreground 10s sh -c 'command & wait'
                
                

                Q3: Why doesn't my program terminate immediately after the timeout?

                A: It may be because the program caught the default TERM signal; try using -s KILL option.

                Q4: How can I tell whether a command was terminated due to a timeout?

                A: Check whether the exit status code is 124:

                Example

                timeout 5s slow_command

                if

                [

                $?

                -eq

                124

                ]

                ;

                then

                   

                echo

                "Command terminated due to timeout"

                fi


                Summary

                The timeout command is a very useful tool in Linux system administration; it can help us:

                1. Control program execution time and prevent resources from being occupied for long periods
                2. Improve script robustness and avoid infinite waits
                3. Implement timeout mechanisms in automated tasks
                4. Handle operations with unpredictable execution times

                By using the timeout command appropriately, you can make your Linux system administration more efficient and reliable.


                Linux Command Reference Linux Command Reference