> For the complete documentation index, see [llms.txt](https://wskdsgcf.gitbook.io/mastering-go-zh-cn/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wskdsgcf.gitbook.io/mastering-go-zh-cn/08.0/08.14.md).

# 08.14 处理Unix信号

`Go`为程序员提供了`os/signal`包来处理信号。本节将向你显示如何处理`Unix`信号。

首先，让我们介绍`Unix`信号的一些有用信息。你是否使用`Ctrl+C`停止正在运行的程序？如果是，则它们已经比较相似，因为`Ctrl+C`向程序发送`SIGINT signal`。严格来讲，`Unix`信号是可以通过名称或数字访问的软件中断，它们提供了在`Unix`系统上处理异步事件的方法。有两种方式发送信号：通过名字或者通过数字。通常来说，通过名字发送信号比较安全，因为你不太可能不小心发出错误的信号。

一个程序是不可能处理所有的信号的：一些信号既不能被捕获，也不能被忽略。`SIGKILL`和`SIGSTOP`信号不能被捕获、阻塞或忽略。这样做的原因是，它们为内核和根用户提供了一种停止任何进程的方法。`SIGKILL`信号，即数字`9`，通常在需要响应迅速的极端条件下调用。因此，它是唯一一个通常由数字调用的信号，这仅仅是因为这样做更快。

> *`signal.SIGINFO`在`Linux`机器上不可用。这意味着，如果你要在一个`Linux`机器上运行包含它的`Go`程序，则需要用另一个信号替换它，否则`Go`程序将无法编译和执行。*

给进程发送信号的最常用方式是通过`kill(1)`方法。默认情况下，`kill(1)`发送`SIGTERM`信号。如果你想查看`Unix`机器上支持的所有信号，可以执行`kill -l`命令。

如果你在无权限的情况下给一个进程发送信号，`kill(1)`并不会执行，且会返回类似如下的错误提示：

```
$ kill 1210
-bash: kill: (1210) - Operation not permitted
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wskdsgcf.gitbook.io/mastering-go-zh-cn/08.0/08.14.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
