Home > Net >  Why is "setsockopt()" needed if "fcntl()" also manipulates file descriptors?
Why is "setsockopt()" needed if "fcntl()" also manipulates file descriptors?

Time:01-01

When socket programming in C, I noticed that sometimes fcntl() is used to manipulate socket behavior while other times setsockopt() is used.

For example, fcntl() is used to make a socket non-blocking, but setsockopt() is used to change the timeout time when sending/receiving data from a socket.

Is there any background / intuitive reasoning as to why both functions are needed?

CodePudding user response:

Sockets are not the only type of file descriptor which you can make non-blocking. In theory, you can mark any file descriptor as non-blocking (by specifying O_NONBLOCK when you open() the file) but it's possible that the setting will be ignored (for regular files or special files which don't implement nonblocking mode). So the non-blocking flag is part of the general file interface.

By contrast, the socket timeouts apply only to sockets. That's made clear by the fact that you can only set them using a socket-specific interface. (Terminal devices have two read timeout attributes -- VTIME and VMIN -- which are vaguely related, but with very different semantics. Those are set with the termios interface.)

There are very few generally-applicable attributes which can be manipulated with fcntl. There are lots of attributes which are specific to certain types of files, and which are manipulated using a variety of specific interfaces.

  • Related