天天看點

家庭作業

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