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?
To set a particular capability on a file, use setcap "capability_string" /path/to/file . To remove all capabilities from a file, use setcap -r /path/to/file . The second command produces no output, meaning this file does not have any capability.
Starting with kernel 2.2, Linux divides the privileges traditionally associated with superuser into distinct units, known as capabilities, which can be independently enabled and disabled. Capabilities are a per-thread attribute.
All the capabilities for processes and threads are stored in the status file under the process/thread directory in the /proc file system. These properties start "Cap" name. Alternatively, for a running process, you can get the hex-encoded capabilities and then later decode it with capsh.
Using the capsh utility we can decode them into the capabilities name. Although that works, there is another and easier way. To see the capabilities of a running process, simply use the getpcaps tool followed by its process ID (PID). You can also provide a list of process IDs.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With