c - pthread_join 不影响主线程

标签 c sockets pthreads pthread-join

我找到了这个 Sockets 教程 http://www.binarytides.com/socket-programming-c-linux-tutorial/我在最后一个例子中遇到了麻烦。它是一个使用套接字和 pthreads 的线程服务器。

代码编译正常,但没有按预期工作。我怀疑 pthread_join 调用是罪魁祸首,但我不确定。

我已经尝试在 Cygwin(32 位)和 Alpine Linux(32 位)上使用 GCC 4.8.3 和 4.8.2 编译和运行服务器和客户端。两种环境中的问题都是一样的。

我已经在 http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_join.html 阅读了 pthreads pthread_join 文档但我似乎找不到在服务器代码中调用 pthread_join 有什么问题。

更新了服务器、客户端和输出。

服务器代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>

void *connection_handler(void *);

int main(int argc, char *argv[])
{
    int socket_desc, new_socket, c;
    struct sockaddr_in server, client;
    char *message;

    // Create socket
    socket_desc = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_desc == -1)
    {
        printf("Could not create socket");
    }

    // Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(2000);

    // Bind
    if (bind(socket_desc, (struct sockaddr *) &server, sizeof(server)) < 0)
    {
        puts("bind failed");
        return 1;
    }
    puts("bind done");

    // Listen
    listen(socket_desc, 3);

    // Accept and incoming connection
    puts("Waiting for incoming connections...");
    c = sizeof(struct sockaddr_in);

    while ((new_socket = accept(socket_desc, (struct sockaddr *) &client, (socklen_t*)&c)) )
    {
        puts("Connection accepted");

        // Reply to the client
        message = "Hello Client, I have received your connection. And now I will assign a handler for you\n";
        write(new_socket, message, strlen(message));

        pthread_t sniffer_thread;

        if (pthread_create(&sniffer_thread, NULL, connection_handler, (void*) new_socket) < 0)
        {
            perror("could not create thread");
            return 1;
        }

        // Now join the thread , so that we don't terminate before the thread
        // pthread_join(sniffer_thread, NULL);
        puts("Handler assigned");
    }

    if (new_socket < 0)
    {
        perror("accept failed");
        return 1;
    }
    return 0;
}

/*
 * This will handle connection for each client
 * */
void *connection_handler(void *socket_desc)
{
    // Get socket descriptor
    int sock = (int)socket_desc;
    int read_size;
    char *message, client_message[2000]; 

    // Send some messages to the client
    message = "Greetings! I am your connection handler\n";
    write(sock, message, strlen(message) + 1);

    message = "Now type something and i shall repeat what you type\n";
    write(sock, message, strlen(message) + 1);

    // Receive a message from client
    read_size = recv(sock, client_message, 1999, 0); 

    if (read_size > 0) 
    {
        client_message[read_size] = 0; 
    }
    else
    {
        puts("recv failed");
    }

    //while(read_size > 0 )
    //{
        // Send the message back to client
        write(sock, client_message, strlen(client_message) + 1);
    //}

    if (read_size == 0)
    {
        puts("Client disconnected");
        fflush(stdout);
    }
    else if (read_size == -1)
    {
        perror("recv failed");
    }

    close(sock);

    return 0;
}

客户端代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>

int main(int arc, char *argv[])
{
    int socket_desc;
    struct sockaddr_in server;
    char *message, server_reply[2000];

    // Create socket
    socket_desc = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_desc == -1)
    {
        printf("Could not create socket");
    }

    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    server.sin_family = AF_INET;
    server.sin_port = htons(2000);

    // Connect to remote server
    if (connect(socket_desc, (struct sockaddr *) &server, sizeof(server)) < 0)
    {
        puts("connect error");
        return 1;
    }

    puts("Connected\n");

    // Send some data
    message = "Hello server!";
    if (send(socket_desc, message, strlen(message), 0) < 0)
    {
        puts("Send failed");
        return 1;
    }
    puts("Data Send\n");

    int length = 0;
    do {
        // Receive a reply from the server
        length = recv(socket_desc, server_reply, 1999, 0); 

        if (length > 0)
        {
            server_reply[length] = 0; 
        }
        else
        {
            puts("Nothing to recieve");
            close(socket_desc);
            return 1;
        }

        puts("Reply received\n");
        puts(server_reply);

    } while (length > 0);

    return 0;
}

服务器输出:

bind done
Waiting for incoming connections...
Connection accepted
Test 1
Segmentation fault (core dumped)

客户端输出:

Connected
Data Send
Reply received
Hello Client , I have received your connection. And now I will assign a handler for you
recv failed

看起来主线程在 sniffer_thread 之前返回/完成。

欢迎提供任何帮助。

最佳答案

您遇到未定义的行为,因为您对未以“\0”结尾的字符串调用 strlenrecv 不会在字符串末尾放置空终止符。

char *message , client_message[2000];
//...
//Receive a message from client
while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
{
//Send the message back to client
write(sock , client_message , strlen(client_message));
                                     ^^^^^^^^^^^^^^
                                     not null terminated

您应该使用 recv 的返回值来检查读取数据的大小。

关于c - pthread_join 不影响主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26126755/

相关文章:

c - C语言中如何将带有终止符的字符串复制到另一个字符串中?

c - 移位运算

c - 找到未对齐结构的正确尺寸

python - 如何为 Tornado IOStream 设置超时?

c - 如何修复这个简单的加密程序中的段错误?

c++ - UDP在不同线程中发送和接收

c - 如何在多线程矩阵乘法中使用线程池和消息队列?

c - pthread_join 总是导致 SIGSEGV

C 将共享变量传递给 pthread

Android Node.js Socket.io 未连接