Echo server: Difference between revisions

m
→‎{{header|C}}: Make a bit easier to read
(C)
m (→‎{{header|C}}: Make a bit easier to read)
Line 28:
void wait_for_zombie(int s)
{
while(waitpid(-1, NULL, WNOHANG) > 0) ;
}
 
int main()
{
struct addrinfo hints, *res;
struct sockaddr addr;
struct sigaction sa;
socklen_t addr_size;
int sock;
 
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
 
if ( getaddrinfo(NULL, PORT_STR, &hints, &res) != 0 ) {
perror("getaddrinfo");
exit(EXIT_FAILURE);
}
 
if ( (sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1 ) {
perror("socket");
exit(EXIT_FAILURE);
}
 
sa.sa_handler = wait_for_zombie;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if ( sigaction(SIGCHLD, &sa, NULL) == - 1 ) {
perror("sigaction");
exit(EXIT_FAILURE);
}
 
if ( bind(sock, res->ai_addr, res->ai_addrlen) == 0 ) {
freeaddrinfo(res);
if ( listen(sock, MAX_ENQUEUED) == 0 ) {
 
/* Serve the listening socket infinitely often */
for(;;) {
addr_size = sizeof(addr);
int csock = accept(sock, &addr, &addr_size);
if ( csock == -1 ) {
perror("accept");
} else {
if ( fork() == 0 ) {
close(sock);
 
/* Echo loop */
if ( (sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1 ) {
char buf[BUF_LEN];
perror("socket");
int r;
exit(EXIT_FAILURE);
while( (r = read(csock, buf, BUF_LEN)) > 0 ) {
}
(void)write(csock, buf, r);
}
sa.sa_handler = wait_for_zombie;
exit(EXIT_SUCCESS);
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if ( sigaction(SIGCHLD, &sa, NULL) == - 1 ) {
perror("sigaction");
exit(EXIT_FAILURE);
}
 
}
if ( bind(sock, res->ai_addr, res->ai_addrlen) == 0 ) {
freeaddrinfo close(rescsock);
if ( listen(sock, MAX_ENQUEUED) == 0 ) { }
for(;;) { }
} else {
addr_size = sizeof(addr);
perror("bindlisten");
int csock = accept(sock, &addr, &addr_size);
exit(EXIT_FAILURE);
if ( csock == -1 ) {
}
perror("accept");
} else {
if ( fork() == 0 ) {
close(sock);
char buf[BUF_LEN];
int r;
while( (r = read(csock, buf, BUF_LEN)) > 0 ) {
(void)write(csock, buf, r);
}
exit(EXIT_SUCCESS);
}
close(csock);
}
}
} else {
perror("listenbind");
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
} else {
perror("bind");
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}</lang>
 
Anonymous user