什么是Linux中的kill命令?

时间:2020-02-23 14:39:23  来源:igfitidea点击:

需要杀死正在运行的进程吗? Linux中的kill命令就是为此而构建的。
没有任何操作系统是完美的。
因此,您的Linux系统通常必须处理偶尔的无响应进程。

为了处理需要结束进程的实例,我们在Linux中使用kill命令。

在本教程中,我们将了解kill命令的工作方式。
稍后,我们将尝试使用kill命令满足我们的要求。

kill命令的基础

有多种实用程序可帮助Linux用户终止可能行为异常的进程。
Linux中的kill命令中用于此目的的最常用的实用程序之一。

Linux中的kill命令用于通过命令行手动终止进程。
它是大多数Bourneshell派生的shell(例如bash)的shell内置实用程序。

Linux中kill命令的bash内置版本的选项与/bin/kill中的独立可执行文件略有不同。

但是,出于本教程的考虑,我们将使用kill命令的bash内置版本。
要检查系统上包含kill命令的所有位置,请在终端中键入以下命令。

root@ubuntu:~# type -a kill
kill is a shell builtin
kill is /bin/kill

您应该获得与上面的屏幕截图类似的输出。
此输出确认kill命令的shell内置版本优先于其独立可执行文件。

因此,使用kill命令将执行bash内置版本。
您可以通过使用命令的完整路径/bin/kill /来使用可执行文件。
但是,我们将继续使用kill命令的bash内置版本。

Linux中的Kill命令

理解任何命令的最佳方法是通过了解其语法。
这是Linux中kill命令的语法。

kill [option] PID

命令kill用于向进程发送信号。
该信号由调用kill命令时使用的选项决定。

使用kill命令处理终止信号

尽管有很多选项可供选择,但我们在下表中列出了最常用的选项。

OptionSignal numberAction
SIGTERM15The SIGTERM signal is used to tell a process to end gracefully. This kill signal Jan get interpreted by the process, or it Jan get ignored.
SIGKILL9The SIGKILL signal is used to force a process to be terminated. It is a signal that cannot be ignored by the process in any case.
SIGHUP1The SIGHUP signal is used to ‘hang up’ on a process. This can be used to restart a process.
SIGINT2The SIGINT signal is used when the user wants to interrupt a process.

如果我们未指定选项,则默认选项将用于kill命令。
Linux中kill命令的默认选项是SIGTERM。
可以通过三种不同的方式在kill命令中使用选项。

使用信号编号

kill -9 [PID]

带有" SIG"前缀

kill -SIGKILL [PID] 

没有" SIG"前缀

kill -KILL [PID]

在Linux中使用kill命令时,进程ID(PID)是什么?

转到最后一个参数PID。
PID是指某个进程的进程ID。
每当进程启动时,内核就会为它分配一个唯一的ID。

我们在Linux的kill命令中使用PID,以指定要将kill信号发送到的进程。

kill命令中使用的PID可以具有任何整数值。
这是一个包含PID值及其对kill命令的影响的列表。

Value of PIDEffect on kill command
PID>0This sends the appropriate kill signal to the process which as a PID equal to the PID mentioned in the command.
PID=0This sends the appropriate kill signal to all the processes which are running under the same group as the one invoking the command.
PID=-1This sends the appropriate kill signal to all the processes which are running under the same user as the one invoking the command. In the event of such command being invoked by the root user, the kill signal is sent to every process except the kill process and init process.
PID<-1This sends the appropriate kill signal to all the processes which are running in a group, such that the group ID is equal to the absolute value of the PID used in the kill command.

当我们想知道进程的PID时,可以使用以下命令。

pidof <processname>

该命令将返回指定进程的所有PID。
现在,我们可以使用此PID向进程发送所需的终止信号。

使用kill命令

现在,我们已经了解了Linux中的kill命令及其参数。
现在是时候使用这些知识来执行两项涉及使用kill命令的常见操作。

杀死进程

顾名思义,kill命令在Linux中最常见的用法是杀死进程。
其中我们将选择使用kill命令杀死系统中最重要的命令进程。

在本演示中,我只是在多个shell上运行了这些程序。

为此,我们将首先使用以下命令查找与top命令进程关联的PID。

pidof top

现在,我们使用SIGKILL kill信号杀死与top命令关联的所有进程。

重启进程

在Linux中使用kill命令可能实现的另一个功能是重新启动进程。
如果服务正在运行,但需要重新读取其配置文件以启用最近的更改,这将很有帮助。

例如,如果要在系统上重新加载Lighttpd服务器进程,则可以运行以下命令。

sudo kill -SIGHUP <process ID of Lighttpd>