如何永久设置给定进程的 CPU 限制。cpulimit 和 nice 不起作用

Raf*_*fal 12 11.10

有很多类似的问题,但没有一个能帮助我解决我的问题。

我在服务器上有 ubuntu 11.10(它是桌面版)。我有一个正在运行的网站。有一个进程非常重要,但不必以高优先级运行。我想永久限制进程的CPU 使用,而不是用户。这个进程是由 exec 函数运行的(它是 php 函数,不是系统进程)。

所以我看到 2 个选项: 1. 每次执行函数时添加某种限制。2. 永久限制此进程的 CPU 使用率。

我尝试使用“nice”和 cpulimit,但似乎没有任何效果。Nice 没有任何效果,cpulimit(带 -e)说:“没有找到目标进程”。

我是一个初学者,所以请假设我几乎一无所知。

Pan*_*her 19

在没有要求的细节...

这是我在 ubuntu 上使用 cgroups 的方法。

在这篇文章中,您需要将变量“$USER”更改为运行该进程的用户

我添加了内存信息,这将成为常见问题解答,如果您不需要它,请不要使用它。

1) 安装 cgroup-bin

sudo apt-get install cgroup-bin
Run Code Online (Sandbox Code Playgroud)

2) 重新启动。cgroups 现在位于/sys/fs/cgroup

3)为您的用户(进程的所有者)创建一个 cgroup

# Change $USER to the system user running your process.
sudo cgcreate -a $USER -g memory,cpu:$USER
Run Code Online (Sandbox Code Playgroud)

4)您的用户可以管理资源。默认情况下,用户获得 1024 个 cpu 单位(份额),因此为了将 cpu 限制在 10% 左右,内存以字节为单位......

# About 10 % cpu
echo 100 > /cgroup/cpu/$USER/cpu.shares

# 10 Mb
echo 10000000 > /cgroup/memory/$USER/memory.limit_in_bytes
Run Code Online (Sandbox Code Playgroud)

5)启动你的进程(将exec改为cgexec)

# -g specifies the control group to run the process in
# Limit cpu
cgexec -g cpu:$USER command <options> &

# Limit cpu and memory
cgexec -g memory,cpu:$USER command <options> &
Run Code Online (Sandbox Code Playgroud)

配置

假设 cgroups 为您工作;)

编辑/etc/cgconfig.conf,添加您的自定义 cgroup

# Graphical
gksudo gedit /etc/cgconfig.conf

# Command line
sudo -e /etc/cgconfig.conf
Run Code Online (Sandbox Code Playgroud)

添加到您的 cgroup 中。再次将 $USER 更改为拥有该进程的用户名。

group $USER {
# Specify which users can admin (set limits) the group
perm {    
    admin {
        uid = $USER;
    }
# Specify which users can add tasks to this group
    task {
        uid = $USER;
    }
}
# Set the cpu and memory limits for this group
cpu {
    cpu.shares = 100;
    }
memory {
    memory.limit_in_bytes = 10000000;
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以指定组gid=$GROUP,/etc/cgconfig.conf 有很好的注释。

现在再次运行您的流程 cgexec -g cpu:$USER command <options>

您可以在 /sys/fs/cgroup/cpu/$USER/tasks

例子

bodhi@ufbt:~$ cgexec -g cpu:bodhi sleep 100 &

[1] 1499

bodhi@ufbt:~$ cat /sys/fs/cgroup/cpu/bodhi/tasks

1499

有关其他信息,请参阅:http : //docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Resource_Management_Guide/

  • 我设法完成了第 1 部分。它正在运行,但是您应该添加仅当其他一些进程需要 cpu/内存时进程受限的信息。这并不明显 - 我需要很长时间才能弄清楚(因为我是初学者)。我是否正确理解“配置”即使在重新启动后也会保存设置? (2认同)