3
$\begingroup$

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:

 #include <string>
 #include <iostream>
using namespace std;
int main()
{
cout << "Enter something";
string input;
cin >> 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.

$\endgroup$

1 Answer 1

3
$\begingroup$

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.

$\endgroup$
1
  • $\begingroup$ You know, I'm thinking of a security system on the market that calls you and can then be controlled over the phone. From your description, it seems kind of like this: When the system is set up, the installer programs a phone number into the system (the "CPU" in this case"), and then, if a sensor is tripped and the alarm goes off, it calls you (the "operating system"), and then you can decide what to do with the info the system gives you (you can have the system call the police, you can talk to whoever's there via the control panel, you can disarm, etc.) $\endgroup$
    – moonman239
    Commented Jan 15, 2016 at 1:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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