可以通过改变进程的优先级来保证进程优先运行。在 Linux下,通过系统调用 nice()可以改变进程的优先级。nice()系统调用用来改变调用进程的优先级。函数声明如下:
#include <unistd.h> int nice( int increment );
#include <sys/resource.h> int getpriority( int which, int two ); int setpriority( int which, int who, int prio );
int nice( int increamet ) { int oldpro = getpriority( PRIO_PROCESS, getpid() ); return setpriority( PRIO_PROCESS, getpid(), oldpro + increament ); }
#include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <sys/resource.h> #include <sys/wait.h> #include <stdlib.h> int main(void) { pid_t pid; int stat_val = 0; int oldpri, newpri; printf("nice study\n"); pid = fork(); switch( pid ) { case 0: printf("Child is running, Curpid is %d, Parentpid is %d\n", pid, getppid()); oldpri = getpriority(PRIO_PROCESS, getpid()); printf("Old priority = %d\n", oldpri); newpri = nice(2); printf("New priority = %d\n", newpri); exit(0); case -1: perror("Process creation failed\n"); break; default: printf("Parent is running,Childpid is %d, Parentpid is %d\n", pid, getpid()); break; } wait(&stat_val); exit(0); }
beyes@linux-beyes:~/C/base> ./nice.exe nice study Child is running, Curpid is 0, Parentpid is 4421 Old priority = 0 New priority = 2 Parent is running,Childpid is 4422, Parentpid is 4421