#include #include #include #include #include #include #include #include #include #include #include #define PORT 845 #define MAX_CONN 5 int daemonize() { pid_t pid, sid; pid = fork(); if(pid < 0) exit(EXIT_FAILURE); if(pid > 0) { printf("\nDaemon started at pid: %d\n", pid); exit(EXIT_SUCCESS); } umask(0); sid = setsid(); if(sid < 0) { printf("Failed to set seesion id.\n"); exit(EXIT_FAILURE); } close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); return pid; } void sigchild_handle(int i) { while(waitpid(-1, NULL, WNOHANG) > 0); } int main(int argc, char **argv) { int sockfd, sessfd, retval; int i, val = 1; struct sockaddr_in serv_addr, conn_addr; socklen_t sin_size; struct sigaction sa; char send_buf[256], recv_buf[256]; retval = daemonize(); if(retval) { /* This should never happen, but... */ printf("Daemonize failed: %d\n", retval); exit(EXIT_FAILURE); } if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) exit(EXIT_FAILURE); if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,&val, sizeof(int)) == -1) exit(EXIT_FAILURE); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); serv_addr.sin_addr.s_addr = INADDR_ANY; memset(&(serv_addr.sin_zero), '\0', 8); if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) == -1) exit(EXIT_FAILURE); if (listen(sockfd, MAX_CONN) == -1) exit(EXIT_FAILURE); sa.sa_handler = sigchild_handle; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sa, NULL) == -1) exit(EXIT_FAILURE); /* Phew. Now we're set up! Let's do the BIG LOOP! */ while(1) { sin_size = sizeof(struct sockaddr_in); if((sessfd = accept(sockfd, (struct sockaddr *)&conn_addr, &sin_size)) == -1) exit(EXIT_FAILURE); if(!fork()) { close(sockfd); strcpy(send_buf, "Service Name: "); send(sessfd, send_buf, strlen(send_buf), 0); recv(sessfd, recv_buf, sizeof(recv_buf), 0); strcpy(send_buf, "The service you have requested does not exist on this server, error: "); strcat(send_buf, recv_buf); send(sessfd, send_buf, strlen(send_buf), 0); close(sessfd); return 0; } close(sessfd); } return 0; }