networking · beginner · ~15 min
Detect the socket() error sentinel.
The complement check: detect the socket() error sentinel, which is any negative fd.
Implement int socket_failed(int fd) that returns 1 if fd < 0 (the error case), otherwise 0.
One int fd — a value returned by socket().
Returns 1 if fd < 0, else 0.
socket_failed(-1) -> 1
socket_failed(4) -> 0
One integer fd returned by socket().
1 if fd < 0, else 0.
A negative fd is the error sentinel.
int socket_failed(int fd) {
/* TODO */
return 0;
}
Assuming read/write transmits all requested bytes at once; ignoring socket file descriptor cleanup; unhandled endianness conversions.
Short reads/writes; peer closing socket (recv returns 0); signal interruption (EINTR); non-blocking EAGAIN.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.