C语言利用fork创建多进程服务端

一、概述

  案例:利用for改造上一节的服务端程序,让其能够和多个客户端之间收发数据。Client端代码请参考上一篇

二、代码示例

#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>

#define PORT 8888
#define MESSAGE_LEN 1024
int main(int argc, char const *argv[])
{
	
	int socket_fd,accept_fd;
	int on= 1;
	int ret =-1;
	int backlog = 10;
	pid_t pid;
	struct sockaddr_in localaddr ,remoteaddr;
	socket_fd = socket(AF_INET,SOCK_STREAM,0);

	char in_buff[MESSAGE_LEN] = {0};
	//如果socket创建失败就退出
	if(socket_fd==-1){
		std::cout<<"Failed to create socket!"<<std::endl;
		exit(-1);
	}

	ret = setsockopt(
		socket_fd,
		SOL_SOCKET,
		SO_REUSEADDR,
		&on,
		sizeof(on));
	if(ret==-1){
		std::cout<<"Failed 通setsocket options!"<<std::endl;
		exit(-1);
	}

	localaddr.sin_family=AF_INET;
	localaddr.sin_port = PORT;
	localaddr.sin_addr.s_addr = INADDR_ANY;
	bzero(&(localaddr.sin_zero),8);


	ret = bind(socket_fd,
		(struct sockaddr*)&localaddr,sizeof(struct sockaddr));
	if(ret  ==-1){
		std::cout<< "Failed to bind addr!"<<std::endl;
		exit(-1);
	}

	ret = listen(socket_fd,backlog);
	if(ret==-1){
		std::cout<< "Failed to bind listen socket!"<<std::endl;
		exit(-1);
	}
	for(;;){
		socklen_t addr_len = sizeof(struct sockaddr);
		accept_fd = accept(socket_fd,(struct sockaddr*)&remoteaddr,&addr_len);

		pid = fork();
		if(pid==0){//pid==0子进程
			for(;;){
				ret=recv(accept_fd,(void*)in_buff,MESSAGE_LEN,0);
				if(ret==0){
					break;
				}
				std::cout << "recv:"<< in_buff<<std::endl;
				send(accept_fd,(void*)in_buff,MESSAGE_LEN,0);
				
			}
			close(accept_fd);
		}
			

	}
	//关闭父进程
	if(pid!=0){
		close(socket_fd);
	}
	
	return 0;
}

  

上一篇:如何创建守护进程


下一篇:system函数