How to wake up socket-blocked Functions

Source: Internet
Author: User
Tags set socket

Recently, a problem occurs in the project. When the program exits, the resources are not released normally. After debugging, it was found that the network thread had been congested, causing some necessary resources not to be released. I wrote a few simple test programs to debug them, in Linux, directly close the file descriptor of the socket does not cause some blocking socket functions called by the program, such as read and recvfrom, to exit blocking, and thus the resource cannot be released normally. The following is a simplified example.

The following is a simplified UDP Service Program. First, create a socket object, enable the service thread, and send the data packets sent from the client back to the client. When you press ENTER twice in shell, the program exits. Let's observe under what circumstances the socket service thread can exit normally after the program exits.

 
 
  1. #include <stdio.h>  
  2. #include <sys/types.h>  
  3. #include <sys/socket.h>  
  4. #include <linux/in.h>  
  5. #include <string.h>  
  6. #include <pthread.h>  
  7.   
  8. #define SERVER_PORT 8888  
  9. #define BUFFER_LEN  256  
  10.   
  11. int g_Exit = 0;  
  12.   
  13. void *service( void* arg )  
  14. {  
  15.     char buff[BUFFER_LEN];  
  16.     struct sockaddr clientAddr;  
  17.     int socklen = sizeof(clientAddr);  
  18.     int recvbytes;  
  19.     int socketfd = *((int *)arg);  
  20.   
  21.     printf("OK, Enter Service!\n");  
  22.   
  23.     while(!g_Exit)  
  24.     {  
  25.         recvbytes = recvfrom(socketfd,buff,BUFFER_LEN,0,&clientAddr,&socklen);  
  26.   
  27.         sendto(socketfd,buff,recvbytes,0,&clientAddr,socklen);  
  28.     }  
  29.   
  30.     printf("OK, Service Thread Exit!\n");  
  31.   
  32.     pthread_exit(NULL);;  
  33. }  
  34.   
  35. int main( int argc,char * argv[] )  
  36. {  
  37.     int fd;  
  38.     void *status;  
  39.     struct sockaddr_in serverAddr;  
  40.     pthread_t thr;  
  41.     pthread_attr_t attr;  
  42.   
  43.     fd = socket(AF_INET,SOCK_DGRAM,0);  
  44.   
  45.     memset(&serverAddr,0,sizeof(serverAddr));  
  46.   
  47.     serverAddr.sin_family = AF_INET;  
  48.     serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);  
  49.     serverAddr.sin_port = htons(SERVER_PORT);  
  50.   
  51.     bind(fd,(struct sockaddr *)&serverAddr,sizeof(serverAddr));  
  52.  
  53.     // create service thread  
  54.     pthread_attr_init(&attr);  
  55.     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);  
  56.     if( pthread_create(&thr,&attr,service,(void *)&fd ) )  
  57.     {  
  58.         printf("pthread_create fail!\n");  
  59.         return -1;  
  60.     }  
  61.     // Free attribute  
  62.     pthread_attr_destroy(&attr);  
  63.   
  64.     // wait user control exit 
  65.     getchar();  
  66.     getchar();  
  67.   
  68.     g_Exit = 1;      
  69.   
  70.     printf("OK, Waiting For Thread Exit...!\n");  
  71.   
  72.    close(fd);
  73.   
  74.     // wait for thread exit
  75.   pthread_join(thr, &status);
  76.  
  77. printf("OK, Exit Main Process !\n");
  78.  
  79.     return 0;  
  80. }  

After you press ENTER twice, the result is as follows:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1AI64537-0.jpg "border =" 0 "alt =" "/>

We can see that the exit information of the main process and service thread is not displayed, and neither the main process nor the service thread Exits normally. Therefore, directly close the socket handle does not cause the recvfrom function to exit.

So what if we replace pthread_join with pthread_cancel? The results are the same. Although the main process exits, the service thread cannot exit normally. So how can we exit the recvfrom blocking?

You can use the shutdown function after searching for it online.

 
 
  1. // The shutdown function is prototype:
  2. # Include <sys/socket. h>
  3. Int shutdown (int s, int how );
  4. // Shutdown () allows for more detailed control over socket shutdown, which allows one-way closure of sockets or all prohibitions.
  5. // The parameter s is the socket descriptor to be closed.
  6. // The how parameter specifies the closing method. The specific values are as follows:
  7. // SHUT_RD: closes the read channel on the connection. After that, the process will no longer receive any data, and the data not read in the receiving buffer will also be discarded, however, data can still be sent on the socket.
  8. // SHUT_WR: closes the write channel on the connection. After that, the process will no longer be able to send any data, and data not sent in the sending buffer will also be discarded, however, data can still be received on the socket.
  9. // SHUT_RDWR: The read and write channels will all be disabled.
  10. // If the execution succeeds, 0 is returned. If an error occurs,-1 is returned. The error code is stored in errno.

You can test the code by adding shutdown (fd, SHUT_RDWR) before pthread_join. then compile and debug the code. The result is as follows:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1AI62F0-1.jpg "border =" 0 "alt =" "/>

We can see that the Service thread has exited normally. Further test: What if I only use the shutdown write channel or the shutdown read channel?

After testing, we can find that if only the write channel shutdown (fd, SHUT_WR) is disabled, the service thread still cannot exit normally, and if only the read channel shutdown (fd, SHUT_RD) is disabled ), the service thread Exits normally. The analysis is as follows:Because recvfrom is in the fd read channel waiting list, you must disable the read channel to wake up the recvfrom blocking.

So why does shutdown cause recvfrom to exit and block, but close is not?

My understanding is as follows: shutdown destroys the read/write channel of the socket connection, leading to the wake-up of the socket function with read/write blocking, while the close function only does the operation to close the connection and release the socket resource, the read/write channel is not cleaned up, and thus the blocking of the read/write function cannot be successfully awakened. Hope experts can give a deeper explanation)

Further, is there any other way to solve this problem?

Below I will briefly list some feasible methods found on the internet, and I will study them further in the future:

1. Set socket sending/receiving timeout

2. Use non-blocking mode, asynchronous socket model

3. You are welcome to add other methods.

The article is written here, welcome to send a letter to further exchange lujun.hust@gmail.com

 

This article from the "three shadows" blog, please be sure to keep this source http://ticktick.blog.51cto.com/823160/845536

Related Article

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.