如何在 Linux 中執行帶時間限制(超時)的命令


有時 Unix 命令可能會執行很長時間而沒有給出最終輸出,或者它可能會進行處理並間歇地給出部分輸出。在這種情況下,我們希望設定一個時間範圍,在此時間範圍內命令必須完成,否則程序應中止。這可以透過使用以下選項來實現。

使用 timeout 工具

Timeout 工具強制命令在給定的時間範圍內無法完成時中止。以下是語法和示例。

語法

timeout DURATION COMMAND [ARG]...

Where Duration is the number seconds you want the command to run
Before aborting if the execution is not complete. In duration flag we have,
s - seconds
m - minutes
h - hours
d - days

示例

在以下示例中,我們使用 ping 命令來 ping 我們的網站,並且該過程僅持續 5 秒,之後命令會自動停止執行。

$ timeout 5s ping tutorialspoint.com

執行以上程式碼將得到以下結果:

PING tutorialspoint.com (94.130.82.52) 56(84) bytes of data.
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=1 ttl=128 time=126 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=2 ttl=128 time=126 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=3 ttl=128 time=126 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=4 ttl=128 time=126 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=5 ttl=128 time=127 ms

使用 timelimit

需要安裝 timelimit 程式才能獲得此功能,以便在特定時間後終止命令。它將傳遞警告訊號,然後在超時後,它將傳送終止訊號。您還可以傳遞引數,例如 - 引數,例如 killtime、warntime 等。因此,此命令使我們可以更精細地控制警告和終止命令。

首先,我們使用以下命令安裝程式。

sudo apt-get install timelimit

接下來,我們檢視以下使用 timelimit 的示例。此處 –t 指定在傳送 warnsig 之前程序的最大執行時間(以秒為單位),而 T 是在傳送 warnsig 後傳送 killsig 之前程序的最大執行時間。

timelimit -t6 -T12 ping tutorialspoint.com

執行以上程式碼將得到以下結果:

PING tutorialspoint.com (94.130.82.52) 56(84) bytes of data.
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=1 ttl=128 time=127 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=2 ttl=128 time=126 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=3 ttl=128 time=126 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=4 ttl=128 time=127 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=5 ttl=128 time=128 ms
64 bytes from tutorialspoint.com (94.130.82.52): icmp_seq=6 ttl=128 time=126 ms
timelimit: sending warning signal 15

更新於: 2020年2月25日

562 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告