【问题标题】:Change niceness of all processes by niceness [closed]通过niceness改变所有进程的niceness [关闭]
【发布时间】:2015-09-22 19:07:33
【问题描述】:

我正在使用 Debian,有没有一种方法可以根据当前的友好度来改变所有正在运行的进程的友好度?例如,将所有当前运行的进程更改为 -20 或 -19 到 -10。 Renice 可以更改进程,并为某些用户更改进程。但据我所知,基于当前的友好度,它无法做到。

我正在尝试以 -20 的精度运行一个程序,以尝试绕过一些似乎是半定期发生的计时尖峰。这些可能是由具有相同优先级的某些进程占用资源引起的。我希望通过一些漂亮的摆弄来检查这一点。

【问题讨论】:

  • 你用什么语言编程?到目前为止,您尝试过什么?
  • 您可以编写一个运行ps -o pid,nibash 脚本,并且对于NI 列为-20 的每个进程,它都会对其进行修改。
  • 该程序是用 C++ 编写的。我会用 system() 调用来试一试。我会在这里更新我的想法。
  • 您应该可以使用/proc 来获取C 程序中的信息。
  • 这与编程无关,而是系统管理。

标签: c linux debian nice


【解决方案1】:

从 C 语言开始:

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>

static char *prstatname(char *buf, char **endptr)
{
    /* parse process name */
    char *ptr = buf;
    while (*ptr && *ptr != '(') ++ptr;
    ++ptr;
    if (!ptr) return 0;

    char *name = ptr;
    while (*ptr)
    {
        if (*ptr == ')' && *(ptr+1) && *(ptr+2) && *(ptr+3)
                && *(ptr+1) == ' ' && *(ptr+3) == ' ')
        {
            *ptr = 0;
            *endptr = ptr + 1;
            return name;
        }
        ++ptr;
    }
    return 0;
}

int main(void)
{
    DIR *proc = opendir("/proc");
    if (!proc) return 1;

    struct dirent *ent;

    while ((ent = readdir(proc)))
    {
        /* check whether filename is all numeric, then it's a process id */
        char *endptr;
        int pid = strtol(ent->d_name, &endptr, 10);
        if (*endptr) continue;

        /* combine to '/proc/{pid}/stat' to get information about process */
        char statname[64] = {0,};       
        strcat(statname, "/proc/");
        strncat(statname, ent->d_name, 52);
        strcat(statname, "/stat");

        FILE *pstat = fopen(statname, "r");
        if (!pstat) continue;

        /* try to read process info */
        char buf[1024];
        if (!fgets(buf, 1024, pstat))
        {
            fclose(pstat);
            continue;
        }
        fclose(pstat);

        char *name = prstatname(buf, &endptr);
        if (!name) continue;

        /* nice value is in the 17th field after process name */
        int i;
        char *tok = strtok(endptr, " ");
        for (i = 0; tok && i < 16; ++i) tok = strtok(0, " ");
        if (!tok || i < 16) continue;

        int nice = strtol(tok, &endptr, 10);
        if (*endptr) continue;

        printf("[%d] %s -- nice: %d\n", pid, name, nice);
    }
}

如果你理解这个程序,你可以很容易地修改它来做你想做的事情。

【讨论】:

    【解决方案2】:

    以niceness 19到10 renice所有进程:

    ps -eo nice,pid | sed -e 's/^ \+19//;tx;d;:x' | xargs sudo renice 10

    弄清楚为什么这样有效,或将其扩展到同时处理多个优先级,留给读者作为练习。

    【讨论】:

      猜你喜欢
      • 2020-04-22
      • 2011-08-08
      • 1970-01-01
      • 1970-01-01
      • 2012-12-13
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      • 2022-06-29
      相关资源
      最近更新 更多