title: Attaching a C/C++ thread to a socket
body: <p>My code, which is taken from on-line sources looks like below:</p>
  
  <pre><code>//.. initialization and other things..
  int connfd = 0;
  connfd = accept(listenfd, (struct sockaddr*)&amp;client_address,&amp;client_address_len);
  //... other code
   pthread_create(&amp;tid, NULL, &amp;foo, &amp;connfd);
  </code></pre>
  
  <p>The code above, will call the function foo with argument id. Now each thread will have its own version of foo to run with the argument. In foo, I am able to send data to a client using the socket. However, I am failing to see how (although it works perfectly fine), what is linking the thread and the socket. I understand that id is passed, but it that is only an integer.  </p>
  
  <p>This is what the foo function looks like:</p>
  
  <pre><code>  void* SendFileToClient(void *var){
     int *connfd;
     connfd =(int*) var;
     std::cout &lt;&lt; "Connection accepted and id:" &lt;&lt; *connfd &lt;&lt; std::endl;
     std::cout &lt;&lt; "Connected to Client with IP: " &lt;&lt;   inet_ntoa(c_addr.sin_addr) &lt;&lt; "Port:" &lt;&lt; ntohs(c_addr.sin_port) &lt;&lt; std::endl; // inet_ntoa converts binary form of IPv4 to IPv4 dotted numbers, ntohs does something silimar for ports
     int write_size = write(*connfd, fname,64);
  
     std::cout &lt;&lt; write_size &lt;&lt; "connfds: " &lt;&lt;  *connfd &lt;&lt; std::endl;
  
     FILE *fp = fopen(fname,"rb");
  
     if(fp==NULL)
      {
          printf("File opern error");
          exit(EXIT_FAILURE);
      }
  
      /* Read data from file and send it */
      while(1)
      {
          /* First read file in chunks of 64 bytes */
          unsigned char buff[1024]={0};
          int nread = fread(buff,1,1024,fp);
  
          /* If read was success, send data. */
          if(nread &gt; 0)
          {
              std::cout &lt;&lt; "Sending..." &lt;&lt; std::endl;
              write_size =  write(*connfd, buff, nread);
          }
          if (nread &lt; 1024)
          {
              if (feof(fp)) //end of file indicator
              {
                  std::cout &lt;&lt; "End of file" &lt;&lt; std::endl;
                  std::cout &lt;&lt; "File transfer completed for id:" &lt;&lt; *connfd &lt;&lt; std::endl;
              }
              if (ferror(fp))
                  std::cout &lt;&lt; "Error reading" &lt;&lt; std::endl;
              break;
          }
      }
      std::cout &lt;&lt; "Closing Connection for id:" &lt;&lt; *connfd &lt;&lt; std::endl;
      close(*connfd);
      shutdown(*connfd,SHUT_WR);
      sleep(2);
      return NULL;
  </code></pre>
  
  <p>}</p>
  
  <p>In the code above, the call to </p>
  
  <pre><code>   write(*connfd, buff, nread);
  </code></pre>
  
  <p>knows to send data through a socket referenced by connfd.</p>