diff src/process-unix.c @ 853:2b6fa2618f76

[xemacs-hg @ 2002-05-28 08:44:22 by ben] merge my stderr-proc ws make-docfile.c: Fix places where we forget to check for EOF. code-init.el: Don't use CRLF conversion by default on process output. CMD.EXE and friends work both ways but Cygwin programs don't like the CRs. code-process.el, multicast.el, process.el: Removed. Improvements to call-process-internal: -- allows a buffer to be specified for input and stderr output -- use it on all systems -- implement C-g as documented -- clean up and comment call-process-region uses new call-process facilities; no temp file. remove duplicate funs in process.el. comment exactly how coding systems work and fix various problems. open-multicast-group now does similar coding-system frobbing to open-network-stream. dumped-lisp.el, faces.el, msw-faces.el: Fix some hidden errors due to code not being defined at the right time. xemacs.mak: Add -DSTRICT. ================================================================ ALLOW SEPARATION OF STDOUT AND STDERR IN PROCESSES ================================================================ Standard output and standard error can be processed separately in a process. Each can have its own buffer, its own mark in that buffer, and its filter function. You can specify a separate buffer for stderr in `start-process' to get things started, or use the new primitives: set-process-stderr-buffer process-stderr-buffer process-stderr-mark set-process-stderr-filter process-stderr-filter Also, process-send-region takes a 4th optional arg, a buffer. Currently always uses a pipe() under Unix to read the error output. (#### Would a PTY be better?) sysdep.h, sysproc.h, unexfreebsd.c, unexsunos4.c, nt.c, emacs.c, callproc.c, symsinit.h, sysdep.c, Makefile.in.in, process-unix.c: Delete callproc.c. Move child_setup() to process-unix.c. wait_for_termination() now only needed on a few really old systems. console-msw.h, event-Xt.c, event-msw.c, event-stream.c, event-tty.c, event-unixoid.c, events.h, process-nt.c, process-unix.c, process.c, process.h, procimpl.h: Rewrite the process methods to handle a separate channel for error input. Create Lstreams for reading in the error channel. Many process methods need change. In general the changes are fairly clear as they involve duplicating what's used for reading the normal stdout and changing for stderr -- although tedious, as such changes are required throughout the entire process code. Rewrote the code that reads process output to do two loops, one for stdout and one for stderr. gpmevent.c, tooltalk.c: set_process_filter takes an argument for stderr. ================================================================ NEW ERROR-TRAPPING MECHANISM ================================================================ Totally rewrite error trapping code to be unified and support more features. Basic function is call_trapping_problems(), which lets you specify, by means of flags, what sorts of problems you want trapped. these can include -- quit -- errors -- throws past the function -- creation of "display objects" (e.g. buffers) -- deletion of already-existing "display objects" (e.g. buffers) -- modification of already-existing buffers -- entering the debugger -- gc -- errors->warnings (ala suspended errors) etc. All other error funs rewritten in terms of this one. Various older mechanisms removed or rewritten. window.c, insdel.c, console.c, buffer.c, device.c, frame.c: When creating a display object, added call to note_object_created(), for use with trapping_problems mechanism. When deleting, call check_allowed_operation() and note_object deleted(). The trapping-problems code records the objects created since the call-trapping-problems began. Those objects can be deleted, but none others (i.e. previously existing ones). bytecode.c, cmdloop.c: internal_catch takes another arg. eval.c: Add long comments describing the "five lists" used to maintain state (backtrace, gcpro, specbind, etc.) in the Lisp engine. backtrace.h, eval.c: Implement trapping-problems mechanism, eliminate old mechanisms or redo in terms of new one. frame.c, gutter.c: Flush out the concept of "critical display section", defined by the in_display() var. Use an internal_bind() to get it reset, rather than just doing it at end, because there may be a non-local exit. event-msw.c, event-stream.c, console-msw.h, device.c, dialog-msw.c, frame.c, frame.h, intl.c, toolbar.c, menubar-msw.c, redisplay.c, alloc.c, menubar-x.c: Make use of new trapping-errors stuff and rewrite code based on old mechanisms. glyphs-widget.c, redisplay.h: Protect calling Lisp in redisplay. insdel.c: Protect hooks against deleting existing buffers. frame-msw.c: Use EQ, not EQUAL in hash tables whose keys are just numbers. Otherwise we run into stickiness in redisplay because internal_equal() can QUIT. ================================================================ SIGNAL, C-G CHANGES ================================================================ Here we change the way that C-g interacts with event reading. The idea is that a C-g occurring while we're reading a user event should be read as C-g, but elsewhere should be a QUIT. The former code did all sorts of bizarreness -- requiring that no QUIT occurs anywhere in event-reading code (impossible to enforce given the stuff called or Lisp code invoked), and having some weird system involving enqueue/dequeue of a C-g and interaction with Vquit_flag -- and it didn't work. Now, we simply enclose all code where we want C-g read as an event with {begin/end}_dont_check_for_quit(). This completely turns off the mechanism that checks (and may remove or alter) C-g in the read-ahead queues, so we just get the C-g normal. Signal.c documents this very carefully. cmdloop.c: Correct use of dont_check_for_quit to new scheme, remove old out-of-date comments. event-stream.c: Fix C-g handling to actually work. device-x.c: Disable quit checking when err out. signal.c: Cleanup. Add large descriptive comment. process-unix.c, process-nt.c, sysdep.c: Use QUIT instead of REALLY_QUIT. It's not necessary to use REALLY_QUIT and just confuses the issue. lisp.h: Comment quit handlers. ================================================================ CONS CHANGES ================================================================ free_cons() now takes a Lisp_Object not the result of XCONS(). car and cdr have been renamed so that they don't get used directly; go through XCAR(), XCDR() instead. alloc.c, dired.c, editfns.c, emodules.c, fns.c, glyphs-msw.c, glyphs-x.c, glyphs.c, keymap.c, minibuf.c, search.c, eval.c, lread.c, lisp.h: Correct free_cons calling convention: now takes Lisp_Object, not Lisp_Cons chartab.c: Eliminate direct use of ->car, ->cdr, should be black box. callint.c: Rewrote using EXTERNAL_LIST_LOOP to avoid use of Lisp_Cons. ================================================================ USE INTERNAL-BIND-* ================================================================ eval.c: Cleanups of these funs. alloc.c, fileio.c, undo.c, specifier.c, text.c, profile.c, lread.c, redisplay.c, menubar-x.c, macros.c: Rewrote to use internal_bind_int() and internal_bind_lisp_object() in place of whatever varied and cumbersome mechanisms were formerly there. ================================================================ SPECBIND SANITY ================================================================ backtrace.h: - Improved comments backtrace.h, bytecode.c, eval.c: Add new mechanism check_specbind_stack_sanity() for sanity checking code each time the catchlist or specbind stack change. Removed older prototype of same mechanism. ================================================================ MISC ================================================================ lisp.h, insdel.c, window.c, device.c, console.c, buffer.c: Fleshed out authorship. device-msw.c: Correct bad Unicode-ization. print.c: Be more careful when not initialized or in fatal error handling. search.c: Eliminate running_asynch_code, an FSF holdover. alloc.c: Added comments about gc-cons-threshold. dialog-x.c: Use begin_gc_forbidden() around code to build up a widget value tree, like in menubar-x.c. gui.c: Use Qunbound not Qnil as the default for gethash. lisp-disunion.h, lisp-union.h: Added warnings on use of VOID_TO_LISP(). lisp.h: Use ERROR_CHECK_STRUCTURES to turn on ERROR_CHECK_TRAPPING_PROBLEMS and ERROR_CHECK_TYPECHECK lisp.h: Add assert_with_message. lisp.h: Add macros for gcproing entire arrays. (You could do this before but it required manual twiddling the gcpro structure.) lisp.h: Add prototypes for new functions defined elsewhere.
author ben
date Tue, 28 May 2002 08:45:36 +0000
parents 6728e641994e
children 1d8fb2eee1bb
line wrap: on
line diff
--- a/src/process-unix.c	Sat May 25 01:55:30 2002 +0000
+++ b/src/process-unix.c	Tue May 28 08:45:36 2002 +0000
@@ -51,6 +51,7 @@
 #include "file-coding.h"
 
 #include <setjmp.h>
+#include "sysdir.h"
 #include "sysfile.h"
 #include "sysproc.h"
 #include "systime.h"
@@ -77,6 +78,9 @@
   int connected_via_filedesc_p;
   /* Descriptor by which we read from this process.  -1 for dead process */
   int infd;
+  /* Descriptor by which we read stderr from this process.  -1 for
+     dead process */
+  int errfd;
   /* Descriptor for the tty which this process is using.
      -1 if we didn't record it (on some systems, there's no need).  */
   int subtty;
@@ -86,7 +90,7 @@
   char pty_flag;
 };
 
-#define UNIX_DATA(p) ((struct unix_process_data*)((p)->process_data))
+#define UNIX_DATA(p) ((struct unix_process_data*) ((p)->process_data))
 
 
 
@@ -126,17 +130,18 @@
    to get rid of irrelevant descriptors.  */
 
 static int
-close_process_descs_mapfun (const void* key, void* contents, void* arg)
+close_process_descs_mapfun (const void *key, void *contents, void *arg)
 {
-  Lisp_Object proc;
-  proc = VOID_TO_LISP (contents);
-  event_stream_delete_stream_pair (XPROCESS(proc)->pipe_instream,
-				   XPROCESS(proc)->pipe_outstream);
+  Lisp_Object proc = VOID_TO_LISP (contents);
+  USID vaffan, culo;
+
+  event_stream_delete_io_streams (XPROCESS (proc)->pipe_instream,
+				  XPROCESS (proc)->pipe_outstream,
+				  XPROCESS (proc)->pipe_errstream,
+				  &vaffan, &culo);
   return 0;
 }
 
-/* #### This function is currently called from child_setup
-   in callproc.c. It should become static though - kkm */
 void
 close_process_descs (void)
 {
@@ -186,11 +191,11 @@
 
   XPROCESS (proc)->pid = Fcons (infd, name);
   XPROCESS (proc)->buffer = buffer;
-  init_process_io_handles (XPROCESS (proc), (void*)inch, (void*)XINT (outfd),
-			   0);
+  init_process_io_handles (XPROCESS (proc), (void *) inch,
+			   (void *) XINT (outfd), (void *) -1, 0);
   UNIX_DATA (XPROCESS (proc))->connected_via_filedesc_p = 1;
 
-  event_stream_select_process (XPROCESS (proc));
+  event_stream_select_process (XPROCESS (proc), 1, 1);
 
   return proc;
 }
@@ -512,7 +517,7 @@
 #endif /* !USE_GETADDRINFO */
 
 static void
-set_socket_nonblocking_maybe (int fd, int port, const char* proto)
+set_socket_nonblocking_maybe (int fd, int port, const char *proto)
 {
 #ifdef PROCESS_IO_BLOCKING
   Lisp_Object tail;
@@ -720,17 +725,18 @@
 process_signal_char (int tty_fd, int signo)
 {
   /* If it's not a tty, pray that these default values work */
-  if (! isatty (tty_fd)) {
+  if (! isatty (tty_fd))
+    {
 #define CNTL(ch) (037 & (ch))
-    switch (signo)
-      {
-      case SIGINT:  return CNTL ('C');
-      case SIGQUIT: return CNTL ('\\');
+      switch (signo)
+	{
+	case SIGINT:  return CNTL ('C');
+	case SIGQUIT: return CNTL ('\\');
 #ifdef SIGTSTP
-      case SIGTSTP: return CNTL ('Z');
+	case SIGTSTP: return CNTL ('Z');
 #endif
-      }
-  }
+	}
+    }
 
 #ifdef HAVE_TERMIOS
   /* TERMIOS is the latest and bestest, and seems most likely to work.
@@ -805,6 +811,7 @@
 
   UNIX_DATA(p)->connected_via_filedesc_p = 0;
   UNIX_DATA(p)->infd   = -1;
+  UNIX_DATA(p)->errfd  = -1;
   UNIX_DATA(p)->subtty = -1;
   UNIX_DATA(p)->tty_name = Qnil;
   UNIX_DATA(p)->pty_flag = 0;
@@ -843,9 +850,197 @@
  */
 
 static void
-unix_init_process_io_handles (Lisp_Process *p, void* in, void* out, int flags)
+unix_init_process_io_handles (Lisp_Process *p, void *in, void *out, void *err,
+			      int flags)
+{
+  UNIX_DATA(p)->infd = (int) in;
+  UNIX_DATA(p)->errfd = (int) err;
+}
+
+/* Move the file descriptor FD so that its number is not less than MIN. *
+   The original file descriptor remains open.  */
+static int
+relocate_fd (int fd, int min)
+{
+  if (fd >= min)
+    return fd;
+  else
+    {
+      int newfd = dup (fd);
+      if (newfd == -1)
+	{
+	  Intbyte *errmess;
+	  GET_STRERROR (errmess, errno);
+	  stderr_out ("Error while setting up child: %s\n", errmess);
+	  _exit (1);
+	}
+      return relocate_fd (newfd, min);
+    }
+}
+
+/* This is the last thing run in a newly forked inferior process.
+   Copy descriptors IN, OUT and ERR
+   as descriptors STDIN_FILENO, STDOUT_FILENO, and STDERR_FILENO.
+   Initialize inferior's priority, pgrp, connected dir and environment.
+   then exec another program based on new_argv.
+
+   XEmacs: We've removed the SET_PGRP argument because it's already
+   done by the callers of child_setup.
+
+   CURRENT_DIR is an elisp string giving the path of the current
+   directory the subprocess should have.  Since we can't really signal
+   a decent error from within the child (#### not quite correct in
+   XEmacs?), this should be verified as an executable directory by the
+   parent.  */
+
+static void
+child_setup (int in, int out, int err, Intbyte **new_argv,
+	     Lisp_Object current_dir)
 {
-  UNIX_DATA(p)->infd = (int)in;
+  Intbyte **env;
+  Intbyte *pwd;
+
+#ifdef SET_EMACS_PRIORITY
+  if (emacs_priority != 0)
+    nice (- emacs_priority);
+#endif
+
+#if !defined (NO_SUBPROCESSES)
+  /* Close Emacs's descriptors that this process should not have.  */
+  close_process_descs ();
+#endif /* not NO_SUBPROCESSES */
+  close_load_descs ();
+
+  /* [[Note that use of alloca is always safe here.  It's obvious for systems
+     that do not have true vfork or that have true (stack) alloca.
+     If using vfork and C_ALLOCA it is safe because that changes
+     the superior's static variables as if the superior had done alloca
+     and will be cleaned up in the usual way.]] -- irrelevant because
+     XEmacs does not use vfork. */
+  {
+    REGISTER Bytecount i;
+
+    i = XSTRING_LENGTH (current_dir);
+    pwd = alloca_array (Intbyte, i + 6);
+    memcpy (pwd, "PWD=", 4);
+    memcpy (pwd + 4, XSTRING_DATA (current_dir), i);
+    i += 4;
+    if (!IS_DIRECTORY_SEP (pwd[i - 1]))
+      pwd[i++] = DIRECTORY_SEP;
+    pwd[i] = 0;
+
+    /* [[We can't signal an Elisp error here; we're in a vfork.  Since
+       the callers check the current directory before forking, this
+       should only return an error if the directory's permissions
+       are changed between the check and this chdir, but we should
+       at least check.]] -- irrelevant because XEmacs does not use vfork. */
+    if (qxe_chdir (pwd + 4) < 0)
+      {
+	/* Don't report the chdir error, or ange-ftp.el doesn't work. */
+	/* (FSFmacs does _exit (errno) here.) */
+	pwd = 0;
+      }
+    else
+      {
+	/* Strip trailing "/".  Cretinous *[]&@$#^%@#$% Un*x */
+	/* leave "//" (from FSF) */
+	while (i > 6 && IS_DIRECTORY_SEP (pwd[i - 1]))
+	  pwd[--i] = 0;
+      }
+  }
+
+  /* Set `env' to a vector of the strings in Vprocess_environment.  */
+  /* + 2 to include PWD and terminating 0.  */
+  env = alloca_array (Intbyte *, XINT (Flength (Vprocess_environment)) + 2);
+  {
+    REGISTER Lisp_Object tail;
+    Intbyte **new_env = env;
+
+    /* If we have a PWD envvar and we know the real current directory,
+       pass one down, but with corrected value.  */
+    if (pwd && egetenv ("PWD"))
+      *new_env++ = pwd;
+
+    /* Copy the Vprocess_environment strings into new_env.  */
+    for (tail = Vprocess_environment;
+	 CONSP (tail) && STRINGP (XCAR (tail));
+	 tail = XCDR (tail))
+      {
+      Intbyte **ep = env;
+      Intbyte *envvar = XSTRING_DATA (XCAR (tail));
+
+      /* See if envvar duplicates any string already in the env.
+	 If so, don't put it in.
+	 When an env var has multiple definitions,
+	 we keep the definition that comes first in process-environment.  */
+      for (; ep != new_env; ep++)
+	{
+	  Intbyte *p = *ep, *q = envvar;
+	  while (1)
+	    {
+	      if (*q == 0)
+		/* The string is malformed; might as well drop it.  */
+		goto duplicate;
+	      if (*q != *p)
+		break;
+	      if (*q == '=')
+		goto duplicate;
+	      p++, q++;
+	    }
+	}
+      if (pwd && !qxestrncmp ((Intbyte *) "PWD=", envvar, 4))
+	{
+	  *new_env++ = pwd;
+	  pwd = 0;
+	}
+      else
+        *new_env++ = envvar;
+
+    duplicate: ;
+    }
+
+    *new_env = 0;
+  }
+
+  /* Make sure that in, out, and err are not actually already in
+     descriptors zero, one, or two; this could happen if Emacs is
+     started with its standard in, out, or error closed, as might
+     happen under X.  */
+  in  = relocate_fd (in,  3);
+  out = relocate_fd (out, 3);
+  err = relocate_fd (err, 3);
+
+  /* Set the standard input/output channels of the new process.  */
+  retry_close (STDIN_FILENO);
+  retry_close (STDOUT_FILENO);
+  retry_close (STDERR_FILENO);
+
+  dup2 (in,  STDIN_FILENO);
+  dup2 (out, STDOUT_FILENO);
+  dup2 (err, STDERR_FILENO);
+
+  retry_close (in);
+  retry_close (out);
+  retry_close (err);
+
+  /* I can't think of any reason why child processes need any more
+     than the standard 3 file descriptors.  It would be cleaner to
+     close just the ones that need to be, but the following brute
+     force approach is certainly effective, and not too slow.
+
+     #### Who the hell added this?  We already close the descriptors
+     by using close_process_descs()!!! --ben */
+  {
+    int fd;
+    for (fd = 3; fd <= 64; fd++)
+      retry_close (fd);
+  }
+
+  /* we've wrapped execve; it translates its arguments */
+  qxe_execve (new_argv[0], new_argv, env);
+
+  stdout_out ("Can't exec program %s\n", new_argv[0]);
+  _exit (1);
 }
 
 /*
@@ -861,14 +1056,17 @@
 static int
 unix_create_process (Lisp_Process *p,
 		     Lisp_Object *argv, int nargv,
-		     Lisp_Object program, Lisp_Object cur_dir)
+		     Lisp_Object program, Lisp_Object cur_dir,
+		     int separate_err)
 {
   int pid;
   int inchannel  = -1;
   int outchannel = -1;
+  int errchannel = -1;
   /* Use volatile to protect variables from being clobbered by longjmp.  */
   volatile int forkin   = -1;
   volatile int forkout  = -1;
+  volatile int forkerr  = -1;
   volatile int pty_flag = 0;
 
   if (!NILP (Vprocess_connection_type))
@@ -887,24 +1085,34 @@
 #if !defined(USG)
       /* On USG systems it does not work to open the pty's tty here
 	 and then close and reopen it in the child.  */
-#ifdef O_NOCTTY
+# ifdef O_NOCTTY
       /* Don't let this terminal become our controlling terminal
 	 (in case we don't have one).  */
       forkout = forkin = qxe_open (pty_name,
 				   O_RDWR | O_NOCTTY | OPEN_BINARY, 0);
-#else
+# else
       forkout = forkin = qxe_open (pty_name, O_RDWR | OPEN_BINARY, 0);
-#endif
+# endif
       if (forkin < 0)
 	goto io_failure;
 #endif /* not USG */
-      UNIX_DATA(p)->pty_flag = pty_flag = 1;
+      UNIX_DATA (p)->pty_flag = pty_flag = 1;
     }
   else
     if (create_bidirectional_pipe (&inchannel, &outchannel,
 				   &forkin, &forkout) < 0)
       goto io_failure;
 
+  if (separate_err)
+    {
+      int sv[2];
+      
+      if (pipe (sv) < 0)
+	goto io_failure;
+      forkerr = sv[1];
+      errchannel = sv[0];
+    }
+      
 #if 0
   /* Replaced by close_process_descs */
   set_exclusive_use (inchannel);
@@ -912,13 +1120,16 @@
 #endif
 
   set_descriptor_non_blocking (inchannel);
+  if (errchannel >= 0)
+    set_descriptor_non_blocking (errchannel);
 
   /* Record this as an active process, with its channels.
      As a result, child_setup will close Emacs's side of the pipes.  */
-  init_process_io_handles (p, (void*)inchannel, (void*)outchannel,
+  init_process_io_handles (p, (void *) inchannel, (void *) outchannel,
+			   (void *) errchannel,
 			   pty_flag ? STREAM_PTY_FLUSHING : 0);
   /* Record the tty descriptor used in the subprocess.  */
-  UNIX_DATA(p)->subtty = forkin;
+  UNIX_DATA (p)->subtty = forkin;
 
   {
     pid = fork ();
@@ -927,6 +1138,7 @@
 	/**** Now we're in the child process ****/
 	int xforkin = forkin;
 	int xforkout = forkout;
+	int xforkerr = forkerr;
 
 	/* Disconnect the current controlling terminal, pursuant to
 	   making the pty be the controlling terminal of the process.
@@ -967,11 +1179,12 @@
 	    /* SunOS has TIOCSCTTY but the close/open method
 	       also works. */
 
-#  if defined (USG) || !defined (TIOCSCTTY)
+#if defined (USG) || !defined (TIOCSCTTY)
 	    /* Now close the pty (if we had it open) and reopen it.
 	       This makes the pty the controlling terminal of the
 	       subprocess.  */
-	    /* I wonder if retry_close (qxe_open (pty_name, ...)) would work?  */
+	    /* I wonder if retry_close (qxe_open (pty_name, ...)) would
+	       work?  */
 	    if (xforkin >= 0)
 	      retry_close (xforkin);
 	    xforkout = xforkin = qxe_open (pty_name, O_RDWR | OPEN_BINARY, 0);
@@ -982,20 +1195,20 @@
 		retry_write (1, "\n", 1);
 		_exit (1);
 	      }
-#  endif /* USG or not TIOCSCTTY */
+#endif /* USG or not TIOCSCTTY */
 
 	    /* Miscellaneous setup required for some systems.
                Must be done before using tc* functions on xforkin.
                This guarantees that isatty(xforkin) is true. */
 
-#  if defined (HAVE_ISASTREAM) && defined (I_PUSH)
+#if defined (HAVE_ISASTREAM) && defined (I_PUSH)
 	    if (isastream (xforkin))
 	      {
-#    if defined (I_FIND)
-#      define stream_module_pushed(fd, module) (ioctl (fd, I_FIND, module) == 1)
-#    else
-#      define stream_module_pushed(fd, module) 0
-#    endif
+# if defined (I_FIND)
+#  define stream_module_pushed(fd, module) (ioctl (fd, I_FIND, module) == 1)
+# else
+#  define stream_module_pushed(fd, module) 0
+# endif
 		if (! stream_module_pushed (xforkin, "ptem"))
 		  ioctl (xforkin, I_PUSH, "ptem");
 		if (! stream_module_pushed (xforkin, "ldterm"))
@@ -1003,18 +1216,18 @@
 		if (! stream_module_pushed (xforkin, "ttcompat"))
 		  ioctl (xforkin, I_PUSH, "ttcompat");
 	      }
-#  endif /* HAVE_ISASTREAM */
+#endif /* defined (HAVE_ISASTREAM) && defined (I_PUSH) */
 
-#  ifdef TIOCSCTTY
+#ifdef TIOCSCTTY
 	    /* We ignore the return value
 	       because faith@cs.unc.edu says that is necessary on Linux.  */
             assert (isatty (xforkin));
 	    ioctl (xforkin, TIOCSCTTY, 0);
-#  endif /* TIOCSCTTY */
+#endif /* TIOCSCTTY */
 
 	    /* Change the line discipline. */
 
-# if defined (HAVE_TERMIOS) && defined (LDISC1)
+#if defined (HAVE_TERMIOS) && defined (LDISC1)
 	    {
 	      struct termios t;
               assert (isatty (xforkin));
@@ -1023,7 +1236,7 @@
 	      if (tcsetattr (xforkin, TCSANOW, &t) < 0)
 		perror ("create_process/tcsetattr LDISC1 failed\n");
 	    }
-# elif defined (NTTYDISC) && defined (TIOCSETD)
+#elif defined (NTTYDISC) && defined (TIOCSETD)
 	    {
 	      /* Use new line discipline.  TIOCSETD is accepted and
                  ignored on Sys5.4 systems with ttcompat. */
@@ -1031,7 +1244,7 @@
               assert (isatty (xforkin));
 	      ioctl (xforkin, TIOCSETD, &ldisc);
 	    }
-# endif /* TIOCSETD & NTTYDISC */
+#endif /* TIOCSETD & NTTYDISC */
 
 	    /* Make our process group be the foreground group
 	       of our new controlling terminal. */
@@ -1071,7 +1284,8 @@
 	    }
 	  new_argv[i + 1] = 0;
 
-	  child_setup (xforkin, xforkout, xforkout, new_argv, cur_dir);
+	  child_setup (xforkin, xforkout, separate_err ? xforkerr : xforkout,
+		       new_argv, cur_dir);
 	}
 
       } /**** End of child code ****/
@@ -1081,15 +1295,20 @@
 
   if (pid < 0)
     {
+      /* Note: The caller set up an unwind-protect to automatically delete
+	 the process if we fail.  This will correctly deselect and close
+	 inchannel, outchannel, and errchannel. */
       int save_errno = errno;
       close_descriptor_pair (forkin, forkout);
+      if (separate_err)
+	retry_close (forkerr);
       errno = save_errno;
       report_process_error ("Doing fork", Qunbound);
     }
 
   /* #### dmoore - why is this commented out, otherwise we leave
      subtty = forkin, but then we close forkin just below. */
-  /* UNIX_DATA(p)->subtty = -1; */
+  /* UNIX_DATA (p)->subtty = -1; */
 
   /* If the subfork execv fails, and it exits,
      this close hangs.  I don't know why.
@@ -1098,6 +1317,8 @@
     close_safely (forkin);
   if (forkin != forkout && forkout >= 0)
     retry_close (forkout);
+  if (separate_err)
+    retry_close (forkerr);
 
   UNIX_DATA (p)->tty_name = pty_flag ? build_intstring (pty_name) : Qnil;
 
@@ -1108,11 +1329,12 @@
      we're waiting for an event, when status_notify() is called). */
   return pid;
 
-io_failure:
+ io_failure:
   {
     int save_errno = errno;
     close_descriptor_pair (forkin, forkout);
     close_descriptor_pair (inchannel, outchannel);
+    close_descriptor_pair (forkerr, errchannel);
     errno = save_errno;
     report_process_error ("Opening pty or pipe", Qunbound);
     RETURN_NOT_REACHED (0)
@@ -1124,15 +1346,15 @@
 static int
 unix_tooltalk_connection_p (Lisp_Process *p)
 {
-  return UNIX_DATA(p)->connected_via_filedesc_p;
+  return UNIX_DATA (p)->connected_via_filedesc_p;
 }
 
 /* This is called to set process' virtual terminal size */
 
 static int
-unix_set_window_size (Lisp_Process* p, int cols, int rows)
+unix_set_window_size (Lisp_Process *p, int cols, int rows)
 {
-  return set_window_size (UNIX_DATA(p)->infd, cols, rows);
+  return set_window_size (UNIX_DATA (p)->infd, cols, rows);
 }
 
 /*
@@ -1145,7 +1367,7 @@
 
 #ifdef HAVE_WAITPID
 static void
-unix_update_status_if_terminated (Lisp_Process* p)
+unix_update_status_if_terminated (Lisp_Process *p)
 {
   int w;
 #ifdef SIGCHLD
@@ -1182,7 +1404,7 @@
       return;
     }
 
-#ifdef  EMACS_BLOCK_SIGNAL
+#ifdef EMACS_BLOCK_SIGNAL
   EMACS_BLOCK_SIGNAL (SIGCHLD);
 #endif
   for (i = 0; i < exited_processes_index; i++)
@@ -1215,7 +1437,7 @@
           /* If process has terminated, stop waiting for its output.  */
 	  if (WIFSIGNALED (w) || WIFEXITED (w))
 	    {
-	      if (!NILP(p->pipe_instream))
+	      if (!NILP (p->pipe_instream))
 		{
 		  /* We can't just call event_stream->unselect_process_cb (p)
 		     here, because that calls XtRemoveInput, which is not
@@ -1225,6 +1447,7 @@
 		}
 	    }
 	}
+#ifdef NEED_SYNC_PROCESS_CODE
       else
 	{
           /* There was no asynchronous process found for that id.  Check
@@ -1242,6 +1465,7 @@
 		synch_process_death = signal_name (WTERMSIG (w));
 	    }
         }
+#endif /* NEED_SYNC_PROCESS_CODE */
     }
 
   exited_processes_index = 0;
@@ -1265,7 +1489,7 @@
 }
 
 static void
-unix_send_process (Lisp_Object proc, struct lstream* lstream)
+unix_send_process (Lisp_Object proc, struct lstream *lstream)
 {
   /* Use volatile to protect variables from being clobbered by longjmp.  */
   SIGTYPE (*volatile old_sigpipe) (int) = 0;
@@ -1381,31 +1605,34 @@
  * inactive state.
  *
  * The return value is a unique stream ID, as returned by
- * event_stream_delete_stream_pair
+ * event_stream_delete_io_streams
  *
- * In the lack of this method, only event_stream_delete_stream_pair
+ * In the lack of this method, only event_stream_delete_io_streams
  * is called on both I/O streams of the process.
  *
  * The UNIX version guards this by ignoring possible SIGPIPE.
  */
 
-static USID
-unix_deactivate_process (Lisp_Process *p)
+static void
+unix_deactivate_process (Lisp_Process *p,
+			 USID *in_usid,
+			 USID *err_usid)
 {
   SIGTYPE (*old_sigpipe) (int) = 0;
-  USID usid;
 
   if (UNIX_DATA(p)->infd >= 0)
     flush_pending_output (UNIX_DATA(p)->infd);
+  if (UNIX_DATA(p)->errfd >= 0)
+    flush_pending_output (UNIX_DATA(p)->errfd);
 
   /* closing the outstream could result in SIGPIPE, so ignore it. */
   old_sigpipe = (SIGTYPE (*) (int)) EMACS_SIGNAL (SIGPIPE, SIG_IGN);
-  usid = event_stream_delete_stream_pair (p->pipe_instream, p->pipe_outstream);
+  event_stream_delete_io_streams (p->pipe_instream, p->pipe_outstream,
+				  p->pipe_errstream, in_usid, err_usid);
   EMACS_SIGNAL (SIGPIPE, old_sigpipe);
 
   UNIX_DATA(p)->infd  = -1;
-
-  return usid;
+  UNIX_DATA(p)->errfd  = -1;
 }
 
 /* If the subtty field of the process data is not filled in, do so now. */
@@ -1456,6 +1683,7 @@
     case SIGQUIT:
     case SIGKILL:
       flush_pending_output (d->infd);
+      flush_pending_output (d->errfd);
       break;
     }
 
@@ -1504,10 +1732,10 @@
       /* If possible, send signals to the entire pgrp
 	 by sending an input character to it.  */
       {
-        char sigchar = process_signal_char (d->subtty, signo);
+        Intbyte sigchar = process_signal_char (d->subtty, signo);
         if (sigchar)
 	  {
-	    send_process (proc, Qnil, (Intbyte *) &sigchar, 0, 1);
+	    send_process (proc, Qnil, &sigchar, 0, 1);
 	    return;
 	  }
       }
@@ -1785,7 +2013,7 @@
 #ifdef CONNECT_NEEDS_SLOWED_INTERRUPTS
 	    speed_up_interrupts ();
 #endif
-	    REALLY_QUIT;
+	    QUIT;
 	    /* In case something really weird happens ... */
 #ifdef CONNECT_NEEDS_SLOWED_INTERRUPTS
 	    slow_down_interrupts ();
@@ -1920,8 +2148,8 @@
 
 static void
 unix_open_multicast_group (Lisp_Object name, Lisp_Object dest,
-			   Lisp_Object port, Lisp_Object ttl, void** vinfd,
-			   void** voutfd)
+			   Lisp_Object port, Lisp_Object ttl, void **vinfd,
+			   void **voutfd)
 {
   struct ip_mreq imr;
   struct sockaddr_in sa;
@@ -2017,7 +2245,7 @@
 #ifdef CONNECT_NEEDS_SLOWED_INTERRUPTS
       speed_up_interrupts ();
 #endif
-      REALLY_QUIT;
+      QUIT;
       /* In case something really weird happens ... */
 #ifdef CONNECT_NEEDS_SLOWED_INTERRUPTS
       slow_down_interrupts ();