Do they repeatedly check for the condition and execute if the condition is met. Ex, how the OS knows exactly when a USB device is plugged in, or how MSN knows exactly when you get an email. How does this work?



At the low level, the OS kernel "knows" when something happens, because the device in question sends the CPU a hardware interrupt.

So when, say a network packet arrives, the network controller sends an interrupt, and the OS kernel responds as appropriate.

At the program level, it works quite differently - most application programs run an "event loop", where they fetch a message (say, a message from the OS saying that "the mouse was clicked on this point in your application"), perform the appropriate actions in response to that, and then, listen for more messages. If there is no message, the OS sleeps the thread until it has a message to deliver.

| improve this answer | |
  • 2
    +1 For clearly explaining the difference between interrupts at the hardware level and event listeners at the software level. – Pete Jul 5 '10 at 21:57

Take a look at Interrupts this should explain how the hardware initiates certain 'events'

| improve this answer | |


Often an event listener is registered with the object that generates the event. When the event occurs, the object iterates through all listeners registered with it informing them of the event. Have a look at the AWT/Swing event model in Java for example.

ow the OS knows exactly when it gets a USB

At a low level I suspect thats a hardware interupt (someone correct me if I'm mistaken) which is handled by the kernel/USB driver. There's often higher level systems (e.g. DBUS) that listen for this and have event listeners listening to them.

or how MSN knows exactly when you get an email.

I suspect that's a simple case of polling the mail box (e.g. over POP3) every x seconds and checking the message count (could be wrong though).

Anon. explains the difference between hardware interrupts and software level event listening quite well.

| improve this answer | |

Programs like email checkers will usually be running background services that query their email server every X period checking for new mail. There are other ways of doing it, but for software level events, it's almost certainly going to be something like that.

| improve this answer | |

Your Answer

