8_30調整nice的值 nice值越高 調用優先級越低。

注意:只有當return 值爲-1 並且errno != 0 時 nice調整纔出錯。

cat -n 8_30.c
     1  #include "apue.h"
     2  #include <errno.h>
     3  #include <sys/time.h>
     4
     5  #if defined(MACOS)
     6  #include <sys/syslimits.h>
     7
     8  #elif defined(SOLARIS)
     9  #include <limit.h>
    10
    11  #elif defined(BSD)
    12  #include <sys/param.h>
    13  #endif
    14  unsigned long long count;
    15  struct timeval end;
    16
    17
    18  void checktime(char *str)
    19  {
    20          struct timeval tv;
    21          gettimeofday(&tv,NULL);
    22          if(tv.tv_sec >= end.tv_sec && tv.tv_usec >= end.tv_usec){
    23                  printf("%s count:%lld\n",str,count);
    24                  exit(0);
    25          }
    26
    27  }
    28
    29  int main(int argc,char **argv){
    30          pid_t pid;
    31          char *s;
    32          int nzero,ret;
    33          int adj;
    34
    35          setbuf(stdout,NULL);
    36
    37  #if defined(NZERO)
    38          nzero = nzero;
    39  #elif defined(_SC_NZERO)
    40          nzero = sysconf(_SC_NZERO);
    41  #else
    42  #error NZERO UNDEFINED
    43  #endif
    44          printf("NZERO = %d\n",nzero);
    45
    46          if (argc == 2)
    47                  adj = strtol(argv[1],NULL,10);
    48
    49          gettimeofday(&end,NULL);
    50          end.tv_sec += 10;
    51
    52          if ((pid = fork()) < 0)
    53                  err_sys("fork error");
    54          else if (pid == 0){
    55                  s = "child";
    56                  printf("Child current value is:%d,adjust by %d\n",nice(0)+nzero,adj);
    57                  errno = 0;
    58                  if ((ret = nice(adj)) == -1 && errno != 0)
    59                          err_sys("nice error");
    60                  printf("Now child's current value is:%d\n",ret+nzero);
    61
    62          }
    63          else if (pid > 0){
    64                  s = "Parent";
    65                  printf("Now parent's current value is:%d\n",nzero+nice(0));
    66          }
    67
    68          for(;;){
    69                  if (++count == 0)
    70                          err_quit("%s counter wrap",s);
    71                  checktime(s);
    72          }
    73          return 0;
    74  }
    75






./nice
NZERO = 20
Now parent's current value is:20
Child current value is:20,adjust by 0
Now child's current value is:20
child count:246983775
Parent count:246975521
<usnavsvmh15:/home/tingbinz/apue.3e/SBSCODE/8>R*_*G:./nice 20
NZERO = 20
Now parent's current value is:20
Child current value is:20,adjust by 20
Now child's current value is:39
child count:246646502
Parent count:246633488

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章