Shell 脚本演示 Linux 中的 Wait 命令

Wait命令是进程管理命令之一。Linux 中有不同的进程命令,主要使用 5 个命令,它们是pswaitsleepkillexit

ps是进程状态缩写。它显示有关活动进程的信息。wait命令将暂停调用线程的执行,直到其子进程之一终止。它将返回该命令的退出状态。sleep命令用于将下一个命令的执行延迟给定的秒数、小时数、分钟数、天数。kill用于终止后台运行的进程。向进程发送终止信号,然后进程停止。它以进程 ID 作为参数。exit命令用于退出当前 shell 环境。

 

让我们通过一些例子来进一步了解 wait 命令:

wait是 Linux shell 中的一个内置命令。它等待进程改变其状态,即等待任何正在运行的进程完成并返回退出状态。

句法:

 

wait [ID]

此处,ID 是PID(进程标识符),对于每个正在运行的进程都是唯一的。要查找进程的进程 ID,可以使用以下命令:

pidof [process_name]

方法:

  • 创建一个简单的过程。
  • 使用特殊变量($!)来查找该特定进程的 PID(进程 ID)。
  • 打印进程 ID。
  • 使用带有进程 ID 的wait命令作为参数来等待该进程完成。
  • 进程完成后,打印进程 ID 及其退出状态

注意:存在状态 0 表示该过程已成功执行且没有任何问题。除 0 以外的任何值均表示该过程尚未成功完成。

脚本:

 

#!/bin/bash

# creating simple process that will create file and write into it
cat > GEEKSFORGEEKS.txt <<< "Something is going to save into this file" &

# this will store the process id of the running process
# $! is a special variable in bash 
# that will hold the PID of the last active process i.e. creating a file.
pid=$!

# print process is running with its PID
echo "Process with PID $pid is running"

# Waiting until process is Completed
wait $pid

# print process id with its Exit status
# $? is special variable that holds the return value of the recently executed command.
echo "Process with PID $pid has finished with Exit status: $?"

 

posted @ 2024-06-02 22:39  wongchaofan  阅读(66)  评论(0编辑  收藏  举报