Created
July 30, 2014 12:51
-
-
Save kouba-c/b68f39f74b102f7c436a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <errno.h> | |
#include <aio.h> | |
static void | |
read_done(union sigval sigval) | |
{ | |
struct aiocb *cb; | |
int n; | |
cb = (struct aiocb*)sigval.sival_ptr; | |
printf("CB\n"); | |
if (aio_error(cb) == 0) { | |
n = aio_return(cb); | |
if (n == 0) { /* EOF */ | |
printf("client %d gone\n", cb->aio_fildes); | |
aio_cancel(cb->aio_fildes, cb); | |
close(cb->aio_fildes); | |
free(cb); | |
return; | |
} | |
printf("client %d (%d)\n", cb->aio_fildes, n); | |
write(cb->aio_fildes, (void*)cb->aio_buf, n); | |
aio_read(cb); | |
} | |
else { | |
perror("aio_return"); | |
return; | |
} | |
return; | |
} | |
static void | |
register_read(int fd) | |
{ | |
struct aiocb *cb; | |
char *buf; | |
int ret; | |
printf("client %d registerd\n", fd); | |
cb = malloc(sizeof(struct aiocb)); | |
buf = malloc(BUFSIZ); | |
memset(cb, 0, sizeof(struct aiocb)); | |
cb->aio_offset = 0; | |
cb->aio_reqprio = 0; | |
cb->aio_fildes = fd; | |
cb->aio_buf = buf; | |
cb->aio_nbytes = BUFSIZ; | |
cb->aio_sigevent.sigev_notify = SIGEV_THREAD; | |
cb->aio_sigevent.sigev_notify_function = read_done; | |
cb->aio_sigevent.sigev_value.sival_ptr = cb; | |
if(aio_read(cb) != 0) { | |
printf( "aio_read : %d : %s\n", errno, strerror( errno ) ); | |
} | |
} | |
int | |
main() | |
{ | |
struct sockaddr_in addr; | |
int s = socket(PF_INET, SOCK_STREAM, 0); | |
addr.sin_family = AF_INET; | |
addr.sin_addr.s_addr = INADDR_ANY; | |
addr.sin_port = htons(9989); | |
if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) < 0) { | |
perror("bind"); | |
exit(1); | |
} | |
listen(s, 5); | |
for (;;) { | |
int c = accept(s, NULL, 0); | |
if (c < 0) continue; | |
register_read(c); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
async_io(スレッド)を使ったエコーサーバ
まつもとゆきひろ コードの未来より引用