how linux's alarm() is handled by kernel

可紊 提交于 2019-12-12 15:07:54

问题


I was reading about how the alarm() call works on the linux.
alarm(5) would send a SIGALRM in a minimum of 5 seconds to the process which has made this call.
The alarm is caused at that moment thanks to a down counter which is set by the kernel reaching zero.
My doubt is here - we can have N number of processes which make an alarm call, and there is one down counter in the system available for this purpose. So the kernel has to keep track of all the processes it has to send a signal to, with one down counter. How does it do it?

[Does it maintain a linked list of sort, with each node signifying the process?]


回答1:


I'm no Linux kernel developer, but given the man-page for alarm(), you can already expect how it is implemented.

First, it is clear that the alarm value is per process. Since the kernel already keeps per-process data structures (task_struct), it just stores the desired alarm time in there. Then Linux just uses its internal timer system to register a callback at the specified time. Said callback then delivers the SIGALRM to your process.

No need for kernel-global state or linked explicit linked lists for the alarms. The kernel simply keeps a process list and stores the alarm timeout as part of the per process data.

If you want to dig deeper, the calling tree looks something like this:

  • sys_alarm()
  • alarm_setitimer()
  • do_setitimer(): This stores a kernel timer under as task_struct->signal->real_timer; it then passes calls
  • hrtimer_start(), which is part of Linux' internal high resolution timer API.

Digging even further, the Linux high-res kernel timer system does a whole number of things, e.g. distinguishing between real time (which may go backwards if someone changes the time/date on the computer) and monotonic time. Take a look at this LWN article for an overview.

For the purposes of this question, it internally keeps a list of timers ordered by expiry time (soon to expire timers first, later expiring timers last). For performance reasons, this is not implemented as a doubly-linked list but as a red-black tree. After the any callback has been handled, hrtimers looks at its list, picks the first entry (the soonest to expire timer) and then tells the underlaying hardware timer to interrupt in time to service the next event. When that happens, hrtimers invokes the relevant callback, and the process repeats.

So there are timer lists (implemented as trees), but no explicit down counter, that part is handled via hardware timers. A leading reference for that part of the source code is enqueue_hrtimer().



来源:https://stackoverflow.com/questions/22437491/how-linuxs-alarm-is-handled-by-kernel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!