希望する結果を得るには、標準入力をノンブロッキングにする必要があります。これは、コードを少し変更することで実現できます。Mac OS X 10.7.5 では問題なく動作しました。読む準備ができている文字がない場合は EOFを返すことに注意してgetchar()
ください (ほとんどの場合、あなたも私も現代のコンピューターにとって重要なほど速く入力することはできません)。getchar()
一部のシステムでは、読み取る文字がないときに一度 EOF を返すと、二度と EOF 以外を返さない可能性があることを少し心配していますが、それは Mac OS X では問題ではありませんでした。
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
static void err_exit(const char *msg);
int main(void)
{
int c;
int oc = '\0';
struct termios staryTermios, novyTermios;
int oflags, nflags;
if (tcgetattr(STDIN_FILENO, &staryTermios) != 0)
err_exit("tcgetattr() failed");
novyTermios = staryTermios;
novyTermios.c_lflag &= ~(ICANON);
if (tcsetattr(STDIN_FILENO, TCSANOW, &novyTermios) != 0)
err_exit("tcsetattr() failed to set standard input");
oflags = fcntl(STDIN_FILENO, F_GETFL);
if (oflags < 0)
err_exit("fcntl() F_GETFL failed");
nflags = oflags;
nflags |= O_NONBLOCK;
if (fcntl(STDIN_FILENO, F_SETFL, nflags) == -1)
err_exit("fcntl() F_SETFL failed");
while ((c = getchar()) != 'q')
{
if (c != EOF)
oc = c;
if (oc != '\0')
putchar(oc);
}
if (tcsetattr(STDIN_FILENO, TCSANOW, &staryTermios) != 0)
err_exit("tcsetattr() failed to reset standard input");
putchar('\n');
return 0;
}
static void err_exit(const char *msg)
{
fprintf(stderr, "%s\n", msg);
exit(1);
}