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

进程调度,关于状态机的问题
我想用fork产生3个子进程执行不同的任务,各个子进程分别按照他们自己的优先级做事情,这个咋弄啊。我原本是通过setpriority函数来设定他们的优先级,可以步行。进程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<sys/mman.h>

int main()
{
  pid_t father,child1,child2,child3;
  int prio;
  int *flag;
  
  flag = (int *)mmap(NULL,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1,0);
  (*flag)=3;
  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) {
  while(1 != (*flag)){
      //printf("child1 wait\n");
      sleep(1);
  }
  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) {
  while(2 != (*flag)){
      //printf("child2 wait\n");
      sleep(1);
  }
  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);
  (*flag) = 1;
  }
  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);
  (*flag) = 2;
  }
  else if(child3>0) {
  printf("my ID is %d\n",getpid());
  printf("my prio is %d\n",getpriority(PRIO_PROCESS,0));
  }
    
  }
  }
    return 0;
}