#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>

#define SIZE sizeof(struct sockaddr_in)
#define BS 20

void catcher(int sig);
int newsockfd;

int main() {
	int sockfd;
	char c[BS];
	struct sockaddr_in server = {AF_INET, 8888, INADDR_ANY};
	static struct sigaction act;
	
	act.sa_handler = catcher;
	sigfillset(&act.sa_mask);
	sigaction(SIGPIPE, &act, NULL);
	
	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)	{
		perror("unable to create socket");
		exit(1);
	}
	
	if(bind(sockfd, (struct sockaddr *)&server, SIZE) == -1) {
		perror("unsuccessful bind");
		exit(1);
	}
	
	if(listen(sockfd, 5) == -1) {
		perror("unsuccessful listen");
		exit(1);
	}
	
	for(;;) {
		if((newsockfd = accept(sockfd, NULL, NULL)) == -1) {
			perror("could not accept");
			continue;
		}
		printf("connect\n");
		if(fork() == 0) {
			int i;
			while(recv(newsockfd, c, BS, 0) > 0) {
				for(i=0;i<BS;i++)
					c[i] = toupper(c[i]);
				send(newsockfd, c, BS, 0);
			}
			close(newsockfd);
			exit(0);
		}
		close(newsockfd);	
	}
}

void catcher(int sig) {
	close(newsockfd);
	exit(0);
}
