Unix C Languages Write small, process-based concurrent servers

Source: Internet
Author: User

Concurrency Introduction

If logical control flows overlap in time, they are concurrent and can appear at different levels of the computer system, and hardware exception handlers, processes, and UNIX signal handlers are both concurrent. Concurrency can be seen as the mechanism used by the operating system kernel to run multiple applications, but concurrency is not limited to the kernel. It can also play a role in the application. The main functions of concurrency are: accessing slow IO devices, interacting with people, delaying work to reduce latency, and servicing requests from multiple network clients. Concurrency can typically be three kinds, based on process, IO multiplexing, and thread-based.

Process-based concurrency

A process is an instance of a program running. Each process has its own separate address space, typically including text areas, data regions, and stacks. The text area is the code that the storage processor executes, the data region stores variables and the dynamically allocated memory used during thread execution, and the stack area stores the instructions and local variables for the active procedure call. The program is an inanimate entity, and only the processor gives the program life, and then the operating system executes it, It can be called an entity, called a process.

the natural way to construct a concurrent server is to accept the client's connection request in the parent process and then create a child process to serve each new client. After the connection accepts the request, the server derives a child process, which obtains a full copy of the Server Descriptor table, the child process closes its copy of the listener descriptor, and the parent process closes its connected descriptor, otherwise the file table entry for the connected descriptor will never be freed. and the resulting memory leaks will eventually consume the available servers, causing the system to crash.

for shared state information between parent and child processes, the process has a very clear model: The shared File table, but does not share the user address space. The process has an independent address space that is both an advantage and a disadvantage, so that one process cannot accidentally overwrite the virtual memory of another process, and on the other hand, a separate address space makes it more difficult to share information between processes. Another disadvantage of process-based design is that it tends to run slower because process control and IPC overhead are relatively high.

Unix C implements small, process-based concurrent servers

This program was developed in the UNIX environment in C language, and called the Csapp.h's ready-made header file.

This program is a multi-process-based concurrent Echo server, the parent process derives a child process to process each new connection request, # include "Csapp.h"//echo program, used to send a response body void echo (int connfd) {int n) to the client; Char buf[maxline];rio_t RIO;RIO_READINITB (&AMP;RIO,CONNFD);//buffered read function while (N=rio_readlineb (&rio,buf,maxline )) {//>0) {//to the connector write to printf ("Server received%d bytes \ n"); Rio_writen (connfd,buf,n);}} Signal processing function, which is used to handle the zombie process, that is, to reclaim the resources that the terminated process brings to the system. Sigchld_handler (int sig) {//-1 represents the child process group that recycles the parent process, because the UNIX signal is not queued, It is therefore necessary to be prepared to reclaim multiple dead child processes while (Waitpid ( -1,0,wnohang) >0); return;} int main (int argc,char **argv) {int listenfd,connfd,port;socklen_t clientlen=sizeof (struct sockaddr_in); struct Sockaddr_in clientaddr;if (argc!=2) {fprintf (stderr, "Usage:%s <port>\n", argv[0]); exit (0);} Convert string to Integer, port number Port=atoi (Argv[1]),//Start signal handler function listener signal (sigchld,sigchld_handler);//Start Server Listener descriptor Listenfd=open_ LISTENFD (port), while (1) {//Connected descriptor, accept connection connfd=accept (LISTENFD, (SA *) &clientaddr,&clientlen);//Open sub-process, Used to process the connection request if (fork () ==0) {//Because the child process shares all the resources of the parent process, the listener descriptor is closed, the request Body command is called, then the connected descriptor is closed, and the process terminates gracefully close (LISTENFD); Echo (CONNFD); cLose (CONNFD); exit (0);} Close the connection descriptor for the parent process close (CONNFD);}}
To test a program using Telnet:

[Email protected]:~$ telnet localhost 8080Trying 127.0.0.1...Connected to localhost. Escape character is ' ^] '. Hellohello



[Email protected]:/home/zzw/doc_main/cprogram/concurrency#./ECHOSERVERP.O 8080server received 7 bytes




Unix C Languages Write small, process-based concurrent servers

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.