--- select.old	Tue Apr 14 01:16:56 2009
+++ select.c	Wed Apr 15 00:28:30 2009
@@ -66,7 +66,7 @@
 {
   DWORD ms_total, limit;
   HANDLE handles[MAXIMUM_WAIT_OBJECTS], hPipes[MAXIMUM_WAIT_OBJECTS];
-  int handle_slot_to_fd[MAXIMUM_WAIT_OBJECTS];
+  int handle_slot_to_fd[MAXIMUM_WAIT_OBJECTS], pipe_slot_to_fd[MAXIMUM_WAIT_OBJECTS];
   int n_handles, i, iPipes;
   fd_set sock_read, sock_write, sock_except;
   fd_set aread, awrite, aexcept;
@@ -127,12 +127,27 @@
       }
       else
       {
-        if (GetFileType ((HANDLE) i) == FILE_TYPE_PIPE)
-          hPipes[iPipes++] = (HANDLE) i;  /* Pipe */
+
+        HANDLE osfhandle = (HANDLE) _get_osfhandle(i);
+
+        /* Original code assumed that i itself would be a pipe,
+           this failed for stdin when run as subprocess under emacs, 
+           where the actual pipe would be the osfhandle. Handle 'old' case
+           here also, just in case. IOK 2009-04-15 */
+        if (GetFileType((HANDLE) i) == FILE_TYPE_PIPE) {
+          hPipes[iPipes] = (HANDLE) i;
+          pipe_slot_to_fd[iPipes] = i;
+          iPipes++;
+        } 
+        else if (GetFileType (osfhandle) == FILE_TYPE_PIPE) {
+          hPipes[iPipes] = osfhandle;  /* Pipe */
+          pipe_slot_to_fd[iPipes] = i;
+          iPipes++;
+        }
         else
         {
-          handles[n_handles] = (HANDLE) _get_osfhandle(i);
-          if ((DWORD) handles[n_handles] == 0xffffffff)
+          handles[n_handles] = osfhandle;
+          if ((DWORD) osfhandle == 0xffffffff)
             handles[n_handles] = (HANDLE) i;
           handle_slot_to_fd[n_handles] = i;
           n_handles++;
@@ -224,7 +239,7 @@
     for(i = 0; i < iPipes; i++)
     {
       DWORD dwBytes;
-      if(SAFE_FD_ISSET(hPipes[i], rfds))
+      if(SAFE_FD_ISSET(pipe_slot_to_fd[i], rfds))
       {
 	    if (! PeekNamedPipe(hPipes[i], NULL, 0, NULL, &dwBytes, NULL))
 	    {
@@ -233,11 +248,11 @@
 	    }
 	    else if (dwBytes)
 	    {
-	      FD_SET((int) hPipes[i], &aread);
+	      FD_SET((int) pipe_slot_to_fd[i], &aread);
 	      retcode++;
 	    }
       }
-      else if (SAFE_FD_ISSET(hPipes[i], wfds) || SAFE_FD_ISSET(hPipes[i], efds))
+      else if (SAFE_FD_ISSET(pipe_slot_to_fd[i], wfds) || SAFE_FD_ISSET(pipe_slot_to_fd[i], efds))
       {
         errno = ENOSYS;
         return -1;  /* Not implemented */
