Premise: Learning based on Linux system
/*Multi-process Implementation Concurrent Server parent Process Task 1. Remove the request from the pending connection queue, establish a connection to the client, and CFD 2. Create a subprocess 3.close (CFD) 4. Task of the child process responsible for the corpse of the child processes 1.close (SFD) 2. Child processes are responsible for processing client messages Close (SFD) exit (0)*/#include<stdio.h>#include<sys/types.h>/*See NOTES*/#include<sys/socket.h>#include<arpa/inet.h>#include<string.h>#include<signal.h>#include<stdlib.h>
//signal customization function to handle the recycling of child process resourcesvoiddoit () {wait (NULL); return;} intMain () {Charbuf[ -]; Charip[ -]; Char*msg="Hector Pro_bf_serv\n"; structsockaddr_in serv; structsockaddr_in Clie; Socklen_t Clie_len; signal (sigchld,doit); //Create socket communication port, SFD intSfd=socket (Af_inet,sock_stream,0); if(sfd==-1) {perror ("Socket"); return 0; } //Initialize the members of the Servserv.sin_family=af_inet; Serv.sin_port=htons (7007); Serv.sin_addr.s_addr=htonl (Inaddr_any); //bind SFD to the server intB=bind (SFD, (structsockaddr*) &serv,sizeof(serv)); if(b==-1) {perror ("Bind"); return-1; } //set the SFD to passive listening stateListen (SFD,5); while(1) {Clie_len=sizeof(Clie); //establishing and connecting to clients intCfd=accept (SFD, (structsockaddr*) &clie,&Clie_len); if(sfd==-1) {perror ("Accept"); return-1; } printf ("%s\n", Inet_ntop (Af_inet,&clie.sin_addr,ip, -)); pid_t PID=Fork (); if(pid==-1) {perror ("Fork"); return-1; } if(pid==0){//Child ProcessClose (SFD); intR=read (Cfd,buf, -); Write (1, Buf,r); Write (Cfd,msg,strlen (msg)); Close (CFD); Exit (0); } Else{//Parent ProcessClose (CFD); } } return 0;}
Multi-process Implementation Concurrent Server (TCP)