Linux 為多路復用 IO 提供了不少介面:select()、pselect()、poll(),分別承襲自 BSD 與 System V 兩大派系。select 的模型相當樸素——「輪詢」檢查 fd_set 的狀態,再採取對應措施。
訊號驅動則值得細究,一般步驟如下:
sigaction() 而非 signal(),因為可以順手設定 SA_RESTART:client 端讀取終端的系統呼叫可能被打斷,需要自動重啟。若堅持用 signal(),就得自行判斷 errno 是否為 EINTR 再重啟,但可攜性問題讓我強烈不建議這麼做。fcntl() 的 F_SETOWN 指定要接收訊號的進程。| 疊加,先 F_GETFL 保留原有狀態再 F_SETFL。另外,在 open() 時指定 O_ASYNC 是沒有實際效果的。sigaction() 完成安裝。On Linux, specifying the O_ASYNC flag when calling open() has no effect. To enable signal-driven I/O, we must instead set this flag using the fcntl() F_SETFL operation. ——《The Linux Programming Interface》4.3.1
下面是一個聊天程式的 demo,把這兩種技術都用上了:伺服器端採用多路復用取代多進程/多執行緒模型,客戶端採用訊號驅動。容易出問題的地方我都寫在註解裡。
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <signal.h>
void endServ(int sig)
{
printf("Server ended!\n");
exit(-1);
}
int main()
{
// 捕捉 CTRL+C
struct sigaction act;
sigemptyset(&act.sa_mask);
act.sa_handler = endServ;
act.sa_flags = 0;
sigaction(SIGINT, &act, 0);
printf("This server is started, enter CTRL+C to end. \n");
int servfd = socket(AF_INET, SOCK_STREAM, 0);
if (servfd == -1) {
printf("something wrong with socket():%m\n");
exit(-1);
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(9999);
inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
if (bind(servfd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
printf("Some thing wrong with bind():%m\n");
exit(-1);
}
printf("Bind success!\n");
listen(servfd, 20);
int numbers = 0; // 已接受的客戶端數量
fd_set fs;
FD_ZERO(&fs);
int client_fd[100];
int i;
for (i = 0; i < 100; ++i)
client_fd[i] = -1;
int maxfd = 0;
char buf[1024];
for (;;) {
maxfd = 0;
FD_ZERO(&fs);
FD_SET(servfd, &fs);
maxfd = maxfd > servfd ? maxfd : servfd;
for (i = 0; i < numbers; ++i) {
if (client_fd[i] != -1) {
FD_SET(client_fd[i], &fs);
maxfd = maxfd > client_fd[i] ? maxfd : client_fd[i];
}
}
int res = select(maxfd + 1, &fs, 0, 0, 0);
if (res == -1) {
printf("Something wrong with select():%m\n");
exit(-1);
}
if (FD_ISSET(servfd, &fs) && numbers < 100) {
printf("New client!\n");
client_fd[numbers] = accept(servfd, 0, 0);
numbers++;
}
for (i = 0; i < numbers; ++i) {
bzero(buf, sizeof(buf));
// 這個 -1 判斷是必要的,而且必須放在前面:
// 若有客戶端離線,下次迴圈不判斷就會出段錯誤
if (client_fd[i] != -1 && FD_ISSET(client_fd[i], &fs)) {
res = recv(client_fd[i], buf, sizeof(buf), 0);
if (res == 0) {
printf("A client quit\n");
close(client_fd[i]);
FD_CLR(client_fd[i], &fs);
client_fd[i] = -1;
} else if (res == -1) {
printf("Something wrong with net.\n");
exit(-1);
} else {
// 廣播給所有連線中的客戶端
int j;
for (j = 0; j < numbers; ++j) {
if (client_fd[j] != -1)
send(client_fd[j], buf, sizeof(buf), 0);
}
}
}
}
}
}
#include <signal.h>
#include <unistd.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
static int fd;
void show(int sig)
{
char buf[1024] = {0};
int n = read(fd, buf, sizeof(buf));
buf[n] = 0;
write(1, "MSG:", strlen("MSG:"));
write(1, buf, strlen(buf));
}
int main()
{
struct sigaction act;
sigemptyset(&act.sa_mask);
act.sa_handler = show;
// 這個是必要的,否則迴圈中的 read() 會被中斷
act.sa_flags = SA_RESTART;
sigaction(SIGIO, &act, 0);
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1) {
printf("Cannot get socketfd!:%m\n");
exit(-1);
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(9999);
inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) != -1)
printf("connect success!\n");
else
exit(-1);
// 疊加 O_ASYNC,保留原有 flag
int flag = fcntl(fd, F_GETFL);
flag |= O_ASYNC;
fcntl(fd, F_SETFL, flag);
fcntl(fd, F_SETOWN, getpid());
char buffer[1024] = {0};
for (;;) {
int n = read(0, buffer, sizeof(buffer));
if (n == -1)
break;
send(fd, buffer, n, 0);
}
write(1, "Closed.", strlen("Closed."));
}
SA_RESTART 不是可選項。少了它,訊號一來 read() 就回 -1,主迴圈會誤判為輸入結束而提前結束。F_SETFL 前一定要先 F_GETFL,直接覆寫會把原本的狀態清掉。