Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - decrease niceness value

Tags:

python

unix

nice

Using python I can easily increase the current process's niceness:

>>> import os
>>> import psutil

>>> # Use os to increase by 3
>>> os.nice(3)
3

>>> # Use psutil to set to 10
>>> psutil.Process(os.getpid()).nice(10)
>>> psutil.Process(os.getpid()).nice()
10

However, decreasing a process's niceness does not seem to be allowed:

>>> os.nice(-1)
OSError: [Errno 1] Operation not permitted

>>> psutil.Process(os.getpid()).nice(5)
psutil.AccessDenied: psutil.AccessDenied (pid=14955)

What is the correct way to do this? And is the ratchet mechanism a bug or a feature?

like image 258
TDN169 Avatar asked Dec 11 '15 15:12

TDN169


2 Answers

Linux, by default, doesn't allow unprivileged users to decrease the nice value (i.e. increase the priority) of their processes, so that one user doesn't create a high-priority process to starve out other users. Python is simply forwarding the error the OS gives you as an exception.

The root user can increase the priority of processes, but running as root has other consequences.

like image 119
Colonel Thirty Two Avatar answered Oct 21 '22 19:10

Colonel Thirty Two


This is not a restriction by Python or the os.nice interface. It is described in man 2 nice that only the superuser may decrease the niceness of a process:

nice() adds inc to the nice value for the calling process. (A higher nice value means a low priority.) Only the superuser may specify a negative increment, or priority increase. The range for nice values is described in getpriority(2).

like image 27
Chris Seymour Avatar answered Oct 21 '22 18:10

Chris Seymour