下面的循环在程序的主体内部。它接受传入的连接,并有一个线程使用它。
问题是,一旦任何线程终止,它就会终止整个程序。这是代码:
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#define BUFLEN 1500
#define MAXCON 30
char *returnTimeDate(int inputchoice);
void readWriteToClient(int inputconnfd);
int main(){
int backlog = 10;
int fd;
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1) {
// Error: unable to create socket
}
struct sockaddr_in cliaddr;
socklen_t cliaddrlen = sizeof(cliaddr);
struct sockaddr_in addr;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_family = AF_INET;
addr.sin_port = htons(5001);
if (bind(fd, (struct sockaddr *) &addr, (socklen_t) sizeof(addr)) == -1) {
fprintf(stderr,"Bind Didn't Work\n");
}
if (listen(fd, backlog) == -1) {
fprintf(stderr,"Listen Didn't Work\n");
}
pthread_t *threadsArray = (pthread_t *)calloc(MAXCON, sizeof(pthread_t));
pthread_t *threadPtr = threadsArray;
int k;
for(k = 0; k < MAXCON; k++){
fprintf(stderr,"Make %d\n",k);
int connfd;
connfd = accept(fd, (struct sockaddr *) &cliaddr, &cliaddrlen);
if (connfd == -1) {
fprintf(stderr,"Accept Didn't Work\n");
}
fprintf(stderr,"Waited\n",k);
pthread_create( &threadPtr, NULL, readWriteToClient, (void *)connfd);
threadPtr++;
}
pthread_t *threadPtrJoin = threadsArray;
for(k = 0; k < MAXCON; k++){
fprintf(stderr,"Join %d\n",k);
pthread_join( *threadPtrJoin, NULL);
threadPtrJoin++;
}
/* readWriteToClient(connfd);*/
close(fd);
return 0;
}
void readWriteToClient(int inputconnfd){
int connfd = inputconnfd;
while(1){
char *dateString = "DATE\r\n";
char *timeString = "TIME\r\n";
char *endString = "end";
char *bufferTime = returnTimeDate(0);
char *bufferDate = returnTimeDate(1);
ssize_t i;
ssize_t rcount;
char buf[BUFLEN];
char *toReturn = (char *)malloc(BUFLEN*sizeof(char));
rcount = read(connfd, buf, BUFLEN);
if((strcmp (buf, dateString)) == 0){
strcpy(toReturn, bufferDate);
}
if((strcmp (buf, timeString)) == 0){
strcpy(toReturn, bufferTime);
}
if((strcmp (buf, endString)) == 0){
goto outside;
}
if (rcount == -1) {
// Error has occurred
printf("Error: rcount -1");
}
/* fprintf(stderr,"I have received = %s\n",buf);*/
if (write(connfd, toReturn, BUFLEN) == -1) {
fprintf(stderr,"I didn't write = %s\n",buf);
}
}
outside: return;
}
char *returnTimeDate(int inputchoice){
time_t timer;
char *bufferTimee = (char *)malloc(25*sizeof(char));
char *bufferDatee = (char *)malloc(25*sizeof(char));
struct tm* tm_info;
time(&timer);
tm_info = localtime(&timer);
strftime(bufferTimee, 25, "%H:%M:%S\n\0", tm_info);
strftime(bufferDatee, 25, "%d:%m:%Y\n\0", tm_info);
if(inputchoice == 0){
return bufferTimee;
}else{
return bufferDatee;
}
}
为什么要这样做?