The value you have passed as the file descriptor is not valid. It is either negative or does not represent a currently open file or socket.
So you have either closed the socket before calling write()
or you have corrupted the value of 'sockfd' somewhere in your code.
It would be useful to trace all calls to close()
, and the value of 'sockfd' prior to the write()
calls.
Your technique of only printing error messages in debug mode seems to me complete madness, and in any case calling another function between a system call and perror()
is invalid, as it may disturb the value of errno
. Indeed it may have done so in this case, and the real underlying error may be different.