# 查找linux下进程占用CPU过高的原因，以php-fpm为例

很多时候，线上服务器的进程在某时间段内长时间占用CPU过高，为了优化，我们需要找出原因。

### 1、找出占用CPU最高的10个进程

```bash
ps aux | sort -k3nr | head -n 10
```

或查看占用内存最高的10个进程

```bash
ps aux | sort -k4nr | head -n 10　
```

或者使用 top ，按 1 显示CPU列表，再按 shift+p 以CPU排序

```bash
top
```

　　

### 2、对进程进行跟踪查看

```bash
# 查看进程打开的文件
lsof -p 进程PID

# 查看进程在处理的文件
ll /proc/进程PID/fd

# 查看进程的内存使用情况
pmap 进程PID

# 通过strace来跟踪进程的系统调用
strace -p 进程PID

# 当然我们也可以查看汇总的信息
strace -cp 进程PID

# 如果我们想跟踪某进程所有的系统调用，并统计调用时间，并导出为文件，可用如下命令
strace -o 导出文件 -T -tt -e trace=all -p 进程PID
```

### 3、查找php-fpm占用过高的原因

我们可以配置php-fpm的慢日志，查找是哪些文件导致php-fpm占用过高。

先找到 php-fpm.conf 文件位置

```bash
ps -ef|grep php
```

修改php-fpm.conf，并打开日志选项

```bash
;错误日志
error_log = log/php-fpm.log

;访问日志
access.log = log/$pool.access.log

;访问日志格式
access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{mili}d %{kilo}M %C%%"

;慢日志
slowlog = log/$pool.log.slow

;慢日志超时时间
request_slowlog_timeout = 3
```

注意：log 目录需要我们自已创建。 我们可以通过 php-fpm 的慢日志定位是哪个文件中哪行哪个方法慢，这样针对性的进行优化。


---

# Agent Instructions: 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://close.gitbook.io/yun-wei-bi-ji/centos/php/cha-zhao-linux-xia-jin-cheng-zhan-yong-cpu-guo-gao-de-yuan-yin-yi-phpfpm-wei-li.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.
