求教,C语言问题,制作一个功能追加的getchar相关的函数mydetchar。信号与时间相关的 getchar能从键盘读取一个文字的输入,现在要制作一个timeout功能追加相关的函数mygetchar。1.timeout的时间,由mygetchar的参数指定。2.返回值是在指定的时间内由键盘输的值,如果是EOF的话就是-1,指定时间内键盘输入没有的话,就发起timeout这是是

题目
求教,C语言问题,制作一个功能追加的getchar相关的函数mydetchar。信号与时间相关的

getchar能从键盘读取一个文字的输入,现在要制作一个timeout功能追加相关的函数mygetchar。1.timeout的时间,由mygetchar的参数指定。

2.返回值是在指定的时间内由键盘输的值,如果是EOF的话就是-1,指定时间内键盘输入没有的话,就发起timeout这是是-2,前两种情况以外的是-3。

3.使用后,不需要的signal的设定就取消,返回原有的设定。

满足以上条件,返回值还有现时间把TIME(3)获得的值变换成CTIME(3)的文字列进行表示。 这个程序不需要重入。

   本人C学得不好,希望给出讲解,运行后的现象,越细越好。

   我的邮箱:1054180441@qq.com

参考答案和解析

#include <stdio.h>#include <unistd.h>#include <errno.h>#include <signal.h>#include <sys/time.h>#include <string.h>void handler(int sig){ if (sig != SIGALRM) { printf("Invalid signal %d\n", sig); }}int mygetchar(int wait){ char ch; int size, ret, clear; struct sigaction act, old; struct itimerval timer; if (wait <= 0) return -3; act.sa_handler = handler; sigemptyset(&act.sa_mask); act.sa_flags = 0; sigaction(SIGALRM, &act, &old); /* set timer */ memset(&timer, 0, sizeof(timer)); timer.it_value.tv_sec = wait; setitimer(ITIMER_REAL, &timer, NULL); size = read(STDIN_FILENO, &ch, sizeof(ch)); clear = 1; /* assume we should disable timer after reading */ if (size == 0) /* eof */ { ret = -1; } else if (size == -1 && errno == EINTR) /* timeout */ { ret = -2; clear = 0; } else if (size < 0) /* other errors */ { ret = -3; } else { ret = ch; } if (clear) { /* disable the running timer */ timer.it_value.tv_sec = 0; setitimer(ITIMER_REAL, &timer, NULL); } sigaction(SIGALRM, &old, NULL); /* restore sig action */ return ret;} int main(){ int ch; time_t t; printf("input a char in 3 seconds\n"); ch = mygetchar(3); t = time(NULL); if (ch < 0) printf("mygetchar returns %d, at %s\n", ch, ctime(&t)); else printf("get char '%c', at %s\n", ch, ctime(&t)); return 0;}

 

更多“求教,C语言问题,制作一个功能追加的getchar相关的函数mydetchar。信号与时间相关的 getchar能从键盘读取一个文字的输入,现在要制作一个timeout功能追加相关的函数mygetchar。1.timeout的时间,由mygetchar的参数指定。2.返回值是在指定的时间内由键盘输的值,如果是EOF的话就是-1,指定时间内键盘输入没有的话,就发起timeout这是是”相关问题