【问题标题】:i am trying this multi threaded code to understand. can anyone help me understand the "print message" part. i am posting the code herewith我正在尝试这个多线程代码来理解。谁能帮我理解“打印信息”部分。我在此发布代码
【发布时间】:2016-02-29 01:47:32
【问题描述】:

我正在尝试理解这个多线程代码。谁能帮我理解“打印信息”部分。我在这里发布代码

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    #include <sys/socket.h>
    #include <linux/in.h>
    #include <unistd.h>

    typedef struct
    {
        int sock;
        struct sockaddr address;
        int addr_len;
    } connection_t;

    void * process(void * ptr)
    {
        char * buffer;
        int len;
        connection_t * conn;
        long addr = 0;

        if (!ptr) pthread_exit(0); 
        conn = (connection_t *)ptr;


        read(conn->sock, &len, sizeof(int));
        if (len > 0)
        {
            addr = (long)((struct sockaddr_in *)&conn->address)->sin_addr.s_addr;
            buffer = (char *)malloc((len+1)*sizeof(char));
            buffer[len] = 0;

            read(conn->sock, buffer, len);

            /* print message */
            printf("%d.%d.%d.%d: %s\n",
                (int)((addr      ) & 0xff),
                (int)((addr >>  8) & 0xff),
                (int)((addr >> 16) & 0xff),
                (int)((addr >> 24) & 0xff),
                buffer);
            free(buffer);
        }


        close(conn->sock);
        free(conn);
        pthread_exit(0);
    }

    int main(int argc, char ** argv)
    {
        ...
        ...
        ...

      return 0;
        }

我知道我们正在尝试从缓冲区打印数据,但是所有这些移位运算符和'& 0xff' 部分有什么帮助? :

printf("%d.%d.%d.%d: %s\n",
                (int)((addr      ) & 0xff),
                (int)((addr >>  8) & 0xff),
                (int)((addr >> 16) & 0xff),
                (int)((addr >> 24) & 0xff),
                buffer);

我们不能像这样简单地使用 printf 语句吗:

printf("Here is the message: %s\n",buffer);

从缓冲区中读取??

【问题讨论】:

  • 没有“解释代码”的网站。就是这样:代码包含“有问题”的部分(例如实现定义的行为)并且写得不好。
  • 您的问题与多线程或套接字无关。

标签: c multithreading sockets


【解决方案1】:

他们将addr(预计长度为 32 位,但并非总是如此)拆分为每个八位字节。

printf("%d.%d.%d.%d: %s\n",
                (int)((addr      ) & 0xff), /* the least octet */
                (int)((addr >>  8) & 0xff), /* the second least octet */
                (int)((addr >> 16) & 0xff), /* the second most octet */
                (int)((addr >> 24) & 0xff), /* the most octet */
                buffer); /* what is received */

你可以使用

printf("Here is the message: %s\n",buffer);

如果您不想知道数据包的发送位置。

请注意,您应该使用calloc 而不是malloc 将缓冲区初始化为零或更改

read(conn->sock, buffer, len);

{
    ssize_t readlen = read(conn->sock, buffer, len);
    if (readlen < 0) readlen = 0;
    buffer[readlen] = '\0';
}

在将buffer 传递给printf() 之前。否则,您可能会调用 未定义的行为 来使用通过 malloc() 分配且未初始化的缓冲区。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-29
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 2014-12-26
    • 1970-01-01
    相关资源
    最近更新 更多