linux c 多进程简易tcpsocket通信


#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define DEFAULT_PORT 6666

void recyle(int num)//回收子进程
{
	pid_t pid;
	while ((pid=waitpid(0, NULL, WNOHANG))> 0);
	printf("removed proc id: %d \n", pid);
}
int main( int argc, char ** argv){
	int serverfd,acceptfd; 
	struct sockaddr_in my_addr; 
	struct sockaddr_in their_addr; 
	unsigned int sin_size, myport=6666, lisnum=10;
	//创建socket
	if ((serverfd = socket(AF_INET , SOCK_STREAM, 0)) == -1) {
		perror("socket" );
		return -1;
	}
	printf("socket ok \n");
	my_addr.sin_family=AF_INET;
	my_addr.sin_port=htons(DEFAULT_PORT);
	my_addr.sin_addr.s_addr = INADDR_ANY;
	bzero(&(my_addr.sin_zero), 0);
	//绑定
	if (bind(serverfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr )) == -1) {
		perror("bind" );
		return -2;
	}
	printf("bind ok \n");
	//监听
	if (listen(serverfd, lisnum) == -1) {
		perror("listen" );
		return -3;
	}
	printf("listen ok \n");

	printf("waiting client...\n");

//信号处理
	struct sigaction newact;
	newact.sa_handler = recyle;
	sigemptyset(&newact.sa_mask);
	newact.sa_flags = 0;
	sigaction(SIGCHLD, &newact, NULL);


	socklen_t len=sizeof(their_addr);

	while(1)
	{
		acceptfd=accept(serverfd,(struct sockaddr*)&their_addr,&len);
		if(acceptfd==-1)
		{
		    continue; //?
		}
		printf("%s,%d:client connect\n",inet_ntoa(their_addr.sin_addr),ntohs(their_addr.sin_port));
		pid_t pid=fork();
		if(pid==0)//子进程处理和客户端通信
		{
			close(serverfd);
			while(1)
			{
				char buf[1024]={0};
				int r=read(acceptfd,buf,sizeof(buf));
				if(r<=0)
				{
					
					printf("%s,%d:client disconnect\n",inet_ntoa(their_addr.sin_addr),ntohs(their_addr.sin_port)); 
close(acceptfd);
					return 0;//?
				}
				else
				{
					printf("%s,%d:%s\n",inet_ntoa(their_addr.sin_addr),ntohs(their_addr.sin_port),buf);
					char s[1024]={0};
                                         sprintf(s,"%s,%ld",buf,strlen(buf));
					write(acceptfd,s,strlen(s));
				}
			}
		}
		else if(pid>0)//父进程
		{
			close(acceptfd);关闭描述符
		}
	}
	close(serverfd);
	return 0;
}

你可能感兴趣的:(linux c 多进程简易tcpsocket通信)