0

我正在用 C 语言开发一个应用程序。我使用管道将数据从一个进程写入另一个进程。进程是远程的,process-1 每次都写入可变大小的数据。char buf[4]进程 1 写入长度为 4 的buf ( )。在进程 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

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

4

1 回答 1

2

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);
}       
于 2013-03-15T03:51:37.950 回答