家庭作业

8.25

fgets的定义如下:

char *fgets(char *buf, int bufsize, FILE *stream);

参数:

*buf: 字符型指针,指向用来存储所得数据的地址。

bufsize: 整型数据,指明buf指向的字符数组的大小。

*stream: 文件结构体指针,将要读取的文件流。

#include <stdio.h>

#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#include <setjmp.h>

sigjmp_buf env;
void tfgets_handler(int sig)
{
    signal(SIGALRM, SIG_DFL);
    siglongjmp(env, 1);
}

char *tfgets(char *buf, int bufsize, FILE *stream)
{
    static const int TimeLimitSecs = 5;
    signal(SIGALRM, tfgets_handler)
    alarm(TimeLimitSecs);
    int rc = sigsetjmp(env, 1);
    if(rc == 0) return fgets(buf, bufsize, stream);
    else return NULL; //alarm,time out
}

posted @ 2015-11-24 22:38  武西垚  阅读(165)  评论(0编辑  收藏  举报