使用Linux上的c ++键退出无限循环

时间:2017-11-16 11:03:16

标签: c++ linux ubuntu while-loop infinite-loop

我有一个无限循环,如果我按任意键就应该结束。该程序在linux中运行。我偶然发现了一个函数这是我的一些代码:

int main(){
      While(1){
        ParseData(); //writing data to a text file
      }
return 0;
}

所以我知道我可以通过在终端中使用ctrl + c来终止进程,但似乎它会中断写入过程,因此数据不会在整个过程中完全写入。我读到我需要使用ncurses库中的函数,但我完全不了解。

有人可以帮助我吗?谢谢!

4 个答案:

答案 0 :(得分:2)

您可以声明atomic_bool并将主循环移动到另一个主题。现在,一旦用户按下退出循环的任何键,您就可以等待一个简单的cin

std::atomic_boolean stop = false;

void loop() {
    while(!stop)
    {
        ParseData(); // your loop body here
    }
}

int main() {

    std::thread t(loop); // Separate thread for loop.

    // Wait for input character (this will suspend the main thread, but the loop
    // thread will keep running).
    std::cin.get();

    // Set the atomic boolean to true. The loop thread will exit from 
    // loop and terminate.
    stop = true;

    t.join();
    return 0;
}

答案 1 :(得分:1)

为什么你需要一个键来退出一个没有完成写入文件的程序,即使你按下按键退出它也会在没有完成的情况下中断文件写入。

为什么在数据写入文件时退出循环,如下所示:

isFinished = false;      
While(!isFinished ){
    ParseData(); //writing data to a text file
   //after data finsihes
   isFinished = false;
  }

答案 2 :(得分:0)

thread.cpp

#include <atomic>
#include <iostream>
#include <thread>

std::atomic<bool> dataReady(false);

void waitingForWork(){
    std::cout << "Waiting... " << std::endl;
    while ( !dataReady.load() ){ 
        std::this_thread::sleep_for(std::chrono::milliseconds(5));
    }
    std::cout << "Work done " << std::endl;
}

int main(){

  std::cout << std::endl;

  std::thread t1(waitingForWork);
  std::cout << "Press Enter to Exit" << std::endl;
  std::cin.get();

  dataReady= true; 
  t1.join();
  std::cout << "\n\n";
}

g ++ -o线程thread.cpp -std = c ++ 11 -pthread

答案 3 :(得分:-1)

实际上C方式(包括conio.h):

char key;

while (1)
{
    key = _getch();

    // P to exit
    if (key == 'p' || key == 'P')
    {
        writer.close();
        exit(1);
    }
}
相关问题