linux 高精度定时器 hrtimer 用户空间的应用 man timer_create

本文介绍Linux系统中通过timer_create系统调用创建进程间定时器的方法,详细解释了定时器的工作原理、参数配置及通知机制,并提供了一个使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

TIMER_CREATE(2)            Linux Programmer's Manual           TIMER_CREATE(2)

NAME
       timer_create - create a POSIX per-process timer

SYNOPSIS
       #include <signal.h>
       #include <time.h>

       int timer_create(clockid_t clockid, struct sigevent *sevp,
                        timer_t *timerid);

       Link with -lrt.

   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

       timer_create(): _POSIX_C_SOURCE >= 199309L

DESCRIPTION
       timer_create() creates a new per-process interval timer.  The ID of the
       new timer is returned in the buffer pointed to by timerid,  which  must
       be a non-null pointer.  This ID is unique within the process, until the
       timer is deleted.  The new timer is initially disarmed.

       The clockid argument specifies the clock that the  new  timer  uses  to
       measure time.  It can be specified as one of the following values:

       CLOCK_REALTIME
              A settable system-wide real-time clock.

       CLOCK_MONOTONIC
              A  nonsettable monotonically increasing clock that measures time
              from some unspecified point in the past  that  does  not  change
              after system startup.

       CLOCK_PROCESS_CPUTIME_ID (since Linux 2.6.12)
              A  clock  that  measures  (user and system) CPU time consumed by
              (all of the threads in) the calling process.

       CLOCK_THREAD_CPUTIME_ID (since Linux 2.6.12)
              A clock that measures (user and system) CPU time consumed by the
              calling thread.

       As  well  as  the above values, clockid can be specified as the clockid
       returned  by  a  call  to  clock_getcpuclockid(3)  or   pthread_getcpu‐
       clockid(3).

       The sevp argument points to a sigevent structure that specifies how the
       caller should be notified when the timer expires.  For  the  definition
       and general details of this structure, see sigevent(7).

       The sevp.sigev_notify field can have the following values:

       SIGEV_NONE
              Don't asynchronously notify when the timer expires.  Progress of
              the timer can be monitored using timer_gettime(2).

       SIGEV_SIGNAL
              Upon timer expiration, generate the signal sigev_signo  for  the
              process.   See  sigevent(7)  for  general  details.  The si_code
              field of the siginfo_t structure will be set  to  SI_TIMER.   At
              any  point  in time, at most one signal is queued to the process
              for a given timer; see timer_getoverrun(2) for more details.

       SIGEV_THREAD
              Upon timer expiration, invoke  sigev_notify_function  as  if  it
              were  the  start  function of a new thread.  See sigevent(7) for
              details.

       SIGEV_THREAD_ID (Linux-specific)
              As for SIGEV_SIGNAL, but the signal is targeted  at  the  thread
              whose  ID  is  given  in sigev_notify_thread_id, which must be a
              thread   in   the   same   process   as   the    caller.     The
              sigev_notify_thread_id  field specifies a kernel thread ID, that
              is, the value returned by clone(2) or gettid(2).  This  flag  is
              intended only for use by threading libraries.

       Specifying  sevp  as  NULL  is  equivalent to specifying a pointer to a
       sigevent structure in which sigev_notify is  SIGEV_SIGNAL,  sigev_signo
       is SIGALRM, and sigev_value.sival_int is the timer ID.

RETURN VALUE
       On  success,  timer_create()  returns 0, and the ID of the new timer is
       placed in *timerid.  On failure, -1 is returned, and errno  is  set  to
       indicate the error.

ERRORS
       EAGAIN Temporary error during kernel allocation of timer structures.

       EINVAL Clock  ID,  sigev_notify, sigev_signo, or sigev_notify_thread_id
              is invalid.

       ENOMEM Could not allocate memory.

VERSIONS
       This system call is available since Linux 2.6.

CONFORMING TO
       POSIX.1-2001, POSIX.1-2008.

NOTES
       A program may create multiple interval timers using timer_create().

       Timers are not inherited by the child of a fork(2),  and  are  disarmed
       and deleted during an execve(2).

       The kernel preallocates a "queued real-time signal" for each timer cre‐
       ated using timer_create().  Consequently, the number of timers is  lim‐
       ited by the RLIMIT_SIGPENDING resource limit (see setrlimit(2)).

       The  timers  created  by  timer_create()  are  commonly known as "POSIX
       (interval) timers".  The POSIX timers API  consists  of  the  following
       interfaces:

       *  timer_create(): Create a timer.

       *  timer_settime(2): Arm (start) or disarm (stop) a timer.

       *  timer_gettime(2): Fetch the time remaining until the next expiration
          of a timer, along with the interval setting of the timer.

       *  timer_getoverrun(2): Return the overrun count  for  the  last  timer
          expiration.

       *  timer_delete(2): Disarm and delete a timer.

       Since  Linux  3.10, the /proc/[pid]/timers file can be used to list the
       POSIX timers for the process with PID pid.   See  proc(5)  for  further
       information.

   C library/kernel differences
       Part  of  the  implementation  of  the  POSIX timers API is provided by
       glibc.  In particular:

       *  Much of the functionality for  SIGEV_THREAD  is  implemented  within
          glibc,  rather  than the kernel.  (This is necessarily so, since the
          thread involved in handling the notification is  one  that  must  be
          managed  by  the  C library POSIX threads implementation.)  Although
          the notification delivered to the process is via  a  thread,  inter‐
          nally   the   NPTL  implementation  uses  a  sigev_notify  value  of
          SIGEV_THREAD_ID along with a real-time signal that  is  reserved  by
          the implementation (see nptl(7)).

       *  The  implementation of the default case where evp is NULL is handled
          inside glibc, which invokes the underlying system call with a  suit‐
          ably populated sigevent structure.

       *  The timer IDs presented at user level are maintained by glibc, which
          maps these IDs to the timer IDs employed by the kernel.

       The POSIX timers system calls first appeared in Linux  2.6.   Prior  to
       this,   glibc   provided   an   incomplete   user-space  implementation
       (CLOCK_REALTIME timers only) using POSIX threads, and in glibc versions
       before 2.17, the implementation falls back to this technique on systems
       running pre-2.6 Linux kernels.

EXAMPLE
       The program below takes two arguments: a sleep period in seconds, and a
       timer  frequency in nanoseconds.  The program establishes a handler for
       the signal it uses for the timer, blocks that signal, creates and  arms
       a timer that expires with the given frequency, sleeps for the specified
       number of seconds, and then unblocks the timer signal.   Assuming  that
       the  timer  expired  at  least once while the program slept, the signal
       handler will be invoked, and  the  handler  displays  some  information
       about the timer notification.  The program terminates after one invoca‐
       tion of the signal handler.

       In the following example run, the program sleeps for  1  second,  after
       creating  a timer that has a frequency of 100 nanoseconds.  By the time
       the signal is unblocked and delivered, there have been around ten  mil‐
       lion overruns.

           $ ./a.out 1 100
           Establishing handler for signal 34
           Blocking signal 34
           timer ID is 0x804c008
           Sleeping for 1 seconds
           Unblocking signal 34
           Caught signal 34
               sival_ptr = 0xbfb174f4;     *sival_ptr = 0x804c008
               overrun count = 10004886

   Program source

       #include <stdlib.h>
       #include <unistd.h>
       #include <stdio.h>
       #include <signal.h>
       #include <time.h>

       #define CLOCKID CLOCK_REALTIME
       #define SIG SIGRTMIN

       #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
                               } while (0)

       static void
       print_siginfo(siginfo_t *si)
       {
           timer_t *tidp;
           int or;

           tidp = si->si_value.sival_ptr;

           printf("    sival_ptr = %p; ", si->si_value.sival_ptr);
           printf("    *sival_ptr = 0x%lx\n", (long) *tidp);

           or = timer_getoverrun(*tidp);
           if (or == -1)
               errExit("timer_getoverrun");

           else
               printf("    overrun count = %d\n", or);
       }

       static void
       handler(int sig, siginfo_t *si, void *uc)
       {
           /* Note: calling printf() from a signal handler is not
              strictly correct, since printf() is not async-signal-safe;
              see signal(7) */

           printf("Caught signal %d\n", sig);
           print_siginfo(si);
           signal(sig, SIG_IGN);
       }

       int
       main(int argc, char *argv[])
       {
           timer_t timerid;
           struct sigevent sev;
           struct itimerspec its;
           long long freq_nanosecs;
           sigset_t mask;
           struct sigaction sa;

           if (argc != 3) {
               fprintf(stderr, "Usage: %s <sleep-secs> <freq-nanosecs>\n",
                       argv[0]);
               exit(EXIT_FAILURE);
           }

           /* Establish handler for timer signal */

           printf("Establishing handler for signal %d\n", SIG);
           sa.sa_flags = SA_SIGINFO;
           sa.sa_sigaction = handler;
           sigemptyset(&sa.sa_mask);
           if (sigaction(SIG, &sa, NULL) == -1)
               errExit("sigaction");

           /* Block timer signal temporarily */

           printf("Blocking signal %d\n", SIG);
           sigemptyset(&mask);
           sigaddset(&mask, SIG);
           if (sigprocmask(SIG_SETMASK, &mask, NULL) == -1)
               errExit("sigprocmask");

           /* Create the timer */

           sev.sigev_notify = SIGEV_SIGNAL;
           sev.sigev_signo = SIG;
           sev.sigev_value.sival_ptr = &timerid;

           if (timer_create(CLOCKID, &sev, &timerid) == -1)
               errExit("timer_create");

           printf("timer ID is 0x%lx\n", (long) timerid);

           /* Start the timer */

           freq_nanosecs = atoll(argv[2]);
           its.it_value.tv_sec = freq_nanosecs / 1000000000;
           its.it_value.tv_nsec = freq_nanosecs % 1000000000;
           its.it_interval.tv_sec = its.it_value.tv_sec;
           its.it_interval.tv_nsec = its.it_value.tv_nsec;

           if (timer_settime(timerid, 0, &its, NULL) == -1)
                errExit("timer_settime");

           /* Sleep for a while; meanwhile, the timer may expire
              multiple times */

           printf("Sleeping for %d seconds\n", atoi(argv[1]));
           sleep(atoi(argv[1]));

           /* Unlock the timer signal, so that timer notification
              can be delivered */

           printf("Unblocking signal %d\n", SIG);
           if (sigprocmask(SIG_UNBLOCK, &mask, NULL) == -1)
               errExit("sigprocmask");

           exit(EXIT_SUCCESS);
       }

SEE ALSO
       clock_gettime(2), setitimer(2), timer_delete(2), timer_getoverrun(2),
       timer_settime(2), timerfd_create(2), clock_getcpuclockid(3),
       pthread_getcpuclockid(3), pthreads(7), sigevent(7), signal(7), time(7)

COLOPHON
       This page is part of release 4.04 of the Linux man-pages project.  A
       description of the project, information about reporting bugs, and the
       latest version of this page, can be found at
       http://www.kernel.org/doc/man-pages/.


http://fangjian0518.blog.163.com/blog/static/559196562011621113010116/
<think>嗯,用户现在想找关于在Linux内核驱动中使用高精度定时器hrtimer实现微秒级延时函数delay_us的代码示例。我需要先回顾之前的对话,确保这次回答符合用户的需求。 用户之前的问题是关于如何在Linux内核中使用_IOW宏定义字节类型的数据,我给出了详细的实现方法和代码示例,还附带了相关问题。现在用户的新问题是关于hrtimer实现微秒延时的代码示例,所以需要重点讲解hrtimer的使用步骤和注意事项。 首先,用户的需求是微秒级延时,而hrtimer正是高精度定时器,适合这个场景。我需要解释hrtimer的基本用法,比如如何初始化定时器、设置回调函数、启动和取消定时器等。同时,用户可能需要一个具体的代码示例,展示如何封装一个delay_us函数。 接下来,考虑用户可能的背景。他们可能正在开发内核驱动,需要精确的延时控制,比如在硬件操作或实时任务中。因此,除了代码示例,还需要强调使用hrtimer的优势,比如相比传统的定时器hrtimer提供更高的精度和更低的延迟。 然后,我需要检查之前的引用文献。用户提到了引用[1],其中提到ioctl接口将内核API映射到用户空间,这可能与当前的hrtimer问题没有直接关系,但可能需要考虑用户空间与内核的交互。不过当前问题集中在内核内部的定时器实现,所以重点应放在内核模块的代码结构上。 用户可能还会关心如何确保延时的准确性,以及如何处理定时器回调函数中的上下文。比如,hrtimer的回调函数是在中断上下文中执行的,不能进行可能导致睡眠的操作。这一点需要明确指出,避免用户在使用时犯错。 另外,需要提到hrtimer的不同模式,比如HRTIMER_MODE_REL(相对时间)和HRTIMER_MODE_ABS(绝对时间),在示例中使用相对时间模式更符合延时的需求。 在代码示例中,应该包括模块的初始化、定时器的设置、回调函数的实现,以及如何启动和停止定时器。同时,需要展示如何将hrtimer封装成delay_us函数,可能需要使用完成量(completion)或者等待队列来让调用线程等待定时器完成。 还要注意内核版本的兼容性,因为hrtimer的API在不同版本中可能有变化。需要建议用户查阅他们使用的内核版本的文档,或者确认示例代码的适用性。 最后,用户可能想知道如何处理多线程环境下的并发问题,或者如何测试这个延时函数的准确性。不过,用户当前的问题主要是代码示例,因此这些可以作为相关问题的补充。 总结下来,回答的结构应包括实现步骤、代码示例、关键注意事项和相关问题。需要确保代码正确使用hrtimer的API,并解释每个部分的作用,帮助用户理解如何集成到他们的驱动中。</think>### Linux内核hrtimer实现微秒级延时函数`delay_us()`代码示例 #### 一、核心实现原理 高精度定时器hrtimer)通过`hrtimer_init()`初始化定时器结构体,使用`hrtimer_start()`设置延时时间,通过`wait_for_completion()`实现同步等待[^1]。关键实现步骤如下: ```c #include <linux/hrtimer.h> #include <linux/completion.h> static struct hrtimer delay_timer; static struct completion delay_complete; // 定时器回调函数 static enum hrtimer_restart delay_callback(struct hrtimer *timer) { complete(&delay_completion); // 唤醒等待线程 return HRTIMER_NORESTART; // 单次触发模式 } // 微秒级延时函数 void delay_us(unsigned long microseconds) { ktime_t delay_time = ktime_set(0, microseconds * NSEC_PER_USEC); hrtimer_init(&delay_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); delay_timer.function = delay_callback; init_completion(&delay_completion); hrtimer_start(&delay_timer, delay_time, HRTIMER_MODE_REL); wait_for_completion(&delay_completion); } ``` #### 二、代码实现细节 ##### 1. **定时器初始化** ```c hrtimer_init(&delay_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); ``` - `CLOCK_MONOTONIC`:使用单调递增时钟,避免系统时间调整影响 - `HRTIMER_MODE_REL`:相对时间模式 ##### 2. **时间单位转换 ```c ktime_t delay_time = ktime_set(0, microseconds * NSEC_PER_USEC); ``` - 将微秒转换为纳秒(1μs = 1000ns) - `ktime_set(secs, nsecs)`创建时间对象 ##### 3. **同步等待机制 ```c init_completion(&delay_completion); wait_for_completion(&delay_completion); ``` - 使用完成量实现线程阻塞/唤醒 - 避免忙等待(busy-loop)造成的CPU资源浪费 #### 三、优化改进方案 ##### 1. 中断上下文安全版 ```c void delay_us_atomic(unsigned long usec) { ktime_t delay = ktime_set(0, usec * NSEC_PER_USEC); hrtimer_init_on_stack(&delay_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); hrtimer_start(&delay_timer, delay, HRTIMER_MODE_REL); while (hrtimer_active(&delay_timer)) cpu_relax(); // 适用于中断上下文 } ``` - 使用`hrtimer_active()`检测定时器状态 - `cpu_relax()`降低CPU占用(需配合`CONFIG_PREEMPT`配置) ##### 2. 批量延时优化 ```c void delay_us_batch(unsigned long total_us, unsigned int batch_size) { unsigned long cycles = total_us / batch_size; ktime_t batch_delay = ktime_set(0, batch_size * NSEC_PER_USEC); for (int i = 0; i < cycles; i++) { hrtimer_start(&delay_timer, batch_delay, HRTIMER_MODE_REL); wait_for_completion(&delay_completion); reinit_completion(&delay_completion); } } ``` #### 四、关键注意事项 1. **精度范围** hrtimer理论最小精度为1ns,实际受以下因素影响: ```text +------------------------+-----------------+ | 影响因素 | 典型误差范围 | +------------------------+-----------------+ | 硬件时钟源 | ±50ns | | 内核配置(CONFIG_HZ) | 100-1000μs | | 中断延迟 | 1-50μs | +------------------------+-----------------+ ``` 2. **上下文限制** - 在**中断上下文**中禁止使用`wait_for_completion()` - 原子版本需使用`hrtimer_init_on_stack()`避免内存分配 3. **资源释放** ```c void cleanup_delay(void) { hrtimer_cancel(&delay_timer); destroy_completion(&delay_completion); } ``` #### 五、性能测试方法 使用`ktime_get()`测量实际延时: ```c ktime_t start = ktime_get(); delay_us(100); // 测试100μs延时 ktime_t end = ktime_get(); s64 actual_delay = ktime_to_ns(end - start); ``` --- ### 相关问题 1. 如何选择hrtimer和传统的timer_list定时器? 2. 在实时内核(PREEMPT_RT)中使用hrtimer有什么特别注意事项? 3. 如何通过ftrace分析hrtimer的实际触发延迟? [^1]: Linux内核文档:`Documentation/timers/hrtimers.txt` [^2]: 《Linux Kernel Development》第11章 "Timers and Time Management"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值