title: program automatically closing after writing to socket
body: <p>I have the following code: </p>
  
  <pre><code>  bytes_read = read(0, buffer_stdin, 65535);
    printf("bytes read from stdin: %d\n", bytes_read);
    bytes_written = write(sock, buffer_stdin, bytes_read);
    printf("bytes written to socket: %d\n", bytes_written); 
  </code></pre>
  
  <p>sock is the socket descriptor. In the code I have connected the socket to a server and the connection returned (0), indicating the connection was successful. </p>
  
  <p>Now in the code above I type something into stdin, let's say "hello" and the number of bytes read would be 6 (because of null termination after letter 'o'). The program executes the first print statement. </p>
  
  <p>But for some reason the program doesn't execute the second print statement. It just exits.</p>
  
  <p>When I commented out line 3 where I write to the socket, the 2nd print statement executes.</p>
  
  <p>My question is, why is the program exiting early without my instruction to do so?</p>
  
  <p>Here is the preliminary code: </p>
  
  <pre><code>int main(int argc, char *argv[]) {
    if (argc != 3) {
      printf("Invalid arguments\n");
      exit(1);
    }
  
    char *serverIP = argv[1]; /*Server hostname*/
    char *portNumber = argv[2]; /*Port Number*/
    void *numericAddress;
    char buffer_stdin[65535];
    char buffer_stdout[65535];
    int bytes_read = 0;
    int bytes_written = 0;
  
    /*getting integral number of string representation of port number*/
    in_port_t servPort = atoi(argv[2]);
  
    /*------------------get binary number of hostname-----------------*/
    struct addrinfo addrCriteria;
    memset(&amp;addrCriteria, 0, sizeof(addrCriteria));
    addrCriteria.ai_family = AF_INET;
    addrCriteria.ai_socktype = SOCK_STREAM;
    addrCriteria.ai_protocol = IPPROTO_TCP;
  
    struct addrinfo *addrList;
  
    int rtnVal = getaddrinfo(serverIP, portNumber, &amp;addrCriteria, &amp;addrList);
    if (rtnVal != 0) {
      printf("getaddrinfo() failed\n");
      exit(1);
    }
    if (rtnVal == 0) {
      printf("getaddrinfo() successful\n");
    }
  
    numericAddress = &amp;((struct sockaddr_in *) (addrList-&gt;ai_addr))-&gt;sin_addr;
    ((struct sockaddr_in *)(addrList-&gt;ai_addr))-&gt;sin_port = htons(servPort);
    /*----------------------------------------------------------------*/
  
    /*Creating socket*/
    int sock = socket(AF_INET,SOCK_STREAM, IPPROTO_TCP);
    if (sock &lt; 0) {
      printf("error creating socket\n");
      exit(1);
    }
  
    /*Establish connection to the echo server*/
    int r = connect(sock, (struct sockaddr *) addrList, sizeof(addrList));
    if (r &lt; 0) {
      printf("Connection failed\n");
      exit(1);
    }
    if (r == 0) {
      printf("connection succesful\n");
    }
  </code></pre>