patternMinor
How does the CPU know to get data from or send data to a peripheral device?
Viewed 0 times
theknowsenddevicegetperipheraldoeshowcpufrom
Problem
We were talking today, in Intro to Programming, about machine language. I know it's a bunch of 0's and 1's. Let's say I compile the following C++ program on an x86 machine:
Now, cin - as I understand - is an input stream. The computer gets input from the keyboard and places it in cin to be read by the program. My question is, how does the CPU know it's supposed to get input from the keyboard when, at the end of the day, the program is just 1's and 0's?
My understanding is that the machine code is kind of broken up.
#include
#include
using namespace std;
int main()
{
cout > input;
return 0;
}Now, cin - as I understand - is an input stream. The computer gets input from the keyboard and places it in cin to be read by the program. My question is, how does the CPU know it's supposed to get input from the keyboard when, at the end of the day, the program is just 1's and 0's?
My understanding is that the machine code is kind of broken up.
Solution
Keyboard input is handled through an interrupt – a signal sent to the CPU by the motherboard in response to your pressing a key. The CPU maintains a table of functions to call for each type of interrupt, and the operating system sets this so that control passes to it whenever a key is pressed.
The operating system maintains a buffer of pressed keys, and passes on this event to the software currently capturing the keyboard (if any), causing the call of an event handler set by the piece of software. If you run your program from a terminal, then the terminal is the relevant piece of software. It stores the keystrokes in its own buffer, which the C standard library has access to. (In terminal-based operating systems such as DOS or a Unix shell, this is handled by a system call, which is a function executed by the operating system.) The C++ iostream library, which is what your program actually uses, is a wrapper of the C standard library.
The operating system maintains a buffer of pressed keys, and passes on this event to the software currently capturing the keyboard (if any), causing the call of an event handler set by the piece of software. If you run your program from a terminal, then the terminal is the relevant piece of software. It stores the keystrokes in its own buffer, which the C standard library has access to. (In terminal-based operating systems such as DOS or a Unix shell, this is handled by a system call, which is a function executed by the operating system.) The C++ iostream library, which is what your program actually uses, is a wrapper of the C standard library.
Context
StackExchange Computer Science Q#51871, answer score: 3
Revisions (0)
No revisions yet.