おそらく、イベントの処理にpoll
(またはselect
)を使用することをお勧めします。したがって、接続を確立した後、ファイル記述子があり、さらに、OSからのファイル記述子(つまり0)もある標準入力があり、それらすべてのファイル記述子をに渡すことができます。これにより、ファイル記述子poll
が通知されます。いずれかのファイル記述子の受信データです。コード例:
/* fd1, fd2 are sockets */
while(1) {
pollfd fds[3];
int ret;
fds[0].fd = fd1;
fds[1].fd = fd2;
fds[2].fd = STDIN_FILENO;
fds[0].events = POLLIN;
fds[1].events = POLLIN;
fds[2].events = POLLIN;
ret = poll(fds, 3, -1); /* poll() blocks, but you can set a timeout here */
if(ret < 0) {
perror("poll");
}
else if(ret == 0) {
printf("timeout\n");
}
else {
if(fds[0].revents & POLLIN) {
/* incoming data from fd1 */
}
if(fds[0].revents & (POLLERR | POLLNVAL)) {
/* error on fd1 */
}
if(fds[1].revents & POLLIN) {
/* incoming data from fd2 */
}
if(fds[1].revents & (POLLERR | POLLNVAL)) {
/* error on fd2 */
}
if(fds[2].revents & POLLIN) {
/* incoming data from stdin */
char buf[1024];
int bytes_read = read(STDIN_FILENO, buf, 1024);
/* handle input, which is stored in buf */
}
}
}
あなたはOSについて言及しませんでした。これはPOSIX(OS X、Linux、Windows with mingw)で機能します。Win32 APIを使用する必要がある場合、外観は少し異なりますが、原則は同じです。