Skip to content

Instantly share code, notes, and snippets.

@cloudwu
Created May 20, 2021 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cloudwu/96ec4d6636d65b7974b633e01d97a1f9 to your computer and use it in GitHub Desktop.
Save cloudwu/96ec4d6636d65b7974b633e01d97a1f9 to your computer and use it in GitHub Desktop.
Turn off canonical mode , forward stdin to stdout, and write \n per 100ms
// Linux: gcc -Wall -o period period.c -lpthread
// Mingw: gcc -Wall -o period.exe period.c
#include <stdio.h>
#define PERIOD 100 // 100 ms
#if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__)
#include <windows.h>
static void
set_non_canonical()
{
DWORD mode;
HANDLE console = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(console, &mode);
SetConsoleMode(console, mode & ~ENABLE_LINE_INPUT);
}
static DWORD WINAPI
timer(LPVOID lpParam) {
for (;;) {
Sleep(PERIOD);
printf("\n");
fflush(stdout);
}
return 0;
}
static void
start_timer() {
CreateThread(NULL, 0, timer, NULL, 0, NULL);
}
#else
#include <termios.h>
static void
set_non_canonical()
{
struct termios mode;
tcgetattr(0, &mode);
mode.c_cc[VMIN] = 1;
mode.c_cc[VTIME] = 0;
tcsetattr (STDIN_FILENO, TCSAFLUSH, &mode);
}
#include <pthread.h>
#include <unistd.h>
static void *
timer(void *dummy) {
for (;;) {
usleep(1000 * PERIOD);
}
return NULL;
}
static void
start_timer() {
pthread_t pid;
pthread_create(&pid, NULL, timer, NULL);
}
#endif
int
main() {
start_timer();
set_non_canonical();
setvbuf(stdin, NULL, _IONBF, 0);
int c;
while((c = getchar()) != EOF)
{
if (c == '\n' || c == '\r') {
if (c == '\n')
putchar(255);
} else {
putchar(c);
fflush(stdout);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment