In ubuntu 12.04, I want to write a concurrent server, which can receive http packets from my virtual machine, then forward the packets to the original destination of my VM. But when I’m reading the packets using read function in C language, sometimes the return value and the length of buffer are not the same (for example: rbyte=1024, strlen(buf)=62 ). I’ve checked errno and find that errno=0, which means no error with the read function. I think that these two variables should be exactly the same, but for my program, they are not. The following is part of my code:
char buf[1024];
size_t rbyte = read(sFrom, buf, sizeof(buf) );
cerr << "length of buf: " << strlen(buf) << "\n";
cerr << "rbyte: " << rbyte << "\n";
I’ve read http://pubs.opengroup.org/onlinepubs/009695399/functions/read.html to get some clues, but still don’t know the reason of this error.
Does anyone know the reason?
As the linked documentation states,
readreads bytes, not strings, so if the input conatins a zero byte, you will get a string that is less than the number of bytes read (remember, C uses null-terminted strings), which means the first null character determines the end — and thus the length — of the string)