void fork_server_routine()
{
int sock = socket(PF_INET, SOCK_STREAM, 0);
if (sock < 0) return;
struct sockaddr_in addr = {0};
addr.sin_family = PF_INET;
addr.sin_port = htons(9999);
int rc = 1;
rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &rc , sizeof(int));
if (rc < 0) {
perror("setsockopt");
return;
}
rc = bind(sock, (struct sockaddr *)&addr, sizeof(addr));
if (rc < 0) {
perror("bind");
return;
}
rc = listen(sock, 32);
if (rc < 0) return;
int ep = epoll_create(1);
struct epoll_event events[32];
events[0].data.fd = sock;
events[0].events = EPOLLIN | EPOLLET;
rc = epoll_ctl(ep, EPOLL_CTL_ADD, sock, &events[0]);
if (rc < 0) return;
rc = epoll_wait(ep, events, 32, -1);
if (rc < 0) return;
printf("epoll_wait: %d\n", rc);
socklen_t sal = sizeof(addr);
int client = accept(sock, (struct sockaddr *)&addr, &sal);
if (client < 0) return;
printf("accepted: %d\n", client);
events[0].data.fd = client;
events[0].events = EPOLLIN | EPOLLET;
rc = epoll_ctl(ep, EPOLL_CTL_ADD, client, &events[0]);
if (rc < 0) return;
rc = fork();
if (rc < 0) return;
if (rc == 0) {
printf("child start\n");
for (;;) {
sleep(3);
}
printf("child quit\n");
} else {
printf("parent start\n");
memset(events, 0, sizeof(events));
rc = epoll_wait(ep, events, 32, -1);
if (rc < 0) {
perror("parent: epoll_wait");
return;
}
printf("parent: epoll1 return %d, fd = %d\n", rc, events[0].data.fd);
memset(events, 0, sizeof(events));
printf("close %d\n", client);
epoll_ctl(ep, EPOLL_CTL_DEL, client, &events[0]);
close(client);
memset(events, 0, sizeof(events));
rc = epoll_wait(ep, events, 32, -1);
if (rc < 0) {
perror("parent: epoll_wait");
return;
}
printf("parent: epoll2 return %d, fd = %d\n", rc, events[0].data.fd);
}
}
void fork_client_routine()
{
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) return;
struct sockaddr_in addr = {0};
addr.sin_family = PF_INET;
addr.sin_port = htons(9999);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
int rc = connect(sock, (struct sockaddr *)&addr, sizeof(addr));
if (rc < 0) return;
for (;;) {
printf("connected, press any\n");
getchar();
send(sock, &addr, 1, 0);
}
}
int
main (int argc, char **argv)
{
if (argc < 2) {
printf("./t1 c or s\n");
return 0;
}
if ('c' == argv[1][0]) {
fork_client_routine();
} else if ('s' == argv[1][0]) {
fork_server_routine();
} else {
printf("./t1 c or s\n");
return 0;
}
return 0;
}