《TCP/IP Sockets 编程》笔记6
时间:2010-09-13 来源:龍蝦
第6章 超越基本的套接字编程
6.1 Socket Options
The functions getsockopt() and setsockopt() allow socket option values to be queried and set, respectively.
int getsockopt(int socket, int level, int optName, void* optVal, socklen_t* optLen)
intsetsockopt(int socket, int level, int optName, const void* optVal, socklen_t optLen)
The second parameter indicates the level of the option in question.
The option itself is specified by the integer optName, which is always specified using a system-defined constant.
The parameter optVal is a pointer to a buffer.
optLen specifies the length of the buffer.
Note that value passed to setsockopt() is not guaranteed to be the new size of the socket buffer, even if the call apparently succeeds. Rather, it is best thought of as a “hint” to the system about the value desired by the user; the system, after all, has to manage resources for all users and may consider other factors in adjusting buffer size.
6.2 Signals
Signals provide a mechanism for notifying programs that certain events have occurred.
Any program that sends on a TCP socket must explicitly deal with SIGPIPE in order to be robust.
在TCP套接字上发送数据的任何程序都必须显示处理SIGPIPE以便保证健壮性。
An application program can change the default behavior for a particular signal using sigaction():
int sigaction (int whichSignal, const struct sigaction* newAction, struct sigaction* oldAction)
return 0 on success and -1 on failure.whichSignal specifies the signal for which the behavior is being changed. The newAction parameter points to a structure that defines the new behavior for the given signal type; if the pointer oldAction is non-null, a structure describing the previous behavior for the given signal is copied into it, sigaction as shown here:
struct sigaction {
void (*sa_handler)(int); // Signal handler
sigset_t sa_mask; // Signals to be blocked during handler execution
int sa_flags; // Flags to modify default behavior
};
sa_mask is implemented as a set of boolean flags, one for each type of signal. This set of flags can be manipulated with the following four functions:
int sigemptyset(sigset_t* set)
int sigfillset(sigset_t* set)
int sigaddset(sigset_t* set, int whichSignal)
int sigdelset(sigset_t* set, int whichSignal)
It is important to realize that signals are not queued—a signal is either pending or it is not. If the same signal is delivered more than once while it is being handled, the handler is only executed once more after it completes the original execution.
重要的一点是认识到信号是不会被排队的,信号要么挂起(pending),要么不是。如果在处理信号时,相同的信号被递送多次,那么处理程序完成原始执行之后它只会再执行一次。