linux

Linux nohup命令如何设置超时时间

小樊
47
2025-03-05 21:30:54
栏目: 智能运维

nohup 命令本身没有直接设置超时时间的功能

方法一:使用 timeout 命令

timeout 命令允许你为其他命令设置超时时间。例如,如果你想让一个名为 my_command 的命令在 60 秒后超时,可以使用以下命令:

timeout 60 nohup my_command &

这将在 60 秒后终止 my_command 进程。请注意,这种方法可能不适用于所有系统,因为 timeout 命令可能不是预装的。你可以使用 which timeout 命令检查它是否在你的系统上可用。

方法二:编写一个简单的 shell 脚本

创建一个名为 run_with_timeout.sh 的 shell 脚本,内容如下:

#!/bin/bash

timeout $1 $2
if [ $? -eq 124 ]; then
  echo "Command timed out"
else
  echo "Command completed successfully"
fi

给脚本添加可执行权限:

chmod +x run_with_timeout.sh

现在,你可以使用这个脚本为其他命令设置超时时间,例如:

nohup ./run_with_timeout.sh 60 my_command &

这将在 60 秒后终止 my_command 进程,并在控制台输出 “Command timed out”。如果命令在超时时间内完成,将输出 “Command completed successfully”。

0
看了该问题的人还看了