터미널 표준입력을 제어해보자


우리가 만든 프로그램이 터미널을 통해 입력을 받을 수 있고, 출력을 할 수 있다면, 각 입력에 대해서도 터미널 기본 속성이 아니라 우리가 원하는 용도로 사용하면 더 좋을 것이다. 예를들어 내가 만든 프로그램이 돌아가는 동안 ctrl + c 를 누른다면 프로그램이 종료되어버리고 이전에 실행 프로그램을 실행했던 쉘(bash or zsh)로 돌아가게된다.

여기서 ctrl + c를 눌렀을 때 프로그램이 종료되는 것이 아니라 작동중인 프로그램 내의 하나의 작업을 중단시키고 싶다면 ctrl + c 입력이 들어왔을 때, 이 기능을 바꿔야 할 것이다.

이때 signal이라는 함수를 사용해 SIG_INT가 들어올 때의 행동을 특정지어주어도 괜찮지만, 만약 ctrl + d와 같이 시그널이 아닌 특수 입력은 어떻게 처리할 수 있을까?

바로 이제부터 설명할 noncanonical input mode를 사용하면 된다.

Noncanonical input mode


그렇다면 canonical, noncanonical의 차이가 뭘까? gnu.org에서는 아래와 같이 설명하고 있다. 우선 canonical input processing mode에 대한 설명이다.

In canonical input processing mode, terminal input is processed in lines terminated by newline ('\n'), EOF, or EOL characters. No input can be read until an entire line has been typed by the user, and the read function (see I/O Primitives) returns at most a single line of input, no matter how many bytes are requested.

canonical input mode(표준 입력 모드)는 우리가 프로그램에서 흔히 사용하는 모델이다. 입력이 들어오면 개행 혹은 EOF와 같은 종료 문자가 나올때까지 처리를 기다리고 있다가 한번에 문장 한 줄을 처리한다.

아래는 noncanonical input processing mode에 대한 설명이다.

In noncanonical input processing mode, characters are not grouped into lines, and ERASE and KILL processing is not performed. The granularity with which bytes are read in noncanonical input mode is controlled by the MIN and TIME settings.