UNIX network programming examples of TCP client-server programming (II.)

Source: Internet
Author: User

In this section we continue to introduce several other TCP client-server programs;

Fourth: TCP concurrent server, one sub-thread per client

As can be seen in the example of the concurrent server program in front of us: The parent process accepts the connection, derives the child process, and the subprocess processes the interaction with the customer.

Problems with this pattern:

Fork () is expensive. The memory image is copied from the parent process to the child process, all the descriptors are replicated in the child process, and so on.

Fork () child process, you need to use interprocess communication to pass information between the parent and child processes.

All threads in a process share the same global memory, which makes it easy for threads to share information, but this simple type also brings synchronization problems. All threads in a process share not only global variables, but also shared:

Process instructions, most data, open files (such as descriptive words), signal handlers and signal disposition, current working directory, user ID and group ID;

That's why we've introduced threads;

When a program is started by exec, a single thread is created that is called the initial thread or the main path. Additional threads are created by the Pthread_create function.

Each thread in a process is identified by a thread ID whose data type is pthread_t (often unsigned int). If the new thread is created successfully, its ID is returned through the TID pointer.

Each thread has a number of properties: The priority, the start stack size, whether it should be a daemon thread, and so on. When creating a thread, we can override the default by initializing a phread_attr_t variable to describe these properties.

Finally, when you create a thread, we describe a function that it will execute. The thread starts by invoking the function, then either the display terminates (calls to pthread_exit) or the implicit termination (the function returns). Parameter with a pointer of Arg.

We can call Pthread_join to wait for a thread to terminate. Similar to Waitpid.

We must specify the TID to wait for the thread. You cannot wait for any one thread to end (similar to the case where the WAITPID process ID parameter is-1).

Mutual exclusion Lock:

Multiple threads Modifying a shared variable is the simplest problem, and the workaround is to protect the shared variable with a mutex (mutex), and only if we hold a mutex to access the variable.

A mutex is a variable of type pthread_mutex_t.

Condition variables:

Mutexes are suitable for blocking simultaneous access to shared variables, but we need something to allow us to sleep and wait for a certain condition to occur. We need a way to make the main loop go to sleep until a thread notifies it that something is ready. Conditional variables plus mutexes can provide this functionality. Mutexes provide mutually exclusive mechanisms, and conditional variables provide a signaling mechanism.

A condition variable is a variable of type pthread_cond_t.

Multithreaded client program:

  1. #include "Unpthread.h"
  2. void* CopyTo (void*);
  3. static int sockfd;//global variable, common to all threads
  4. Static FILE *FP;
  5. void Str_cli1 (FILE *fp_arg, int sockfd_arg) {
  6. Char Recvline[maxline];
  7. pthread_t Tid;
  8. sockfd = Sockfd_arg;
  9. fp = Fp_arg;
  10. Pthread_create (&tid,null,copyto,null);
  11. While (Readline (sockfd,recvline,maxline) >0)
  12. Fputs (recvline,stdout);
  13. }
  14. void* CopyTo (void* Arg) {
  15. Char Sendline[maxline];
  16. while (Fgets (SENDLINE,MAXLINE,FP)!=null)
  17. Writen (Sockfd,sendline,strlen (sendline));
  18. Shutdown (SOCKFD,SHUT_WR);
  19. return (NULL);
  20. }
  21. Int
  22. Main (int argc, char **argv)
  23. {
  24. int sockfd;
  25. struct sockaddr_in servaddr;
  26. if (argc! = 2)
  27. err_quit ("Usage:tcpcli <ipaddress>");
  28. sockfd = Socket (af_inet, sock_stream, 0);
  29. Bzero (&servaddr, sizeof (SERVADDR));
  30. servaddr.sin_family = af_inet;
  31. Servaddr.sin_port = htons (Serv_port);
  32. Inet_pton (Af_inet, argv[1], &servaddr.sin_addr);
  33. Connect (SOCKFD, (SA *) &servaddr, sizeof (SERVADDR));
  34. Str_cli1 (stdin, SOCKFD); /* Do it all */
  35. Exit (0);
  36. }

Server program:

  1. #include "Unpthread.h"
  2. static void *doit (void *); /* Each thread executes the This function */
  3. Int
  4. Main (int argc, char **argv)
  5. {
  6. int LISTENFD, CONNFD;
  7. pthread_t Tid;
  8. Socklen_t Addrlen, Len;
  9. struct SOCKADDR *cliaddr;
  10. if (argc = = 2)
  11. listenfd = Tcp_listen (NULL, argv[1], &addrlen);
  12. else if (argc = = 3)
  13. listenfd = Tcp_listen (argv[1], argv[2], &addrlen);
  14. Else
  15. err_quit ("Usage:tcpserv01 [<host>] <service or port>");
  16. cliaddr = Malloc (Addrlen);
  17. for (;;) {
  18. len = Addrlen;
  19. connfd = Accept (LISTENFD, cliaddr, &len);
  20. Pthread_create (&tid, NULL, &doit, (void *) CONNFD);
  21. }
  22. }
  23. static void *
  24. doit (void *arg)
  25. {
  26. Pthread_detach (Pthread_self ());
  27. Str_echo ((int) arg); /* Same function as before */
  28. Close ((int) arg); /* Do with connected socket */
  29. return (NULL);
  30. }


Note: Here we compile, because pthread is not the system default library, so use the command:

GCC Tcpcli.c-o client-lunp-lpthread

GCC Tcpserv.c-o server-lunp-lpthread

Server Run command: sudo./server 127.0.0.1 9877

Client Run command:./client 127.0.0.1

We notice that each client's program is actually a change of the STR_CLI function, and the main function does not change;

OK, and introduced a design example, continue tomorrow, not to be continued ...


Copyright NOTICE: This article for Bo Master http://www.zuiniusn.com original article, without Bo Master permission not reproduced.

UNIX network programming examples of TCP client-server programming (II.)

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.