本文介绍了相当于Windows getch()Mac / Linux崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 c>

Linking/compiling is not an issue; I include <curses.h> and link with -lcurses in XCode, while Windows uses <conio.h>.

推荐答案

< curses.h> 以查看 getch()函数是什么?

Have you looked in <curses.h> to see what the getch() function does?

提示:OSX和Linux与Windows不同。

Hint: OSX and Linux are not the same as Windows.

具体来说,作为< curses.h> ,我们找到:

Specifically, as a macro in <curses.h>, we find:

#define getch() wgetch(stdscr)

现在,在您的系统上,出现了一个实际的函数 getch() curses库,但它期望设置 stdscr ,这是由curses初始化函数( initscr()和亲戚),这是明智的做不到你的代码。因此,您的代码通过在正确的初始化完成之前调用curses例程来调用未定义的行为,从而导致崩溃。

Now, there appears, on your system, to be an actual function getch() in the curses library, but it expects stdscr to be set up, and that is done by the curses initialization functions (initscr() and relatives), and that is signally not done by your code. So, your code is invoking undefined behaviour by calling curses routines before the correct initialization is done, leading to the crash.

(来自dmckee的好提示 - line out of acidzombie24,这很重要。)

(Good hint from dmckee - it helped get the link line out of acidzombie24, which was important.)

为了得到一个单一的关键笔划可以被读取和程序终止干净的点,你必须做一个在Unix上很好的工作(OSX,Linux)。你必须陷阱终端的初始状态,安排一个 atexit()函数 - 或一些类似的机制 - 恢复终端的状态,改变终端从cooked模式转换为raw模式,然后调用一个函数来读取一个字符(可能只是 read(0,& c,1)),然后退出。

To get to a point where a single key-stroke can be read and the program terminated cleanly, you have to do a good deal of work on Unix (OSX, Linux). You would have to trap the initial state of the terminal, arrange for an atexit() function - or some similar mechanism - to restore the state of the terminal, change the terminal from cooked mode into raw mode, then invoke a function to read a character (possibly just read(0, &c, 1)), and do your exit. There might be other ways to do it - but it certainly will involve some setup and teardown operations.

一本可能会有帮助的书是 by Mark Rochkind;它涵盖了所需级别的终端处理。或者,您可以正确使用< curses.h> - 这将比滚动自己的解决方案更简单,并且可能更可靠。

One book that might help is Advanced Unix Programming, 2nd Edn by Mark Rochkind; it covers terminal handling at the level needed. Alternatively, you can use <curses.h> properly - that will be simpler than a roll-your-own solution, and probably more reliable.

这篇关于相当于Windows getch()Mac / Linux崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 22:09