Getting and setting process priority (nice value))

Thanks for taking the time.

I’m trying to find a way to set the priority of the current process (niceness) for a CLI I’m building.

In Ruby, it is possible to do something like:

Process.setpriority(Process::PRIO_PROCESS, 0, -20)

I’m trying to find a way to do it in Crystal.

Hi!

Here’s something that should work for linux and mac:

lib LibC
  fun setpriority(which : Int, who : Int, prio : Int) : Int
  fun getpriority(which : Int, who : Int) : Int
end

class Process
  enum PriorityKind
    Process = 0
    Group   = 1
    User    = 2
  end

  def self.set_priority(which : PriorityKind, who : Int32, priority : Int32)
    LibC.setpriority(which.value, who, priority)
  end

  def self.get_priority(which : PriorityKind, who : Int32)
    LibC.getpriority(which.value, who)
  end
end

p Process.get_priority(:process, 0)
p Process.set_priority(:process, 0, 20)
p Process.get_priority(:process, 0)

Please consider opening an issue in our GitHub repo to discuss including this in the standard library.

Thank you!

EDIT: updated with getpriority too.

5 Likes