Handle client session ended by server

This commit is contained in:
flyingscorpio@clevo 2022-10-21 16:08:24 +02:00
parent e18d002947
commit d2983ff1d3
2 changed files with 18 additions and 7 deletions

View file

@ -13,7 +13,7 @@ int main(int argc, char *argv[]) {
int sockid;
struct sockaddr_in client_socket;
struct hostent *host;
pid_t listener_pid, sender_pid;
pid_t listener_pid, sender_pid, changed_pid;
/* Signal handling */
signal(SIGPIPE, SIG_IGN);
@ -76,10 +76,14 @@ int main(int argc, char *argv[]) {
return EXIT_SUCCESS;
}
// TODO: make sure to quit processes cleanly and check order of wait calls
waitpid(sender_pid, NULL, 0);
if (kill(listener_pid, SIGKILL) == -1) perror("kill");
else waitpid(listener_pid, NULL, 0);
/* Wait for end of session: when one process ends, kill the other */
changed_pid = waitpid(-1, NULL, 0); // Wait for one of listener_pid or sender_pid
if (changed_pid == sender_pid) {
if (kill(listener_pid, SIGKILL) == -1) perror("kill");
} else if (changed_pid == listener_pid) {
if (kill(sender_pid, SIGKILL) == -1) perror("kill");
}
waitpid(-1, NULL, 0);
/* Close the connection */
close(sockid);
@ -97,6 +101,9 @@ void Listener(int sockid) {
/* Read n bytes at a time, because we don't know how long the message will be */
while ((n = read(sockid, buf, BUF_LEN)) > 0) {
write(STDOUT_FILENO, buf, n);
if (buf[n - 1] == EOT) { // Got EOT from server, close the session
return;
}
}
if (n < 0) {
fprintf(stderr, "ERROR: read\n");

View file

@ -29,6 +29,7 @@ int main(void) {
void *retval;
pid_t pid;
long addr_len;
char eot = EOT;
/* Signal handling */
signal(SIGCHLD, interrupt);
@ -100,6 +101,7 @@ int main(void) {
/* Client array is full, refuse connection */
fprintf(stderr, "get_next_free_client_id: Client array must be full\n");
write(client_sockid, "Too many clients connected, come back later!\n", 45);
write(client_sockid, &eot, 1);
close(client_sockid);
continue;
}
@ -122,6 +124,8 @@ int main(void) {
}
}
printf("Server end, closing connection\n");
close(serv_sockid);
return EXIT_SUCCESS;
}
@ -241,12 +245,12 @@ void interrupt(int signal) {
while (waitpid(-1, NULL, WNOHANG) != -1);
break;
case SIGINT:
RUN = 0;
fprintf(stderr, "server interrupted\n");
exit(EXIT_FAILURE);
break;
case SIGTERM:
fprintf(stderr, "server killed\n");
exit(EXIT_SUCCESS);
exit(EXIT_FAILURE);
break;
default:
fprintf(stderr, "received unexpected signal %d\n", signal);