int main(void) {
int sock_fd = connect_to_server(PORT, "127.0.0.1");
char username[50];
// Ask for username
printf("Username: \n");
// Read the username from STDIN
scanf("%s", username);
// write that username to the socket
write(sock_fd, username, 50);
char buf[BUF_SIZE + 1];
//Initialize the file descriptor set fdset
fd_set read_fds;
// Then have zero bits for all file descriptors
FD_ZERO(&read_fds);
while (1) {
int num_read;
char myString[10];
myString[0] = '\0';
if (write(sock_fd, myString, 10) == 0) {
printf("SERVER Shutting down\n");
}
FD_SET(sock_fd, &read_fds);
FD_SET(STDIN_FILENO, &read_fds);
select(sock_fd + 1, &read_fds, '\0', '\0', '\0');
if (FD_ISSET(STDIN_FILENO, &read_fds)) { //check whether the fd value is in the fd_set
num_read = read(STDIN_FILENO, buf, BUF_SIZE);
if (num_read == 0) {
break;
}
buf[num_read] = '\0'; // Just because I'm paranoid
int num_written = write(sock_fd, buf, num_read);
if (num_written != num_read) {
perror("client: write");
close(sock_fd);
exit(1);
}
}
if (FD_ISSET(sock_fd, &read_fds)) { //the socket with the server
num_read = read(sock_fd, buf, BUF_SIZE);
buf[num_read] = '\0';
printf("%s", buf);
}
}
close(sock_fd);
printf("SERVER Shutting down\n");
return 0;
}
When my server exits, I want it to close all of the client sockets then the clients should be sent the message, "SERVER Shutting down". I want this to happen if my server receives a SIGINT (Ctrl-C) signal. I basically want it to "clean up" and then exit with status code 0.
How can I check if my server is terminated?