并发服务器 典型模型

#include "header.h"



#define MAXBUF 1024

typedef struct sockaddr SA;



void child_function(int connect_fd);



void child_function(int connect_fd)

{

			char buffer[MAXBUF];

			

			memset(buffer,'\0',sizeof(buffer));

			if(read(connect_fd,buffer,sizeof(buffer)) < 0)

			{

				perror("read error");

				exit(-1);

			}



			printf("the client message :%s\n",buffer);



			int i;

			for(i = 0; i < strlen(buffer); i++)

			{

				buffer[i] = toupper(buffer[i]);

			}



			if(write(connect_fd,buffer,strlen(buffer)) < 0)

			{

				perror("write error");

				exit(-1);

			}

			close(connect_fd);

}



int main(void)

{

	int listen_fd,connect_fd;

	struct sockaddr_in serveraddr,clientaddr;

	socklen_t addrlen;

	pid_t pid;



	if((listen_fd=socket(AF_INET,SOCK_STREAM,0)) == -1)

	{

		perror("socket fail");

		exit(-1);

	}

  

	memset(&serveraddr,0,sizeof(serveraddr));

	serveraddr.sin_family=AF_INET;

	serveraddr.sin_port=htons(8000);

	serveraddr.sin_addr.s_addr=inet_addr("127.0.0.1");

	



	if(bind(listen_fd,(SA *)&serveraddr,sizeof(serveraddr)) == -1)

	{

		perror("bind fail");

		exit(-1);

	}

	if(listen(listen_fd,10) == -1)

	{

		perror("listen fail");

		exit(-1);

	}

	while(1)

	{

		addrlen = sizeof(clientaddr);

		if((connect_fd=accept(listen_fd,(SA *)&clientaddr,&addrlen)) == -1)

		{

			perror("accept fail");

			exit(-1);

		}

		printf("a new connection :%d\n",connect_fd);

		if((pid = fork()) == 0)

		{

			close(listen_fd);

			child_function(connect_fd);

			exit(0);

		}else if(pid < 0)

		{

			perror("fork");

			break;

		}else

		{

			close(connect_fd);

		}

	}

	close(listen_fd);

}


你可能感兴趣的:(C)