该代码怎么在关闭服务器端时候不出现bind error: Address already in use错误
#include<ctype.h>
#include<unistd.h>
#include<errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include<pthread.h>
#define SERV_PORT 9527
void sys_err(const char* str) {
perror(str);
exit(1);
}
int main(int argc, char* argv[]) {
int lfd, cfd;
struct sockaddr_in serv_addr, client_addr;
socklen_t client_len = sizeof(client_addr);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(SERV_PORT);
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
lfd = socket(AF_INET, SOCK_STREAM, 0);
if (lfd == -1) {
sys_err("socket error");
}
int isbind = bind(lfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
if (isbind == -1) {
sys_err("bind error");
}
int islisten = listen(lfd, 10);
if (islisten == -1) {
sys_err("listen error");
}
char buf[BUFSIZ];
static int t = 1;
while (1) {
printf("\tclient_len: %d\n", client_len);
cfd = accept(lfd, (struct sockaddr*)&client_addr, &client_len);
printf("\tclient_len: %d\n", client_len);
printf("%s %d\n", inet_ntoa(client_addr.sin_addr), client_addr.sin_port);
if (cfd == -1) {
sys_err("accept error");
}
while (1)
{
int ret = read(cfd, buf, sizeof(buf));
for (int i = 0; i < ret; i++) buf[i] = toupper(buf[i]);
write(cfd, buf, ret);
write(STDOUT_FILENO, buf, ret);
sleep(t);
t++;
break;
}
close(cfd);
}
close(lfd);
return 0;
}