メモ:非ブロックリード端末と待機タイムアウト

1557 ワード

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

#define MSG_TRY "try again
" #define MSG_TIMEOUT "timeout
" int main(void) { char buf[10]; int fd, n, i; fd = open("/dev/tty", O_RDONLY|O_NONBLOCK); if(fd<0) { perror("open /dev/tty"); exit(1); } for(i=0; i<5; i++) { n = read(fd, buf, 10); if(n>=0) break; if(errno!=EAGAIN) { perror("read /dev/tty"); exit(1); } sleep(1); write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY)); } if(i==5) write(STDOUT_FILENO, MSG_TIMEOUT, strlen(MSG_TIMEOUT)); else write(STDOUT_FILENO, buf, n); close(fd); return 0; }

非ブロック方式で端末I/Oを開く第2の方式を実現する
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

#define MSG_TRY "try again
" int main(void) {     char buf[10];     int n;     int flags;     flags = fcntl(STDIN_FILENO, F_GETFL);     flags |= O_NONBLOCK;     if (fcntl(STDIN_FILENO, F_SETFL, flags) == -1)     {         perror("fcntl");         exit(1);     } tryagain:     n = read(STDIN_FILENO, buf, 10);     if (n < 0)     {         if (errno == EAGAIN)         {             sleep(1);             write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY));             goto tryagain;         }         perror("read stdin");         exit(1);     }     write(STDOUT_FILENO, buf, n);     return 0; }