在Linux上的C++程序中,如果你想要使用密钥来退出一个无限循环,你可以使用非阻塞输入来实现这个功能。以下是一个简单的示例代码,展示了如何实现这一功能:
#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
#include <unistd.h> // For isatty() and read()
#include <termios.h> // For termios structure
// Function to set the terminal in non-canonical mode
void set_non_canonical_mode() {
struct termios tty;
tcgetattr(STDIN_FILENO, &tty);
tty.c_lflag &= ~ICANON; // Disable canonical mode
tty.c_cc[VMIN] = 0; // Minimum number of characters for noncanonical read
tty.c_cc[VTIME] = 1; // Timeout in deciseconds for noncanonical read
tcsetattr(STDIN_FILENO, TCSANOW, &tty);
}
// Function to reset the terminal to canonical mode
void reset_terminal_mode() {
struct termios tty;
tcgetattr(STDIN_FILENO, &tty);
tty.c_lflag |= ICANON; // Enable canonical mode
tcsetattr(STDIN_FILENO, TCSANOW, &tty);
}
int main() {
std::atomic<bool> running(true);
// Set terminal to non-canonical mode
set_non_canonical_mode();
// Start a thread to check for key press
std::thread([&running]() {
char ch;
while (running) {
if (read(STDIN_FILENO, &ch, 1) > 0 && ch == 'q') {
running = false;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}).detach();
// Your infinite loop
while (running) {
std::cout << "Running..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
// Reset terminal mode before exiting
reset_terminal_mode();
std::cout << "Exited the loop." << std::endl;
return 0;
}
termios
结构体的设置,确保ICANON
标志被正确地启用或禁用。通过上述代码和解释,你应该能够在Linux上的C++程序中实现使用密钥退出无限循环的功能。
领取专属 10元无门槛券
手把手带您无忧上云