2013-03-15 38 views
0

我正在用C開發應用程序。我使用管道將數據從一個進程寫入另一個進程。 進程是遠程進程,進程1每次都寫入可變大小的數據。 進程1寫入長度爲4的buf(char buf[4])。在進程2中,我讀取了這些數據。確定我使用ioctl()函數調用的大小的敵人。爲什麼buf的大小從4更改爲1

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()函數在進程2()(正如所期望的)處讀取4個字節到另一個buf中。但在此之後,當我打印緩衝區的長度使用strlen的(),它給人的長度爲1

OUTPUT: 
count:4 buf size: 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); 
}  
+0

感謝您的回答。對於二進制數據,我將如何獲得緩衝區的總長度? – 2013-03-15 03:54:11

+1

你不能真正得到總長度。正如我上面所解釋的,你需要自己跟蹤它。 – perreal 2013-03-15 03:55:31

相關問題