title: Python Mutliprocessing/Sockets - Bad File Descriptor
body: <p>I am writing a server in Python which the client will send the command (via command line arg) "BYE". The connection between the client/server should be terminated at this time. (I figured that socket.close() would terminate the connection but I am not completely sure if that is correct)</p>
  
  <p>I wrote the adapted an echo server where clientsocket.close() was at the end of the server iteration. I want this to occur only if BYE is recieved.</p>
  
  <p>I am not sure if the structure of my server program is causing the issue (I am not using getopt yet - as I still need to figure it out)</p>
  
  <p>The server:</p>
  
  <pre><code>from multiprocessing import Process
  import socket
  import os
  
  def handler(clientsocket, clientaddr):
      print "Accepted connection from: ", clientaddr
      while 1:
          data = clientsocket.recv(1024)
          if data:
              if data == "BYE":
                  print "recvd BYE"
                  clientsocket.send("BYE")
                  clientsocket.close()
  #                p.join()
              elif data == "DIR":
                  print "recvd DIR"
                  DIR = os.getcwd()
                  clientsocket.send(DIR)
  
              print "data recieved:"
              print data
              msg = "You sent me: %s" % data
              clientsocket.send(msg)
              clientsocket.close()
              return
  
  if __name__ == "__main__":
  
      TCP_IP = '127.0.0.1'
      TCP_PORT = 5004
      BUFFER_SIZE = 1024
  
      print 'socket()'
      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  
      print 'bind()'
      s.bind((TCP_IP, TCP_PORT))
  
  #    f = open('recv.txt', 'wb')
  
      print 'listen()'
      s.listen(5)
  
      workerProcesses =[]
  
      while 1:
          print "Server is listening for connections\n"
          clientsocket, clientaddr = s.accept()
          p = Process(target=handler, args = (clientsocket, clientaddr))
          p.start()
  #        p.join()
          workerProcesses.append(p)
  
      serversocket.close()
  </code></pre>
  
  <p>When I put my clientsocket.close() in the if "BYE" statement, I get the error: bad socket descriptor. The output of the server is:</p>
  
  <pre><code>data recieved:
  BYE
  Process Process-1:
  Traceback (most recent call last):
    File "/usr/lib64/python2.6/multiprocessing/process.py", line 232, in _bootstrap
      self.run()
    File "/usr/lib64/python2.6/multiprocessing/process.py", line 88, in run
      self._target(*self._args, **self._kwargs)
    File "pyServ.py", line 26, in handler
      clientsocket.send(msg)
    File "/usr/lib64/python2.6/socket.py", line 167, in _dummy
      raise error(EBADF, 'Bad file descriptor')
  error: [Errno 9] Bad file descriptor
  </code></pre>
  
  <p>Any ides on why this is happening?</p>