日期:2014-05-16  浏览次数:20599 次

你敢吗?抛砖引玉的问题,值得一看
路过的技术牛人,想请教一个问题。我想用fork产生3个子进程,分别执行不同的任务。并且给他们设定不同的优先级,让他们按照优先级执行。
我的代码在下面。进程1,child1的优先级是14.child2的优先级是10.child3的优先级是-3.按道理应该是子进程child3先执行。

#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/time.h>
#include<sys/resource.h>
#include<sys/types.h>


void main()
{
  pid_t father,child1,child2,child3;
  int prio;
  father=getpid();
  setpriority(PRIO_PROCESS,0,20);
  //nice(10);
  printf("the father ID is : %d\n",father);
  prio=getpriority(PRIO_PROCESS,0);
  printf("the father priority is %d\n",prio);
  child1=fork();
  if(child1==0) {
  setpriority(PRIO_PROCESS,0,14);
  prio=getpriority(PRIO_PROCESS,0);
  printf("the child one ID is : %d\n",getpid());
  printf("the child one priority is %d\n",prio);
  }
  else if(child1>0){
  child2=fork();
  if(child2==0) {
  setpriority(PRIO_PROCESS,0,10);
  prio=getpriority(PRIO_PROCESS,0);
  printf("the child two ID is : %d\n",getpid());
  printf("the child two priority is %d\n",prio);
  }
  else if(child2>0){
  child3=fork();
  if(child3==0) {
  setpriority(PRIO_PROCESS,0,-3);
  prio=getpriority(PRIO_PROCESS,0);
  printf("the child three ID is : %d\n",getpid());
  printf("the child three priority is %d\n",prio);
  }
  else if(child3>0) {
  printf("my ID is %d\n",getpid());
  printf("my prio is %d\n",getpriority(PRIO_PROCESS,0));
  }
   
  }
  }

}

执行结果是:
先执行1,再 2,再3


------解决方案--------------------
C/C++ code

#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/time.h>
#include<sys/resource.h>
#include<sys/types.h>
#include<sched.h>


void main()
{
  pid_t father,child1,child2,child3;
  int prio;
  int rt,curr_policy;
  struct sched_param my_params;

  my_params.sched_priority=sched_get_priority_max(SCHED_RR);

  father=getpid();
  curr_policy=sched_getscheduler(father);
  printf("SCHED_OTHER = %d SCHED_FIFO =%d SCHED_RR=%d \n",SCHED_OTHER,SCHED_FIFO,SCHED_RR);
  printf("the current scheduler = %d \n",curr_policy);

  rt=sched_setscheduler(0,SCHED_RR,&my_params);
  if(rt<0)
  {
    perror("sched_setscheduler to SCHED_RR error");
    exit(0);
  }
  curr_policy=sched_getscheduler(father);
  printf("the current scheduler = %d \n",curr_policy);

  //father=getpid();
  setpriority(PRIO_PROCESS,0,20);
  //nice(10);
  printf("the father ID is : %d\n",father);
  prio=getpriority(PRIO_PROCESS,0);
  printf("the father priority is %d\n",prio);
  child1=fork();
  if(child1==0) {
  curr_policy=sched_getscheduler(child1);
  printf("child1 scheduler = %d \n",curr_policy);
  setpriority(PRIO_PROCESS,0,14);
  prio=getpriority(PRIO_PROCESS,0);
  printf("the child one ID is : %d\n",getpid());
  printf("the child one priority is %d\n",prio);
  }
  else if(child1>0){
  child2=fork();
  if(child2==0) {
  curr_policy=sched_getscheduler(child2);
  printf("child2 scheduler = %d \n",curr_policy);
  setpriority(PRIO_PROCESS,0,10);
  prio=get