C语言Linux多进程实现并发服务器

开一个进程处理用户请求,客户端命令使用shell命令

nc 127.0.0.1 9527
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
void recyle(int num)
{
	pid_t pid;
	while((pid = waitpid(-1,NULL, WNOHANG))>0)
		printf("child died ,pid = %d\n", pid);
}

int main(int argc, char* argv[])
{

	if(argc <2){
		printf("eg: ./a.out port\n");
		exit(1);
	}

	int port = atoi(argv[1]);    // port


	int Socket_fd = socket(AF_INET, SOCK_STREAM, 0);   // create socket

	if(Socket_fd==-1){
		perror("create socket error");
		exit(EXIT_FAILURE);
	}

	struct sockaddr_in serv;

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

	serv.sin_family = AF_INET;                               // ipv4
	serv.sin_port = htons(port);                             // port
        serv.sin_addr.s_addr = INADDR_ANY;                        // ip

	if(-1==bind(Socket_fd, (struct sockaddr*)&serv, sizeof(serv))){
		perror("bind error");
		close(Socket_fd);
		exit(EXIT_FAILURE);
	}

	if(-1==listen(Socket_fd,10)){
		perror("listen error");
		close(Socket_fd);
		exit(EXIT_FAILURE);
       	}

	// signal
	struct sigaction act;
	act.sa_handler = recyle;
	act.sa_flags = 0;
	sigemptyset(&act.sa_mask);
	sigaction(SIGCHLD,&act,NULL);


	struct sockaddr_in client_addr;
        socklen_t cli_len = sizeof(client_addr);
	while(1){
		char ip[64];
		int cfd = accept(Socket_fd,(struct sockaddr*)&client_addr,
				&cli_len);
		while(cfd == -1 && errno == EINTR){
			int cfd = accept(Socket_fd,(struct sockaddr*)&client_addr,
				&cli_len);
		}

		pid_t pid = fork();
		if(pid == 0){
			// child process
			close(Socket_fd);
			char ip[64];
			while(1){
				printf("client IP: %s, port:%d\n",
				inet_ntop(AF_INET,&client_addr.sin_addr.s_addr,
				ip,sizeof(ip)),ntohs(client_addr.sin_port));

				char buf[1024];
				int len = read(cfd,buf,sizeof(buf));
				if(len == -1){
					perror("read error");
					exit(1);
				}

				else if(len ==0){
					printf("client disconnect");
					close(cfd);
					break;
				}

				else{
					printf("recv buf: %s\n", buf);
					write(cfd,buf,len);
				}
			}

			return 0;
		}

		else if(pid>0){
			
			// parent process
			close(cfd);
		}
	}
	
	close(Socket_fd);

 	
}

 

你可能感兴趣的:(算法)