Skip to content

How can I close a tcp/ip socket without killing the owning process?

Problem: a program has a socket open and you want to force it to close without killing the owning process.

Solution: get the file descriptor of the socket, debug the process and manually call close on the file descriptor.

On Linux systems:

  1. Find the offending process: netstat -np
  2. Find the socket file descriptor: lsof -np $PID
  3. Debug the process: gdb -p $PID
  4. Close the socket: call close($FD)
  5. Close the debugger: quit
  6. Profit.

From here.

On OSX the incantations are differently formed:

  1. Find the offending process and file descriptor: lsof -ni TCP
  2. Debug the process: lldb -p $PID
  3. Close the socket: call (int)close($FD)
  4. Close the debugger: quit
  5. Profit.