New unwind-protect flavors to better type-check C callbacks.
[bpt/emacs.git] / src / process.c
index 7ab651a..42a625b 100644 (file)
@@ -1,7 +1,7 @@
 /* Asynchronous subprocess control for GNU Emacs.
 
-Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2012
-  Free Software Foundation, Inc.
+Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2013 Free Software
+Foundation, Inc.
 
 This file is part of GNU Emacs.
 
@@ -78,7 +78,6 @@ along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
 #endif
 
 #ifdef HAVE_RES_INIT
-#include <netinet/in.h>
 #include <arpa/nameser.h>
 #include <resolv.h>
 #endif
@@ -124,8 +123,11 @@ along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
 #include TERM_HEADER
 #endif /* HAVE_WINDOW_SYSTEM */
 
-#if defined (USE_GTK) || defined (HAVE_GCONF) || defined (HAVE_GSETTINGS)
+#ifdef HAVE_GLIB
 #include "xgselect.h"
+#ifndef WINDOWSNT
+#include <glib.h>
+#endif
 #endif
 
 #ifdef WINDOWSNT
@@ -133,10 +135,41 @@ extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
                       EMACS_TIME *, void *);
 #endif
 
+#ifndef SOCK_CLOEXEC
+# define SOCK_CLOEXEC 0
+#endif
+
+#ifndef HAVE_ACCEPT4
+
+/* Emulate GNU/Linux accept4 and socket well enough for this module.  */
+
+static int
+close_on_exec (int fd)
+{
+  if (0 <= fd)
+    fcntl (fd, F_SETFD, FD_CLOEXEC);
+  return fd;
+}
+
+static int
+accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
+{
+  return close_on_exec (accept (sockfd, addr, addrlen));
+}
+
+static int
+process_socket (int domain, int type, int protocol)
+{
+  return close_on_exec (socket (domain, type, protocol));
+}
+# undef socket
+# define socket(domain, type, protocol) process_socket (domain, type, protocol)
+#endif
+
 /* Work around GCC 4.7.0 bug with strict overflow checking; see
    <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
    These lines can be removed once the GCC bug is fixed.  */
-#if (__GNUC__ == 4 && 3 <= __GNUC_MINOR__) || 4 < __GNUC__
+#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
 # pragma GCC diagnostic ignored "-Wstrict-overflow"
 #endif
 
@@ -146,13 +179,13 @@ Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
 Lisp_Object QCname, QCtype;
 \f
-/* Non-zero if keyboard input is on hold, zero otherwise.  */
+/* True if keyboard input is on hold, zero otherwise.  */
 
-static int kbd_is_on_hold;
+static bool kbd_is_on_hold;
 
 /* Nonzero means don't run process sentinels.  This is used
    when exiting.  */
-int inhibit_sentinels;
+bool inhibit_sentinels;
 
 #ifdef subprocesses
 
@@ -174,16 +207,14 @@ static Lisp_Object QClocal, QCremote, QCcoding;
 static Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
 static Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
 static Lisp_Object Qlast_nonmenu_event;
+static Lisp_Object Qinternal_default_process_sentinel;
+static Lisp_Object Qinternal_default_process_filter;
 
 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
 
-#ifndef HAVE_H_ERRNO
-extern int h_errno;
-#endif
-
 /* Number of events of change of status of a process.  */
 static EMACS_INT process_tick;
 /* Number of events for which the user or sentinel has been notified.  */
@@ -238,9 +269,9 @@ static EMACS_INT update_tick;
 
 static int process_output_delay_count;
 
-/* Non-zero if any process has non-nil read_output_skip.  */
+/* True if any process has non-nil read_output_skip.  */
 
-static int process_output_skip;
+static bool process_output_skip;
 
 #else
 #define process_output_delay_count 0
@@ -248,7 +279,7 @@ static int process_output_skip;
 
 static void create_process (Lisp_Object, char **, Lisp_Object);
 #ifdef USABLE_SIGIO
-static int keyboard_bit_set (SELECT_TYPE *);
+static bool keyboard_bit_set (SELECT_TYPE *);
 #endif
 static void deactivate_process (Lisp_Object);
 static void status_notify (struct Lisp_Process *);
@@ -363,7 +394,7 @@ pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
 static void
 pset_filter (struct Lisp_Process *p, Lisp_Object val)
 {
-  p->filter = val;
+  p->filter = NILP (val) ? Qinternal_default_process_filter : val;
 }
 static void
 pset_log (struct Lisp_Process *p, Lisp_Object val)
@@ -388,7 +419,7 @@ pset_plist (struct Lisp_Process *p, Lisp_Object val)
 static void
 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
 {
-  p->sentinel = val;
+  p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
 }
 static void
 pset_status (struct Lisp_Process *p, Lisp_Object val)
@@ -531,7 +562,7 @@ status_convert (int w)
    and store them individually through the three pointers.  */
 
 static void
-decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, int *coredump)
+decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
 {
   Lisp_Object tem;
 
@@ -558,7 +589,8 @@ status_message (struct Lisp_Process *p)
 {
   Lisp_Object status = p->status;
   Lisp_Object symbol;
-  int code, coredump;
+  int code;
+  bool coredump;
   Lisp_Object string, string2;
 
   decode_status (status, &symbol, &code, &coredump);
@@ -703,6 +735,8 @@ make_process (Lisp_Object name)
     }
   name = name1;
   pset_name (p, name);
+  pset_sentinel (p, Qinternal_default_process_sentinel);
+  pset_filter (p, Qinternal_default_process_filter);
   XSETPROCESS (val, p);
   Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
   return val;
@@ -807,7 +841,7 @@ nil, indicating the current buffer's process.  */)
   p->raw_status_new = 0;
   if (NETCONN1_P (p) || SERIALCONN1_P (p))
     {
-      pset_status (p, Fcons (Qexit, Fcons (make_number (0), Qnil)));
+      pset_status (p, list2 (Qexit, make_number (0)));
       p->tick = ++process_tick;
       status_notify (p);
       redisplay_preserve_echo_area (13);
@@ -982,10 +1016,10 @@ DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
 
 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
        2, 2, 0,
-       doc: /* Give PROCESS the filter function FILTER; nil means no filter.
+       doc: /* Give PROCESS the filter function FILTER; nil means default.
 A value of t means stop accepting output from the process.
 
-When a process has a filter, its buffer is not used for output.
+When a process has a non-default filter, its buffer is not used for output.
 Instead, each time it does output, the entire string of output is
 passed to the filter.
 
@@ -1011,6 +1045,9 @@ The string argument is normally a multibyte string, except:
      (debug)
      (set-process-filter process ...)  */
 
+  if (NILP (filter))
+    filter = Qinternal_default_process_filter;
+
   if (p->infd >= 0)
     {
       if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
@@ -1036,7 +1073,7 @@ The string argument is normally a multibyte string, except:
 
 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
        1, 1, 0,
-       doc: /* Returns the filter function of PROCESS; nil if none.
+       doc: /* Return the filter function of PROCESS.
 See `set-process-filter' for more info on filter functions.  */)
   (register Lisp_Object process)
 {
@@ -1046,7 +1083,7 @@ See `set-process-filter' for more info on filter functions.  */)
 
 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
        2, 2, 0,
-       doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
+       doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
 The sentinel is called as a function when the process changes state.
 It gets two arguments: the process, and a string describing the change.  */)
   (register Lisp_Object process, Lisp_Object sentinel)
@@ -1056,6 +1093,9 @@ It gets two arguments: the process, and a string describing the change.  */)
   CHECK_PROCESS (process);
   p = XPROCESS (process);
 
+  if (NILP (sentinel))
+    sentinel = Qinternal_default_process_sentinel;
+
   pset_sentinel (p, sentinel);
   if (NETCONN1_P (p) || SERIALCONN1_P (p))
     pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
@@ -1064,7 +1104,7 @@ It gets two arguments: the process, and a string describing the change.  */)
 
 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
        1, 1, 0,
-       doc: /* Return the sentinel of PROCESS; nil if none.
+       doc: /* Return the sentinel of PROCESS.
 See `set-process-sentinel' for more info on sentinels.  */)
   (register Lisp_Object process)
 {
@@ -1166,11 +1206,11 @@ list of keywords.  */)
   if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
     return contact;
   if (NILP (key) && NETCONN_P (process))
-    return Fcons (Fplist_get (contact, QChost),
-                 Fcons (Fplist_get (contact, QCservice), Qnil));
+    return list2 (Fplist_get (contact, QChost),
+                 Fplist_get (contact, QCservice));
   if (NILP (key) && SERIALCONN_P (process))
-    return Fcons (Fplist_get (contact, QCport),
-                 Fcons (Fplist_get (contact, QCspeed), Qnil));
+    return list2 (Fplist_get (contact, QCport),
+                 Fplist_get (contact, QCspeed));
   return Fplist_get (contact, key);
 }
 
@@ -1301,7 +1341,7 @@ DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
 \f
 /* Starting asynchronous inferior processes.  */
 
-static Lisp_Object start_process_unwind (Lisp_Object proc);
+static void start_process_unwind (Lisp_Object proc);
 
 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
        doc: /* Start a program in a subprocess.  Return the process object for it.
@@ -1357,7 +1397,7 @@ usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS)  */)
     current_dir = expand_and_dir_to_file (current_dir, Qnil);
     if (NILP (Ffile_accessible_directory_p (current_dir)))
       report_file_error ("Setting current directory",
-                        Fcons (BVAR (current_buffer, directory), Qnil));
+                        BVAR (current_buffer, directory));
 
     UNGCPRO;
   }
@@ -1381,8 +1421,8 @@ usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS)  */)
   pset_plist (XPROCESS (proc), Qnil);
   pset_type (XPROCESS (proc), Qreal);
   pset_buffer (XPROCESS (proc), buffer);
-  pset_sentinel (XPROCESS (proc), Qnil);
-  pset_filter (XPROCESS (proc), Qnil);
+  pset_sentinel (XPROCESS (proc), Qinternal_default_process_sentinel);
+  pset_filter (XPROCESS (proc), Qinternal_default_process_filter);
   pset_command (XPROCESS (proc), Flist (nargs - 2, args + 2));
 
 #ifdef HAVE_GNUTLS
@@ -1479,7 +1519,7 @@ usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS)  */)
          openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
          UNGCPRO;
          if (NILP (tem))
-           report_file_error ("Searching for program", Fcons (program, Qnil));
+           report_file_error ("Searching for program", program);
          tem = Fexpand_file_name (tem, Qnil);
        }
       else
@@ -1502,7 +1542,7 @@ usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS)  */)
 
        /* Encode the file name and put it in NEW_ARGV.
           That's where the child will use it to execute the program.  */
-       tem = Fcons (ENCODE_FILE (tem), Qnil);
+       tem = list1 (ENCODE_FILE (tem));
 
        /* Here we encode arguments by the coding system used for sending
           data to the process.  We don't support using different coding
@@ -1550,7 +1590,7 @@ usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS)  */)
    PROC doesn't have its pid set, then we know someone has signaled
    an error and the process wasn't started successfully, so we should
    remove it from the process list.  */
-static Lisp_Object
+static void
 start_process_unwind (Lisp_Object proc)
 {
   if (!PROCESSP (proc))
@@ -1560,8 +1600,6 @@ start_process_unwind (Lisp_Object proc)
      -2 is used for a pty with no process, eg for gdb.  */
   if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
     remove_process (proc);
-
-  return Qnil;
 }
 
 static void
@@ -1576,16 +1614,15 @@ create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
 {
   int inchannel, outchannel;
   pid_t pid;
+  int vfork_errno;
   int sv[2];
 #ifndef WINDOWSNT
   int wait_child_setup[2];
 #endif
-  sigset_t blocked;
-  /* Use volatile to protect variables from being clobbered by vfork.  */
-  volatile int forkin, forkout;
-  volatile int pty_flag = 0;
-  volatile Lisp_Object lisp_pty_name = Qnil;
-  volatile Lisp_Object encoded_current_dir;
+  int forkin, forkout;
+  bool pty_flag = 0;
+  Lisp_Object lisp_pty_name = Qnil;
+  Lisp_Object encoded_current_dir;
 
   inchannel = outchannel = -1;
 
@@ -1612,47 +1649,30 @@ create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
   else
 #endif /* HAVE_PTYS */
     {
-      int tem;
-      tem = pipe (sv);
-      if (tem < 0)
+      if (emacs_pipe (sv) != 0)
        report_file_error ("Creating pipe", Qnil);
       inchannel = sv[0];
       forkout = sv[1];
-      tem = pipe (sv);
-      if (tem < 0)
+      if (emacs_pipe (sv) != 0)
        {
+         int pipe_errno = errno;
          emacs_close (inchannel);
          emacs_close (forkout);
-         report_file_error ("Creating pipe", Qnil);
+         report_file_errno ("Creating pipe", Qnil, pipe_errno);
        }
       outchannel = sv[1];
       forkin = sv[0];
     }
 
 #ifndef WINDOWSNT
-    {
-      int tem;
-
-      tem = pipe (wait_child_setup);
-      if (tem < 0)
-       report_file_error ("Creating pipe", Qnil);
-      tem = fcntl (wait_child_setup[1], F_GETFD, 0);
-      if (tem >= 0)
-       tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
-      if (tem < 0)
-       {
-         emacs_close (wait_child_setup[0]);
-         emacs_close (wait_child_setup[1]);
-         report_file_error ("Setting file descriptor flags", Qnil);
-       }
-    }
+  if (emacs_pipe (wait_child_setup) != 0)
+    report_file_error ("Creating pipe", Qnil);
 #endif
 
   fcntl (inchannel, F_SETFL, O_NONBLOCK);
   fcntl (outchannel, F_SETFL, O_NONBLOCK);
 
-  /* Record this as an active process, with its channels.
-     As a result, child_setup will close Emacs's side of the pipes.  */
+  /* Record this as an active process, with its channels.  */
   chan_process[inchannel] = process;
   XPROCESS (process)->infd = inchannel;
   XPROCESS (process)->outfd = outchannel;
@@ -1676,15 +1696,34 @@ create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
   encoded_current_dir = ENCODE_FILE (current_dir);
 
   block_input ();
-
-  /* Block SIGCHLD until we have a chance to store the new fork's
-     pid in its process structure.  */
-  sigemptyset (&blocked);
-  sigaddset (&blocked, SIGCHLD);
-  pthread_sigmask (SIG_BLOCK, &blocked, 0);
+  block_child_signal ();
 
 #ifndef WINDOWSNT
-  pid = vfork ();
+  /* vfork, and prevent local vars from being clobbered by the vfork.  */
+  {
+    Lisp_Object volatile encoded_current_dir_volatile = encoded_current_dir;
+    Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
+    Lisp_Object volatile process_volatile = process;
+    bool volatile pty_flag_volatile = pty_flag;
+    char **volatile new_argv_volatile = new_argv;
+    int volatile forkin_volatile = forkin;
+    int volatile forkout_volatile = forkout;
+    int volatile wait_child_setup_0_volatile = wait_child_setup[0];
+    int volatile wait_child_setup_1_volatile = wait_child_setup[1];
+
+    pid = vfork ();
+
+    encoded_current_dir = encoded_current_dir_volatile;
+    lisp_pty_name = lisp_pty_name_volatile;
+    process = process_volatile;
+    pty_flag = pty_flag_volatile;
+    new_argv = new_argv_volatile;
+    forkin = forkin_volatile;
+    forkout = forkout_volatile;
+    wait_child_setup[0] = wait_child_setup_0_volatile;
+    wait_child_setup[1] = wait_child_setup_1_volatile;
+  }
+
   if (pid == 0)
 #endif /* not WINDOWSNT */
     {
@@ -1713,7 +1752,7 @@ create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
          tcgetattr (xforkin, &t);
          t.c_lflag = LDISC1;
          if (tcsetattr (xforkin, TCSANOW, &t) < 0)
-           emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
+           emacs_perror ("create_process/tcsetattr LDISC1");
        }
 #else
 #if defined (NTTYDISC) && defined (TIOCSETD)
@@ -1760,10 +1799,8 @@ create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
 
          if (xforkin < 0)
            {
-             emacs_write (1, "Couldn't open the pty terminal ", 31);
-             emacs_write (1, pty_name, strlen (pty_name));
-             emacs_write (1, "\n", 1);
-             _exit (1);
+             emacs_perror (pty_name);
+             _exit (EXIT_CANCELED);
            }
 
        }
@@ -1775,12 +1812,6 @@ create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
          SETUP_SLAVE_PTY;
        }
 #endif /* SETUP_SLAVE_PTY */
-#ifdef AIX
-      /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
-        Now reenable it in the child, so it will die when we want it to.  */
-      if (pty_flag)
-       signal (SIGHUP, SIG_DFL);
-#endif
 #endif /* HAVE_PTYS */
 
       signal (SIGINT, SIG_DFL);
@@ -1789,8 +1820,8 @@ create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
       /* Emacs ignores SIGPIPE, but the child should not.  */
       signal (SIGPIPE, SIG_DFL);
 
-       /* Stop blocking signals in the child.  */
-      pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
+      /* Stop blocking SIGCHLD in the child.  */
+      unblock_child_signal ();
 
       if (pty_flag)
        child_setup_tty (xforkout);
@@ -1798,7 +1829,6 @@ create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
       pid = child_setup (xforkin, xforkout, xforkout,
                         new_argv, 1, encoded_current_dir);
 #else  /* not WINDOWSNT */
-      emacs_close (wait_child_setup[0]);
       child_setup (xforkin, xforkout, xforkout,
                   new_argv, 1, encoded_current_dir);
 #endif /* not WINDOWSNT */
@@ -1806,12 +1836,13 @@ create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
 
   /* Back in the parent process.  */
 
+  vfork_errno = errno;
   XPROCESS (process)->pid = pid;
-  if (0 <= pid)
+  if (pid >= 0)
     XPROCESS (process)->alive = 1;
 
-  /* Stop blocking signals in the parent.  */
-  pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
+  /* Stop blocking in the parent.  */
+  unblock_child_signal ();
   unblock_input ();
 
   if (pid < 0)
@@ -1820,6 +1851,7 @@ create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
        emacs_close (forkin);
       if (forkin != forkout && forkout >= 0)
        emacs_close (forkout);
+      report_file_errno ("Doing vfork", Qnil, vfork_errno);
     }
   else
     {
@@ -1865,17 +1897,13 @@ create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
       }
 #endif
     }
-
-  /* Now generate the error if vfork failed.  */
-  if (pid < 0)
-    report_file_error ("Doing vfork", Qnil);
 }
 
 void
 create_pty (Lisp_Object process)
 {
   int inchannel, outchannel;
-  int pty_flag = 0;
+  bool pty_flag = 0;
 
   inchannel = outchannel = -1;
 
@@ -2158,7 +2186,7 @@ Returns nil upon error setting address, ADDRESS otherwise.  */)
   channel = XPROCESS (process)->infd;
 
   len = get_lisp_to_sockaddr_size (address, &family);
-  if (datagram_address[channel].len != len)
+  if (len == 0 || datagram_address[channel].len != len)
     return Qnil;
   conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
   return address;
@@ -2293,8 +2321,7 @@ set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
     }
 
   if (ret < 0)
-    report_file_error ("Cannot set network option",
-                      Fcons (opt, Fcons (val, Qnil)));
+    report_file_error ("Cannot set network option", list2 (opt, val));
   return (1 << sopt->optbit);
 }
 
@@ -2426,16 +2453,6 @@ usage: (serial-process-configure &rest ARGS)  */)
   return Qnil;
 }
 
-/* Used by make-serial-process to recover from errors.  */
-static Lisp_Object
-make_serial_process_unwind (Lisp_Object proc)
-{
-  if (!PROCESSP (proc))
-    emacs_abort ();
-  remove_process (proc);
-  return Qnil;
-}
-
 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
        0, MANY, 0,
        doc: /* Create and return a serial port process.
@@ -2517,7 +2534,7 @@ usage:  (make-serial-process &rest ARGS)  */)
   struct gcpro gcpro1;
   Lisp_Object name, buffer;
   Lisp_Object tem, val;
-  ptrdiff_t specpdl_count = -1;
+  ptrdiff_t specpdl_count;
 
   if (nargs == 0)
     return Qnil;
@@ -2541,10 +2558,10 @@ usage:  (make-serial-process &rest ARGS)  */)
   CHECK_STRING (name);
   proc = make_process (name);
   specpdl_count = SPECPDL_INDEX ();
-  record_unwind_protect (make_serial_process_unwind, proc);
+  record_unwind_protect (remove_process, proc);
   p = XPROCESS (proc);
 
-  fd = serial_open (SSDATA (port));
+  fd = serial_open (port);
   p->infd = fd;
   p->outfd = fd;
   if (fd > max_process_desc)
@@ -2823,8 +2840,9 @@ usage: (make-network-process &rest ARGS)  */)
   Lisp_Object tem;
   Lisp_Object name, buffer, host, service, address;
   Lisp_Object filter, sentinel;
-  int is_non_blocking_client = 0;
-  int is_server = 0, backlog = 5;
+  bool is_non_blocking_client = 0;
+  bool is_server = 0;
+  int backlog = 5;
   int socktype;
   int family = -1;
 
@@ -2976,7 +2994,7 @@ usage: (make-network-process &rest ARGS)  */)
 #ifdef POLL_FOR_INPUT
   if (socktype != SOCK_DGRAM)
     {
-      record_unwind_protect (unwind_stop_other_atimers, Qnil);
+      record_unwind_protect_void (run_all_atimers);
       bind_polling_period (10);
     }
 #endif
@@ -3108,7 +3126,8 @@ usage: (make-network-process &rest ARGS)  */)
     retry_connect:
 #endif
 
-      s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
+      s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
+                 lres->ai_protocol);
       if (s < 0)
        {
          xerrno = errno;
@@ -3135,7 +3154,7 @@ usage: (make-network-process &rest ARGS)  */)
 #endif
 
       /* Make us close S if quit.  */
-      record_unwind_protect (close_file_unwind, make_number (s));
+      record_unwind_protect_int (close_file_unwind, s);
 
       /* Parse network options in the arg list.
         We simply ignore anything which isn't a known option (including other keywords).
@@ -3226,18 +3245,17 @@ usage: (make-network-process &rest ARGS)  */)
              if (errno == EINTR)
                goto retry_select;
              else
-               report_file_error ("select failed", Qnil);
+               report_file_error ("Failed select", Qnil);
            }
          eassert (sc > 0);
 
          len = sizeof xerrno;
          eassert (FD_ISSET (s, &fdset));
-         if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
-           report_file_error ("getsockopt failed", Qnil);
+         if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
+           report_file_error ("Failed getsockopt", Qnil);
          if (xerrno)
-           errno = xerrno, report_file_error ("error during connect", Qnil);
-         else
-           break;
+           report_file_errno ("Failed connect", Qnil, xerrno);
+         break;
        }
 #endif /* !WINDOWSNT */
 
@@ -3271,7 +3289,8 @@ usage: (make-network-process &rest ARGS)  */)
                {
                  int rfamily, rlen;
                  rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
-                 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
+                 if (rlen != 0 && rfamily == lres->ai_family
+                     && rlen == lres->ai_addrlen)
                    conv_lisp_to_sockaddr (rfamily, remote,
                                           datagram_address[s].sa, rlen);
                }
@@ -3320,11 +3339,10 @@ usage: (make-network-process &rest ARGS)  */)
       if (is_non_blocking_client)
          return Qnil;
 
-      errno = xerrno;
-      if (is_server)
-       report_file_error ("make server process failed", contact);
-      else
-       report_file_error ("make client process failed", contact);
+      report_file_errno ((is_server
+                         ? "make server process failed"
+                         : "make client process failed"),
+                        contact, xerrno);
     }
 
   inch = s;
@@ -3501,10 +3519,10 @@ format; see the description of ADDRESS in `make-network-process'.  */)
   struct ifreq *ifreq;
   void *buf = NULL;
   ptrdiff_t buf_size = 512;
-  int s, i;
+  int s;
   Lisp_Object res;
 
-  s = socket (AF_INET, SOCK_STREAM, 0);
+  s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
   if (s < 0)
     return Qnil;
 
@@ -3515,14 +3533,14 @@ format; see the description of ADDRESS in `make-network-process'.  */)
       ifconf.ifc_len = buf_size;
       if (ioctl (s, SIOCGIFCONF, &ifconf))
        {
-         close (s);
+         emacs_close (s);
          xfree (buf);
          return Qnil;
        }
     }
   while (ifconf.ifc_len == buf_size);
 
-  close (s);
+  emacs_close (s);
 
   res = Qnil;
   ifreq = ifconf.ifc_req;
@@ -3539,7 +3557,6 @@ format; see the description of ADDRESS in `make-network-process'.  */)
       int len = sizeof (*ifreq);
 #endif
       char namebuf[sizeof (ifq->ifr_name) + 1];
-      i += len;
       ifreq = (struct ifreq *) ((char *) ifreq + len);
 
       if (ifq->ifr_addr.sa_family != AF_INET)
@@ -3649,7 +3666,7 @@ FLAGS is the current flags of the interface.  */)
   Lisp_Object res = Qnil;
   Lisp_Object elt;
   int s;
-  int any = 0;
+  bool any = 0;
 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
      && defined HAVE_GETIFADDRS && defined LLADDR)
   struct ifaddrs *ifap;
@@ -3661,7 +3678,7 @@ FLAGS is the current flags of the interface.  */)
     error ("interface name too long");
   strcpy (rq.ifr_name, SSDATA (ifname));
 
-  s = socket (AF_INET, SOCK_STREAM, 0);
+  s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
   if (s < 0)
     return Qnil;
 
@@ -3780,7 +3797,7 @@ FLAGS is the current flags of the interface.  */)
 #endif
   res = Fcons (elt, res);
 
-  close (s);
+  emacs_close (s);
 
   return any ? res : Qnil;
 }
@@ -3903,7 +3920,7 @@ Return non-nil if we received any output before the timeout expired.  */)
     {
       if (INTEGERP (seconds))
        {
-         if (0 < XINT (seconds))
+         if (XINT (seconds) > 0)
            {
              secs = XINT (seconds);
              nsecs = 0;
@@ -3911,7 +3928,7 @@ Return non-nil if we received any output before the timeout expired.  */)
        }
       else if (FLOATP (seconds))
        {
-         if (0 < XFLOAT_DATA (seconds))
+         if (XFLOAT_DATA (seconds) > 0)
            {
              EMACS_TIME t = EMACS_TIME_FROM_DOUBLE (XFLOAT_DATA (seconds));
              secs = min (EMACS_SECS (t), WAIT_READING_MAX);
@@ -3935,7 +3952,7 @@ Return non-nil if we received any output before the timeout expired.  */)
 
 /* Accept a connection for server process SERVER on CHANNEL.  */
 
-static int connect_counter = 0;
+static EMACS_INT connect_counter = 0;
 
 static void
 server_accept_connection (Lisp_Object server, int channel)
@@ -3957,7 +3974,7 @@ server_accept_connection (Lisp_Object server, int channel)
   } saddr;
   socklen_t len = sizeof saddr;
 
-  s = accept (channel, &saddr.sa, &len);
+  s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
 
   if (s < 0)
     {
@@ -4041,7 +4058,8 @@ server_accept_connection (Lisp_Object server, int channel)
      process name of the server process concatenated with the caller
      identification.  */
 
-  if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
+  if (!(EQ (ps->filter, Qinternal_default_process_filter)
+       || EQ (ps->filter, Qt)))
     buffer = Qnil;
   else
     {
@@ -4110,7 +4128,7 @@ server_accept_connection (Lisp_Object server, int channel)
   /* Setup coding system for new process based on server process.
      This seems to be the proper thing to do, as the coding system
      of the new process should reflect the settings at the time the
-     server socket was opened; not the current settings. */
+     server socket was opened; not the current settings.  */
 
   pset_decode_coding_system (p, ps->decode_coding_system);
   pset_encode_coding_system (p, ps->encode_coding_system);
@@ -4129,11 +4147,10 @@ server_accept_connection (Lisp_Object server, int channel)
                      (STRINGP (host) ? host : build_string ("-")),
                      build_string ("\n")));
 
-  if (!NILP (p->sentinel))
-    exec_sentinel (proc,
-                  concat3 (build_string ("open from "),
-                           (STRINGP (host) ? host : build_string ("-")),
-                           build_string ("\n")));
+  exec_sentinel (proc,
+                concat3 (build_string ("open from "),
+                         (STRINGP (host) ? host : build_string ("-")),
+                         build_string ("\n")));
 }
 
 /* This variable is different from waiting_for_input in keyboard.c.
@@ -4147,11 +4164,10 @@ server_accept_connection (Lisp_Object server, int channel)
    when not inside wait_reading_process_output.  */
 static int waiting_for_user_input_p;
 
-static Lisp_Object
-wait_reading_process_output_unwind (Lisp_Object data)
+static void
+wait_reading_process_output_unwind (int data)
 {
-  waiting_for_user_input_p = XINT (data);
-  return Qnil;
+  waiting_for_user_input_p = data;
 }
 
 /* This is here so breakpoints can be put on it.  */
@@ -4190,7 +4206,7 @@ wait_reading_process_output_1 (void)
      process.  The return value is true if we read some input from
      that process.
 
-   If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
+   If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
      (suspending output from other processes).  A negative value
      means don't run any timers either.
 
@@ -4198,22 +4214,23 @@ wait_reading_process_output_1 (void)
      received input from that process before the timeout elapsed.
    Otherwise, return true if we received input from any process.  */
 
-int
+bool
 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
                             bool do_display,
                             Lisp_Object wait_for_cell,
                             struct Lisp_Process *wait_proc, int just_wait_proc)
 {
-  register int channel, nfds;
+  int channel, nfds;
   SELECT_TYPE Available;
   SELECT_TYPE Writeok;
-  int check_write;
-  int check_delay, no_avail;
+  bool check_write;
+  int check_delay;
+  bool no_avail;
   int xerrno;
   Lisp_Object proc;
   EMACS_TIME timeout, end_time;
   int wait_channel = -1;
-  int got_some_input = 0;
+  bool got_some_input = 0;
   ptrdiff_t count = SPECPDL_INDEX ();
 
   FD_ZERO (&Available);
@@ -4222,14 +4239,14 @@ wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
   if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
       && !(CONSP (wait_proc->status)
           && EQ (XCAR (wait_proc->status), Qexit)))
-    message ("Blocking call to accept-process-output with quit inhibited!!");
+    message1 ("Blocking call to accept-process-output with quit inhibited!!");
 
   /* If wait_proc is a process to watch, set wait_channel accordingly.  */
   if (wait_proc != NULL)
     wait_channel = wait_proc->infd;
 
-  record_unwind_protect (wait_reading_process_output_unwind,
-                        make_number (waiting_for_user_input_p));
+  record_unwind_protect_int (wait_reading_process_output_unwind,
+                            waiting_for_user_input_p);
   waiting_for_user_input_p = read_kbd;
 
   if (time_limit < 0)
@@ -4242,7 +4259,7 @@ wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
 
   /* Since we may need to wait several times,
      compute the absolute time to return at.  */
-  if (time_limit || 0 < nsecs)
+  if (time_limit || nsecs > 0)
     {
       timeout = make_emacs_time (time_limit, nsecs);
       end_time = add_emacs_time (current_emacs_time (), timeout);
@@ -4250,7 +4267,7 @@ wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
 
   while (1)
     {
-      int timeout_reduced_for_timers = 0;
+      bool timeout_reduced_for_timers = 0;
 
       /* If calling from keyboard input, do not quit
         since we want to return C-g as an input character.
@@ -4264,8 +4281,8 @@ wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
       if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
        break;
 
-      /* Compute time from now till when time limit is up */
-      /* Exit if already run out */
+      /* Compute time from now till when time limit is up */
+      /* Exit if already run out */
       if (nsecs < 0)
        {
          /* A negative timeout means
@@ -4274,7 +4291,7 @@ wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
 
          timeout = make_emacs_time (0, 0);
        }
-      else if (time_limit || 0 < nsecs)
+      else if (time_limit || nsecs > 0)
        {
          EMACS_TIME now = current_emacs_time ();
          if (EMACS_TIME_LE (end_time, now))
@@ -4326,7 +4343,7 @@ wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
            break;
 
          /* A negative timeout means do not wait at all.  */
-         if (0 <= nsecs)
+         if (nsecs >= 0)
            {
              if (EMACS_TIME_VALID_P (timer_delay))
                {
@@ -4395,7 +4412,7 @@ wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
          && ! EQ (wait_proc->status, Qrun)
          && ! EQ (wait_proc->status, Qconnect))
        {
-         int nread, total_nread = 0;
+         bool read_some_bytes = 0;
 
          clear_waiting_for_input ();
          XSETPROCESS (proc, wait_proc);
@@ -4403,16 +4420,13 @@ wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
          /* Read data from the process, until we exhaust it.  */
          while (wait_proc->infd >= 0)
            {
-             nread = read_process_output (proc, wait_proc->infd);
+             int nread = read_process_output (proc, wait_proc->infd);
 
              if (nread == 0)
                break;
 
-             if (0 < nread)
-               {
-                 total_nread += nread;
-                 got_some_input = 1;
-               }
+             if (nread > 0)
+               got_some_input = read_some_bytes = 1;
              else if (nread == -1 && (errno == EIO || errno == EAGAIN))
                break;
 #ifdef EWOULDBLOCK
@@ -4420,7 +4434,7 @@ wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
                break;
 #endif
            }
-         if (total_nread > 0 && do_display)
+         if (read_some_bytes && do_display)
            redisplay_preserve_echo_area (10);
 
          break;
@@ -4519,10 +4533,10 @@ wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
            }
 #endif
 
-#if defined (USE_GTK) || defined (HAVE_GCONF) || defined (HAVE_GSETTINGS)
-          nfds = xg_select
-#elif defined (HAVE_NS)
-         nfds = ns_select
+#if defined (HAVE_NS)
+          nfds = ns_select
+#elif defined (HAVE_GLIB)
+         nfds = xg_select
 #else
          nfds = pselect
 #endif
@@ -4595,22 +4609,9 @@ wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
          if (xerrno == EINTR)
            no_avail = 1;
          else if (xerrno == EBADF)
-           {
-#ifdef AIX
-             /* AIX doesn't handle PTY closure the same way BSD does.  On AIX,
-                the child's closure of the pts gives the parent a SIGHUP, and
-                the ptc file descriptor is automatically closed,
-                yielding EBADF here or at select() call above.
-                So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
-                in m/ibmrt-aix.h), and here we just ignore the select error.
-                Cleanup occurs c/o status_notify after SIGCHLD. */
-             no_avail = 1; /* Cannot depend on values returned */
-#else
-             emacs_abort ();
-#endif
-           }
+           emacs_abort ();
          else
-           error ("select error: %s", emacs_strerror (xerrno));
+           report_file_errno ("Failed select", Qnil, xerrno);
        }
 
       if (no_avail)
@@ -4628,7 +4629,7 @@ wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
          unsigned old_timers_run = timers_run;
          struct buffer *old_buffer = current_buffer;
          Lisp_Object old_window = selected_window;
-         int leave = 0;
+         bool leave = 0;
 
          if (detect_input_pending_run_timers (do_display))
            {
@@ -4872,8 +4873,8 @@ wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
                }
            }
 #endif /* NON_BLOCKING_CONNECT */
-       }                       /* end for each file descriptor */
-    }                          /* end while exit conditions not met */
+       }                       /* End for each file descriptor.  */
+    }                          /* End while exit conditions not met.  */
 
   unbind_to (count, Qnil);
 
@@ -4908,6 +4909,11 @@ read_process_output_error_handler (Lisp_Object error_val)
   return Qt;
 }
 
+static void
+read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
+                                   ssize_t nbytes,
+                                   struct coding_system *coding);
+
 /* Read pending output from the process channel,
    starting with our buffered-ahead character if we have one.
    Yield number of decoded characters read.
@@ -4924,9 +4930,7 @@ read_process_output (Lisp_Object proc, register int channel)
 {
   register ssize_t nbytes;
   char *chars;
-  register Lisp_Object outstream;
   register struct Lisp_Process *p = XPROCESS (proc);
-  register ptrdiff_t opoint;
   struct coding_system *coding = proc_decode_coding_system[channel];
   int carryover = p->decoding_carryover;
   int readmax = 4096;
@@ -4949,7 +4953,7 @@ read_process_output (Lisp_Object proc, register int channel)
   else
 #endif
     {
-      int buffered = 0 <= proc_buffered_char[channel];
+      bool buffered = proc_buffered_char[channel] >= 0;
       if (buffered)
        {
          chars[carryover] = proc_buffered_char[channel];
@@ -5014,122 +5018,142 @@ read_process_output (Lisp_Object proc, register int channel)
      friends don't expect current-buffer to be changed from under them.  */
   record_unwind_current_buffer ();
 
-  /* Read and dispose of the process output.  */
-  outstream = p->filter;
-  if (!NILP (outstream))
-    {
-      Lisp_Object text;
-      bool outer_running_asynch_code = running_asynch_code;
-      int waiting = waiting_for_user_input_p;
+  read_and_dispose_of_process_output (p, chars, nbytes, coding);
+
+  /* Handling the process output should not deactivate the mark.  */
+  Vdeactivate_mark = odeactivate;
+
+  unbind_to (count, Qnil);
+  return nbytes;
+}
 
-      /* No need to gcpro these, because all we do with them later
-        is test them for EQness, and none of them should be a string.  */
+static void
+read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
+                                   ssize_t nbytes,
+                                   struct coding_system *coding)
+{
+  Lisp_Object outstream = p->filter;
+  Lisp_Object text;
+  bool outer_running_asynch_code = running_asynch_code;
+  int waiting = waiting_for_user_input_p;
+
+  /* No need to gcpro these, because all we do with them later
+     is test them for EQness, and none of them should be a string.  */
 #if 0
-      Lisp_Object obuffer, okeymap;
-      XSETBUFFER (obuffer, current_buffer);
-      okeymap = BVAR (current_buffer, keymap);
+  Lisp_Object obuffer, okeymap;
+  XSETBUFFER (obuffer, current_buffer);
+  okeymap = BVAR (current_buffer, keymap);
 #endif
 
-      /* We inhibit quit here instead of just catching it so that
-        hitting ^G when a filter happens to be running won't screw
-        it up.  */
-      specbind (Qinhibit_quit, Qt);
-      specbind (Qlast_nonmenu_event, Qt);
-
-      /* In case we get recursively called,
-        and we already saved the match data nonrecursively,
-        save the same match data in safely recursive fashion.  */
-      if (outer_running_asynch_code)
-       {
-         Lisp_Object tem;
-         /* Don't clobber the CURRENT match data, either!  */
-         tem = Fmatch_data (Qnil, Qnil, Qnil);
-         restore_search_regs ();
-         record_unwind_save_match_data ();
-         Fset_match_data (tem, Qt);
-       }
+  /* We inhibit quit here instead of just catching it so that
+     hitting ^G when a filter happens to be running won't screw
+     it up.  */
+  specbind (Qinhibit_quit, Qt);
+  specbind (Qlast_nonmenu_event, Qt);
 
-      /* For speed, if a search happens within this code,
-        save the match data in a special nonrecursive fashion.  */
-      running_asynch_code = 1;
+  /* In case we get recursively called,
+     and we already saved the match data nonrecursively,
+     save the same match data in safely recursive fashion.  */
+  if (outer_running_asynch_code)
+    {
+      Lisp_Object tem;
+      /* Don't clobber the CURRENT match data, either!  */
+      tem = Fmatch_data (Qnil, Qnil, Qnil);
+      restore_search_regs ();
+      record_unwind_save_match_data ();
+      Fset_match_data (tem, Qt);
+    }
 
-      decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
-      text = coding->dst_object;
-      Vlast_coding_system_used = CODING_ID_NAME (coding->id);
-      /* A new coding system might be found.  */
-      if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
-       {
-         pset_decode_coding_system (p, Vlast_coding_system_used);
+  /* For speed, if a search happens within this code,
+     save the match data in a special nonrecursive fashion.  */
+  running_asynch_code = 1;
 
-         /* Don't call setup_coding_system for
-            proc_decode_coding_system[channel] here.  It is done in
-            detect_coding called via decode_coding above.  */
+  decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
+  text = coding->dst_object;
+  Vlast_coding_system_used = CODING_ID_NAME (coding->id);
+  /* A new coding system might be found.  */
+  if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
+    {
+      pset_decode_coding_system (p, Vlast_coding_system_used);
 
-         /* If a coding system for encoding is not yet decided, we set
-            it as the same as coding-system for decoding.
+      /* Don't call setup_coding_system for
+        proc_decode_coding_system[channel] here.  It is done in
+        detect_coding called via decode_coding above.  */
 
-            But, before doing that we must check if
-            proc_encode_coding_system[p->outfd] surely points to a
-            valid memory because p->outfd will be changed once EOF is
-            sent to the process.  */
-         if (NILP (p->encode_coding_system)
-             && proc_encode_coding_system[p->outfd])
-           {
-             pset_encode_coding_system
-               (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
-             setup_coding_system (p->encode_coding_system,
-                                  proc_encode_coding_system[p->outfd]);
-           }
-       }
+      /* If a coding system for encoding is not yet decided, we set
+        it as the same as coding-system for decoding.
 
-      if (coding->carryover_bytes > 0)
+        But, before doing that we must check if
+        proc_encode_coding_system[p->outfd] surely points to a
+        valid memory because p->outfd will be changed once EOF is
+        sent to the process.  */
+      if (NILP (p->encode_coding_system)
+         && proc_encode_coding_system[p->outfd])
        {
-         if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
-           pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
-         memcpy (SDATA (p->decoding_buf), coding->carryover,
-                 coding->carryover_bytes);
-         p->decoding_carryover = coding->carryover_bytes;
+         pset_encode_coding_system
+           (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
+         setup_coding_system (p->encode_coding_system,
+                              proc_encode_coding_system[p->outfd]);
        }
-      if (SBYTES (text) > 0)
-       /* FIXME: It's wrong to wrap or not based on debug-on-error, and
-          sometimes it's simply wrong to wrap (e.g. when called from
-          accept-process-output).  */
-       internal_condition_case_1 (read_process_output_call,
-                                  Fcons (outstream,
-                                         Fcons (proc, Fcons (text, Qnil))),
-                                  !NILP (Vdebug_on_error) ? Qnil : Qerror,
-                                  read_process_output_error_handler);
-
-      /* If we saved the match data nonrecursively, restore it now.  */
-      restore_search_regs ();
-      running_asynch_code = outer_running_asynch_code;
+    }
+
+  if (coding->carryover_bytes > 0)
+    {
+      if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
+       pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
+      memcpy (SDATA (p->decoding_buf), coding->carryover,
+             coding->carryover_bytes);
+      p->decoding_carryover = coding->carryover_bytes;
+    }
+  if (SBYTES (text) > 0)
+    /* FIXME: It's wrong to wrap or not based on debug-on-error, and
+       sometimes it's simply wrong to wrap (e.g. when called from
+       accept-process-output).  */
+    internal_condition_case_1 (read_process_output_call,
+                              list3 (outstream, make_lisp_proc (p), text),
+                              !NILP (Vdebug_on_error) ? Qnil : Qerror,
+                              read_process_output_error_handler);
 
-      /* Restore waiting_for_user_input_p as it was
-        when we were called, in case the filter clobbered it.  */
-      waiting_for_user_input_p = waiting;
+  /* If we saved the match data nonrecursively, restore it now.  */
+  restore_search_regs ();
+  running_asynch_code = outer_running_asynch_code;
+
+  /* Restore waiting_for_user_input_p as it was
+     when we were called, in case the filter clobbered it.  */
+  waiting_for_user_input_p = waiting;
 
 #if 0 /* Call record_asynch_buffer_change unconditionally,
         because we might have changed minor modes or other things
         that affect key bindings.  */
-      if (! EQ (Fcurrent_buffer (), obuffer)
-         || ! EQ (current_buffer->keymap, okeymap))
-#endif
-       /* But do it only if the caller is actually going to read events.
-          Otherwise there's no need to make him wake up, and it could
-          cause trouble (for example it would make sit_for return).  */
-       if (waiting_for_user_input_p == -1)
-         record_asynch_buffer_change ();
-    }
+  if (! EQ (Fcurrent_buffer (), obuffer)
+      || ! EQ (current_buffer->keymap, okeymap))
+#endif
+    /* But do it only if the caller is actually going to read events.
+       Otherwise there's no need to make him wake up, and it could
+       cause trouble (for example it would make sit_for return).  */
+    if (waiting_for_user_input_p == -1)
+      record_asynch_buffer_change ();
+}
 
-  /* If no filter, write into buffer if it isn't dead.  */
-  else if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
+DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
+       Sinternal_default_process_filter, 2, 2, 0,
+       doc: /* Function used as default process filter.  */)
+  (Lisp_Object proc, Lisp_Object text)
+{
+  struct Lisp_Process *p;
+  ptrdiff_t opoint;
+
+  CHECK_PROCESS (proc);
+  p = XPROCESS (proc);
+  CHECK_STRING (text);
+
+  if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
     {
       Lisp_Object old_read_only;
       ptrdiff_t old_begv, old_zv;
       ptrdiff_t old_begv_byte, old_zv_byte;
       ptrdiff_t before, before_byte;
       ptrdiff_t opoint_byte;
-      Lisp_Object text;
       struct buffer *b;
 
       Fset_buffer (p->buffer);
@@ -5162,31 +5186,6 @@ read_process_output (Lisp_Object proc, register int channel)
       if (! (BEGV <= PT && PT <= ZV))
        Fwiden ();
 
-      decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
-      text = coding->dst_object;
-      Vlast_coding_system_used = CODING_ID_NAME (coding->id);
-      /* A new coding system might be found.  See the comment in the
-        similar code in the previous `if' block.  */
-      if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
-       {
-         pset_decode_coding_system (p, Vlast_coding_system_used);
-         if (NILP (p->encode_coding_system)
-             && proc_encode_coding_system[p->outfd])
-           {
-             pset_encode_coding_system
-               (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
-             setup_coding_system (p->encode_coding_system,
-                                  proc_encode_coding_system[p->outfd]);
-           }
-       }
-      if (coding->carryover_bytes > 0)
-       {
-         if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
-           pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
-         memcpy (SDATA (p->decoding_buf), coding->carryover,
-                 coding->carryover_bytes);
-         p->decoding_carryover = coding->carryover_bytes;
-       }
       /* Adjust the multibyteness of TEXT to that of the buffer.  */
       if (NILP (BVAR (current_buffer, enable_multibyte_characters))
          != ! STRING_MULTIBYTE (text))
@@ -5231,18 +5230,13 @@ read_process_output (Lisp_Object proc, register int channel)
       if (old_begv != BEGV || old_zv != ZV)
        Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
 
-
       bset_read_only (current_buffer, old_read_only);
       SET_PT_BOTH (opoint, opoint_byte);
     }
-  /* Handling the process output should not deactivate the mark.  */
-  Vdeactivate_mark = odeactivate;
-
-  unbind_to (count, Qnil);
-  return nbytes;
+  return Qnil;
 }
 \f
-/* Sending data to subprocess */
+/* Sending data to subprocess */
 
 /* In send_process, when a write fails temporarily,
    wait_reading_process_output is called.  It may execute user code,
@@ -5265,7 +5259,7 @@ read_process_output (Lisp_Object proc, register int channel)
 
 static void
 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
-                  const char *buf, ptrdiff_t len, int front)
+                  const char *buf, ptrdiff_t len, bool front)
 {
   ptrdiff_t offset;
   Lisp_Object entry, obj;
@@ -5286,14 +5280,14 @@ write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
   if (front)
     pset_write_queue (p, Fcons (entry, p->write_queue));
   else
-    pset_write_queue (p, nconc2 (p->write_queue, Fcons (entry, Qnil)));
+    pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
 }
 
 /* Remove the first element in the write_queue of process P, put its
-   contents in OBJ, BUF and LEN, and return non-zero.  If the
-   write_queue is empty, return zero.  */
+   contents in OBJ, BUF and LEN, and return true.  If the
+   write_queue is empty, return false.  */
 
-static int
+static bool
 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
                 const char **buf, ptrdiff_t *len)
 {
@@ -5456,10 +5450,10 @@ send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
              rv = sendto (outfd, cur_buf, cur_len,
                           0, datagram_address[outfd].sa,
                           datagram_address[outfd].len);
-             if (0 <= rv)
+             if (rv >= 0)
                written = rv;
              else if (errno == EMSGSIZE)
-               report_file_error ("sending datagram", Fcons (proc, Qnil));
+               report_file_error ("Sending datagram", proc);
            }
          else
 #endif
@@ -5469,7 +5463,7 @@ send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
                written = emacs_gnutls_write (p, cur_buf, cur_len);
              else
 #endif
-               written = emacs_write (outfd, cur_buf, cur_len);
+               written = emacs_write_sig (outfd, cur_buf, cur_len);
              rv = (written ? 0 : -1);
 #ifdef ADAPTIVE_READ_BUFFERING
              if (p->read_output_delay > 0
@@ -5536,7 +5530,7 @@ send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
                }
              else
                /* This is a real error.  */
-               report_file_error ("writing to process", Fcons (proc, Qnil));
+               report_file_error ("Writing to process", proc);
            }
          cur_buf += written;
          cur_len -= written;
@@ -5567,7 +5561,7 @@ Output from processes can arrive in between bunches.  */)
   if (XINT (start) < GPT && XINT (end) > GPT)
     move_gap_both (XINT (start), start_byte);
 
-  send_process (proc, (char *) BYTE_POS_ADDR (start_byte), 
+  send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
                end_byte - start_byte, Fcurrent_buffer ());
 
   return Qnil;
@@ -5654,7 +5648,7 @@ return t unconditionally.  */)
    If CURRENT_GROUP is lambda, that means send to the process group
    that currently owns the terminal, but only if it is NOT the shell itself.
 
-   If NOMSG is zero, insert signal-announcements into process's buffers
+   If NOMSG is false, insert signal-announcements into process's buffers
    right away.
 
    If we can, we try to signal PROCESS by sending control characters
@@ -5663,12 +5657,12 @@ return t unconditionally.  */)
 
 static void
 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
-                    int nomsg)
+                    bool nomsg)
 {
   Lisp_Object proc;
-  register struct Lisp_Process *p;
+  struct Lisp_Process *p;
   pid_t gid;
-  int no_pgrp = 0;
+  bool no_pgrp = 0;
 
   proc = get_process (process);
   p = XPROCESS (proc);
@@ -6030,7 +6024,7 @@ process has been transmitted to the serial port.  */)
     {
 #ifndef WINDOWSNT
       if (tcdrain (XPROCESS (proc)->outfd) != 0)
-       error ("tcdrain() failed: %s", emacs_strerror (errno));
+       report_file_error ("Failed tcdrain", Qnil);
 #endif /* not WINDOWSNT */
       /* Do nothing on Windows because writes are blocking.  */
     }
@@ -6096,6 +6090,13 @@ process has been transmitted to the serial port.  */)
    might inadvertently reap a GTK-created process that happened to
    have the same process ID.  */
 
+/* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
+   its own SIGCHLD handling.  On POSIXish systems, glib needs this to
+   keep track of its own children.  GNUstep is similar.  */
+
+static void dummy_handler (int sig) {}
+static signal_handler_t volatile lib_child_handler;
+
 /* Handle a SIGCHLD signal by looking for known child processes of
    Emacs whose status have changed.  For each one found, record its
    new status.
@@ -6155,7 +6156,8 @@ handle_child_signal (int sig)
       struct Lisp_Process *p = XPROCESS (proc);
       int status;
 
-      if (p->alive && child_status_changed (p->pid, &status, WUNTRACED))
+      if (p->alive
+         && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
        {
          /* Change the status of the process that was found.  */
          p->tick = ++process_tick;
@@ -6165,7 +6167,7 @@ handle_child_signal (int sig)
          /* If process has terminated, stop waiting for its output.  */
          if (WIFSIGNALED (status) || WIFEXITED (status))
            {
-             int clear_desc_flag = 0;
+             bool clear_desc_flag = 0;
              p->alive = 0;
              if (p->infd >= 0)
                clear_desc_flag = 1;
@@ -6179,6 +6181,13 @@ handle_child_signal (int sig)
            }
        }
     }
+
+  lib_child_handler (sig);
+#ifdef NS_IMPL_GNUSTEP
+  /* NSTask in GNUStep sets its child handler each time it is called.
+     So we must re-set ours.  */
+  catch_child_signal();
+#endif
 }
 
 static void
@@ -6188,13 +6197,6 @@ deliver_child_signal (int sig)
 }
 \f
 
-static Lisp_Object
-exec_sentinel_unwind (Lisp_Object data)
-{
-  pset_sentinel (XPROCESS (XCAR (data)), XCDR (data));
-  return Qnil;
-}
-
 static Lisp_Object
 exec_sentinel_error_handler (Lisp_Object error_val)
 {
@@ -6232,13 +6234,7 @@ exec_sentinel (Lisp_Object proc, Lisp_Object reason)
   record_unwind_current_buffer ();
 
   sentinel = p->sentinel;
-  if (NILP (sentinel))
-    return;
 
-  /* Zilch the sentinel while it's running, to avoid recursive invocations;
-     assure that it gets restored no matter how the sentinel exits.  */
-  pset_sentinel (p, Qnil);
-  record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
   /* Inhibit quit so that random quits don't screw up a running filter.  */
   specbind (Qinhibit_quit, Qt);
   specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef  */
@@ -6260,8 +6256,7 @@ exec_sentinel (Lisp_Object proc, Lisp_Object reason)
   running_asynch_code = 1;
 
   internal_condition_case_1 (read_process_output_call,
-                            Fcons (sentinel,
-                                   Fcons (proc, Fcons (reason, Qnil))),
+                            list3 (sentinel, proc, reason),
                             !NILP (Vdebug_on_error) ? Qnil : Qerror,
                             exec_sentinel_error_handler);
 
@@ -6296,7 +6291,7 @@ exec_sentinel (Lisp_Object proc, Lisp_Object reason)
 static void
 status_notify (struct Lisp_Process *deleting_process)
 {
-  register Lisp_Object proc, buffer;
+  register Lisp_Object proc;
   Lisp_Object tail, msg;
   struct gcpro gcpro1, gcpro2;
 
@@ -6334,8 +6329,6 @@ status_notify (struct Lisp_Process *deleting_process)
                 && p != deleting_process
                 && read_process_output (proc, p->infd) > 0);
 
-         buffer = p->buffer;
-
          /* Get the text to use for the message.  */
          if (p->raw_status_new)
            update_status (p);
@@ -6356,66 +6349,83 @@ status_notify (struct Lisp_Process *deleting_process)
            }
 
          /* The actions above may have further incremented p->tick.
-            So set p->update_tick again
-            so that an error in the sentinel will not cause
-            this code to be run again.  */
+            So set p->update_tick again so that an error in the sentinel will
+            not cause this code to be run again.  */
          p->update_tick = p->tick;
          /* Now output the message suitably.  */
-         if (!NILP (p->sentinel))
-           exec_sentinel (proc, msg);
-         /* Don't bother with a message in the buffer
-            when a process becomes runnable.  */
-         else if (!EQ (symbol, Qrun) && !NILP (buffer))
-           {
-             Lisp_Object tem;
-             struct buffer *old = current_buffer;
-             ptrdiff_t opoint, opoint_byte;
-             ptrdiff_t before, before_byte;
-
-             /* Avoid error if buffer is deleted
-                (probably that's why the process is dead, too) */
-             if (!BUFFER_LIVE_P (XBUFFER (buffer)))
-               continue;
-             Fset_buffer (buffer);
-
-             opoint = PT;
-             opoint_byte = PT_BYTE;
-             /* Insert new output into buffer
-                at the current end-of-output marker,
-                thus preserving logical ordering of input and output.  */
-             if (XMARKER (p->mark)->buffer)
-               Fgoto_char (p->mark);
-             else
-               SET_PT_BOTH (ZV, ZV_BYTE);
-
-             before = PT;
-             before_byte = PT_BYTE;
-
-             tem = BVAR (current_buffer, read_only);
-             bset_read_only (current_buffer, Qnil);
-             insert_string ("\nProcess ");
-             { /* FIXME: temporary kludge */
-               Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
-             insert_string (" ");
-             Finsert (1, &msg);
-             bset_read_only (current_buffer, tem);
-             set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
-
-             if (opoint >= before)
-               SET_PT_BOTH (opoint + (PT - before),
-                            opoint_byte + (PT_BYTE - before_byte));
-             else
-               SET_PT_BOTH (opoint, opoint_byte);
-
-             set_buffer_internal (old);
-           }
+         exec_sentinel (proc, msg);
        }
     } /* end for */
 
-  update_mode_lines++;  /* in case buffers use %s in mode-line-format */
+  update_mode_lines++;  /* In case buffers use %s in mode-line-format.  */
   UNGCPRO;
 }
 
+DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
+       Sinternal_default_process_sentinel, 2, 2, 0,
+       doc: /* Function used as default sentinel for processes.  */)
+     (Lisp_Object proc, Lisp_Object msg)
+{
+  Lisp_Object buffer, symbol;
+  struct Lisp_Process *p;
+  CHECK_PROCESS (proc);
+  p = XPROCESS (proc);
+  buffer = p->buffer;
+  symbol = p->status;
+  if (CONSP (symbol))
+    symbol = XCAR (symbol);
+
+  if (!EQ (symbol, Qrun) && !NILP (buffer))
+    {
+      Lisp_Object tem;
+      struct buffer *old = current_buffer;
+      ptrdiff_t opoint, opoint_byte;
+      ptrdiff_t before, before_byte;
+
+      /* Avoid error if buffer is deleted
+        (probably that's why the process is dead, too).  */
+      if (!BUFFER_LIVE_P (XBUFFER (buffer)))
+       return Qnil;
+      Fset_buffer (buffer);
+
+      if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
+       msg = (code_convert_string_norecord
+              (msg, Vlocale_coding_system, 1));
+
+      opoint = PT;
+      opoint_byte = PT_BYTE;
+      /* Insert new output into buffer
+        at the current end-of-output marker,
+        thus preserving logical ordering of input and output.  */
+      if (XMARKER (p->mark)->buffer)
+       Fgoto_char (p->mark);
+      else
+       SET_PT_BOTH (ZV, ZV_BYTE);
+
+      before = PT;
+      before_byte = PT_BYTE;
+
+      tem = BVAR (current_buffer, read_only);
+      bset_read_only (current_buffer, Qnil);
+      insert_string ("\nProcess ");
+      { /* FIXME: temporary kludge.  */
+       Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
+      insert_string (" ");
+      Finsert (1, &msg);
+      bset_read_only (current_buffer, tem);
+      set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
+
+      if (opoint >= before)
+       SET_PT_BOTH (opoint + (PT - before),
+                    opoint_byte + (PT_BYTE - before_byte));
+      else
+       SET_PT_BOTH (opoint, opoint_byte);
+
+      set_buffer_internal (old);
+    }
+  return Qnil;
+}
+
 \f
 DEFUN ("set-process-coding-system", Fset_process_coding_system,
        Sset_process_coding_system, 1, 3, 0,
@@ -6508,10 +6518,10 @@ delete_gpm_wait_descriptor (int desc)
 
 # ifdef USABLE_SIGIO
 
-/* Return nonzero if *MASK has a bit set
+/* Return true if *MASK has a bit set
    that corresponds to one of the keyboard input descriptors.  */
 
-static int
+static bool
 keyboard_bit_set (fd_set *mask)
 {
   int fd;
@@ -6561,7 +6571,7 @@ extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
 
    Return true if we received input from any process.  */
 
-int
+bool
 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
                             bool do_display,
                             Lisp_Object wait_for_cell,
@@ -6579,7 +6589,7 @@ wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
     time_limit = TYPE_MAXIMUM (time_t);
 
   /* What does time_limit really mean?  */
-  if (time_limit || 0 < nsecs)
+  if (time_limit || nsecs > 0)
     {
       timeout = make_emacs_time (time_limit, nsecs);
       end_time = add_emacs_time (current_emacs_time (), timeout);
@@ -6593,7 +6603,7 @@ wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
 
   while (1)
     {
-      int timeout_reduced_for_timers = 0;
+      bool timeout_reduced_for_timers = 0;
       SELECT_TYPE waitchannels;
       int xerrno;
 
@@ -6607,17 +6617,17 @@ wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
       if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
        break;
 
-      /* Compute time from now till when time limit is up */
-      /* Exit if already run out */
+      /* Compute time from now till when time limit is up */
+      /* Exit if already run out */
       if (nsecs < 0)
        {
          /* A negative timeout means
             gobble output available now
-            but don't wait at all. */
+            but don't wait at all.  */
 
          timeout = make_emacs_time (0, 0);
        }
-      else if (time_limit || 0 < nsecs)
+      else if (time_limit || nsecs > 0)
        {
          EMACS_TIME now = current_emacs_time ();
          if (EMACS_TIME_LE (end_time, now))
@@ -6655,7 +6665,7 @@ wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
              && requeued_events_pending_p ())
            break;
 
-         if (EMACS_TIME_VALID_P (timer_delay) && 0 <= nsecs)
+         if (EMACS_TIME_VALID_P (timer_delay) && nsecs >= 0)
            {
              if (EMACS_TIME_LT (timer_delay, timeout))
                {
@@ -6710,7 +6720,7 @@ wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
          if (xerrno == EINTR)
            FD_ZERO (&waitchannels);
          else
-           error ("select error: %s", emacs_strerror (xerrno));
+           report_file_errno ("Failed select", Qnil, xerrno);
        }
 
       /* Check for keyboard input */
@@ -6806,9 +6816,8 @@ setup_process_coding_systems (Lisp_Object process)
   if (!proc_decode_coding_system[inch])
     proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
   coding_system = p->decode_coding_system;
-  if (! NILP (p->filter))
-    ;
-  else if (BUFFERP (p->buffer))
+  if (EQ (p->filter, Qinternal_default_process_filter)
+      && BUFFERP (p->buffer))
     {
       if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
        coding_system = raw_text_coding_system (coding_system);
@@ -6822,32 +6831,6 @@ setup_process_coding_systems (Lisp_Object process)
 #endif
 }
 
-/* Close all descriptors currently in use for communication
-   with subprocess.  This is used in a newly-forked subprocess
-   to get rid of irrelevant descriptors.  */
-
-void
-close_process_descs (void)
-{
-#ifndef DOS_NT
-  int i;
-  for (i = 0; i < MAXDESC; i++)
-    {
-      Lisp_Object process;
-      process = chan_process[i];
-      if (!NILP (process))
-       {
-         int in  = XPROCESS (process)->infd;
-         int out = XPROCESS (process)->outfd;
-         if (in >= 0)
-           emacs_close (in);
-         if (out >= 0 && in != out)
-           emacs_close (out);
-       }
-    }
-#endif
-}
-
 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
        doc: /* Return the (or a) process associated with BUFFER.
 BUFFER may be a buffer or the name of one.  */)
@@ -6917,7 +6900,7 @@ kill_buffer_processes (Lisp_Object buffer)
 
 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
        Swaiting_for_user_input_p, 0, 0, 0,
-       doc: /* Returns non-nil if Emacs is waiting for input from the user.
+       doc: /* Return non-nil if Emacs is waiting for input from the user.
 This is intended for use by asynchronous process output filters and sentinels.  */)
   (void)
 {
@@ -6944,9 +6927,9 @@ unhold_keyboard_input (void)
   kbd_is_on_hold = 0;
 }
 
-/* Return non-zero if keyboard input is on hold, zero otherwise.  */
+/* Return true if keyboard input is on hold, zero otherwise.  */
 
-int
+bool
 kbd_on_hold_p (void)
 {
   return kbd_is_on_hold;
@@ -7023,6 +7006,31 @@ integer or floating point values.
   return system_process_attributes (pid);
 }
 
+/* Arrange to catch SIGCHLD if this hasn't already been arranged.
+   Invoke this after init_process_emacs, and after glib and/or GNUstep
+   futz with the SIGCHLD handler, but before Emacs forks any children.
+   This function's caller should block SIGCHLD.  */
+
+#ifndef NS_IMPL_GNUSTEP
+static
+#endif
+void
+catch_child_signal (void)
+{
+  struct sigaction action, old_action;
+  emacs_sigaction_init (&action, deliver_child_signal);
+  block_child_signal ();
+  sigaction (SIGCHLD, &action, &old_action);
+  eassert (! (old_action.sa_flags & SA_SIGINFO));
+
+  if (old_action.sa_handler != deliver_child_signal)
+    lib_child_handler
+      = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
+        ? dummy_handler
+        : old_action.sa_handler);
+  unblock_child_signal ();
+}
+
 \f
 /* This is not called "init_process" because that is the name of a
    Mach system call, so it would cause problems on Darwin systems.  */
@@ -7038,9 +7046,14 @@ init_process_emacs (void)
   if (! noninteractive || initialized)
 #endif
     {
-      struct sigaction action;
-      emacs_sigaction_init (&action, deliver_child_signal);
-      sigaction (SIGCHLD, &action, 0);
+#if defined HAVE_GLIB && !defined WINDOWSNT
+      /* Tickle glib's child-handling code.  Ask glib to wait for Emacs itself;
+        this should always fail, but is enough to initialize glib's
+        private SIGCHLD handler, allowing catch_child_signal to copy
+        it into lib_child_handler.  */
+      g_source_unref (g_child_watch_source_new (getpid ()));
+#endif
+      catch_child_signal ();
     }
 
   FD_ZERO (&input_wait_mask);
@@ -7223,6 +7236,10 @@ syms_of_process (void)
   DEFSYM (Qcutime, "cutime");
   DEFSYM (Qcstime, "cstime");
   DEFSYM (Qctime, "ctime");
+  DEFSYM (Qinternal_default_process_sentinel,
+         "internal-default-process-sentinel");
+  DEFSYM (Qinternal_default_process_filter,
+         "internal-default-process-filter");
   DEFSYM (Qpri, "pri");
   DEFSYM (Qnice, "nice");
   DEFSYM (Qthcount, "thcount");
@@ -7318,6 +7335,8 @@ The variable takes effect when `start-process' is called.  */);
   defsubr (&Ssignal_process);
   defsubr (&Swaiting_for_user_input_p);
   defsubr (&Sprocess_type);
+  defsubr (&Sinternal_default_process_sentinel);
+  defsubr (&Sinternal_default_process_filter);
   defsubr (&Sset_process_coding_system);
   defsubr (&Sprocess_coding_system);
   defsubr (&Sset_process_filter_multibyte);