Multi-process multi-user connection, that is, each user has a connection. Here, the server still converts the received string to uppercase and returns it to the client.
# Include <stdio. h> # include <string. h> # include <netinet/in. h> # include <arpa/inet. h> # include <unistd. h> # include <ctype. h> # include <stdlib. h> # include <sys/wait. h> # define SERV_IP "127.0.0.1" # define SERV_PORT 8000 void wait_child (int signo) // reclaim the sub-process function {while (waitpid (0, NULL, WNOHANG)> 0 ); return;} int main (int argc, char * argv []) {pid_t pid; // process ID int sfd, cfd; // receives the connected sfd, cfd struct sockaddr_in serv_addr and clie_addr for communication with the client; // create the socklen_t clie_addr_len server and client struct; // The length of the client struct is char buf [BUFSIZ] And clie_IP [BUFSIZ]; // buf stores the received int n, I; // The number of read data n, the cycle factor I sfd = socket (AF_INET, SOCK_STREAM, 0 ); // create socket bzero (& serv_addr, sizeof (serv_addr); // reset serv_addr.sin_family = AF_INET; // set the protocol family to IPv4 protocol = htonl (INADDR_ANY ); // set the NIC to any valid Nic // inet_pton (AF_INET, SERV_IP, & serv_addr.sin_addr.s_addr); serv_addr.sin_port = htons (SERV_PORT); // set port bind (sfd, (struct sockaddr *) & serv_addr, sizeof (serv_addr); // sets the listen (sfd, 128) associated with the socket and sfd; // sets the maximum number of uncompleted accept. start listening. while (1) // cyclically receive client connection {clie_addr_len = sizeof (clie_addr); // initialize client struct length cfd = accept (sfd, (struct sockaddr *) & clie_addr, & clie_addr_len); // receive client connection printf ("client IP: % s, port: % d \ n", inet_ntop (AF_INET, & clie_addr.sin_addr.s_addr, clie_IP, sizeof (clie_IP), ntohs (clie_addr.sin_port); pid = fork (); // create a new process if (pid <0) // error {perror ("fork error"); exit (1);} else if (pid = 0) // sub-process {close (sfd ); // first shut down the parent process file descriptor break in the child process;} else if (pid> 0) // parent process {close (cfd ); // first shut down the sub-process file descriptor signal (SIGCHLD, wait_child) in the parent process; // register the signal to recycle the completed sub-process} if (pid = 0) // The following is the real service processing part of the sub-process {while (1) // The Client Service of loop processing {n = read (cfd, buf, sizeof (buf )); if (n = 0) // if read returns 0, the client is disconnected {close (cfd); // closes the client file descriptor return 0 ;} else if (n =-1) // error {perror ("read error"); exit (1) ;}else {write (STDOUT_FILENO, buf, n ); for (I = 0; I <n; ++ I) {buf [I] = toupper (buf [I]);} write (cfd, buf, n) ;}}return 0 ;}