【发布时间】:2019-03-10 05:08:12
【问题描述】:
我无法理解为什么我的自制 Web 服务器出现分段错误。我正在尝试正确标记 .html 和 .txt 文档的内容类型。当我的服务器运行时,我可以在我的网络浏览器中打开一个 .html 文件。但是,当我尝试打开 .txt 文档时,我的服务器因分段错误而关闭。下面的代码是我遇到问题的地方。
void* thread_runner(void* sockfd)
{
char buffer[256];
int n;
int sock = *(int*)sockfd;
bzero(buffer,256);
char filename[256];
bzero(filename,256);
n = read(sock,filename,255);
if (n < 0) error("ERROR reading from socket");
FILE *fp;
char file[4096];
char* word = strtok(filename, " ");
word = strtok(NULL, " ");
word++;
printf("filename = \"%s\"\n", word);
fp = fopen(word, "r");
if (fp == NULL) {
printf("file pointer is NULL\n");
return 0;
}
char string[4096];
char* extension;
bzero(string, 4096);
bzero(file, 4096);
char* word2;
word2 = strtok(word, ".");
while ((word2 = strtok(NULL, ".")) != NULL)
{
extension = word2;
}
printf("File Extension: %s\n", extension);
if (strncmp(extension, "html", 4096) == 0) {
printf("HTML FILE FOUND\n");
strcat(string, "HTTP/1.1 200 OK\nContent-Type: text/html\nContent-Length: 4096 \nConnection: keep-alive\n\n");
}
else if (strncmp(extension, "txt", 4096) == 0) {
printf("TXT FILE FOUND\n");
strcat(string, "HTTP/1.1 200 OK\nContent-Type: text/plain\nContent-Length: 4096\nConnection: keep-alive\n\n");
}
错误发生在这个循环中。 我在“字符串”上使用了 bzero。
while (fgets(file, 4096, fp))
{
strcat(string, file);
}
//printf("Sending text:%s", string);
printf("The requested file was: %s.%s\n",word,extension);
n = write(sock,string,4096);
printf("file contents are %s\n", string);
fclose(fp);
if (n < 0) error("ERROR writing to socket");
if (n == 0)
{
close(sock);
}
【问题讨论】:
-
你有没有逐行调试看看发生了什么?你的文件在4k以下吗?为什么数据少了你总是发4k?
-
word++是干什么用的?这会跳过文件名的第一个字符。 -
1) 您已经多次使用“strcat()”。如果溢出 4096 会怎样?你在哪里检查以确保不会发生这种情况? 2)像
char string[4096];和bzero(string, 4096);这样的“幻数”是“坏的”。考虑改用#define MAXLEN 4096、const int MAXLEN = 4096;、sizeof (string)或等效项。而是。