I am completely clueless about the inner workings of an operating system, but I can more or less guess the approximate behaviour of many functions. One thing that I am not able to figure out, though, is multitasking.
In theory, the operating system manages time, according the CPU for small intervals to the various programs running. But it is not clear how this really works.
Say the operating system wants to start my program. The machine code is loaded somewhere in RAM, starting at a certain address. I guess then a jump should be performed to that address, allowing my code to execute. But in this way, the OS cannot regain control until I jump back.
Basically, I can imagine just two ways of making this work, but neither seems really suitable:
The operating system could read the machine instructions I want to perform and emulate them instead of executing them directly. I am intentionally vague, since I do not know how this would work, but it seems like it would slow down the program considerably.
Alternatively, the operating system could wait until I make a system call. In that moment it regains control and can check how long I have been running and do its timesharing stuff. This may work, but it seems unreliable, as I could make a long calculation which does not involve system calls and hang everything for a while.
So, it seems neither mechanism would work very well. How is multitasking actually performed?