进程控制13 - 进程调度

在这里插入图片描述

在这里插入图片描述

#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占用比。

相关推荐

  1. 11. Linux中进程控制细节

    2024-04-29 08:06:05       39 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-29 08:06:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-29 08:06:05       101 阅读
  3. 在Django里面运行非项目文件

    2024-04-29 08:06:05       82 阅读
  4. Python语言-面向对象

    2024-04-29 08:06:05       91 阅读

热门阅读

  1. Python.第六章函数应用实例

    2024-04-29 08:06:05       32 阅读
  2. Chrome插件开发:开启浏览器功能的无限可能

    2024-04-29 08:06:05       27 阅读
  3. Rapidly exploring Random Trees(RRT)类算法

    2024-04-29 08:06:05       35 阅读
  4. 并发编程中的各类锁

    2024-04-29 08:06:05       27 阅读