2

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))

9
  • Make sure some library call (used by error handling) doesn't override the errno. Try running the program under strace. Commented Jun 16, 2010 at 22:48
  • What does read() return? Does it work as you expect? What do you see when you do something like fprintf(stderr, "%s\n", strerror(errno));? Commented Jun 16, 2010 at 22:59
  • I'm fairly certain read() does not work on sockets, only files, but that would not affect the write. Can you show code which shows you handling the error? Commented Jun 16, 2010 at 22:59
  • read() should work on sockets, but it won't let you pass in flags or get the sender's address (for datagrams). Commented Jun 16, 2010 at 23:07
  • @vput3833 It says Bad File Descriptor. I guess that solves it. Although I have no idea what may have caused the errno to be zero. I'm running the server program on the same machine, and it uses pthreads. Can that somehow mess up the errno? Commented Jun 16, 2010 at 23:09

3 Answers 3

2
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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.