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

你是强人吗?进程优先级的!
关于进程优先级的设定,我用getpriority()函数设定普通进程的动态优先级,父进程的设定是12,子进程设定是9。按道理,应该子进程先执行啊,(执行的内容是打印“i am child”8个),再执行父进程啊。
可是我的运行结果是每次都先执行父进程的(“i am father ”)。下面写的代码,以及运行结果。请牛人看看。



void main()
{
  pid_t father,child;
  int prio1,prio2,i;
  father=getpid();
  setpriority(PRIO_PROCESS,0,10);
  //nice(12);
  printf("the father ID is : %d\n",father);
  prio1=getpriority(PRIO_PROCESS,father);
  printf("the father priority is %d\n",prio1);
  child=fork();
  if(child==0) {
  // nice(13);
  setpriority(PRIO_PROCESS,0,9);
  prio2=getpriority(PRIO_PROCESS,getpid());
  printf("the child ID is : %d\n",getpid());
  printf("the child priority is %d\n",prio2);
  for(i=0;i<8;i++) {
  printf("child counter %d\n",i);
  }
  }
  if(child !=0) {
  for(i=0;i<8;i++) {
  printf("father counter is %d\n",i);
  }
  }

}


运行结果:
[root@localhost sched]# ./nice
the father ID is : 23336
the father priority is 10
the child ID is : 23337
father counter is 0
father counter is 1
father counter is 2
father counter is 3
father counter is 4
father counter is 5
father counter is 6
father counter is 7
[root@localhost sched]# the child priority is 9
child counter 0
child counter 1
child counter 2
child counter 3
child counter 4
child counter 5
child counter 6
child counter 7

------解决方案--------------------
In general, we never know whether the child starts executing before the parent or vice versa. This depends on the scheduling algorithm used by the kernel. 
unix环境高级编程中认为fork之后是父进程先执行还是子进程先执行,取决于内核所使用的调度算法。
楼主你确定,在父进程执行之前,子进程已经setpriority了?
------解决方案--------------------
楼主,细心最重要.