我已经制作了一个聊天服务器,使用多线程处理多个客户端。我有一个无限循环的while循环,等待新的客户端。我想在按下ctrl + c后退出它。因此,我正在尝试捕获SIGINT信号,如此处所述。但是我无法退出程序。我在Linux终端上工作。
server.c
server.c
//for running type ./a.out anyportnumber
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#include <signal.h>
int s2;
int arr[100];
int tc = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
volatile sig_atomic_t flag = 1;
void handler(int signal)
{
flag = 0;
}
void sendtoall(char *msg,int s1)
{
int i;
pthread_mutex_lock(&mutex);
for(i = 0; i < tc; i++) {
if(arr[i] != s1)
write(arr[i],msg,strlen(msg));
}
pthread_mutex_unlock(&mutex);
}
void *function(void *s)
{
int s1;
int n;
char rmsg[500];
s1 = *(int *)s;
while((n = read(s1,rmsg,500)) > 0) {
rmsg[n] = '\0';
sendtoall(rmsg,s1);
bzero(rmsg,500);
}
pthread_exit(NULL);
}
int main(int arrc,char *argv[])
{
struct sockaddr_in server,client;
int s1,len;
int n;
int port;
pthread_t t1;
char message[500];
port = atoi(argv[1]);
bzero((char *)&server,sizeof(server));
server.sin_port = htons(port);
server.sin_addr.s_addr = INADDR_ANY;
server.sin_family = AF_INET;
s1 = socket(AF_INET,SOCK_STREAM,0);
if(s1 == -1) {
perror("socket not created\n");
exit(1);
}
if(bind(s1,(struct sockaddr *)&server,sizeof(struct sockaddr)) == -1) {
perror("socket not binded\n");
exit(1);
}
if(listen(s1,5) == -1) {
perror("unable to listen");
exit(1);
}
len = sizeof(struct sockaddr_in);
signal(SIGINT, handler);
while(flag) {
s2 = accept(s1,(struct sockaddr *)&client,&len);
pthread_create(&t1,NULL,function,(void *)&s2);
arr[tc] = s2;
tc++;
}
close(s1);
close(s2);
return 0;
}
gdb
)。 - Jason