I have read that a hardware interrupt is handled asynchronously by the CPU, which means that the interrupt signal may arrive at any point of time with respect to the CPU clock cycle. Now, this means that an interrupt may asynchronously hit the processor when it is in the middle of executing some instruction. So, how does the control pass to the OS in this case? For the case of software interrupts (exceptions), we know that the instruction being executed (trap instruction) itself is the cause of the interrupt. So, it will synchronously finish executing and then the control will transfer to the kernel as per the trap instruction nature. How does all this happen for hardware interrupts?

  • $\begingroup$ One way to handle interrupt signals is to raise a flag in some clock-independent storage. CPU will look at this flag (and reset it) at some point (next cycle, or before fetching next instruction). $\endgroup$ – Dmitri Urbanowicz Aug 23 '19 at 6:20

This is architecture specific so the following might not be true for all architectures.

Normally there is a special hardware in the CPU called interrupt controller that will react to interrupts. You usually program this hardware on boot time by writing a handler for each interrupt (called interrupt service routine) and giving the interrupt controller a table with the location of these handlers (the interrupt vector table https://en.wikipedia.org/wiki/Interrupt_vector_table).

When a hardware interrupt happens, the interrupt controller will automatically lookup the location of the corresponding handler and immediately continue execution there (on the very next assembler instruction). Depending on the architecture, there might now be a second set of registers, another stackpointer etc. that the ISR uses or it has to save the status of the interrupted program to the memory (RAM) perform it's actions and restore the state once it finishes.

The ISR is automatically run in a higher privilege mode on the CPU (if not already in a high privillege mode) and can therefore invoke other OS functionality. How the ISR is now interacting with the OS can't be answered in general. It could for example set some flags which are then checked by the OS threads.

Maybe you will also find this answer interesting: https://cs.stackexchange.com/a/85156/108759

| cite | improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.