Skip to content

Instantly share code, notes, and snippets.

@cloudwu

cloudwu/period.c

Created May 20, 2021
Embed
What would you like to do?
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