Why Linux doesn’t have a Main Event Loop Like Web Servers

As System Programming lovers, you might have seen some web server code, or might have created a small web server in C or C++ or java, if not, then for sure you might have created some application programs, the design of many softwares is like this: One main loop for example while(1){ //all code here with exit statementes }.

Many web servers, even today, follow the design where the main event infinite loop is a central component.

Does Linux, the world’s most popular open source Operating System, follow the same Main loop design, where all code and function calls happen, and the loop keeps running until the user shuts down the machine?

The answer is Linux does not have a Main event loop, though it has an idle loop, but as a central component, it does not havean infinite loop like while(1) { os code goes here }, but Linux is primarily driven by the Interrupt mechanism, Linux kernel runs the code when hardware interrupt,s, like disk, keyboard, and network, arrive.

Apart from interrupts, the Linux kernel reports on duty if the Process Scheduler decides that a particular process needs the kernel’s attention to pass the executable code to the CPU

The third most important thing that wakes Linux code is System calls. Whenever a user programs wants to read a file, access any device like usb or want to maipulate any resource, a System call goes to the Kernel and then kernel runs the code.

So basically, instead of executing under rounds of an infinite loop, Linux code runs on Interrupts, Scheduler calls, and System Calls.

But Linux still has a loop, an idle loop

When the Scheduler does not find any task for the kernel or no Interrupt happens, then this idle loop or idle task runs on the CPU.

So the question is Infinite loop-based design is not possible in OS kernel development? The answer is that it is possible, but intentionally avoided by Unix and Unix-like systems like Linux, havingan infinite loop wastes CPU power, and Interrupts fill the purpose, so designers avoided this type of system.

Even Minix avoided this design, Minix was the OS that motivated Linus to create Linux

is an infinite loop-based design good for at least other types of software?

Today, many popular software are using infinite loop-based design, for ex. Nginx tops the list, one of the most popular reverse proxy server, uses this design

Another popular product that uses infinite loop design in Node js.

We should remember that most of these software which use infinite loops does not burn the CPU by always executing the loop, but this loop also waits and sleeps

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *