#include "processmanagement.h" #include "socketserver.h" // package variables: int forks = 0; int decs = 0; int existing_children = 0; int clients = 0; void decrement_children(int signal) { int status; int pid; #ifdef DEBUG_HIGHEST fprintf(logfile, "Decrementing to %d minus one\n", existing_children); #endif while (pid = waitpid(-1, &status, WNOHANG) > 0) { if (WIFEXITED(status) || WIFSIGNALED(status)) { decs++; existing_children--; } } } void init_process_management() { // when children die, they decrement existing_children: signal(SIGCHLD, decrement_children); signal(SIGTERM, server_shutdown); } void init_logging() { logfile = fopen(LOG_FILE, "a"); if (logfile == NULL) { perror("bad open"); } //fflush(logfile); } void stop_logging() { int _fstat; fflush(logfile); _fstat = fclose (logfile); if (_fstat < 0) { perror("bad close"); } } void log_message(int priority, const char *message) { if ((priority <= DEBUG_LEVEL) && (message != NULL)) { fprintf(logfile, "%s\n", message); fflush(logfile); } } void log_message_pid(int priority, const char *message, int pid) { if ((priority <= DEBUG_LEVEL) && (message != NULL)) { fprintf(logfile, "%s (pid: %d)\n", message, pid); fflush(logfile); } } void server_shutdown() { fprintf(logfile, "Closing parent with forks %d and decs %d\n", forks, decs); stop_logging(); exit (0); } void child_shutdown() { log_message_pid(0, "Closing child", getpid()); stop_logging(); exit (0); } void server_add_client() { struct sockaddr_in server_addr, local_addr; int rsocket, rc; char *readbuff; int result; char *sendmessage; int smeslen; int readdata; // send the message local_addr.sin_family = AF_INET; local_addr.sin_addr.s_addr = htonl(INADDR_ANY); local_addr.sin_port = htons(0); // server addr server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); server_addr.sin_port = htons(SERVER_PORT); // open dest socket rsocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (rsocket < 0) { perror("client socket"); return; } rc = bind(rsocket, (struct sockaddr *) &local_addr, sizeof(struct sockaddr_in)); if (rc < 0) { perror("client socket bind"); return; } rc = connect(rsocket, (struct sockaddr *) &server_addr, sizeof(struct sockaddr_in)); if (rc < 0) { perror("client socket connect"); return; } rc = send(rsocket, "ADDCLIENT\r\n", 11, 0); if (rc < 0) { perror("client socket send"); return; } // read response readbuff = calloc(sizeof(char), (11 + 1)); rc = read(rsocket, readbuff, 11); if (readbuff == NULL) { log_message(1, "critical error: no response to addclient"); close (rsocket); return; } if (strcmp(readbuff, "CLIENTADDED") == 0) { log_message(5, "successful add client"); } close (rsocket); return; }