title: WinSock Non-Blocking I/O
body: <p>I have a WSASocket which when connected calls CreateProcess and servers cmd.exe, I wanted to implement a pipe in-between the processes hStdInput and the Socket Handle to parse commands that get sent over the socket, everything seems to run smoothly except for when I run a command like "ping 127.0.0.1" and have to wait for output, nothing shows up until I send more data over the socket, it seems my ReadFile call is blocking hStdOut handler from sending anything. Is there any way to fix this? Please don't be offended by my code I'm writing this project as a learning exercise, any help would be appreciated.</p>
  
  <pre><code>int syncShell(SOCKET *ConnectSocket) {
      int iResult = 0;
      printf("Spawning process\n");
      char Process[] = "C:\\Windows\\System32\\cmd.exe";
      STARTUPINFO sinfo;
      PROCESS_INFORMATION pinfo;
      memset(&amp;sinfo, 0, sizeof(sinfo));
      sinfo.cb = sizeof(sinfo);
      sinfo.dwFlags = (STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW);
  
      // create pipe for external commands
      SECURITY_ATTRIBUTES  saAttr;
      saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
      saAttr.bInheritHandle = TRUE; 
      saAttr.lpSecurityDescriptor = NULL;
      HANDLE hReadPipe = NULL, hWritePipe = NULL;
      iResult = CreatePipe(&amp;hReadPipe, &amp;hWritePipe, &amp;saAttr, DEFAULT_BUFLEN);
      if (iResult == 0) {
          printf("Pipe Error");
      }
  
      sinfo.hStdOutput = sinfo.hStdError = (HANDLE) *ConnectSocket;
      sinfo.hStdInput = hReadPipe;
  
      if (!CreateProcessA(NULL, Process, NULL, NULL, TRUE, 0, NULL, NULL, &amp;sinfo, &amp;pinfo)) {
          printf("CreateProcess failed (%d).\n", GetLastError());
      }
  
      // implement pipe logic
      char buf[DEFAULT_BUFLEN];
      DWORD len = 0;
      WSABUF DataBuf;
  
      while (1) {
          // causing the block?
          iResult = ReadFile((HANDLE) *ConnectSocket, buf, DEFAULT_BUFLEN, &amp;len, NULL);
          if (iResult == 0) {
              printf("File Error or non-blocking");
          }
          else {
              printf("%d: %.*s\n", len, len, buf);
              WriteFile(hWritePipe, buf, len, NULL, NULL);
          }
          Sleep(1000);
      }
  
      WaitForSingleObject(pinfo.hProcess, INFINITE); // waits till proc finishes
      CloseHandle(pinfo.hProcess);
      CloseHandle(pinfo.hThread);
      printf("Process exited\n");
  
      return 0;
  }
  </code></pre>