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;
}
当我的服务器退出时,我希望它关闭所有客户端套接字,然后应该向客户端发送消息“SERVER Shutting down”。如果我的服务器收到SIGINT(Ctrl-C)信号,我希望这发生。我基本上希望它“清理”然后以状态码0退出。
如何检查我的服务器是否已终止?