An Operating System (OS) is a software application that controls the hardware (HW) and regulates access to the HW for the convienience and safety of the user and applications. Conceptually the OS sits between the HW and the applications and the applications access the hardware indirectly via the operating system.
The OS handles all of the lower-level details of controlling the HW directly, via cosde called device drivers. Users and applications are usually not allowed to access the harware directly but must go through the OS. In this way, the OS controls who access the HW at what times. By hiding the details of the HW and presenting intuitive aspects of it to users and applications, the OS makes life more convienient for users and application developers. By regulating access to the HW, the OS ensures that users and applications do not step on each others toes or gain access to data they should not see.
The OS achieves its goals by preventing the users and applications from accessing the HW directly, forcing them to go through the OS instead. This allows the OS to regulate access to the HW and provide the abstractions. Besides making devices simpler and safer to use, providing abstractions allows a wide range of devices to appear the same or simular enough that the same applications can run on a wide range of hardware configurations and users can move from one computer to another with little trouble.
The secret to how the OS prevents access to the HW while still having access itself lies with the CPU. The CPU has at least 2 different modes of operation; the kernel mode and the user mode. In the user mode, certain instructions cannot be executed where as in the kernel mode, all instructions can be executed. The instructions that cannot be executed in user mode, are those that control the HW. An ordinary application runs with the CPU in user mode. When the application needs access to the HW, it switches to kernel mode via a “trap”. Executing this trap also switches execution to the OS. So the application itself never executes in kernel mode. The OS performs the HW access, switches back to user mode and the returns execution to the application.