用叉子和DUP简单的HTTP通用服务器 [英] Simple http generic server using fork and dup

查看:196
本文介绍了用叉子和DUP简单的HTTP通用服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个非常基本的HTTP服务器。我想单独服务器,并在两个独立的可执行文件服务(类似inetd的)。

I'm trying to write a very basic HTTP server. I want to separate the server and the service in two separate executable (similar to inetd).

所以我有一个通用的服务器,那叉子服务,并使用EXEC执行其code。主循环如下:

So I have a generic server, that forks a service and execute its code using exec. The main loop is as follows:

while(true) {
    int client_sock;

    if ((client_sock = accept(server_sock, (struct sockaddr *) NULL, NULL)) < 0) {
        return -1;
    } 

    pid_t pid = fork();

    if (pid == 0) {
        close(server_sock);
        close(0);
        dup(client_sock);
        close(1);
        dup(client_sock);
        execvp(argv[2], argv+2);
        return -1;
    } else if (pid < 0) {
       assert(false);
    }
    close(client_sock);
}

此服务在标准输入读取,并在标准输出上写入和处理简单的HTTP请求。一切似乎当我使用NC连接到我的服务器,以做工精细。 NC接收并显示预期的HTTP回复。

The service reads on stdin, and writes on stdout and processes simple http requests. Everything seems to work fine when I connect to my server using nc. nc receives and displays the expected http reply.

但是,当我连接到使用Web浏览我的服务器,浏览器告诉我,服务器关闭连接突然(ECONNRESET错误,我相信)。我敢肯定,我的服务处理请求:我检查我的服务与strace的执行,所有预期的写(1,...)在那里,而且没有任何关闭(1)。甚至更令人惊讶的,有时,网络浏览器得到的答复。

However, when I connect to my server using a web browser, the browser tells me that the server closed the connection abruptly (ECONNRESET error I believe). I'm sure that my service processed the request: I checked the execution of my service with strace, all the expected "write(1,...)" are there, and there are not any close(1). Even more surprising, some times, the web browser gets the reply.

做任何事情看起来错在提供的code?如果不是,有什么可能导致问题?

Does anything look wrong in the provided code? if not, what could cause the problem?

推荐答案

我想问题不在于code你有显示,但在节目中你EXEC。一个典型的问题是,客户端(即程序)不读取HTTP头,但实际上只是写入数据和完成。在这种情况下,文件描述符到浏览器被关闭,同时还存在着从在插座缓冲器服务器未处理的数据。这会导致服务器操作系统发送RST包然后使在浏览器中ECONNRESET。如果你是幸运的得到了浏览器和呈现响应之前就拿到了RST,所以你有时会,有时不到连接复位错误。

I guess the problems lies not in the code you have shown, but in the program you exec. A typical problem is that the client (i.e. your program) does not read the HTTP header but instead just writes the data and finishes. In this case the file descriptor to the browser gets closed while there are still unprocessed data from the server in the socket buffer. This causes the server OS to send a RST packet which then causes the ECONNRESET in the browser. If you are lucky the browser got and rendered the response before it got the RST, so you will see the connection reset error sometimes and sometimes not.

这篇关于用叉子和DUP简单的HTTP通用服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆