编写一个名为 tfgets 的 fgets 函数版本
编写一个名为 tfgets
的 fgets
函数版本,该函数在 5 秒后超时。tfgets
函数接受与 fgets
相同的输入参数。如果用户在 5 秒内未输入一行内容,tfgets
将返回 NULL
。否则,它返回指向输入行的指针。
#include "csapp.h"static sigjmp_buf env;static void handler(int sig)
{Alarm(0);siglongjmp(env, 1);
}char *tfgets(char *s, int size, FILE *stream)
{Signal(SIGALRM, handler);Alarm(5);if (sigsetjmp(env, 1) == 0)return Fgets(s, size, stream); /* return user input */elsereturn NULL; /* return NULL if fgets times out */
}
int main()
{char buf[MAXLINE];while (1) {bzero(buf, MAXLINE);if (tfgets(buf, sizeof(buf), stdin) != NULL)printf("read: %s", buf);elseprintf("timed out\n");}exit(0);
}