I am implementing a timer using timerfd. This is a relative timer that I just need to repeat forever at the rate it is set to. I want to poll on this event and originally tried using poll. When I did this, I would see the timer event the first time and then never again. However, when I changed to using epoll (no change at all to how the timerfd was set up) it works as expected.
Here is the code with poll:
#include <sys/timerfd.h>
#include <sys/poll.h>
#include <sys/epoll.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
int main(int ac, char *av[])
{
struct pollfd p;
int timerfd;
struct itimerspec timerValue;
/* clear pollfd */
bzero(&p, sizeof(p));
/* set timerfd */
timerfd = timerfd_create(CLOCK_REALTIME, 0);
if (timerfd < 0) {
printf("failed to create timer fd\n");
exit(1);
}
bzero(&timerValue, sizeof(timerValue));
timerValue.it_value.tv_sec = 1;
timerValue.it_value.tv_nsec = 0;
timerValue.it_interval.tv_sec = 1;
timerValue.it_interval.tv_nsec = 0;
/* set events */
p.fd = timerfd;
p.revents = 0;
p.events = POLLIN;
/* start timer */
if (timerfd_settime(timerfd, 0, &timerValue, NULL) < 0) {
printf("could not start timer\n");
exit(1);
}
/* wait for events */
while (1) {
int numEvents = poll(&p, 1, -1);
if (numEvents > 0) {
int timersElapsed = 0;
(void) read(p.fd, &timersElapsed, 8);
printf("timers elapsed: %d\n", timersElapsed);
}
}
exit(0);
}
And here is the code with epoll:
#include <sys/timerfd.h>
#include <sys/poll.h>
#include <sys/epoll.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
int main(int ac, char *av[])
{
struct epoll_event epollEvent;
struct epoll_event newEvents;
int timerfd;
int epollfd;
struct itimerspec timerValue;
/* set timerfd */
timerfd = timerfd_create(CLOCK_MONOTONIC, 0);
if (timerfd < 0) {
printf("failed to create timer fd\n");
exit(1);
}
bzero(&timerValue, sizeof(timerValue));
timerValue.it_value.tv_sec = 1;
timerValue.it_value.tv_nsec = 0;
timerValue.it_interval.tv_sec = 1;
timerValue.it_interval.tv_nsec = 0;
/* set events */
epollfd = epoll_create1(0);
epollEvent.events = EPOLLIN;
epollEvent.data.fd = timerfd;
epoll_ctl(epollfd, EPOLL_CTL_ADD, timerfd, &epollEvent);
/* start timer */
if (timerfd_settime(timerfd, 0, &timerValue, NULL) < 0) {
printf("could not start timer\n");
exit(1);
}
/* wait for events */
while (1) {
int numEvents = epoll_wait(epollfd, &newEvents, 1, 0);
if (numEvents > 0) {
int timersElapsed = 0;
(void) read(epollEvent.data.fd, &timersElapsed, 8);
printf("timers elapsed: %d\n", timersElapsed);
}
}
exit(0);
}
Any idea what I might be doing wrong with poll? Maybe it is not meant to be used this way with a timerfd? Thank you.
Ok, this is an old question, but nevertheless. The problem lies in these lines of code:
int timersElapsed = 0;
(void) read(p.fd, &timersElapsed, 8);
printf("timers elapsed: %d\n", timersElapsed);
int timersElapsed is 4 bytes. Reading 8 bytes into this results in a stack overflow, giving unpredictable behaviour.
Changing timersElapsed to a long int and fixing the printf did the trick for me.
long int timersElapsed = 0;
(void) read(p.fd, &timersElapsed, 8);
printf("timers elapsed: %ld\n", timersElapsed);
This appears to be an issue with Fedora (or my installation of Fedora). That system is running 3.16, and poll() does not work.
However, on a separate Ubuntu installation with 3.13, the poll() code above works just fine. As I will be using Ubuntu in the future anyway, I will not try to track down the issue on Fedora. Though I am curious if others are seeing this same issue on Fedora systems.
I faced the same problem.
After debugging, the root cause in poll example is that
timerValue should be declared as uint64_t.
- int timersElapsed = 0;
+ uint64_t timersElapsed = 0;
The man page of timerfd_create() describes this.
Operating on a timer file descriptor
The file descriptor returned by timerfd_create() supports the following
operations:
read(2)
If the timer has already expired one or more times since its settings
were last modified using timerfd_settime(), or since the last suc‐
cessful read(2), then the buffer given to read(2) returns an unsigned
8-byte integer (uint64_t) containing the number of expirations that
have occurred. (The returned value is in host byte order—that is,
the native byte order for integers on the host machine.)
Related
I'm writing a daemon which checks the battery capacity. This is for a solar powered embedded device running Linux. I've read that it's a bad idea to use sleep() in daemons, thus I'm trying to use events. So I wrote some PoCs, but I'm not getting any events! My first implementation, as they recommended to me, uses libudev and poll():
#include <fcntl.h>
#include <libudev.h>
#include <poll.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(void)
{
struct udev *udev;
struct udev_monitor *mon;
struct pollfd fds[1];
int fd;
udev = udev_new();
if (udev == NULL)
return 1;
mon = udev_monitor_new_from_netlink(udev, "udev");
udev_monitor_filter_add_match_subsystem_devtype(mon, "power_supply", NULL);
udev_monitor_enable_receiving(mon);
fd = udev_monitor_get_fd(mon);
fds[0].fd = fd;
fds[0].events = POLLIN;
fds[0].revents = 0;
if (poll(fds, 1, -1) > 0) {
/* Never gets here! */
struct udev_device *const dev = udev_monitor_receive_device(mon);
if (dev != NULL) {
puts(udev_device_get_sysname(dev));
udev_device_unref(dev);
}
else
fputs("udev_monitor_receive_device() failed\n", stderr);
}
udev_unref(udev);
return 0;
}
They only event I get, is when I plug/unplug the charger! Then I thought that the status bar I use in my laptop's installation does show the battery capacity. I looked at the source and they're using inotify to monitor the battery's uevent. But I've read everywhere that I shouldn't use inotify for sysfs! I tried nonetheless:
#include <stdio.h>
#include <sys/inotify.h>
#include <unistd.h>
#define BAT_PATH "/sys/class/power_supply/BAT0"
int main(void)
{
struct inotify_event ev = {0};
int wd, ret = 1;
ssize_t len;
const int fd = inotify_init1(IN_CLOEXEC);
if (fd < 0) {
perror("inotify_init() failed");
return ret;
}
/* else */
wd = inotify_add_watch(fd, BAT_PATH "/uevent", IN_ACCESS);
if (wd < 0)
goto end;
/* else */
len = read(fd, &ev, sizeof(ev));
/* Again... never gets here. */
if (len > 0 && (ev.mask & IN_ACCESS))
puts("It worked!");
inotify_rm_watch(fd, wd);
ret = 0;
end:
close(fd);
return ret;
}
Turns out that doesn't work either! How can it work for my status bar but not work when I try it? Am I doing something horribly wrong? Thank you.
Regarding your first implementation (would comment but not enough rep. as i know nothing about libudev): the guide i followed to successfully use sysfs to poll() a GPIO for interrupt suggests to look for a POLLPRI event, instead of POLLIN as you show in the first implementation (see man poll for event types).
More importantly, you say you get a single event when you connect/disconnect charger, do you mean a single event per software execution? If this is the case, it might be due to the fact that you don't clear the interrupt flag: after poll() hits, in sysfs one needs to int len = read(fds[0].fd, *buf, SIZE); to mark the interrupt as served, and also lseek(fds[0].fd, 0, 0); in order for the next read() to be succesful (see my other answer here for a code example).
i dont know whether this answer will help you or not, but i am writing answer because if any other users face same issue they can get it resolved.
the solution is:
you need to monitor kernel Events, so you need to change line
form
mon = udev_monitor_new_from_netlink(udev, "udev");
to
mon = udev_monitor_new_from_netlink(udev, "kernel");
then you will get events.
I have written some code that tries to call a function (called worker) every x seconds (in this example, I chose 1s as the interval time). The code is a minimal working example that in reality is way more complex than this.
The code works when it is this simple, but I stumble across errors when running the more complex version for a longer period of time. Thus, I want to increase the robustness of this code an would like to get some ideas on how to do that.
Basically, the worker gets some data, processes it an writes it to a file. I open the file during every call to the worker. In the tests, after some time I get an error that the file cannot be opened anymore. In this regard I also noticed that this happens (maybe just by chance) everytime the worker execution time exceeds the interval time. Reason for this is the getter function which pulls data from remote and this can take some time, depending on the network traffic.
I've been thinking of trying a multithreaded approach, but I am not sure if this is worth the hassle. I would be grateful for any pointers on how to do this in a more robust way.
#include <unistd.h>
#include <stdbool.h>
#include <stdio.h>
#include <signal.h>
#include <stdint.h>
#include <time.h>
#define ALARM_INTERVAL_SEC 1
#define ALARM_INTERVAL_USEC 0
static bool running = true;
static struct itimerval alarm_interval;
static struct timeval previous_time;
static uint64_t loop_count = 0;
static FILE* testfile;
static void
signal_handler(int signum)
{
if (signum == SIGINT || signum == SIGTERM)
{
running = false;
}
}
static void
worker(int signum)
{
// Reset the alarm interval
if(setitimer(ITIMER_REAL, &alarm_interval, NULL) < 0)
{
perror("Error: setitimer");
raise(SIGTERM);
return;
}
struct timeval current_time;
gettimeofday(¤t_time, NULL);
printf("Loop count: %lu\n", loop_count);
printf("Loop time: %f us\n\n", (current_time.tv_sec - previous_time.tv_sec) * 1e6 +
(current_time.tv_usec - previous_time.tv_usec));
previous_time = current_time;
// convert time to human-readable format
char tmbuf[64];
char buf[64];
time_t nowtime = current_time.tv_sec;
struct tm *nowtm = localtime(&nowtime);
strftime(tmbuf, sizeof(tmbuf), "%Y-%m-%d %H:%M:%S", nowtm);
snprintf(buf, sizeof(buf), "%s.%06ld", tmbuf, current_time.tv_usec);
sleep(0.5);
// DO STH
testfile = fopen("testfile.txt", "ab+");
if(testfile == NULL)
{
printf("Error: open testfile");
raise(SIGTERM);
return;
}
fprintf(testfile, "[%s] Loop count: %lu\n", buf, loop_count);
fclose(testfile);
loop_count++;
}
int
main(int argc, char* argv[])
{
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
signal(SIGALRM, worker);
// Set the alarm interval
alarm_interval.it_interval.tv_sec = 0;
alarm_interval.it_interval.tv_usec = 0;
alarm_interval.it_value.tv_sec = ALARM_INTERVAL_SEC;
alarm_interval.it_value.tv_usec = ALARM_INTERVAL_USEC;
if(setitimer(ITIMER_REAL, &alarm_interval, NULL) < 0)
{
perror("Error: setitimer");
return -1;
}
gettimeofday(&previous_time, NULL);
while(running)
{
sleep(1);
}
alarm_interval.it_value.tv_sec = 0;
alarm_interval.it_value.tv_usec = 0;
if(setitimer(ITIMER_REAL, &alarm_interval, NULL) < 0)
{
perror("Error: resetting itimer failed");
return -1;
}
return 0;
}
I'm intending to use epoll to check out timerfd and fire some actions.
Code is blow:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/timerfd.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/epoll.h>
int main(int argc, char const *argv[])
{
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
int timerfd;
timerfd = timerfd_create(CLOCK_MONOTONIC, 0);
struct itimerspec new_value;
new_value.it_value.tv_sec = 1;
new_value.it_interval.tv_sec = 1;
timerfd_settime(timerfd, 0, &new_value, NULL);
// uint64_t buff;
// while(true) {
// read(timerfd, &buff, sizeof(uint64_t));
// printf("%s\n", "ding");
// }
// code above works fine.
struct epoll_event ev, events[10];
int epollfd;
epollfd = epoll_create1(0);
if (epollfd == -1) {
perror("epoll_create1");
exit(EXIT_FAILURE);
}
ev.events = EPOLLIN;
ev.data.fd = timerfd;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, timerfd, &ev) == -1) {
perror("epoll_ctl: timerfd");
exit(EXIT_FAILURE);
}
int num;
printf("start\n");
while(true) {
num = epoll_wait(epollfd, events, 10, -1);
printf("%d\n", num);
uint64_t buff;
read(timerfd, &buff, sizeof(uint64_t));
printf("%s\n", "ding");
}
return 0;
}
When using timerfd seperately, it works fine. Every second will print "ding". But when adding epoll to observe timerfd, progrom will block at epoll_wait for ever.
I'v tryed using EPOLLET, but noting changed. What's wrong with this code?
Your itimerspec is not properly initialized, so depending on what particular garbage values it contains, timerfd_settime() might fail. To detect that, do error checking:
if (timerfd_settime(timerfd, 0, &new_value, NULL) != 0) {
perror("settime");
exit(-1);
}
Another way to debug this is to run your program under the strace, program, and you will see which, if any, system calls that fails.
The relevant structs looks like this:
struct timespec {
time_t tv_sec;
long tv_nsec;
};
struct itimerspec {
struct timespec it_interval;
struct timespec it_value;
};
You have to initialize both these members completely, and your program will work reliably:
new_value.it_value.tv_sec = 1;
new_value.it_value.tv_nsec = 0;
new_value.it_interval.tv_sec = 1;
new_value.it_interval.tv_nsec = 0;
I need to call a function every second exactly as I want to store the data based on the every second so I cannot miss the second? What is best method in C?
Below is a skeleton of the timer_create method is this reliable enough?
#include <stdio.h>
#include <time.h>
#include <signal.h>
timer_t gTimerid;
void start_timer(void)
{
struct itimerspec value;
value.it_value.tv_sec = 1;
value.it_value.tv_nsec = 0;
value.it_interval.tv_sec = 1;
value.it_interval.tv_nsec = 0;
timer_create (CLOCK_REALTIME, NULL, &gTimerid);
timer_settime (gTimerid, 0, &value, NULL);
}
void stop_timer(void)
{
struct itimerspec value;
value.it_value.tv_sec = 0;
value.it_value.tv_nsec = 0;
value.it_interval.tv_sec = 0;
value.it_interval.tv_nsec = 0;
timer_settime (gTimerid, 0, &value, NULL);
}
void timer_callback(int sig)
{
printf(" Catched timer signal: %d ... !!\n", sig);
}
int main(int ac, char **av)
{
(void) signal(SIGALRM, timer_callback);
start_timer();
while(1);
}
On Linux and other POSIX systems, timer_create is the function you're looking for. Set the timer to be delivered via a signal and it will be very reliable. Don't use the older ualarm or setitimer apis which are deprecated and have various ugly issues that you probably don't want to get into unless you're already an expert on realtime unix stuff...
You have two options to call a function every other second:
Do a "busy wait"
Make your process/thread sleep for an amount of time
The first option is definitely more accurate but a lot more CPU consumptive and less responsive. It can simply be done with a while or for loop.
Here a small example of how this busy-wait loop might look like:
#include <time.h>
#define TIME_TO_WAIT 1 /* wait for one second */
...
clock_t last = clock();
while(1) {
clock_t current = clock();
if (current >= (last + TIME_TO_WAIT * CLOCKS_PER_SEC)) {
yourSpecialFunction(); /* insert your function here */
last = current;
}
}
The second option is maybe less accurate (since your process may wait a little less or more than the specified time) but it is the preferred option in terms of multiprocessing and scheduling. You can use your systems sleep()/usleep()/Sleep() (depends on your system) function for it. Alternatively you can use signals.
ualarm() is probably the simplest way of doing this. As others have mentioned, perfect accuracy isn't guaranteed, but the resolution is likely sufficient.
void each_sec(int x)
{
printf("%d", (int)time(NULL));
}
int main()
{
signal(SIGALRM, each_sec);
ualarm(1000000, 1000000);
}
I used signal for clarity, but sigaction/sigprocmask is more portable and featureful.
on Unix/Linux, you can use a timer, here's an example:
#include <stdio.h>
#include <signal.h>
#include <sys/time.h>
int limit = 10;
/* signal process */
void timeout_info(int signo)
{
if(limit == 0)
{
printf("Sorry, time limit reached.\n");
exit(0);
}
printf("only %d senconds left.\n", limit--);
}
/* init sigaction */
void init_sigaction(void)
{
struct sigaction act;
act.sa_handler = timeout_info;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
sigaction(SIGPROF, &act, NULL);
}
/* init */
void init_time(void)
{
struct itimerval val;
val.it_value.tv_sec = 1;
val.it_value.tv_usec = 0;
val.it_interval = val.it_value;
setitimer(ITIMER_PROF, &val, NULL);
}
int main(void)
{
char *str;
char c;
init_sigaction();
init_time();
printf("You have only 10 seconds for thinking.\n");
while(1);
exit(0);
}
substitute your own function for timeout_info
On Linux it is very common to use select() for timing. This way you can also be notified about file descriptors activity.
You need to have a struct timeval for interval and pass it as the last argument of select.
I want to create a timer in our C program so that it can print the variable after every 1 second.
Can anybody help me in doing this?
Don't use busy waiting, because you've got 100% CPU utilization.
You must use system function which turns process into sleeping mode for example select():
#include <stdio.h>
#include <sys/select.h>
void your_callback()
{
printf("%s\n", __FUNCTION__);
}
int main()
{
struct timeval t;
while (1) {
t.tv_sec = 1;
t.tv_usec = 0;
select(0, NULL, NULL, NULL, &t);
your_callback();
}
return 0;
}
If all you are interested in doing is printing the value of a variable at a one second interval, using time(2) or clock(3) as suggested in the other answers might suffice. In general, I would not recommend these busy-waiting techniques.
If your program is more complex, I suggest you investigate using the alarm(2) or settimer(2) function to asynchronously deliver a signal to your application at a one second interval.
The following example uses select(2) to block indefinitely in order to minimize CPU usage associated with busy-waiting techniques. The blocking select() call is interrupted and returns when a signal is caught. In the case of the SIGALRM signal, the print_variable flag is set and the value of variable is printed.
Example 1: using alarm()
#include <signal.h>
#include <stdio.h>
#include <sys/select.h>
#include <unistd.h>
volatile unsigned int variable = 0;
volatile unsigned int print_variable = 0;
void alarm_handler(int signum)
{
variable++;
print_variable = 1;
alarm(1);
}
int main()
{
signal(SIGALRM, alarm_handler);
alarm(1);
for (;;)
{
select(0, NULL, NULL, NULL, NULL);
if (print_variable)
{
printf("Variable = %u\n", variable);
}
}
}
Note: Error checking was omitted from the above code for simplicity.
A printf() function could have been called inside the SIGALRM handler, but calling non-reentrant functions in a signal handler is generally discouraged.
A timeout of one second can also be passed to select(), but if it were interrupted by any signal, additional logic is necessary to ensure that the remainder of the one second timeout is honored. Fortunately on Linux, select() modifies the timeout value to reflect the amount of time not slept. This allows interruption cases to be detected followed by subsequent call(s) select() to complete the timeout.
Example 2: using select()
#include <errno.h>
#include <stdio.h>
#include <sys/select.h>
volatile unsigned int variable = 0;
int main()
{
struct timeval tv;
int val;
for (;;)
{
tv.tv_sec = 1;
tv.tv_usec = 0;
do
{
val = select(0, NULL, NULL, NULL, &tv);
} while (val != 0 && errno == EINTR);
printf("Variable = %u\n", ++variable);
}
}
If you want only second precision. Use time(0) which returns current time if time.h is included.
update:
Adding simple example which prints 10 in every second during 20 seconds:
#include <time.h>
#include <stdio.h>
int main()
{
int a = 10;
int num = 20;
int c = time(0);
while(n--)
{
printf("%d\n", a);
while(!(time(0) - c));
c = time(0);
}
return 0;
}
use time(0) see this example
/* timer.c */
#include <stdio.h>
#include <time.h>
void delay_sec( int seconds ){
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC;
while (clock() < endwait) {}
}
int main (void){
time_t rawtime, ini_time, now;
struct tm *ptm;
time ( &ini_time );
for(;;){
time ( &rawtime );
//ptm = gmtime ( &rawtime );
//printf ("%2d:%02d:%02d\n", ptm_2->tm_hour, ptm_2->tm_min, ptm_2->tm_sec);
now = rawtime - ini_time;
ptm = gmtime ( &now );
printf ("%2d:%02d:%02d\n", ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
delay_sec(1);
}
return 0;
}
I believe you know 1000 Milliseconds equals to 1 Second.
#include <stdio.h>
#include <time.h>
#define mydelay 1000
void delay(int mseconds)
{
clock_t wait = mseconds + clock();
while (wait > clock());
}
int main()
{
int i=100;
while(1)
{
printf("%d\n",i);
delay(mydelay);
}
return 0;
}
A simple example which prints the value of the variable a for every 1 sec:
#include<stdio.h>
void main(void)
{
int a = 10;
while(a--)
{
printf("Value of a = %d\n", a);
sleep(1);
}
}
Output:
Value of a = 9
...
value of a = 0