Original aircraft
Original link: https://www.cnblogs.com/DOMLX/p/9612820.html
Under Linux:
I. Service-side code
The following closed file descriptor with multiple close, there may be some small partners have doubts .... I'll just say that when you create a process, you copy the resources of the parent process, and you just need to keep the resources you need to handle, and the rest of the nature will be shut down.
Or the father, a son, a little later.
Note: Just like inter-process communication needs to belong to the operating system's resource pipeline, socket also belongs to the operating system, so the creation of a new process is still only the original, the copy of the resource is just a file descriptor, we closed this file descriptor
//implementation of concurrent server based on multi-process//Note: Child processes replicate all resources owned by the parent process#include <stdio.h>#include<stdlib.h>#include<string.h>#include<unistd.h>#include<arpa/inet.h>#include<sys/socket.h>#include<signal.h>#include<sys/wait.h>#defineBuf_size 30voidError_handling (Char*message);voidRead_childproc (intSIG); intMainintargcChar*argv[]) { //Defining a TCP connection variable intServ_sock; intClnt_sock; structsockaddr_in serv_addr; structsockaddr_in clnt_addr; Socklen_t clnt_addr_size; intStr_len; CharBuf[buf_size]; //defining signal Processing variablespid_t pid; structSigaction Act; intState ; if(argc!=2) {exit (1); } //configuring signal Processing functionsAct.sa_handler=Read_childproc; Sigemptyset (&act.sa_mask); Act.sa_flags=0; Sigaction (SIGCHLD,&act,0); //TCP Socket ConfigurationServ_sock=socket (Pf_inet, Sock_stream,0); if(Serv_sock = =-1) error_handling ("Socket error!"); memset (&SERV_ADDR,0,sizeof(SERV_ADDR)); Serv_addr.sin_family= Af_inet;//IPV4 Protocol FamilySERV_ADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);//host byte order (hostname) converted to network byte order (NET) (big endian)Serv_addr.sin_port = htons (Atoi (argv[1]));//Port number if(Bind (Serv_sock, (structsockaddr*) &serv_addr,sizeof(SERV_ADDR)) == -1) error_handling ("bind error"); if(Listen (Serv_sock,5) == -1) error_handling ("Listen error"); while(1) {clnt_addr_size=sizeof(CLNT_ADDR); Clnt_sock=accept (Serv_sock, (structsockaddr*) &clnt_addr, &clnt_addr_size); if(Clnt_sock = =-1) Continue; Elseputs ("new Client Connected ..."); PID=fork ();//Create a new process if(pid==-1) {close (Clnt_sock); Continue; } if(pid==0)//child process Run area{Close (serv_sock); //to close the server socket file descriptor in a child process while((Str_len=read (Clnt_sock, buf, buf_size))! =0) Write (Clnt_sock, buf, Str_len); Close (clnt_sock);//close your own file descriptor after executionPuts"Client Disconnected ..."); return 0; } Else //Parent Process Run Area { //after calling the fork function, close the irrelevant socket file descriptorClose (Clnt_sock); }} close (Serv_sock); return 0;} voidError_handling (Char*message) {fputs (message, stderr); FPUTC ('\ n', stderr); Exit (1);} //This function is called once the child process has endedvoidRead_childproc (intSIG) { intstatus; pid_t ID=waitpid (-1, &status, Wnohang);//wait for the child process to terminate if(wifexited (status)) {printf ("remove proc ID:%d \ n", id); printf ("Child Send:%d \ n", Wexitstatus (status)); }}
Two. Client code
Here to say here with the multi-process partition I/O (input/output), is for the code segmentation to Improve program optimization, in the input data without the need to consider the output, in a place without writing two local code, although the code may be more, but the program is really optimized, the old experience of the programmer can appreciate the
And then why is the Write_routine to call shutdown to the server transport Eof,main function Finally, there is no close can be sent to the server??? This is because we created the subprocess, there is no way to pass the EOF through a call to close, otherwise it will be a big problem!! So oneself in the child process manually call shutdown send EOF, tell the server: "Hey, man, I almost want to cool the next life is destined to see Qaq" ha ha haha haha
//Split IO realizes the sending and receiving process of segmented data//The parent process is responsible for receiving, and the child process is responsible for sending#include <stdio.h>#include<stdlib.h>#include<string.h>#include<unistd.h>#include<arpa/inet.h>#include<sys/socket.h>#defineBuf_size 30voidError_handling (Char*message);voidRead_routine (intSockChar*buf);voidWrite_routine (intSockChar*buf); intMainintargcChar*argv[]) { intsock; pid_t pid; structsockaddr_in serv_addr; intStr_len; CharBuf[buf_size]; if(argc!=3) {exit (1); } sock=socket (Pf_inet, Sock_stream,0); if(Sock = =-1) error_handling ("Socket error!"); memset (&SERV_ADDR,0,sizeof(SERV_ADDR)); Serv_addr.sin_family=af_inet; Serv_addr.sin_addr.s_addr= Inet_addr (argv[1]); Serv_addr.sin_port= Htons (Atoi (argv[2])); if(Connect (sock,structsockaddr*) &serv_addr,sizeof(SERV_ADDR)) == -1) error_handling ("Connect Error"); Elseputs ("Connected ....."); PID=Fork (); if(pid==0)//Child Process Writewrite_routine (sock, buf); Else //Parent Process Readread_routine (sock, buf); Close (sock); return 0;} voidError_handling (Char*message) {fputs (message, stderr); FPUTC ('\ n', stderr); Exit (1);} //here the implementation reads in the relevant codevoidRead_routine (intSockChar*buf) { while(1) { intstr_len=Read (sock, buf, buf_size); if(str_len==0) return;//returns when the EOF end is acceptedBuf[str_len]=0; printf ("message from server:%s \ n", BUF); }} //this is responsible for implementing the output codevoidWrite_routine (intSockChar*buf) { while(1) {fgets (buf, Buf_size, stdin); if(!STRCMP (BUF,"q\n") || !STRCMP (BUF,"q\n") {shutdown (sock, SHUT_WR); return; } write (sock, buf, strlen (BUF)); }}
at the same time the multi-process server also has shortcomings, each creation of a process represents a large number of operations and memory space consumption, mutual process data exchange is also very troublesome ... So how to fix it, the blog behind me may give an answer-----hhhhhhh
Reference book "TCP/IP network programming---Yin San Yu"
C + + Network programming (ii) TCP/IP Linux multi-process socket communication multiple clients and a single server-side interactive code implementation echo Server