Multi-process Implementation Concurrent Server (TCP)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.