Implementing general timeouts - c

I'm porting some code from C# to C. In the C# code there are three timers that fire if particular events take too long and they set flags that are checked next time a thread runs a bit of housekeeping.
The C is pure C, not C++, and will eventually be used on both Linux and in embedded targets, so I can't use any OS oriented stuff- simple soft timers. I started off using just an "enabled" flag and a due time for each timer, in ms, and when I call the housekeeping function I'll pass the current ms timer value to it. Then I started thinking of the wraparound issue and decided I wanted the start time as well, so if the present time isn't between the start time and the due time I know it's expired. And I want the default duration to be there as well, so it ends up being worth making a structure to represent a timer. And then making functions that work with pointers to these structures. And then it started me thinking I may be reinventing the wheel.
I don't see anything in the standard libraries that looks like this. Am I missing something? Is this just something that's just easier to do than to look for? :)

Ta for commenting. That's the way I went, just wanted to make sure I wasn't wasting work. Yeah embedded stuff tends to have a timer interrupt, but three is probably asking a bit much and adds hardware dependencies- I'm just passing the current ms timer value to my code and then it doesn't have to care about where that value's coming from. – Craig Graham

Related

clock_settime backward correction

I'm trying to do a couple of tests where I need to set the computer time backward or forward depending on some external values. I know that I can do this using clock_settime() in time.h.
I've encountered the problem that when needing to set the time backward, the operation fails.
The documentation for clock_settime states that
Only the CLOCK_REALTIME clock can be set, and only the superuser may do so. If the system securelevel is greater than 1 (see init(8)), the time may only be advanced. This limitation is imposed to prevent a malicious superuser from setting arbitrary time stamps on files. The system time can still be adjusted backwards using the adjtime(2) system call even when the system is secure.
I require nanosecond precision, and adjtime() as far as I understand, does not allow nanosecond precision. The other problem with ajdtime() is that it does not set the clock outright, rather slows it down, until the clock catches up to the set value.
I've done some reading on init() but I'm not sure how to lower the securelevel, and frankly I'd rather not be forced to do this, however, if there's no other way, I'm willing to try it.
Thanks in advance
Update 1
I started looking into altering securelevel and now i'm not even sure if that's something that can be done on Ubuntu. Around the web, I have come across mentions of editing /etc/init/rc-sysinit.conf, /etc/init/rc.conf, or /etc/sysctl.conf and, again, I'm not sure what needs to be added in order to lower the securelevel if, in fact, this is something that can be done. Especially since I could not find a 'rc.securelvel' file.

Understanding pthreads a little more in C

So I only very recently heard about these pthreads and my understanding of them is very limited so far but I just wanted to know if it would be able to do what I want before I get real into learning about them.
I have written a program that generates two output pulses from a micro-controller which happen with different frequencies, periods and duty cycles. At the moment the functions to output the pulses are happening in a loop and it works well because the timings I am using are multiples of each other so stopping one while not interrupting the other is not too much hassle.
However I want it be a lot more dynamic so I can change the duty cycles or periods easily without having to make some complicated loop specific for those timings... Below shows a quick sketch of what I am trying to achieve and I hope you can understand it...
So basically my question is, is something like this possible with pthreads in C, ie do they run simultaneously so one could be pulsing on and off while the one is waiting for a delay to finish?
If not is there anything that I could use for this instead?
In general, it's not worth using threads for such functionality on a uC. The cost of extra stacks etc. for such limited operations is not worth it, tempting it might be from a simplicity POV.
A hardware timer, interrupt and a delta-queue of events is probably the best you could do.

Programmatically Detect Context Switch via Assembly

I am aware that one cannot listen for, detect, and perform some action upon encountering context switches on Windows machines via managed languages such as C#, Java, etc. However, I was wondering if there was a way of doing this using assembly (or some other language, perhaps C)? If so, could you provide a small code snippet that gives an idea of how to do this (as I am relatively new to kernel programming)?
What this code will essentially be designed to do is run in the background on a standard Windows UI and listen for when a particular process is either context switched in or out of the CPU. Upon hearing either of these actions, it will send a signal. To clarify, I am looking to detect only the context switches directly involving a specific process, not any context switches. What I ultimately would like to achieve is to be able to notify another machine (via the internet signal) whenever a specific process begins making use of the CPU, as well as when it ceases doing so.
My first attempt at doing this involved simply calculating the CPU usage percentage of the specific process, but this ultimately proved to be too course-grained to catch the most minute calculations. For example, I wrote a test program that simply performed the operation 2+2 and placed the answer inside of an int. The CPU usage method did not pick up on this. Thus, I am looking for something lower level, hence the origin of this question. If there are potential alternatives, I would be more than happy to field them.
There's Event Tracing for Windows (ETW), which you can configure to receive messages about a variety of events occurring in the system.
You should be able to receive messages about thread scheduling events. The CSwitch class of events is for that.
Sorry, I don't know any good ETW samples that you could easily reuse for your task. Read MSDN and look around.
Simon pointed out a good link explaining why ETW can be useful. Very enlightening: http://randomascii.wordpress.com/2012/05/11/the-lost-xperf-documentationcpu-scheduling/
Please see the edits below. In particular #3, ETW appears to be the way to go.
In theory you could install your own trap handler for the old int 2Eh and the new sysenter. However, in practice this isn't going to be as easy anymore as it used to be because of Patchguard (since Vista) and signing requirements. I'm not aware of any other generic means to detect context switches, meaning you'd have to roll your own. All context switches of the OS go through call gates (the aforementioned trap handlers) and ReactOS allows you to peek behind the scenes if you feel uncomfortable with debugging/disassembling.
However, in either case there shouldn't be a generic way to install something like this without kernel mode privileges (usually referred to as ring 0) - anything else would be a security flaw in Windows. I'm not aware of a Windows-supplied method to achieve what you want either.
The book "Undocumented Windows NT" has a pretty good chapter about the exact topic (although obviously targeted at the old int 2Eh method).
If you can live with hooking only certain functions, you may be able to get away with some filter driver(s) or user-mode API hooking. Depends on your exact requirements.
Update: reading your updated question, I think you need to read up on the internals, in particular on the concept of IRQLs (not to be confused with IRQs from DOS times) and the scheduler. The problem is that there can - and usually will - be literally hundreds of context switches every second. However, your watcher process (the one watching for context switches) will, like any user-mode process be preemptable. This means that there is no way for you to achieve real-time signaling or anything close to it, which puts a big question mark on the method.
What is it actually that you want to achieve? The number of context switches doesn't really give you anything. Every single SEH exception will cause a context switch. What is it that you are interested in? Perhaps performance counters cater your needs better?
Update 2: the sheer amount of context switches even for a single thread will be flabbergasting within a single second. So assuming you'd install your own trap handler, you'd still end up (adversely) affecting all other threads on the system (after all you'd catch every context switch and then see whether it's the process/threads you care about and then do your thing or pass it on).
If you could tell us what you ultimately want to achieve, not with the means already pre-defined, we may be able to suggest alternatives.
Update 3: so apparently I was wrong in one respect here. Windows comes with something on board that signals context switches. And ETW can be harnessed to tap into those. Thanks to Simon for pointing out.

Threading OR multiple flow of control in Pacman

I am planning to write a Pacman game in C language, right from scratch. The most basic challenge that I am facing is how to maintain multiple flows of control at the same time.
I mean how does the Pacman move, the ghosts move, the score being updated -- all at the same time. In general it is very common for all games. Is any kind of threading involved here?
If so can anyone please tell as to how to make your program do many things at the same time (it will be helpful if you tell for C language).
Thanks in advance
One of the fundamental principle in real time game development is the game tick. It represents a small unit of time for things to happen in. So you might have a tick every 0.100 seconds. The smaller the tick, the finer control you have.
You can think of them as really fast turns with a time limit on them. If you don't do anything on that turn you forfeit the turn.
I think it's pretty unlikely that the original version of Pac-Man was multithreaded in the sense we use the term today. It was more likely implemented as a simple loop with some kind of interrupt support. You can do the same to implement rudimentary multithreading - write your program in a while (1) or for (;;) loop, and set up a timer to interrupt your loop at regular intervals to perform the screen updates.

How to retrieve the current processor time in Linux?

I am using C language and Linux as my programming platform in embedded device.
My question is, how to correctly retrieve the current processor time(tick). I am using clock() function in time.h and it seems I am getting inconsistent value.
Thanks.
The clock() function measures the CPU time consumed by your process. It doesn't increment while your process is sleeping or blocked.
If you want a high resolution clock that advances continually, use clock_gettime(CLOCK_MONOTONIC, ..).
I am not real clear on what, specifically, you are asking. If you want another method to get the time your process is using, I often use getitimer() / setitimer() with ITIMER_PROF versus ITIMER_REAL. I find that can be a bit quirky, however.
You may be interested in the LWN article "The trouble with TSC", and the attached comments. While gettimeofday and clock_gettime seem to be the correct thing to go to, there's a lot to consider: performance may vary, there may be consistency issues between different CPUs in multithreaded or multiprocess programs, and the presence of e.g. NTP can mutate the clock value (CLOCK_MONOTONIC will not be affected by NTP, but others may).
Be careful, and make sure you read up on whatever you pursue to make sure it fits your requirements. If you're lucky you're on a fixed hardware and library platform, or you can afford some kinds of inaccuracy or imprecision.

Resources