Implementing timer callback in c - c

I am new to callback functions in C. I want to create a timed callback.
Scenario: I want a timer function which will trigger the callback function when timer expires. For example, every 5 sec the timer expires and calls the function.
How should I approach this problem ?

How should you approach this problem?
As with all problems:
Figure out what you want to do precisely
Ask yourself how you would do it yourself if you needed to (and if you could)
Try to formalize previous step as close as possible to single statements sentences, one step at a time.
Identify what blocks you / what you don't know how to do. Do some research on that.
What you want to do precisely
You want to "create a timed callback". I think this means :
You have a function foo doing some work
You have your program running
You want to be able to say "From right now, in X miliseconds, call foo" anywhere in your program
How would you do this yourself?
I think you would, for example, launch a stopwatch with X miliseconds then keep doing whatever you were doing. When the stopwatch reaches zero, you stop what you do and do the thing needed. Finally, resume what you were doing.
What blocks you?
Judging by your question I think two things block you:
You need to understand how to do function callbacks in C. See "function pointers"
You need to understand how to have a timer and do something when the timer reaches zero.
A few google searches will help you with both.

Related

Is there an algorithm to schedule overlapping turn-on/turn-off commands?

The problem I want to solve is as follow:
Each task (the green bar) represents a pair of turn-on (green-dashed-line) and turn-off (red-dashed-line) commands. Tasks may or may not overlap with one another. This a real-time application where we don't know when or if another task is coming. The goal is to turn the valve on if it's not already on and avoid turn off the valve prematurely.
What I mean by not turn off the valve prematurely is, for example, if we turn off the valve at time off-1, that's wrong because the valve should still stay on at that point in time, the correct action is to turn off the valve at time off-4.
Regarding the implementation details, each task is an async task (via. GLib async API). I simulate the waiting for task-duration with the sleep function, a timer is probably more appropriate. Right now, the tasks run independently and there is no coordination between them, thus the valve is being turn-off prematurely.
I searched around to find a similar problem but the closest I found is interval scheduling whose goal is different. Has anyone encountered a similar problem before and can give me some pointers on how to solve this problem?
It seems like this could be solved with a simple counter. You increment the counter for each opening command, and decrement it for each closing command - when the count reaches zero, you close the valve.

Increment an output signal in labview

![enter image description here][1]I have a high voltage control VI and I'd like it to increase the output voltage by a user set increment every x number of seconds. At the moment I have a timed sequence outside the main while loop but it never starts. When it's inside the while loop it delays all other functions. I'm afraid I'm such a beginner at this that I can't post a picture yet. All that needs to happen is an increase in voltage by x amount every y seconds. Is there a way to fix this or a better way of doing it? I'm open to suggestions! Thanks!
Eric,
Without seeing the code I am guessing that you have the two loops in series (i.e. the starting of the while loop depends upon an output of the timed loop; this is the only way that one loop might block another). If this is the case, then decouple the two loops so that they are not directly dependent on each other.
If the while loop is dependent on user input, then use an event structure and then pass the new parameters via a queue (this would be your producer-consumer pattern).
Also, get rid of the timed loop and replace with a while loop. The timed loop is only simulated on non-real time machines and it can disrupt determinisitic features of a real-time system. Given that you are looking for sending out a a signal on the order of seconds, it is absolutely not necessary.
Anyways, if I am off base, please throw the code in question up so that we can review it.
Cheers, Matt

Waiting maximum of X time for input, then proceeding with the program?

Hello I'm creating a game in C.
I want there to be a frame printed every 0.1 seconds. During that time, the user may or may not input using getch().
How do I write such a program? Heres what I can offer you guys to work with.
do{
usleep(100000); // simple 100 mili second delay
if (getch()==32) (ASCII for a space) // may or may not be inputed in 0.1 second timeframe.
playerJumps;
// even if user inputs early, I still want game printed exactly every 0.1 sec not sooner/later.
printGame;
}while(notDead);
I really hope I kept code nice and clear
I've done this before, you are going to have to talk about what platform you are on. All of the C library input functions block to wait for input. One way to do it is with threads -- you have one thread block on the user input, and the other does the game, and it gets notified by the input thread when there is input. The other way is to use a function like poll() on linux, which I believe is what I used, they basically allow you to specify a wait period, or to just try to see if there is input and return immediately if there isn't. Though I think select() should also work, and I think that should be relatively cross platform.

Programmatically Getting Total Time and Busy Time of Function on Linux

Is there any way to programmatically get the total time that a C program has been running, as well as the amount of that time spent inside a particular function? I need to do this in the code since I want to use these two values as arguments for another function. Since I am on Linux, would I be able to use gprof or perf to do this?
Grab the system time when the program starts. Then, whenever you want, you can get the current time and subtract the start time. That tells how long you've been running, in wall-clock time.
Have a global boolean Q that is set True when your function is entered, and False when it exits, so it is only True while the program is "in" the function (inclusively).
Setup a timer interrupt to go off every N ms, and have two global counters, A and B. (N does not have to be small.) When the timer interrupts, have it increment B regardless, but only increment A if Q is true.
This way, you know how much time has elapsed, and A/B is the fraction of that time your function was on the stack.
BTW: If the function is recursive, let Q be an integer "depth counter". Otherwise, no change.
Yes, you can use gprof, but that requires re-compiling the binary you want to measure to insert the required monitoring code. By default, programs don't spend time recording this data, so you must add it. With gcc, this is done using the -pg option.
You can use gprof for the same.

run func() based on what time it is

i wrote some code that monitors a directory DIR with inotify() and when a file gets moved in DIR i get a .txt output of that file(its an nfcapd file with flows of my network interface). This happens every 5 minutes.
After that, i used Snort's DPX starter kit, with which you can extend Snort by writing your own preprocessor. This preprocessor,like all the others, is just a function that's executed every time a new packet is available. My problem is that i want, when a new file gets exported from my previous code(so every 5 minutes), to read that file inside the preprocessor's function.
So, is there any way of getting the time and executing only if it's the desired time?
if (time is 15:36){
func(output.txt);}
i'm writing in c.
Thanks
You can do something like the following:
#include <time.h>
...
time_t t = time(NULL); //obtain current time in seconds
struct tm broken_time;
localtime_r(&t, &broken_time); // split time into fields
if(broken_time.tm_hour == 15 && broken_time.tm_min == 36) { //perform the check
func(output.txt);
}
Since you're using inotify, I'm assuming your environment supports POSIX signals.
You can use alarm() to raise a signal after a predetermined amount of time has passed and have the appropriate signal handler do whatever work you need to do. It would avoid what I think is going to end up being a very ugly infinite loop in your code.
So, in your case, the function handling SIGALRM would not need to worry what time it was, it would know that a predetermined amount of time has passed by the fact that it was entered. However, you'll need to provide some context that function can access to know what to do, kind of hard to suggest how without seeing your code.
I'm not entirely sure you're going down the right path with this, but using alarm() would probably be the sanest approach given what you described.

Resources