Docs/linux基础/linux限制单用户的cpu与内存使用率.md

37 lines
No EOL
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

在Linux中可以使用cgroups来限制单用户的CPU和内存使用率。以下是一个简单的例子演示如何为用户username设置CPU和内存的使用限制。
首先确保你的系统已经安装了cgroups和pam_cgroup模块。
创建cgroup子系统目录
```
sudo mkdir /sys/fs/cgroup/cpu,memory/username
```
编辑/etc/cgconfig.conf文件添加以下内容来确保在系统重启后自动创建cgroup
```text
group username {
cpu {
cpu.cfs_period_us = "100000";
cpu.cfs_quota_us = "50000";
}
memory {
memory.limit_in_bytes = "256M";
}
}
```
设置用户的session自动挂载cgroup
编辑/etc/pam.d/common-session添加以下行
```bash
session required pam_cgroup.so
```
设置用户的CPU和内存使用限制
```bash
sudo cgset -r cpu.cfs_period_us=100000 -r cpu.cfs_quota_us=50000 -r memory.limit_in_bytes=268435456 /username
```
重新登录或重启以应用这些设置。
请注意这些设置将在用户下次登录时生效。你可以根据需要调整cpu.cfs_quota_usCPU使用限额单位为微秒和memory.limit_in_bytes内存使用限额单位为字节的值。
这个例子中的设置将用户username的CPU使用限制为50%的可用CPU时间并将内存使用限制为256MB。