Copy int s1, s2;
int rv;
char buf1[256], buf2[256];
struct pollfd ufds[2];
s1 = socket(PF_INET, SOCK_STREAM, 0);
s2 = socket(PF_INET, SOCK_STREAM, 0);
// 假設此時我們已經都連線到 server 了
//connect(s1, ...)...
//connect(s2, ...)...
// 設定 file descriptors 陣列
//
// 在此例中,我們想要知道何時有就緒的一般資料或 out-of-band(頻外)資料要收
//
ufds[0].fd = s1;
ufds[0].events = POLLIN | POLLPRI; // 要檢查是一般資料或 out-of-band 資料
ufds[1] = s2;
ufds[1].events = POLLIN; // 只檢查一般的資料
// 等待 sockets 上的事件,timeout 時間是 3.5 秒
rv = poll(ufds, 2, 3500);
if (rv == -1) {
perror("poll"); // poll() 時發生錯誤
} else if (rv == 0) {
printf("Timeout occurred! No data after 3.5 seconds.\n");
} else {
// 檢查 s1 上的事件:
if (ufds[0].revents & POLLIN) {
recv(s1, buf1, sizeof buf1, 0); // 接收一般的資料
}
if (ufds[0].revents & POLLPRI) {
recv(s1, buf1, sizeof buf1, MSG_OOB); // out-of-band 資料
}
// 檢查 s2 上的事件:
if (ufds[1].revents & POLLIN) {
recv(s2, buf2, sizeof buf2, 0);
}
}