-1

我正在尝试创建一个侦听套接字连接的进程。当我在 main() 函数中绑定、侦听和等待接受时,它似乎起作用了。但是,当我尝试创建一个新线程并在该新线程上绑定、侦听和接受时,它会失败。这是我的代码。

void request_handler(int clientSock) {
    FILE *requestedFile = NULL;
    long fileSize = 0;
    struct stat st;
    long bytesRead;
    char buffer[1024];

    requestedFile = fopen("/PATH/book.txt", "rb");

    while(!feof(requestedFile)) {
        bytesRead = fread(buffer, 1, sizeof(buffer), requestedFile);
        send(clientSock, buffer, bytesRead, 0);
    }

}

void listener() {
    int server_sock_desc;
    struct sockaddr_in name;

    int client_sock_desc;
    struct sockaddr_in client_name;
    socklen_t addr_size;

    pthread_t handler_thread;

    printf("waiting");

    //connection setup
    server_sock_desc = socket(PF_INET, SOCK_STREAM, 0);


    if(server_sock_desc != -1) {
        memset(&name, 0, sizeof(name));
        name.sin_family = AF_INET;
        name.sin_port = htons(5000);
        name.sin_addr.s_addr = htonl(INADDR_ANY);
        int bind_result = bind(server_sock_desc, (struct sockaddr *) &name, sizeof(name));
        if(bind_result == 0) {
            if(listen(server_sock_desc, BACKLOG) < 0) {
                perror("listen failed");
            }

            addr_size = sizeof(client_name);

            //Server Loop will continue to run listening for clients connecting to the server
            while(1) {

                //new client attempting to connect to the server

                client_sock_desc = accept(server_sock_desc, (struct sockaddr *) &client_name, &addr_size);
                if(client_sock_desc == -1) {
                    if(errno == EINTR) {
                        continue;
                    }
                    else {
                        perror("accept failed");
                        exit(1);
                    }
                }

                //connection starts here

                //create a thread for the new clients request to be handled
                if(pthread_create(&handler_thread, NULL, request_handler, client_sock_desc) != 0) {
                    perror("pthread_create failed");
                }
            }
        }
        else {
            perror("bind failed");
        }
    }
    else {
        perror("socket failed");
    }

}

int main(int argc, const char * argv[])
{
    pthread_t listenerThread;

    if(pthread_create(&listenerThread, NULL,listener, NULL) != 0) {
        perror("Listener thread create failed");
    }
}

奇怪的是,当我尝试通过调试器运行它时,有时 listener() 的一部分会执行,然后突然停止。

4

1 回答 1

5

您需要给线程一个运行的机会。main您的程序在创建线程后立即终止(通过从返回)!

如果您希望初始线程终止并让另一个线程继续运行,请调用pthread_exit而不是从main. 如果您希望该线程等到侦听线程终止,请调用pthread_join侦听线程。

你让初始线程跑出地图的边缘。有龙。

于 2013-05-04T19:05:11.547 回答