In my inside has introduced the Linux the following C's process, the thread interface, here does not do too much elaboration.
Multi-process
Many processes here use traditional multi-process models. Whenever a connection is made to a client, a process is created to process the connection, and a child process corresponds to a connection.
With the foundation of the last single process, it is possible to do this simply by making a simple change.
while (1) { clientfd = Accept (servfd, (struct sockaddr*) &cliaddr, &clientlen); Host = gethostbyaddr ((const char*) &cliaddr.sin_addr.s_addr, sizeof (CLIADDR.SIN_ADDR.S_ADDR), af_inet); printf ("Server Connect to host:%s%s\n", Host->h_name, Inet_ntoa (CLIADDR.SIN_ADDR)); if ((Child_pid = Fork ()) = = 0) { Close (servfd); Echo (CLIENTFD); Close (CLIENTFD); } Close (CLIENTFD); }
Simply add the process creation to the while and then close the parent process's listener socket in the child process.
Of course. Do not forget to add the wrapping function with fork error handling (as described in the Fork section).
void Error_msg (char *msg) { perror (msg); Exit (0);} int Fork () { pid_t pid; if (PID = fork ()) < 0) error_msg ("fork Failed"); return PID;}
Execution Result:
Client
Server
Multithreading
Threads and processes are interlinked in very many ways, modeled on the traditional model of multi-process above. It is not difficult to implement the traditional model of multithreading.
is still in the while inside to make simple changes can be.
CLIENTFD = (int*) malloc (sizeof (int)); *CLIENTFD = Accept (servfd, (struct sockaddr*) &cliaddr, &clientlen); Host = gethostbyaddr ((const char*) &cliaddr.sin_addr.s_addr, sizeof (CLIADDR.SIN_ADDR.S_ADDR), af_inet); printf ("Server Connect to host:%s%s\n", Host->h_name, Inet_ntoa (CLIADDR.SIN_ADDR)); Pthread_create (&tid, NULL, &thread, clientfd); Close (*CLIENTFD);
malloc is used to avoid the unintended consequences of having to ask the same clientfd for multithreading, all manually assigned.
The thread function is
void *thread (void* arg) { int clientfd = * ((int*) arg); Free (ARG); Pthread_detach (Pthread_self ()); Echo (CLIENTFD); Close (CLIENTFD); return NULL;}
Execution Result:
There is a problem with this code, CLIENTFD after the incoming thread. The arg pointer did not receive a value, meaning it was in an inaccessible place (GDB displays a value of 0x00) and baffled.
(The principle is very easy, the problems encountered first recorded, assuming that someone knows where the wrong hope to correct it out.)
。
Environment Ubuntu 64 bit, compiler GCC)
Linux network Programming (3)-multi-process, multi-threaded