1

试图限制我的客户端-服务器 c 应用程序中的客户端连接数量。这就是我所拥有的,但是它不起作用。(甚至无法识别何时达到 max_connections。我该如何解决这个问题?

int main(int argc, char *argv[])
{
        //fill db
        if (obtainDb() == false) {
                printf("Database obtain error.\n");
                exit(true);
        }
        //initialise variables
        total_connections = 0;

        /* generate the socket */
        if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
                perror("socket");
                exit(true);
        }

        /* generate the end point */
        my_addr.sin_family = AF_INET;         // host byte order
        my_addr.sin_port = htons(MYPORT);     // short, network byte order
        my_addr.sin_addr.s_addr = INADDR_ANY; // auto-fill with my IP

        /* bind the socket to the end point */
        if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) \
        == -1) {
                perror("bind");
                exit(true);
        }

        /* start listnening */
        if (listen(sockfd, BACKLOG) == -1) {
                perror("listen");
                exit(true);
        }

        printf("server starts listnening ...\n");

        while(true){
                sin_size = sizeof(struct sockaddr_in);

                if (total_connections == max_connections) {
                        printf("Max Number of clients connected!\n");
                        while(total_connections == max_connections);
                }

                if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, \
                &sin_size)) == -1) {
                        perror("accept");
                        continue;
                }
                total_connections++;
                printf("server: got connection from %s\n", \
                        inet_ntoa(their_addr.sin_addr));

                userInput();

                while(waitpid(-1,NULL,WNOHANG)>0);

        }

        return false;

}

谢谢

编辑:用户输入():

void userInput(void) {
if (!fork()) { // this is the child process
    while(true){
        char buffer[MAXDATASIZE];
        char res[MAXDATASIZE];

        memset(buffer, '\0', MAXDATASIZE);
            memset(res, '\0', sizeof(res));

        if ((numbytes=recv(new_fd, buffer, sizeof(buffer), 0)) == -1) {
            perror("recv");
            exit(true);
        }
        if (numbytes == 0) {
            printf("client left");
            close(new_fd);
            total_connections--;
            exit(false);
        }
        buffer[numbytes] = '\0'; // add null terminator
        printf("Request: %s\n",buffer);
        search(buffer,res);
    }
    close(new_fd);  // parent doesn't need this
    exit(false);
}
close(new_fd);

}

4

2 回答 2

2

当您fork将所有变量复制到新进程时。这意味着孩子们拥有自己的total_connections.

而不是使用变量,您应该使用wait来找出是否有任何孩子已经退出。

于 2013-10-17T07:37:41.913 回答
1

分叉会为您的进程创建一个新实例,这也意味着每个变量都被复制到新进程中。您的初始total_connections值实际上永远不会超过 1。

C fork 处理全局变量

一个相对简单的选择是使用线程而不是进程来同时处理多个客户端。

于 2013-10-17T07:33:42.530 回答