c - non-buffering stdin reading -
my test application is
#include <sys/types.h> #include <sys/wait.h> #include <signal.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> int main(int argc, char *argv[], char *envp[]) { int fd[2]; if(pipe(fd) < 0) { printf("can\'t create pipe\n"); exit(-1); } pid_t fpid = fork(); if (fpid == 0) { close(0); close(fd[1]); char *s = (char *) malloc(sizeof(char)); while(1) if (read(fd[0], s, 1)) printf("%i\n", *s); } close(fd[0]); char *c = (char *) malloc(sizeof(char)); while (1) { if (read(0, c, 1) > 0) write(fd[1], c, 1); } return 0; }
i want see char-code after each entered char. in fact *s printed after '\n' in console. seems stdin (file desc 0) buffered. read function buffer-less, isn't it? wrong.
upd: use linux.
so solution is
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <termios.h> int main(int argc, char *argv[], char *envp[]) { int fd[2]; if(pipe(fd) < 0) { printf("can\'t create pipe\n"); exit(-1); } struct termios term, term_orig; if(tcgetattr(0, &term_orig)) { printf("tcgetattr failed\n"); exit(-1); } term = term_orig; term.c_lflag &= ~icanon; term.c_lflag |= echo; term.c_cc[vmin] = 0; term.c_cc[vtime] = 0; if (tcsetattr(0, tcsanow, &term)) { printf("tcsetattr failed\n"); exit(-1); } pid_t fpid = fork(); if (fpid == 0) { close(0); close(fd[1]); char *s = (char *) malloc(sizeof(char)); while(1) if (read(fd[0], s, 1)) printf("%i\n", *s); } close(fd[0]); char *c = (char *) malloc(sizeof(char)); while (1) { if (read(0, c, 1) > 0) write(fd[1], c, 1); } return 0; }
unfortunately, behavior you're looking not possible standard ansi c, , default mode unix terminal i/o line-oriented, means need inputted \n
character retrieve input. you'll need use terminal i/o facilities let program in non-canonical mode, each key-press triggers event. on linux/unix, can <termios.h>
header, or ncurses library.
Comments
Post a Comment