【问题标题】:Why does the size of buf changed to 1 from 4为什么buf的大小从4变成了1
【发布时间】:2013-03-03 16:35:52
【问题描述】:

我正在用 C 语言开发一个应用程序。我使用管道将数据从一个进程写入另一个进程。 进程是远程的,process-1 每次都写入可变大小的数据。 进程 1 写入长度为 4 的 buf (char buf[4])。在进程 2 中,我读取了该数据。确定大小的敌人我使用了 ioctl() 函数调用。

while(read(to_child[0], &byte, 1) == 1)               // Read first byte as ioctl is not
        {                                             //blocking and then allocate the                                        
                fprintf(fp,"\n Inside teh if block"); // buffer size = count+1;                                       
                ioctl(to_child[0], FIONREAD, &count);                                        
                buf = malloc(count+1);                // count is 3 here                                       
                buf[0] = byte;                                                               
                read(to_child[0], buf+1, count);      // total length read is 4.                                       
        }                                          
  printf("count :%d, buf size: %d", count+1, strlen(buf));

Ioctl() 函数在 process-2() 处将 4 个字节读入另一个 buf(如预期的那样)。但在此之后,当我使用 strlen() 打印缓冲区的长度时,它给出的长度为 1。

OUTPUT:
count:4 buf size: 1

这里出了什么问题?我对变量的数据类型做错了吗?

【问题讨论】:

    标签: c types ipc


    【解决方案1】:

    strlen 返回 c 风格字符串的长度,即一个以空字符结尾的字符数组(它们最后只有一个空字节)。如果您正在发送/接收二进制数据,它将返回第一个“0”字节的位置。如果您已经知道不需要查询的二进制数据的大小,也许您需要一个包含数据和长度字段的结构。

    在您的情况下,您只需执行read(to_child[0], buf, 4) == 4 即可确保每次读取接收 4 个字节。一个毫无意义的例子:

    typedef struct { char data[4]; int cnt; }  Buffer;
    Buffer buf;
    while( (buf.cnt = read(to_child[0], buf.data, 4)) == 4) {
      fprintf(fp,"\n Inside teh if block");
        printf("buf size: %d", buf.cnt);
    }       
    

    【讨论】:

    • 感谢您的回答。对于二进制数据,我将如何获得缓冲区的总长度?
    • 您无法真正获得总长度。正如我上面解释的那样,您需要自己跟踪它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    相关资源
    最近更新 更多