title: netcat-like simultaneous read/write on a socket?
body: <p>I'm in the process of learning how to do networking in C. I want to implement a simple netcat-like program for educational purposes. Something I can't figure out how to implement, however, is the program simultaneously reading input from stdin/writing it to the connection, and reading data from the connection/printing it to stdout.</p>
  <p>I came up with a potential solution: spawn a child process using <code>fork()</code> that reads data from the connection and writes it to stdout, while the parent process handles reading data from the user and writing it to the connection.</p>
  <p>The code I wrote to implement this doesn't work and is probably in violation of several safety practices, but it's just a proof of concept to show my idea.</p>
  <pre class="lang-c prettyprint-override"><code>if (fork() == 0) {
      char line[1024];
  
      for (;;) {
          memset(line, 0, 1024);
  
          n = read(fd, line, 1023);
  
          if (n)
              fputs(line, stdout);
      }
  } else {
      while ((c = getchar()) != EOF) {
          if (c == '\n')
              write(fd, &quot;\r\n&quot;, 2);
          else
              write(fd, &amp;c, 1);
      }
  }
  </code></pre>
  <p>Is there a canonical way to do something like this in C?</p>