【问题标题】:C Web Server Segmentation FaultC Web 服务器分段故障
【发布时间】: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) 或等效项。而是。

标签: c http web webserver


【解决方案1】:

您正在写超过string 的结尾。 string 中只有 4096 个字符,但是当您的循环在循环中不断调用 strcat() 时,它会尝试将整个文件读入其中。

不要将整个文件连接成一个变量然后全部写入,而是使用fread() 分块读取文件并立即将它们写入套接字。无需逐行阅读。

size_t in;
while ((in = fread(file, 1, sizeof file, fp) > 0) {
    int n = write(sock, file, in);
    if (n < in) {
        error("ERROR writing to socket");
    }
}
close(sock);
fclose(fp);

【讨论】:

  • 我现在在尝试加载 .html 时得到一个空白页
  • 对于完整的错误检查 ferror() 应该在 while-loop 之后立即调用。
  • @tyler7410 您是否尝试过在调试器下运行服务器以查看它在做什么?我认为这段代码很简单,应该可以工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-24
  • 2011-07-16
  • 1970-01-01
  • 1970-01-01
  • 2018-09-14
  • 1970-01-01
相关资源
最近更新 更多