views:

85

answers:

3

I have a client server situation in which I receive data using

read(socket, char_buf, BUF_SIZE)

and then try to write it into a log file using

write(filefd, char_buf, strlen(char_buf))

Strangely enough this fails (write returns -1), and yet the errno is set to 0, and I can print the message, AND the log file descriptor works (I write to it before and after this command).

What's going on??

(Working on Linux kernel 2.4 (homework))

A: 

Did you check the status of your read()? It may have an error, that results in the length of char_buf to be zero.

BikeRacer
I print it right after reading it, so it cannot be 0.
EpsilonVector
A: 

Step through your code with a debugger and make sure that each statement is doing exactly what you think it should be doing. I bet you'll find an earlier bug.

Also, the return value for the read() is important. It tells you how many bytes were actually read. For a successful read, it could be anywhere between 1 and BUF_SIZE.

Karmastan
+1  A: 
int reads = read(socket, char_buf, BUF_SIZE);

if ( reads != BUF_SIZE )
{
    /* something might have gone wrong */
    fprintf( stderr, "%s\n", strerror( errno ));
}

int writes= = write( filedes, buffer, buffer_size );

if ( writes != buffer_size )
{
    /* something might have gone wrong */
    fprintf( stderr, "%s\n", strerror( errno ));
}

I'd do something like this always following a read or write or such calls.

vpit3833