You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求问Linux内核直接设置时间的函数及__host_set_time的来源与作用

关于__host_set_time的来源与作用说明

首先需要明确:你贴出的这段__clock_settime实现是**GNU Hurd系统(而非Linux)**下GLIBC的代码,__host_set_time属于Mach微内核的接口,和Linux内核没有关系。

1. __host_set_time的来源

  • __host_set_time是Mach微内核提供的宿主特权接口,Mach是GNU Hurd的底层内核,和Linux是完全不同的内核实现。
  • 这个函数的定义存在于Mach内核的源码中,GLIBC中只是通过Mach IPC机制发起对该内核接口的调用,所以你在Linux相关的库或内核代码里找不到它的实现。

2. __host_set_time的作用

  • 它的作用是设置系统的实时时钟,调用时需要传入**宿主特权端口(hostpriv)**和time_value_t类型的时间参数。
  • 只有持有宿主特权端口的进程才能调用该函数,这也是代码中先调用__get_privileged_ports获取特权端口的原因,而普通用户无法获取该端口,因此只有超级用户能执行这个时间设置操作。

关于你要找的Linux内核直接设置时间的函数

如果你需要的是Linux内核中直接设置时间的函数,核心实现是do_settimeofday64(Linux 5.1+版本),旧版本内核则是do_settimeofday。用户空间的clock_settime最终会通过同名系统调用进入内核,调用该函数完成时间设置。

你贴出的完整代码如下:

* Copyright (C) 1991-2022 Free Software Foundation, Inc.
   This file is part of the GNU C Library.

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, see
   <https://www.gnu.org/licenses/>.  */

#include <errno.h>
#include <time.h>
#include <hurd.h>
#include <hurd/port.h>
#include <shlib-compat.h>

/* Set the current time of day.
   This call is restricted to the super-user.  */
int
__clock_settime (clockid_t clock_id, const struct timespec *ts)
{
  error_t err;
  mach_port_t hostpriv;
  time_value_t tv;

  if (clock_id != CLOCK_REALTIME
      || ! valid_nanoseconds (ts->tv_nsec))
    return __hurd_fail (EINVAL);

  err = __get_privileged_ports (&hostpriv, NULL);
  if (err)
    return __hurd_fail (EPERM);

  TIMESPEC_TO_TIME_VALUE (&tv, ts);
  err = __host_set_time (hostpriv, tv);
  __mach_port_deallocate (__mach_task_self (), hostpriv);

  return __hurd_fail (err);
}
libc_hidden_def (__clock_settime)

versioned_symbol (libc, __clock_settime, clock_settime, GLIBC_2_17);
/* clock_settime moved to libc in version 2.17;
   old binaries may expect the symbol version it had in librt.  */
#if SHLIB_COMPAT (libc, GLIBC_2_2, GLIBC_2_17)
strong_alias (__clock_settime, __clock_settime_2);
compat_symbol (libc, __clock_settime_2, clock_settime, GLIBC_2_2);
#endif

内容的提问来源于stack exchange,提问作者Cesar Rodriguez Serrano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 09:41:29