我正在用C语言开发一个应用程序,我使用管道将数据从一个进程写到另一个进程。进程是远程的,并且process-1每次写入可变大小的数据。process-1写入长度为4的buf (char buf[4])。在process-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 ()(如exepected所示)。但是之后,当我使用strlen()输出buffer的长度时,它给出的长度是1。
OUTPUT:
count:4 buf size: 1这里出了什么问题?我是不是在变量的数据类型上做错了?
发布于 2013-03-15 11:51:38
strlen返回c样式字符串的长度,即以null结尾的字符数组(它们的末尾只有一个空字节)。如果你正在发送/接收二进制数据,它将返回第一个'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);
} https://stackoverflow.com/questions/15424342
复制相似问题