#include "unistd.h"
#include "sys/time.h"
#include "stdio.h"
#include "errno.h"
#include "sys/param.h"
unsigned long long int count=0;
struct timeval end;
void TimeCheck(char *name)
{
struct timeval custom;
gettimeofday(&custom,NULL);
if(custom.tv_sec >= end.tv_sec && custom.tv_usec >= end.tv_usec){
fprintf(stdout,"%s end, count=%d\n",name,count);
exit(0);
}
}
int main(int argc,char* argv[])
{
pid_t pid;
char* name;
int ret;
int level=0;
int nzero;
setbuf(stdout,NULL);
nzero = sysconf(_SC_NZERO);
if(argc > 1)
level = strtol(argv[1],NULL,10);
gettimeofday(&end,NULL);
end.tv_sec += 10;
fprintf(stdout,"NZERO = %d \n",nzero);
pid = fork();
if(pid<0)
fprintf(stderr,"fork err\n");
if(pid == 0){
fprintf(stdout,"Child current nice value is %d\n",nice(0)+nzero);
name = "Child";
}else{
printf("Parent current nice value is %d, adjusting by %d\n",nice(0)+nzero, level);
errno = 0;
ret = nice(level);
if((ret==-1) && (errno!=0)){
printf(stderr,"nice error \n");
}
name = "Parent";
printf("now Parent nice value is %d\n", ret+nzero);
}
while(1){
TimeCheck(name);
count ++;
}
}
mhr@ubuntu:~/Desktop/xitongbiancheng/test$ ./a.out
NZERO = 20
Parent current nice value is 20, adjusting by 0
now Parent nice value is 20
Child current nice value is 20
Parent end, count=221346030
Child end, count=220661588
mhr@ubuntu:~/Desktop/xitongbiancheng/test$
mhr@ubuntu:~/Desktop/xitongbiancheng/test$
当两个进程 nice值相同的时候,两个进程各自占用进阶50%的CPU。可以看到,两个进程被有效地进行了平等对待。百分比并不完全相同,是因为进程调度并不精确。
mhr@ubuntu:~/Desktop/xitongbiancheng/test$
mhr@ubuntu:~/Desktop/xitongbiancheng/test$ ./a.out 20
NZERO = 20
Parent current nice value is 20, adjusting by 20
now Parent nice value is 39
Child current nice value is 20
Child end, count=460304979
Parent end, count=6689695
mhr@ubuntu:~/Desktop/xitongbiancheng/test$
相比之下 当父进程有最高的nice值(最低优先级)时,我们看到父进程占用 1.4%的CPU,而子进程占用 98.6%的CPU,这些值取决于进程调用程序如何使用nice值,因此不同的UNIX系统会产生不同的CPU占用比。