How to set CAP_SYS_NICE capability to a Linux user?

CJlano picture CJlano · Oct 3, 2011 · Viewed 22.3k times · Source

My program is using the Linux system call setpriority() to change the priorities of the threads it creates. It needs to set negative priorities (-10) but, as mentioned on the documentation, this fails when run as a normal user.

The user needs the CAP_SYS_NICE capability to be able to set the priorities as he wants, but I have no idea how to give such capability to the user.

So my question: how to set CAP_SYS_NICE capability to a Linux user?

Answer

Ryan Armstrong picture Ryan Armstrong · May 30, 2016

There is a nice handy utility for setting capabilities on a binary: setcap. This needs to be run as root on your application binary, but once set, can be run as a normal user. Example:

$ sudo setcap 'cap_sys_nice=eip' <application>

You can confirm what capabilities are on an application using getcap:

$ getcap <application>
<application> = cap_sys_nice+eip

I'd suggest integrating the capabilities into your makefile in the install line, which is typically run as root anyhow. Note that capabilities cannot be stored in a TAR file or any derivative package formats. If you do package your application later on, you will need a script (postinst for Debian packages) to apply the capability on deploy.