[apue] sysconf 的四种返回状态

众所周知,sysconf 用来返回某种常量的定义或者资源的上限,前者用于应用动态的判断系统是否支持某种标准或能力、后者用于决定资源分配的尺寸。
但是你可能不知道的是,sysconf 可以返回四种状态:

  • 常量定义本身或资源上限 (>=0, 整型值)
  • 无限制 (no limit)
  • 不支持
  • 出错

那一个小小的 int 返回类型,如何能容纳这许多含义? 各位看过下面这段代码,就一目了然了:

static void 
pr_sysconf (char *msg, int name) 
{
  long val; 
  fputs (msg, stdout); 
  errno = 0; 
  if ((val = sysconf (name)) < 0) { 
    if (errno != 0) { 
      if (errno == EINVAL)
        fputs ("(not supported)\n", stdout); 
      else 
        err_sys ("sysconf error"); 
    }
    else
      fputs ("(no limit)\n", stdout); 
  }
  else
    printf ("%ld\n", val); 
}

conf.c


这段代码用来打印 sysconf 的返回值,可以看到基本是通过 '返回值 + errno' 的方式实现的:

  • 返回值 >= 0: 常量定义或资源本身
  • 返回值 < 0:
    • errno == 0: 无限制
    • errno != 0:
      • errno == EINVAL: 不支持
      • 其它:出错

其实看下 sysconf 的手册页的话,确实是这么说的:

RETURN VALUE
If name is invalid, -1 is returned, and errno is set to EINVAL. Otherwise, the value returned is the value of the system resource
and errno is not changed. In the case of options, a positive value is returned if a queried option is available, and -1 if it is
not. In the case of limits, -1 means that there is no definite limit.

posted @ 2020-06-12 17:28  goodcitizen  阅读(500)  评论(0编辑  收藏  举报