Issue
I want to sleep in the kernel for a specific amount of time, and I use time_before
and jiffies
to calculate the amount of time I should sleep, however I don't understand how the calculation actually works. I know that HZ
is 250 and jiffies
is a huge dynamic value. I know what them both are and what they are used for.
I calculate the time with jiffies + (10 * HZ)
.
static unsigned long j1;
static int __init sys_module_init(void)
{
j1 = jiffies + (10 * HZ);
while (time_before(jiffies, j1))
schedule();
printk("Hello World - %d - %ld\n", HZ, jiffies); // Hello World - 250 - 4296485594 (dynamic)
return 0;
}
How does the calculation work and how many seconds will I sleep? I want to know that because in the future I'll probably want to sleep for a specific time.
Solution
HZ
represents the amount of ticks in a second, and multiplying that by 10
gives the amount of ticks in 10 seconds. So the calculation jiffies + 10 * HZ
yields the expected value of jiffies
10 seconds from now.
However, calling schedule()
in a loop until that value is hit is not the recommended way to go. If you want to sleep in the kernel, you don't need to reinvent the wheel, there already is a set of APIs just for this purpose, documented here, which will make your life a lot easier. The simplest way to sleep in your specific case would be to use msleep()
, passing the number of milliseconds you want to sleep for:
#include <linux/delay.h>
static int __init sys_module_init(void)
{
msleep(10 * 1000);
return 0;
}
Answered By - Marco Bonelli Answer Checked By - Robin (WPSolving Admin)