Change priority of the current process in C

2019-04-04 23:52发布

On Windows I can do:

HANDLE hCurrentProcess = GetCurrentProcess();

SetPriorityClass(hCurrentProcess, ABOVE_NORMAL_PRIORITY_CLASS);

How can I do the same thing on *nix?

3条回答
在下西门庆
2楼-- · 2019-04-05 00:41

If doing something like this under unix your want to (as root) chmod you task and set the s bit. Then you can change who you are running as, what your priority is, your thread scheduling, etc. at run time.

It is great as long as you are not writing a massively multithreaded app with a bug in it so that you take over a 48 CPU box and nobody can shut you down because your have each CPU spinning at 100% with all thread set to SHED_FIFO (runs to completion) running as root.

Nah .. I wouldn't be speaking from experience ....

查看更多
地球回转人心会变
3楼-- · 2019-04-05 00:46

Try:

#include <sys/time.h>
#include <sys/resource.h>

int main(){
    setpriority(PRIO_PROCESS, 0, -20);
}

Note that you must be running as superuser for this to work.

(for more info, type 'man setpriority' at a prompt.)

查看更多
爷、活的狠高调
4楼-- · 2019-04-05 00:51

@ allain

Can you lower your own process' priority without being superuser?

Sure. Be aware, however, that this is a one way street. You can't even get back to where you started. And even fairly small reductions in priority can have startlingly large effects on running time when there is significant load on the system.

查看更多
登录 后发表回答