background

Recently, I used go to reconstruct the c++ order sending service, and used the rabbitmq component to send messages. I wanted to test an exception: if the order sending service disconnects from the socket to rabbitmq, the service will be reconnected and send messages normally.

Simulate closing a TCP Socket connection online

If you are asked to close a TCP Socket connection online, you might say that this is easy: netstat -antp finds the connection and kills the process. As follows:

# netstat -antp|grep 5672TCP 0 0 10.133.145.109:43433 10.133.145.105:5672 ESTABLISHED 8226/./dao_deal_msg# kill 8226
Copy the code

Based on the above action, the connection is indeed closed and the process is killed. But this wave of operations falls short of being “online”.

Is there a way to close the Socket without killing the process?

The answer is absolutely yes. We can close a Socket by calling the close function. We can close a Socket by calling the close function.

See how this works by attaching GDB to the process context and executing call Close ($fd).

The first to usenetstatFind the corresponding process, for example, the order sending service to connect to the MQ socket process, MQ port number 5672:

# netstat -antp|grep 5672TCP 0 0 10.133.145.109:43433 10.133.145.105:5672 ESTABLISHED 8226/./dao_deal_msgCopy the code

You can see that the pid of the above process is 8226.

Then use lsof to find all file descriptors opened by process 8226, and find the corresponding Socket connections as follows:

# lsof -np 8226COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME cont_serv 8226 appadmin 12u IPv4 4120590453 0t0 TCP 10.133.145.109:43433 - > 10.133.145.105: closer (ESTABLISHED)Copy the code

Where 12U is the file descriptor of the Socket connection above.

GDB then connects to the process with PID 8226

# gdb -p 8226
Copy the code

GDB enters the process as follows:

Finally close12uSocket connection (file descriptor)

# call close(12u)
Copy the code

After closing the socket, check whether the process still exists and whether the 12U socket connection is no longer available:

You can see that the Socket connection is closed, but process 8226 is fine.

With the scenario

When will this feature be used, you may ask? For example, if you want to test whether the application will automatically reconnect to MySQL or RabbitMQ, this is a convenient way to test whether the service will reconnect to RabbitMQ.

Welcome to pay attention to the public number: “Go keyboard man”, check out more quality technical articles.