在研究CSAPP中的家庭作业(job)问题8.25时,我提到了它的解决方案,在https://dreamanddead.github.io/CSAPP-3e-Solutions/.提供的解决方案包括以下C代码:
#include <stdio.h>
#include "csapp.h"
sigjmp_buf buf;
void handler(int sig) {
/* jump */
siglongjmp(buf, 1);
}
char* tfgets(char* s, int size, FILE* stream) {
char* result;
if (!sigsetjmp(buf, 1)) {
alarm(5);
if (signal(SIGALRM, handler) == SIG_ERR)
unix_error("set alarm handler error");
return fgets(s, size, stream);
} else {
/* run out of time */
return NULL;
}
}
tfgets
功能是具有超时功能的fgets
.然而,使用siglong jmp跳出IO操作的安全性引起了人们的关注.
使用sigLongjMP中断IO操作并突然退出是否安全?
我找不到任何关于堆栈溢出的文档或相关问题.