Reputation: 728
I'm reading about std::cin
and I see that my program stops at a line with it and kind of "waits" for me to enter input and press Enter. What is happening under the hood? How does std:cin
suspend the entire program?
Upvotes: 1
Views: 303
Reputation: 99993
Roughly speaking, a call to read from std::cin will result in a system call to read from 'Standard Input'. On Linux, that's File Descriptor 0. When your process makes a system call, you are in the kernel, which can leave your process snoozing until it has some data to hand you (which it writes into your buffer and resumes your execution).
Note: completely oversimplified and abstracted to answer the spirit of the question.
Elaboration in response to note:
So, here's the CPU, ambling along executing the instructions of your executable (in the context of your process). You make a system call. The CPU stops executing your program's instructions, saves the state of your program in a kernel data structure, and starts executing the kernel. Your process is now sleeping. It remain asleep until kissed a prince the kernel decides to wake it up, at which point the kernel arranges for the CPU to restore its state and continue along.
Any time you enter the kernel via a system call, the kernel has the option to leave you sleeping for a while. (It also has the ability to put you to sleep based on an I/O interrupt or a timer, as needed, to share the CPU with other processes.)
Upvotes: 4