Automatically adjusting process priorities under Linux

前端 未结 7 1551
眼角桃花
眼角桃花 2021-02-20 11:52

I\'m trying to write a program that automatically sets process priorities based on a configuration file (basically path - priority pairs).

I thought the best solution wo

7条回答
  •  别那么骄傲
    2021-02-20 12:26

    If the processes in question are started by executing an executable file with a known path, you can use the inotify mechanism to watch for events on that file. Executing it will trigger an I_OPEN and an I_ACCESS event.

    Unfortunately, this won't tell you which process caused the event to trigger, but you can then check which /proc/*/exe are a symlink to the executable file in question and renice the process id in question.

    E.g. here is a crude implementation in Perl using Linux::Inotify2 (which, on Ubuntu, is provided by the liblinux-inotify2-perl package):

    perl -MLinux::Inotify2 -e '
      use warnings;
      use strict;
      my $x = shift(@ARGV);
      my $w = new Linux::Inotify2;
      $w->watch($x, IN_ACCESS, sub
      {
        for (glob("/proc/*/exe"))
        {
          if (-r $_ && readlink($_) eq $x && m#^/proc/(\d+)/#)
          {
            system(@ARGV, $1)
          }
        }
      });
      1 while $w->poll
    ' /bin/ls renice
    

    You can of course save the Perl code to a file, say onexecuting, prepend a first line #!/usr/bin/env perl, make the file executable, put it on your $PATH, and from then on use onexecuting /bin/ls renice.

    Then you can use this utility as a basis for implementing various policies for renicing executables. (or doing other things).

提交回复
热议问题