XEmacs 21.4.9 "Informed Management".
[chise/xemacs-chise.git.1] / src / process-unix.c
1 /* Asynchronous subprocess implementation for UNIX
2    Copyright (C) 1985, 1986, 1987, 1988, 1992, 1993, 1994, 1995
3    Free Software Foundation, Inc.
4    Copyright (C) 1995 Sun Microsystems, Inc.
5    Copyright (C) 1995, 1996 Ben Wing.
6
7 This file is part of XEmacs.
8
9 XEmacs is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
12 later version.
13
14 XEmacs is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with XEmacs; see the file COPYING.  If not, write to
21 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 Boston, MA 02111-1307, USA.  */
23
24 /* This file has been Mule-ized except for `start-process-internal',
25    `open-network-stream-internal' and `open-multicast-group-internal'. */
26
27 /* This file has been split into process.c and process-unix.c by
28    Kirill M. Katsnelson <kkm@kis.ru>, so please bash him and not
29    the original author(s) */
30
31 /* The IPv6 support is derived from the code for GNU Emacs-20.3
32    written by Wolfgang S. Rupprecht */
33
34 #include <config.h>
35
36 #if !defined (NO_SUBPROCESSES)
37
38 /* The entire file is within this conditional */
39
40 #include "lisp.h"
41
42 #include "buffer.h"
43 #include "events.h"
44 #include "frame.h"
45 #include "hash.h"
46 #include "lstream.h"
47 #include "opaque.h"
48 #include "process.h"
49 #include "procimpl.h"
50 #include "sysdep.h"
51 #include "window.h"
52 #ifdef FILE_CODING
53 #include "file-coding.h"
54 #endif
55
56 #include <setjmp.h>
57 #include "sysfile.h"
58 #include "sysproc.h"
59 #include "systime.h"
60 #include "syssignal.h" /* Always include before systty.h */
61 #include "systty.h"
62 #include "syswait.h"
63
64 #ifdef HPUX
65 #include <grp.h>                /* See grantpt fixups for HPUX below. */
66 #endif
67
68 /*
69  * Implementation-specific data. Pointed to by Lisp_Process->process_data
70  */
71
72 struct unix_process_data
73 {
74   /* Non-0 if this is really a ToolTalk channel. */
75   int connected_via_filedesc_p;
76   /* Descriptor by which we read from this process.  -1 for dead process */
77   int infd;
78   /* Descriptor for the tty which this process is using.
79      -1 if we didn't record it (on some systems, there's no need).  */
80   int subtty;
81   /* Name of subprocess terminal. */
82   Lisp_Object tty_name;
83   /* Non-false if communicating through a pty.  */
84   char pty_flag;
85 };
86
87 #define UNIX_DATA(p) ((struct unix_process_data*)((p)->process_data))
88
89
90 \f
91 /**********************************************************************/
92 /*                    Static helper routines                          */
93 /**********************************************************************/
94
95 static SIGTYPE
96 close_safely_handler (int signo)
97 {
98   EMACS_REESTABLISH_SIGNAL (signo, close_safely_handler);
99   SIGRETURN;
100 }
101
102 static void
103 close_safely (int fd)
104 {
105   stop_interrupts ();
106   signal (SIGALRM, close_safely_handler);
107   alarm (1);
108   close (fd);
109   alarm (0);
110   start_interrupts ();
111 }
112
113 static void
114 close_descriptor_pair (int in, int out)
115 {
116   if (in >= 0)
117     close (in);
118   if (out != in && out >= 0)
119     close (out);
120 }
121
122 /* Close all descriptors currently in use for communication
123    with subprocess.  This is used in a newly-forked subprocess
124    to get rid of irrelevant descriptors.  */
125
126 static int
127 close_process_descs_mapfun (const void* key, void* contents, void* arg)
128 {
129   Lisp_Object proc;
130   CVOID_TO_LISP (proc, contents);
131   event_stream_delete_stream_pair (XPROCESS(proc)->pipe_instream,
132                                    XPROCESS(proc)->pipe_outstream);
133   return 0;
134 }
135
136 /* #### This function is currently called from child_setup
137    in callproc.c. It should become static though - kkm */
138 void
139 close_process_descs (void)
140 {
141   maphash (close_process_descs_mapfun, usid_to_process, 0);
142 }
143
144 /* connect to an existing file descriptor.  This is very similar to
145    open-network-stream except that it assumes that the connection has
146    already been initialized.  It is currently used for ToolTalk
147    communication. */
148
149 /* This function used to be visible on the Lisp level, but there is no
150    real point in doing that.  Here is the doc string:
151
152   "Connect to an existing file descriptor.
153 Return a subprocess-object to represent the connection.
154 Input and output work as for subprocesses; `delete-process' closes it.
155 Args are NAME BUFFER INFD OUTFD.
156 NAME is name for process.  It is modified if necessary to make it unique.
157 BUFFER is the buffer (or buffer-name) to associate with the process.
158  Process output goes at end of that buffer, unless you specify
159  an output stream or filter function to handle the output.
160  BUFFER may also be nil, meaning that this process is not associated
161  with any buffer.
162 INFD and OUTFD specify the file descriptors to use for input and
163  output, respectively."
164 */
165
166 Lisp_Object
167 connect_to_file_descriptor (Lisp_Object name, Lisp_Object buffer,
168                             Lisp_Object infd, Lisp_Object outfd)
169 {
170   /* This function can GC */
171   Lisp_Object proc;
172   int inch;
173
174   CHECK_STRING (name);
175   CHECK_INT (infd);
176   CHECK_INT (outfd);
177
178   inch = XINT (infd);
179   if (get_process_from_usid (FD_TO_USID (inch)))
180     invalid_operation ("There is already a process connected to fd", infd);
181   if (!NILP (buffer))
182     buffer = Fget_buffer_create (buffer);
183   proc = make_process_internal (name);
184
185   XPROCESS (proc)->pid = Fcons (infd, name);
186   XPROCESS (proc)->buffer = buffer;
187   init_process_io_handles (XPROCESS (proc), (void*)inch, (void*)XINT (outfd),
188                            0);
189   UNIX_DATA (XPROCESS (proc))->connected_via_filedesc_p = 1;
190
191   event_stream_select_process (XPROCESS (proc));
192
193   return proc;
194 }
195
196 #ifdef HAVE_PTYS
197 static int allocate_pty_the_old_fashioned_way (void);
198
199 /* The file name of the (slave) pty opened by allocate_pty().  */
200 #ifndef MAX_PTYNAME_LEN
201 #define MAX_PTYNAME_LEN 64
202 #endif
203 static char pty_name[MAX_PTYNAME_LEN];
204
205 /* Open an available pty, returning a file descriptor.
206    Return -1 on failure.
207    The file name of the terminal corresponding to the pty
208    is left in the variable `pty_name'.  */
209
210 static int
211 allocate_pty (void)
212 {
213   /* Unix98 standardized grantpt, unlockpt, and ptsname, but not the
214      functions required to open a master pty in the first place :-(
215
216      Modern Unix systems all seems to have convenience methods to open
217      a master pty fd in one function call, but there is little
218      agreement on how to do it.
219
220      allocate_pty() tries all the different known easy ways of opening
221      a pty.  In case of failure, we resort to the old BSD-style pty
222      grovelling code in allocate_pty_the_old_fashioned_way(). */
223 #ifndef FORCE_ALLOCATE_PTY_THE_OLD_FASHIONED_WAY
224   int master_fd = -1;
225   const char *slave_name = NULL;
226   const char *clone = NULL;
227   static const char * const clones[] = /* Different pty master clone devices */
228     {
229       "/dev/ptmx",      /* Various systems */
230       "/dev/ptm/clone", /* HPUX */
231       "/dev/ptc",       /* AIX */
232       "/dev/ptmx_bsd"   /* Tru64 */
233     };
234
235 #ifdef HAVE_GETPT /* glibc */
236   master_fd = getpt ();
237   if (master_fd >= 0)
238     goto have_master;
239 #endif /* HAVE_GETPT */
240
241
242 #if defined(HAVE_OPENPTY) /* BSD, Tru64, glibc */
243   {
244     int slave_fd = -1;
245     int rc;
246     EMACS_BLOCK_SIGNAL (SIGCHLD);
247     rc = openpty (&master_fd, &slave_fd, NULL, NULL, NULL);
248     EMACS_UNBLOCK_SIGNAL (SIGCHLD);
249     if (rc == 0)
250       {
251         slave_name = ttyname (slave_fd);
252         close (slave_fd);
253         goto have_slave_name;
254       }
255     else
256       {
257         if (master_fd >= 0)
258           close (master_fd);
259         if (slave_fd >= 0)
260           close (slave_fd);
261       }
262   }
263 #endif /* HAVE_OPENPTY */
264
265 #if defined(HAVE__GETPTY) && defined (O_NDELAY) /* SGI */
266   master_fd = -1;
267   EMACS_BLOCK_SIGNAL (SIGCHLD);
268   slave_name = _getpty (&master_fd, O_RDWR | O_NDELAY, 0600, 0);
269   EMACS_UNBLOCK_SIGNAL (SIGCHLD);
270   if (master_fd >= 0 && slave_name != NULL)
271     goto have_slave_name;
272 #endif /* HAVE__GETPTY */
273
274   /* Master clone devices are available on most systems */
275   {
276     int i;
277     for (i = 0; i < countof (clones); i++)
278       {
279         clone = clones[i];
280         master_fd = open (clone, O_RDWR | O_NONBLOCK | OPEN_BINARY, 0);
281         if (master_fd >= 0)
282           goto have_master;
283       }
284     clone = NULL;
285   }
286
287   goto lose;
288
289  have_master:
290
291 #if defined (HAVE_PTSNAME)
292   slave_name = ptsname (master_fd);
293   if (slave_name)
294     goto have_slave_name;
295 #endif
296
297   /* AIX docs say to use ttyname, not ptsname, to get slave_name */
298   if (clone
299       && !strcmp (clone, "/dev/ptc")
300       && (slave_name = ttyname (master_fd)) != NULL)
301     goto have_slave_name;
302
303   goto lose;
304
305  have_slave_name:
306   strncpy (pty_name, slave_name, sizeof (pty_name));
307   pty_name[sizeof (pty_name) - 1] = '\0';
308   setup_pty (master_fd);
309
310   /* We jump through some hoops to frob the pty.
311      It's not obvious that checking the return code here is useful. */
312
313   /* "The grantpt() function will fail if it is unable to successfully
314       invoke the setuid root program.  It may also fail if the
315       application has installed a signal handler to catch SIGCHLD
316       signals." */
317 #if defined (HAVE_GRANTPT) || defined (HAVE_UNLOCKPT)
318   EMACS_BLOCK_SIGNAL (SIGCHLD);
319
320 #if defined (HAVE_GRANTPT)
321   grantpt (master_fd);
322 #ifdef HPUX
323   /* grantpt() behavior on some versions of HP-UX differs from what's
324      specified in the man page: the group of the slave PTY is set to
325      the user's primary group, and we fix that. */
326   {
327     struct group *tty_group = getgrnam ("tty");
328     if (tty_group != NULL)
329       chown (pty_name, (uid_t) -1, tty_group->gr_gid);
330   }
331 #endif /* HPUX has broken grantpt() */
332 #endif /* HAVE_GRANTPT */
333
334 #if defined (HAVE_UNLOCKPT)
335   unlockpt (master_fd);
336 #endif
337
338   EMACS_UNBLOCK_SIGNAL (SIGCHLD);
339 #endif /* HAVE_GRANTPT || HAVE_UNLOCKPT */
340
341   return master_fd;
342
343  lose:
344   if (master_fd >= 0)
345     close (master_fd);
346 #endif /* ndef FORCE_ALLOCATE_PTY_THE_OLD_FASHIONED_WAY */
347   return allocate_pty_the_old_fashioned_way ();
348 }
349
350 /* This function tries to allocate a pty by iterating through file
351    pairs with names like /dev/ptyp1 and /dev/ttyp1. */
352 static int
353 allocate_pty_the_old_fashioned_way (void)
354 {
355   struct stat stb;
356
357   /* Some systems name their pseudoterminals so that there are gaps in
358      the usual sequence - for example, on HP9000/S700 systems, there
359      are no pseudoterminals with names ending in 'f'.  So we wait for
360      three failures in a row before deciding that we've reached the
361      end of the ptys.  */
362   int failed_count = 0;
363   int fd;
364   int i;
365   int c;
366
367 #ifdef PTY_ITERATION
368   PTY_ITERATION
369 #else
370 # ifndef FIRST_PTY_LETTER
371 # define FIRST_PTY_LETTER 'p'
372 # endif
373   for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
374     for (i = 0; i < 16; i++)
375 #endif /* PTY_ITERATION */
376
377       {
378 #ifdef PTY_NAME_SPRINTF
379         PTY_NAME_SPRINTF
380 #else
381         sprintf (pty_name, "/dev/pty%c%x", c, i);
382 #endif /* no PTY_NAME_SPRINTF */
383
384         if (xemacs_stat (pty_name, &stb) < 0)
385           {
386             if (++failed_count >= 3)
387               return -1;
388           }
389         else
390           failed_count = 0;
391         fd = open (pty_name, O_RDWR | O_NONBLOCK | OPEN_BINARY, 0);
392
393         if (fd >= 0)
394           {
395 #ifdef PTY_TTY_NAME_SPRINTF
396             PTY_TTY_NAME_SPRINTF
397 #else
398             sprintf (pty_name, "/dev/tty%c%x", c, i);
399 #endif /* no PTY_TTY_NAME_SPRINTF */
400             if (access (pty_name, R_OK | W_OK) == 0)
401               {
402                 setup_pty (fd);
403                 return fd;
404               }
405             close (fd);
406           }
407       } /* iteration */
408   return -1;
409 }
410 #endif /* HAVE_PTYS */
411
412 static int
413 create_bidirectional_pipe (int *inchannel, int *outchannel,
414                            volatile int *forkin, volatile int *forkout)
415 {
416   int sv[2];
417
418 #ifdef SKTPAIR
419   if (socketpair (AF_UNIX, SOCK_STREAM, 0, sv) < 0)
420     return -1;
421   *outchannel = *inchannel = sv[0];
422   *forkout = *forkin = sv[1];
423 #else /* not SKTPAIR */
424   int temp;
425   temp = pipe (sv);
426   if (temp < 0) return -1;
427   *inchannel = sv[0];
428   *forkout = sv[1];
429   temp = pipe (sv);
430   if (temp < 0) return -1;
431   *outchannel = sv[1];
432   *forkin = sv[0];
433 #endif /* not SKTPAIR */
434   return 0;
435 }
436
437
438 #ifdef HAVE_SOCKETS
439
440 #if !(defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO))
441 static int
442 get_internet_address (Lisp_Object host, struct sockaddr_in *address,
443                       Error_behavior errb)
444 {
445   struct hostent *host_info_ptr = NULL;
446 #ifdef TRY_AGAIN
447   int count = 0;
448 #endif
449
450   xzero (*address);
451
452   while (1)
453     {
454 #ifdef TRY_AGAIN
455       if (count++ > 10) break;
456 #ifndef BROKEN_CYGWIN
457       h_errno = 0;
458 #endif
459 #endif
460       /* Some systems can't handle SIGIO/SIGALARM in gethostbyname. */
461       slow_down_interrupts ();
462       host_info_ptr = gethostbyname ((char *) XSTRING_DATA (host));
463       speed_up_interrupts ();
464 #ifdef TRY_AGAIN
465       if (! (host_info_ptr == 0 && h_errno == TRY_AGAIN))
466 #endif
467         break;
468       Fsleep_for (make_int (1));
469     }
470   if (host_info_ptr)
471     {
472       address->sin_family = host_info_ptr->h_addrtype;
473       memcpy (&address->sin_addr, host_info_ptr->h_addr, host_info_ptr->h_length);
474     }
475   else
476     {
477       IN_ADDR numeric_addr;
478       /* Attempt to interpret host as numeric inet address */
479       numeric_addr = inet_addr ((char *) XSTRING_DATA (host));
480       if (NUMERIC_ADDR_ERROR)
481         {
482           maybe_error (Qprocess, errb,
483                        "Unknown host \"%s\"", XSTRING_DATA (host));
484           return 0;
485         }
486
487       /* There was some broken code here that called strlen() here
488          on (char *) &numeric_addr and even sometimes accessed
489          uninitialized data. */
490       address->sin_family = AF_INET;
491       * (IN_ADDR *) &address->sin_addr = numeric_addr;
492     }
493
494   return 1;
495 }
496 #endif /*  !(HAVE_GETADDRINFO && HAVE_GETNAMEINFO) */
497
498 static void
499 set_socket_nonblocking_maybe (int fd, int port, const char* proto)
500 {
501 #ifdef PROCESS_IO_BLOCKING
502   Lisp_Object tail;
503
504   for (tail = network_stream_blocking_port_list; CONSP (tail); tail = XCDR (tail))
505     {
506       Lisp_Object tail_port = XCAR (tail);
507
508       if (STRINGP (tail_port))
509         {
510           struct servent *svc_info;
511           CHECK_STRING (tail_port);
512           svc_info = getservbyname ((char *) XSTRING_DATA (tail_port), proto);
513           if ((svc_info != 0) && (svc_info->s_port == port))
514             break;
515           else
516             continue;
517         }
518       else if (INTP (tail_port) && (htons ((unsigned short) XINT (tail_port)) == port))
519         break;
520     }
521
522   if (!CONSP (tail))
523     {
524       set_descriptor_non_blocking (fd);
525     }
526 #else
527   set_descriptor_non_blocking (fd);
528 #endif  /* PROCESS_IO_BLOCKING */
529 }
530
531 #endif /* HAVE_SOCKETS */
532
533 /* Compute the Lisp form of the process status from
534    the numeric status that was returned by `wait'.  */
535
536 static void
537 update_status_from_wait_code (Lisp_Process *p, int *w_fmh)
538 {
539   /* C compiler lossage when attempting to pass w directly */
540   int w = *w_fmh;
541
542   if (WIFSTOPPED (w))
543     {
544       p->status_symbol = Qstop;
545       p->exit_code = WSTOPSIG (w);
546       p->core_dumped = 0;
547     }
548   else if (WIFEXITED (w))
549     {
550       p->status_symbol = Qexit;
551       p->exit_code = WEXITSTATUS (w);
552       p->core_dumped = 0;
553     }
554   else if (WIFSIGNALED (w))
555     {
556       p->status_symbol = Qsignal;
557       p->exit_code = WTERMSIG (w);
558       p->core_dumped = WCOREDUMP (w);
559     }
560   else
561     {
562       p->status_symbol = Qrun;
563       p->exit_code = 0;
564     }
565 }
566
567 #ifdef SIGCHLD
568
569 #define MAX_EXITED_PROCESSES 1000
570 static volatile pid_t exited_processes[MAX_EXITED_PROCESSES];
571 static volatile int exited_processes_status[MAX_EXITED_PROCESSES];
572 static volatile int exited_processes_index;
573
574 static volatile int sigchld_happened;
575
576 /* On receipt of a signal that a child status has changed,
577  loop asking about children with changed statuses until
578  the system says there are no more.  All we do is record
579  the processes and wait status.
580
581  This function could be called from within the SIGCHLD
582  handler, so it must be completely reentrant.  When
583  not called from a SIGCHLD handler, BLOCK_SIGCHLD should
584  be non-zero so that SIGCHLD is blocked while this
585  function is running. (This is necessary so avoid
586  race conditions with the SIGCHLD_HAPPENED flag). */
587
588 static void
589 record_exited_processes (int block_sigchld)
590 {
591   if (!sigchld_happened)
592     {
593       return;
594     }
595
596 #ifdef EMACS_BLOCK_SIGNAL
597   if (block_sigchld)
598     EMACS_BLOCK_SIGNAL (SIGCHLD);
599 #endif
600
601   while (sigchld_happened)
602     {
603       int pid;
604       int w;
605
606       /* Keep trying to get a status until we get a definitive result.  */
607       do
608         {
609           errno = 0;
610 #ifdef WNOHANG
611 #  ifndef WUNTRACED
612 #    define WUNTRACED 0
613 #  endif /* not WUNTRACED */
614 #  ifdef HAVE_WAITPID
615           pid = waitpid ((pid_t) -1, &w, WNOHANG | WUNTRACED);
616 #  else
617           pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
618 #  endif
619 #else /* not WNOHANG */
620           pid = wait (&w);
621 #endif /* not WNOHANG */
622         }
623       while (pid <= 0 && errno == EINTR);
624
625       if (pid <= 0)
626         break;
627
628       if (exited_processes_index < MAX_EXITED_PROCESSES)
629         {
630           exited_processes[exited_processes_index] = pid;
631           exited_processes_status[exited_processes_index] = w;
632           exited_processes_index++;
633         }
634
635       /* On systems with WNOHANG, we just ignore the number
636          of times that SIGCHLD was signalled, and keep looping
637          until there are no more processes to wait on.  If we
638          don't have WNOHANG, we have to rely on the count in
639          SIGCHLD_HAPPENED. */
640 #ifndef WNOHANG
641       sigchld_happened--;
642 #endif /* not WNOHANG */
643     }
644
645   sigchld_happened = 0;
646
647   if (block_sigchld)
648     EMACS_UNBLOCK_SIGNAL (SIGCHLD);
649 }
650
651 /* For any processes that have changed status and are recorded
652    and such, update the corresponding Lisp_Process.
653    We separate this from record_exited_processes() so that
654    we never have to call this function from within a signal
655    handler.  We block SIGCHLD in case record_exited_processes()
656    is called from a signal handler. */
657
658 /** USG WARNING:  Although it is not obvious from the documentation
659  in signal(2), on a USG system the SIGCLD handler MUST NOT call
660  signal() before executing at least one wait(), otherwise the handler
661  will be called again, resulting in an infinite loop.  The relevant
662  portion of the documentation reads "SIGCLD signals will be queued
663  and the signal-catching function will be continually reentered until
664  the queue is empty".  Invoking signal() causes the kernel to reexamine
665  the SIGCLD queue.   Fred Fish, UniSoft Systems Inc.
666
667  (Note that now this only applies in SYS V Release 2 and before.
668  On SYS V Release 3, we use sigset() to set the signal handler for
669  the first time, and so we don't have to reestablish the signal handler
670  in the handler below.  On SYS V Release 4, we don't get this weirdo
671  behavior when we use sigaction(), which we do use.) */
672
673 static SIGTYPE
674 sigchld_handler (int signo)
675 {
676 #ifdef OBNOXIOUS_SYSV_SIGCLD_BEHAVIOR
677   int old_errno = errno;
678
679   sigchld_happened++;
680   record_exited_processes (0);
681   errno = old_errno;
682 #else
683   sigchld_happened++;
684 #endif
685 #ifdef HAVE_UNIXOID_EVENT_LOOP
686   signal_fake_event ();
687 #endif
688   /* WARNING - must come after wait3() for USG systems */
689   EMACS_REESTABLISH_SIGNAL (signo, sigchld_handler);
690   SIGRETURN;
691 }
692
693 #endif /* SIGCHLD */
694
695 #ifdef SIGNALS_VIA_CHARACTERS
696 /* Get signal character to send to process if SIGNALS_VIA_CHARACTERS */
697
698 static int
699 process_signal_char (int tty_fd, int signo)
700 {
701   /* If it's not a tty, pray that these default values work */
702   if (! isatty (tty_fd)) {
703 #define CNTL(ch) (037 & (ch))
704     switch (signo)
705       {
706       case SIGINT:  return CNTL ('C');
707       case SIGQUIT: return CNTL ('\\');
708 #ifdef SIGTSTP
709       case SIGTSTP: return CNTL ('Z');
710 #endif
711       }
712   }
713
714 #ifdef HAVE_TERMIOS
715   /* TERMIOS is the latest and bestest, and seems most likely to work.
716      If the system has it, use it. */
717   {
718     struct termios t;
719     tcgetattr (tty_fd, &t);
720     switch (signo)
721       {
722       case SIGINT:  return t.c_cc[VINTR];
723       case SIGQUIT: return t.c_cc[VQUIT];
724 #if defined(SIGTSTP) && defined(VSUSP)
725       case SIGTSTP: return t.c_cc[VSUSP];
726 #endif
727       }
728   }
729
730 # elif defined (TIOCGLTC) && defined (TIOCGETC) /* not HAVE_TERMIOS */
731   {
732     /* On Berkeley descendants, the following IOCTL's retrieve the
733        current control characters.  */
734     struct tchars c;
735     struct ltchars lc;
736     switch (signo)
737       {
738       case SIGINT:  ioctl (tty_fd, TIOCGETC, &c);  return c.t_intrc;
739       case SIGQUIT: ioctl (tty_fd, TIOCGETC, &c);  return c.t_quitc;
740 #  ifdef SIGTSTP
741       case SIGTSTP: ioctl (tty_fd, TIOCGLTC, &lc); return lc.t_suspc;
742 #  endif /* SIGTSTP */
743       }
744   }
745
746 # elif defined (TCGETA) /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
747   {
748     /* On SYSV descendants, the TCGETA ioctl retrieves the current
749        control characters.  */
750     struct termio t;
751     ioctl (tty_fd, TCGETA, &t);
752     switch (signo) {
753     case SIGINT:  return t.c_cc[VINTR];
754     case SIGQUIT: return t.c_cc[VQUIT];
755 #  ifdef SIGTSTP
756     case SIGTSTP: return t.c_cc[VSWTCH];
757 #  endif /* SIGTSTP */
758     }
759   }
760 # else /* ! defined (TCGETA) */
761 #error ERROR! Using SIGNALS_VIA_CHARACTERS, but not HAVE_TERMIOS || (TIOCGLTC && TIOCGETC) || TCGETA
762   /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
763      you'd better be using one of the alternatives above!  */
764 # endif /* ! defined (TCGETA) */
765   return '\0';
766 }
767 #endif /* SIGNALS_VIA_CHARACTERS */
768
769
770
771 \f
772 /**********************************************************************/
773 /*              Process implementation methods                        */
774 /**********************************************************************/
775
776 /*
777  * Allocate and initialize Lisp_Process->process_data
778  */
779
780 static void
781 unix_alloc_process_data (Lisp_Process *p)
782 {
783   p->process_data = xnew (struct unix_process_data);
784
785   UNIX_DATA(p)->connected_via_filedesc_p = 0;
786   UNIX_DATA(p)->infd   = -1;
787   UNIX_DATA(p)->subtty = -1;
788   UNIX_DATA(p)->tty_name = Qnil;
789   UNIX_DATA(p)->pty_flag = 0;
790 }
791
792 /*
793  * Mark any Lisp objects in Lisp_Process->process_data
794  */
795
796 static void
797 unix_mark_process_data (Lisp_Process *proc)
798 {
799   mark_object (UNIX_DATA(proc)->tty_name);
800 }
801
802 /*
803  * Initialize XEmacs process implementation once
804  */
805
806 #ifdef SIGCHLD
807 static void
808 unix_init_process (void)
809 {
810 #ifndef CANNOT_DUMP
811   if (! noninteractive || initialized)
812 #endif
813     signal (SIGCHLD, sigchld_handler);
814 }
815 #endif /* SIGCHLD */
816
817 /*
818  * Initialize any process local data. This is called when newly
819  * created process is connected to real OS file handles. The
820  * handles are generally represented by void* type, but are
821  * of type int (file descriptors) for UNIX.
822  */
823
824 static void
825 unix_init_process_io_handles (Lisp_Process *p, void* in, void* out, int flags)
826 {
827   UNIX_DATA(p)->infd = (int)in;
828 }
829
830 /*
831  * Fork off a subprocess. P is a pointer to a newly created subprocess
832  * object. If this function signals, the caller is responsible for
833  * deleting (and finalizing) the process object.
834  *
835  * The method must return PID of the new process, a (positive??? ####) number
836  * which fits into Lisp_Int. No return value indicates an error, the method
837  * must signal an error instead.
838  */
839
840 static int
841 unix_create_process (Lisp_Process *p,
842                      Lisp_Object *argv, int nargv,
843                      Lisp_Object program, Lisp_Object cur_dir)
844 {
845   int pid;
846   int inchannel  = -1;
847   int outchannel = -1;
848   /* Use volatile to protect variables from being clobbered by longjmp.  */
849   volatile int forkin   = -1;
850   volatile int forkout  = -1;
851   volatile int pty_flag = 0;
852
853 #ifdef HAVE_PTYS
854   if (!NILP (Vprocess_connection_type))
855     {
856       /* find a new pty, open the master side, return the opened
857          file handle, and store the name of the corresponding slave
858          side in global variable pty_name. */
859       outchannel = inchannel = allocate_pty ();
860     }
861
862   if (inchannel >= 0)
863     {
864       /* You're "supposed" to now open the slave in the child.
865          On some systems, we can open it here; this allows for
866          better error checking. */
867 #if !defined(USG)
868       /* On USG systems it does not work to open the pty's tty here
869          and then close and reopen it in the child.  */
870 #ifdef O_NOCTTY
871       /* Don't let this terminal become our controlling terminal
872          (in case we don't have one).  */
873       forkout = forkin = open (pty_name, O_RDWR | O_NOCTTY | OPEN_BINARY, 0);
874 #else
875       forkout = forkin = open (pty_name, O_RDWR | OPEN_BINARY, 0);
876 #endif
877       if (forkin < 0)
878         goto io_failure;
879 #endif /* not USG */
880       UNIX_DATA(p)->pty_flag = pty_flag = 1;
881     }
882   else
883 #endif /* HAVE_PTYS */
884     if (create_bidirectional_pipe (&inchannel, &outchannel,
885                                    &forkin, &forkout) < 0)
886       goto io_failure;
887
888 #if 0
889   /* Replaced by close_process_descs */
890   set_exclusive_use (inchannel);
891   set_exclusive_use (outchannel);
892 #endif
893
894   set_descriptor_non_blocking (inchannel);
895
896   /* Record this as an active process, with its channels.
897      As a result, child_setup will close Emacs's side of the pipes.  */
898   init_process_io_handles (p, (void*)inchannel, (void*)outchannel,
899                            pty_flag ? STREAM_PTY_FLUSHING : 0);
900   /* Record the tty descriptor used in the subprocess.  */
901   UNIX_DATA(p)->subtty = forkin;
902
903   {
904 #if !defined(CYGWIN)
905     /* child_setup must clobber environ on systems with true vfork.
906        Protect it from permanent change.  */
907     char **save_environ = environ;
908 #endif
909
910     pid = fork ();
911     if (pid == 0)
912       {
913         /**** Now we're in the child process ****/
914         int xforkin = forkin;
915         int xforkout = forkout;
916
917         /* Disconnect the current controlling terminal, pursuant to
918            making the pty be the controlling terminal of the process.
919            Also put us in our own process group. */
920
921         disconnect_controlling_terminal ();
922
923 #ifdef HAVE_PTYS
924         if (pty_flag)
925           {
926             /* Open the pty connection and make the pty's terminal
927                our controlling terminal.
928
929                On systems with TIOCSCTTY, we just use it to set
930                the controlling terminal.  On other systems, the
931                first TTY we open becomes the controlling terminal.
932                So, we end up with four possibilities:
933
934                (1) on USG and TIOCSCTTY systems, we open the pty
935                    and use TIOCSCTTY.
936                (2) on other USG systems, we just open the pty.
937                (3) on non-USG systems with TIOCSCTTY, we
938                    just use TIOCSCTTY. (On non-USG systems, we
939                    already opened the pty in the parent process.)
940                (4) on non-USG systems without TIOCSCTTY, we
941                    close the pty and reopen it.
942
943                This would be cleaner if we didn't open the pty
944                in the parent process, but doing it that way
945                makes it possible to trap error conditions.
946                It's harder to convey an error from the child
947                process, and I don't feel like messing with
948                this now. */
949
950             /* There was some weirdo, probably wrong,
951                conditionalization on RTU and UNIPLUS here.
952                I deleted it.  So sue me. */
953
954             /* SunOS has TIOCSCTTY but the close/open method
955                also works. */
956
957 #  if defined (USG) || !defined (TIOCSCTTY)
958             /* Now close the pty (if we had it open) and reopen it.
959                This makes the pty the controlling terminal of the
960                subprocess.  */
961             /* I wonder if close (open (pty_name, ...)) would work?  */
962             if (xforkin >= 0)
963               close (xforkin);
964             xforkout = xforkin = open (pty_name, O_RDWR | OPEN_BINARY, 0);
965             if (xforkin < 0)
966               {
967                 write (1, "Couldn't open the pty terminal ", 31);
968                 write (1, pty_name, strlen (pty_name));
969                 write (1, "\n", 1);
970                 _exit (1);
971               }
972 #  endif /* USG or not TIOCSCTTY */
973
974             /* Miscellaneous setup required for some systems.
975                Must be done before using tc* functions on xforkin.
976                This guarantees that isatty(xforkin) is true. */
977
978 #  if defined (HAVE_ISASTREAM) && defined (I_PUSH)
979             if (isastream (xforkin))
980               {
981 #    if defined (I_FIND)
982 #      define stream_module_pushed(fd, module) (ioctl (fd, I_FIND, module) == 1)
983 #    else
984 #      define stream_module_pushed(fd, module) 0
985 #    endif
986                 if (! stream_module_pushed (xforkin, "ptem"))
987                   ioctl (xforkin, I_PUSH, "ptem");
988                 if (! stream_module_pushed (xforkin, "ldterm"))
989                   ioctl (xforkin, I_PUSH, "ldterm");
990                 if (! stream_module_pushed (xforkin, "ttcompat"))
991                   ioctl (xforkin, I_PUSH, "ttcompat");
992               }
993 #  endif /* HAVE_ISASTREAM */
994
995 #  ifdef TIOCSCTTY
996             /* We ignore the return value
997                because faith@cs.unc.edu says that is necessary on Linux.  */
998             assert (isatty (xforkin));
999             ioctl (xforkin, TIOCSCTTY, 0);
1000 #  endif /* TIOCSCTTY */
1001
1002             /* Change the line discipline. */
1003
1004 # if defined (HAVE_TERMIOS) && defined (LDISC1)
1005             {
1006               struct termios t;
1007               assert (isatty (xforkin));
1008               tcgetattr (xforkin, &t);
1009               t.c_lflag = LDISC1;
1010               if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1011                 perror ("create_process/tcsetattr LDISC1 failed\n");
1012             }
1013 # elif defined (NTTYDISC) && defined (TIOCSETD)
1014             {
1015               /* Use new line discipline.  TIOCSETD is accepted and
1016                  ignored on Sys5.4 systems with ttcompat. */
1017               int ldisc = NTTYDISC;
1018               assert (isatty (xforkin));
1019               ioctl (xforkin, TIOCSETD, &ldisc);
1020             }
1021 # endif /* TIOCSETD & NTTYDISC */
1022
1023             /* Make our process group be the foreground group
1024                of our new controlling terminal. */
1025
1026             {
1027               pid_t piddly = EMACS_GET_PROCESS_GROUP ();
1028               EMACS_SET_TTY_PROCESS_GROUP (xforkin, &piddly);
1029             }
1030
1031             /* On AIX, we've disabled SIGHUP above once we start a
1032                child on a pty.  Now reenable it in the child, so it
1033                will die when we want it to.
1034                JV: This needs to be done ALWAYS as we might have inherited
1035                a SIG_IGN handling from our parent (nohup) and we are in new
1036                process group.
1037             */
1038             signal (SIGHUP, SIG_DFL);
1039           }
1040
1041         if (pty_flag)
1042           /* Set up the terminal characteristics of the pty. */
1043           child_setup_tty (xforkout);
1044
1045 #endif /* HAVE_PTYS */
1046
1047         signal (SIGINT,  SIG_DFL);
1048         signal (SIGQUIT, SIG_DFL);
1049
1050         {
1051           char *current_dir;
1052           char **new_argv = alloca_array (char *, nargv + 2);
1053           int i;
1054
1055           /* Nothing below here GCs so our string pointers shouldn't move. */
1056           new_argv[0] = (char *) XSTRING_DATA (program);
1057           for (i = 0; i < nargv; i++)
1058             {
1059               CHECK_STRING (argv[i]);
1060               new_argv[i + 1] = (char *) XSTRING_DATA (argv[i]);
1061             }
1062           new_argv[i + 1] = 0;
1063
1064           LISP_STRING_TO_EXTERNAL (cur_dir, current_dir, Qfile_name);
1065
1066           child_setup (xforkin, xforkout, xforkout, new_argv, current_dir);
1067         }
1068
1069       } /**** End of child code ****/
1070
1071     /**** Back in parent process ****/
1072 #if !defined(CYGWIN)
1073     environ = save_environ;
1074 #endif
1075   }
1076
1077   if (pid < 0)
1078     {
1079       int save_errno = errno;
1080       close_descriptor_pair (forkin, forkout);
1081       errno = save_errno;
1082       report_file_error ("Doing fork", Qnil);
1083     }
1084
1085   /* #### dmoore - why is this commented out, otherwise we leave
1086      subtty = forkin, but then we close forkin just below. */
1087   /* UNIX_DATA(p)->subtty = -1; */
1088
1089   /* If the subfork execv fails, and it exits,
1090      this close hangs.  I don't know why.
1091      So have an interrupt jar it loose.  */
1092   if (forkin >= 0)
1093     close_safely (forkin);
1094   if (forkin != forkout && forkout >= 0)
1095     close (forkout);
1096
1097 #ifdef HAVE_PTYS
1098   if (pty_flag)
1099     UNIX_DATA (p)->tty_name = build_string (pty_name);
1100   else
1101 #endif
1102     UNIX_DATA (p)->tty_name = Qnil;
1103
1104   /* Notice that SIGCHLD was not blocked. (This is not possible on
1105      some systems.) No biggie if SIGCHLD occurs right around the
1106      time that this call happens, because SIGCHLD() does not actually
1107      deselect the process (that doesn't occur until the next time
1108      we're waiting for an event, when status_notify() is called). */
1109   return pid;
1110
1111 io_failure:
1112   {
1113     int save_errno = errno;
1114     close_descriptor_pair (forkin, forkout);
1115     close_descriptor_pair (inchannel, outchannel);
1116     errno = save_errno;
1117     report_file_error ("Opening pty or pipe", Qnil);
1118     return 0; /* not reached */
1119   }
1120 }
1121
1122 /* Return nonzero if this process is a ToolTalk connection. */
1123
1124 static int
1125 unix_tooltalk_connection_p (Lisp_Process *p)
1126 {
1127   return UNIX_DATA(p)->connected_via_filedesc_p;
1128 }
1129
1130 /* This is called to set process' virtual terminal size */
1131
1132 static int
1133 unix_set_window_size (Lisp_Process* p, int cols, int rows)
1134 {
1135   return set_window_size (UNIX_DATA(p)->infd, cols, rows);
1136 }
1137
1138 /*
1139  * This method is called to update status fields of the process
1140  * structure. If the process has not existed, this method is
1141  * expected to do nothing.
1142  *
1143  * The method is called only for real child processes.
1144  */
1145
1146 #ifdef HAVE_WAITPID
1147 static void
1148 unix_update_status_if_terminated (Lisp_Process* p)
1149 {
1150   int w;
1151 #ifdef SIGCHLD
1152   EMACS_BLOCK_SIGNAL (SIGCHLD);
1153 #endif
1154   if (waitpid (XINT (p->pid), &w, WNOHANG) == XINT (p->pid))
1155     {
1156       p->tick++;
1157       update_status_from_wait_code (p, &w);
1158     }
1159 #ifdef SIGCHLD
1160   EMACS_UNBLOCK_SIGNAL (SIGCHLD);
1161 #endif
1162 }
1163 #endif
1164
1165 /*
1166  * Update status of all exited processes. Called when SIGCLD has signaled.
1167  */
1168
1169 #ifdef SIGCHLD
1170 static void
1171 unix_reap_exited_processes (void)
1172 {
1173   int i;
1174   Lisp_Process *p;
1175
1176 #ifndef OBNOXIOUS_SYSV_SIGCLD_BEHAVIOR
1177   record_exited_processes (1);
1178 #endif
1179
1180   if (exited_processes_index <= 0)
1181     {
1182       return;
1183     }
1184
1185 #ifdef  EMACS_BLOCK_SIGNAL
1186   EMACS_BLOCK_SIGNAL (SIGCHLD);
1187 #endif
1188   for (i = 0; i < exited_processes_index; i++)
1189     {
1190       int pid = exited_processes[i];
1191       int w = exited_processes_status[i];
1192
1193       /* Find the process that signaled us, and record its status.  */
1194
1195       p = 0;
1196       {
1197         Lisp_Object tail;
1198         LIST_LOOP (tail, Vprocess_list)
1199           {
1200             Lisp_Object proc = XCAR (tail);
1201             p = XPROCESS (proc);
1202             if (INTP (p->pid) && XINT (p->pid) == pid)
1203               break;
1204             p = 0;
1205           }
1206       }
1207
1208       if (p)
1209         {
1210           /* Change the status of the process that was found.  */
1211           p->tick++;
1212           process_tick++;
1213           update_status_from_wait_code (p, &w);
1214
1215           /* If process has terminated, stop waiting for its output.  */
1216           if (WIFSIGNALED (w) || WIFEXITED (w))
1217             {
1218               if (!NILP(p->pipe_instream))
1219                 {
1220                   /* We can't just call event_stream->unselect_process_cb (p)
1221                      here, because that calls XtRemoveInput, which is not
1222                      necessarily reentrant, so we can't call this at interrupt
1223                      level.
1224                    */
1225                 }
1226             }
1227         }
1228       else
1229         {
1230           /* There was no asynchronous process found for that id.  Check
1231              if we have a synchronous process. Only set sync process status
1232              if there is one, so we work OK with the waitpid() call in
1233              wait_for_termination(). */
1234           if (synch_process_alive != 0)
1235             { /* Set the global sync process status variables. */
1236               synch_process_alive = 0;
1237
1238               /* Report the status of the synchronous process.  */
1239               if (WIFEXITED (w))
1240                 synch_process_retcode = WEXITSTATUS (w);
1241               else if (WIFSIGNALED (w))
1242                 synch_process_death = signal_name (WTERMSIG (w));
1243             }
1244         }
1245     }
1246
1247   exited_processes_index = 0;
1248
1249   EMACS_UNBLOCK_SIGNAL (SIGCHLD);
1250 }
1251 #endif /* SIGCHLD */
1252
1253 /*
1254  * Stuff the entire contents of LSTREAM to the process output pipe
1255  */
1256
1257 static JMP_BUF send_process_frame;
1258
1259 static SIGTYPE
1260 send_process_trap (int signum)
1261 {
1262   EMACS_REESTABLISH_SIGNAL (signum, send_process_trap);
1263   EMACS_UNBLOCK_SIGNAL (signum);
1264   LONGJMP (send_process_frame, 1);
1265 }
1266
1267 static void
1268 unix_send_process (Lisp_Object proc, struct lstream* lstream)
1269 {
1270   /* Use volatile to protect variables from being clobbered by longjmp.  */
1271   SIGTYPE (*volatile old_sigpipe) (int) = 0;
1272   volatile Lisp_Object vol_proc = proc;
1273   Lisp_Process *volatile p = XPROCESS (proc);
1274
1275   /* #### JV: layering violation?
1276
1277      This function knows too much about the relation between the encoding
1278      stream (DATA_OUTSTREAM) and the actual output stream p->output_stream.
1279
1280      If encoding streams properly forwarded all calls, we could simply
1281      use DATA_OUTSTREAM everywhere. */
1282
1283   if (!SETJMP (send_process_frame))
1284     {
1285       /* use a reasonable-sized buffer (somewhere around the size of the
1286          stream buffer) so as to avoid inundating the stream with blocked
1287          data. */
1288       Bufbyte chunkbuf[512];
1289       Bytecount chunklen;
1290
1291       while (1)
1292         {
1293           Lstream_data_count writeret;
1294
1295           chunklen = Lstream_read (lstream, chunkbuf, 512);
1296           if (chunklen <= 0)
1297             break; /* perhaps should abort() if < 0?
1298                       This should never happen. */
1299           old_sigpipe =
1300             (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
1301           /* Lstream_write() will never successfully write less than
1302              the amount sent in.  In the worst case, it just buffers
1303              the unwritten data. */
1304           writeret = Lstream_write (XLSTREAM (DATA_OUTSTREAM(p)), chunkbuf,
1305                                     chunklen);
1306           signal (SIGPIPE, old_sigpipe);
1307           if (writeret < 0)
1308             /* This is a real error.  Blocking errors are handled
1309                specially inside of the filedesc stream. */
1310             report_file_error ("writing to process", list1 (proc));
1311           while (Lstream_was_blocked_p (XLSTREAM (p->pipe_outstream)))
1312             {
1313               /* Buffer is full.  Wait, accepting input;
1314                  that may allow the program
1315                  to finish doing output and read more.  */
1316               Faccept_process_output (Qnil, make_int (1), Qnil);
1317               /* It could have *really* finished, deleting the process */
1318               if (NILP(p->pipe_outstream))
1319                 return;
1320               old_sigpipe =
1321                 (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
1322               Lstream_flush (XLSTREAM (p->pipe_outstream));
1323               signal (SIGPIPE, old_sigpipe);
1324             }
1325         }
1326     }
1327   else
1328     { /* We got here from a longjmp() from the SIGPIPE handler */
1329       signal (SIGPIPE, old_sigpipe);
1330       /* Close the file lstream so we don't attempt to write to it further */
1331       /* #### There is controversy over whether this might cause fd leakage */
1332       /*      my tests say no. -slb */
1333       XLSTREAM (p->pipe_outstream)->flags &= ~LSTREAM_FL_IS_OPEN;
1334 #ifdef FILE_CODING
1335       XLSTREAM (p->coding_outstream)->flags &= ~LSTREAM_FL_IS_OPEN;
1336 #endif
1337       p->status_symbol = Qexit;
1338       p->exit_code = 256; /* #### SIGPIPE ??? */
1339       p->core_dumped = 0;
1340       p->tick++;
1341       process_tick++;
1342       deactivate_process (vol_proc);
1343       invalid_operation ("SIGPIPE raised on process; closed it", p->name);
1344     }
1345
1346   old_sigpipe = (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
1347   Lstream_flush (XLSTREAM (DATA_OUTSTREAM(p)));
1348   signal (SIGPIPE, old_sigpipe);
1349 }
1350
1351 /*
1352  * Send EOF to the process. The default implementation simply
1353  * closes the output stream. The method must return 0 to call
1354  * the default implementation, or 1 if it has taken all care about
1355  * sending EOF to the process.
1356  */
1357
1358 static int
1359 unix_process_send_eof (Lisp_Object proc)
1360 {
1361   if (!UNIX_DATA (XPROCESS (proc))->pty_flag)
1362     return 0;
1363
1364   /* #### get_eof_char simply doesn't return the correct character
1365      here.  Maybe it is needed to determine the right eof
1366      character in init_process_io_handles but here it simply screws
1367      things up. */
1368 #if 0
1369   Bufbyte eof_char = get_eof_char (XPROCESS (proc));
1370   send_process (proc, Qnil, &eof_char, 0, 1);
1371 #else
1372   send_process (proc, Qnil, (const Bufbyte *) "\004", 0, 1);
1373 #endif
1374   return 1;
1375 }
1376
1377 /*
1378  * Called before the process is deactivated. The process object
1379  * is not immediately finalized, just undergoes a transition to
1380  * inactive state.
1381  *
1382  * The return value is a unique stream ID, as returned by
1383  * event_stream_delete_stream_pair
1384  *
1385  * In the lack of this method, only event_stream_delete_stream_pair
1386  * is called on both I/O streams of the process.
1387  *
1388  * The UNIX version guards this by ignoring possible SIGPIPE.
1389  */
1390
1391 static USID
1392 unix_deactivate_process (Lisp_Process *p)
1393 {
1394   SIGTYPE (*old_sigpipe) (int) = 0;
1395   USID usid;
1396
1397   if (UNIX_DATA(p)->infd >= 0)
1398     flush_pending_output (UNIX_DATA(p)->infd);
1399
1400   /* closing the outstream could result in SIGPIPE, so ignore it. */
1401   old_sigpipe = (SIGTYPE (*) (int)) signal (SIGPIPE, SIG_IGN);
1402   usid = event_stream_delete_stream_pair (p->pipe_instream, p->pipe_outstream);
1403   signal (SIGPIPE, old_sigpipe);
1404
1405   UNIX_DATA(p)->infd  = -1;
1406
1407   return usid;
1408 }
1409
1410 /* If the subtty field of the process data is not filled in, do so now. */
1411 static void
1412 try_to_initialize_subtty (struct unix_process_data *upd)
1413 {
1414   if (upd->pty_flag
1415       && (upd->subtty == -1 || ! isatty (upd->subtty))
1416       && STRINGP (upd->tty_name))
1417     upd->subtty = open ((char *) XSTRING_DATA (upd->tty_name), O_RDWR, 0);
1418 }
1419
1420 /* Send signal number SIGNO to PROCESS.
1421    CURRENT_GROUP means send to the process group that currently owns
1422    the terminal being used to communicate with PROCESS.
1423    This is used for various commands in shell mode.
1424    If NOMSG is zero, insert signal-announcements into process's buffers
1425    right away.
1426
1427    If we can, we try to signal PROCESS by sending control characters
1428    down the pty.  This allows us to signal inferiors who have changed
1429    their uid, for which killpg would return an EPERM error,
1430    or processes running on other machines via remote login.
1431
1432    The method signals an error if the given SIGNO is not valid. */
1433
1434 static void
1435 unix_kill_child_process (Lisp_Object proc, int signo,
1436                          int current_group, int nomsg)
1437 {
1438   pid_t pgid = -1;
1439   Lisp_Process *p = XPROCESS (proc);
1440   struct unix_process_data *d = UNIX_DATA (p);
1441
1442   switch (signo)
1443     {
1444 #ifdef SIGCONT
1445     case SIGCONT:
1446       p->status_symbol = Qrun;
1447       p->exit_code = 0;
1448       p->tick++;
1449       process_tick++;
1450       if (!nomsg)
1451         status_notify ();
1452       break;
1453 #endif /* ! defined (SIGCONT) */
1454     case SIGINT:
1455     case SIGQUIT:
1456     case SIGKILL:
1457       flush_pending_output (d->infd);
1458       break;
1459     }
1460
1461   if (! d->pty_flag)
1462     current_group = 0;
1463
1464   /* If current_group is true, we want to send a signal to the
1465      foreground process group of the terminal our child process is
1466      running on.  You would think that would be easy.
1467
1468      The BSD people invented the TIOCPGRP ioctl to get the foreground
1469      process group of a tty.  That, combined with killpg, gives us
1470      what we want.
1471
1472      However, the POSIX standards people, in their infinite wisdom,
1473      have seen fit to only allow this for processes which have the
1474      terminal as controlling terminal, which doesn't apply to us.
1475
1476      Sooo..., we have to do something non-standard.  The ioctls
1477      TIOCSIGNAL, TIOCSIG, and TIOCSIGSEND send the signal directly on
1478      many systems.  POSIX tcgetpgrp(), since it is *documented* as not
1479      doing what we want, is actually less likely to work than the BSD
1480      ioctl TIOCGPGRP it is supposed to obsolete.  Sometimes we have to
1481      use TIOCGPGRP on the master end, sometimes the slave end
1482      (probably an AIX bug).  So we better get a fd for the slave if we
1483      haven't got it yet.
1484
1485      Anal operating systems like SGI Irix and Compaq Tru64 adhere
1486      strictly to the letter of the law, so our hack doesn't work.
1487      The following fragment from an Irix header file is suggestive:
1488
1489      #ifdef __notdef__
1490      // this is not currently supported
1491      #define TIOCSIGNAL      (tIOC|31)       // pty: send signal to slave
1492      #endif
1493
1494      On those systems where none of our tricks work, we just fall back
1495      to the non-current_group behavior and kill the process group of
1496      the child.
1497   */
1498   if (current_group)
1499     {
1500       try_to_initialize_subtty (d);
1501
1502 #ifdef SIGNALS_VIA_CHARACTERS
1503       /* If possible, send signals to the entire pgrp
1504          by sending an input character to it.  */
1505       {
1506         char sigchar = process_signal_char (d->subtty, signo);
1507         if (sigchar)
1508           {
1509             send_process (proc, Qnil, (Bufbyte *) &sigchar, 0, 1);
1510             return;
1511           }
1512       }
1513 #endif /* SIGNALS_VIA_CHARACTERS */
1514
1515 #ifdef TIOCGPGRP
1516       if (pgid == -1)
1517         ioctl (d->infd, TIOCGPGRP, &pgid); /* BSD */
1518       if (pgid == -1 && d->subtty != -1)
1519         ioctl (d->subtty, TIOCGPGRP, &pgid); /* Only this works on AIX! */
1520 #endif /* TIOCGPGRP */
1521
1522       if (pgid == -1)
1523         {
1524           /* Many systems provide an ioctl to send a signal directly */
1525 #ifdef TIOCSIGNAL /* Solaris, HP-UX */
1526           if (ioctl (d->infd, TIOCSIGNAL, signo) != -1)
1527             return;
1528 #endif /* TIOCSIGNAL */
1529
1530 #ifdef TIOCSIG /* BSD */
1531           if (ioctl (d->infd, TIOCSIG, signo) != -1)
1532             return;
1533 #endif /* TIOCSIG */
1534         }
1535     } /* current_group */
1536
1537   if (pgid == -1)
1538     /* Either current_group is 0, or we failed to get the foreground
1539        process group using the trickery above.  So we fall back to
1540        sending the signal to the process group of our child process.
1541        Since this is often a shell that ignores signals like SIGINT,
1542        the shell's subprocess is killed, which is the desired effect.
1543        The process group of p->pid is always p->pid, since it was
1544        created as a process group leader. */
1545     pgid = XINT (p->pid);
1546
1547   /* Finally send the signal. */
1548   if (EMACS_KILLPG (pgid, signo) == -1)
1549     {
1550       /* It's not an error if our victim is already dead.
1551          And we can't rely on the result of killing a zombie, since
1552          XPG 4.2 requires that killing a zombie fail with ESRCH,
1553          while FIPS 151-2 requires that it succeeds! */
1554 #ifdef ESRCH
1555       if (errno != ESRCH)
1556 #endif
1557         error ("kill (%ld, %ld) failed: %s",
1558                (long) pgid, (long) signo, strerror (errno));
1559     }
1560 }
1561
1562 /* Send signal SIGCODE to any process in the system given its PID.
1563    Return zero if successful, a negative number upon failure. */
1564
1565 static int
1566 unix_kill_process_by_pid (int pid, int sigcode)
1567 {
1568   return kill (pid, sigcode);
1569 }
1570
1571 /* Return TTY name used to communicate with subprocess. */
1572
1573 static Lisp_Object
1574 unix_get_tty_name (Lisp_Process *p)
1575 {
1576   return UNIX_DATA (p)->tty_name;
1577 }
1578
1579 /* Canonicalize host name HOST, and return its canonical form.
1580    The default implementation just takes HOST for a canonical name. */
1581
1582 #ifdef HAVE_SOCKETS
1583 static Lisp_Object
1584 unix_canonicalize_host_name (Lisp_Object host)
1585 {
1586 #if defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO)
1587   struct addrinfo hints, *res;
1588   static char addrbuf[NI_MAXHOST];
1589   Lisp_Object canonname;
1590   int retval;
1591   char *ext_host;
1592
1593   xzero (hints);
1594   hints.ai_flags = AI_CANONNAME;
1595 #ifdef IPV6_CANONICALIZE
1596   hints.ai_family = AF_UNSPEC;
1597 #else
1598   hints.ai_family = PF_INET;
1599 #endif
1600   hints.ai_socktype = SOCK_STREAM;
1601   hints.ai_protocol = 0;
1602   LISP_STRING_TO_EXTERNAL (host, ext_host, Qnative);
1603   retval = getaddrinfo (ext_host, NULL, &hints, &res);
1604   if (retval != 0)
1605     {
1606       char *gai_error;
1607
1608       EXTERNAL_TO_C_STRING (gai_strerror (retval), gai_error, Qnative);
1609       maybe_error (Qprocess, ERROR_ME_NOT,
1610                    "%s \"%s\"", gai_error, XSTRING_DATA (host));
1611       canonname = host;
1612     }
1613   else
1614     {
1615       int gni = getnameinfo (res->ai_addr, res->ai_addrlen,
1616                              addrbuf, sizeof(addrbuf),
1617                              NULL, 0, NI_NUMERICHOST);
1618       canonname = gni ? host : build_ext_string (addrbuf, Qnative);
1619
1620       freeaddrinfo (res);
1621     }
1622
1623   return canonname;
1624 #else /* ! HAVE_GETADDRINFO */
1625   struct sockaddr_in address;
1626
1627   if (!get_internet_address (host, &address, ERROR_ME_NOT))
1628     return host;
1629
1630   if (address.sin_family == AF_INET)
1631     return build_string (inet_ntoa (address.sin_addr));
1632   else
1633     /* #### any clue what to do here? */
1634     return host;
1635 #endif /* ! HAVE_GETADDRINFO */
1636 }
1637
1638 /* Open a TCP network connection to a given HOST/SERVICE.
1639    Treated exactly like a normal process when reading and writing.
1640    Only differences are in status display and process deletion.
1641    A network connection has no PID; you cannot signal it.  All you can
1642    do is deactivate and close it via delete-process. */
1643
1644 static void
1645 unix_open_network_stream (Lisp_Object name, Lisp_Object host, Lisp_Object service,
1646                           Lisp_Object protocol, void** vinfd, void** voutfd)
1647 {
1648   int inch;
1649   int outch;
1650   volatile int s;
1651   volatile int port;
1652   volatile int retry = 0;
1653   int retval;
1654
1655   CHECK_STRING (host);
1656
1657   if (!EQ (protocol, Qtcp) && !EQ (protocol, Qudp))
1658     invalid_argument ("Unsupported protocol", protocol);
1659
1660   {
1661 #if defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO)
1662     struct addrinfo hints, *res;
1663     struct addrinfo * volatile lres;
1664     char *portstring;
1665     volatile int xerrno = 0;
1666     volatile int failed_connect = 0;
1667     char *ext_host;
1668     /*
1669      * Caution: service can either be a string or int.
1670      * Convert to a C string for later use by getaddrinfo.
1671      */
1672     if (INTP (service))
1673       {
1674         char portbuf[128];
1675         snprintf (portbuf, sizeof (portbuf), "%ld", (long) XINT (service));
1676         portstring = portbuf;
1677         port = htons ((unsigned short) XINT (service));
1678       }
1679     else
1680       {
1681         CHECK_STRING (service);
1682         LISP_STRING_TO_EXTERNAL (service, portstring, Qnative);
1683         port = 0;
1684       }
1685
1686     xzero (hints);
1687     hints.ai_flags = 0;
1688     hints.ai_family = AF_UNSPEC;
1689     if (EQ (protocol, Qtcp))
1690       hints.ai_socktype = SOCK_STREAM;
1691     else /* EQ (protocol, Qudp) */
1692       hints.ai_socktype = SOCK_DGRAM;
1693     hints.ai_protocol = 0;
1694     LISP_STRING_TO_EXTERNAL (host, ext_host, Qnative);
1695     retval = getaddrinfo (ext_host, portstring, &hints, &res);
1696     if (retval != 0)
1697       {
1698         char *gai_error;
1699
1700         EXTERNAL_TO_C_STRING (gai_strerror (retval), gai_error, Qnative);
1701         error ("%s/%s %s", XSTRING_DATA (host), portstring, gai_error);
1702       }
1703
1704     /* address loop */
1705     for (lres = res; lres ; lres = lres->ai_next)
1706       {
1707         if (EQ (protocol, Qtcp))
1708           s = socket (lres->ai_family, SOCK_STREAM, 0);
1709         else /* EQ (protocol, Qudp) */
1710           s = socket (lres->ai_family, SOCK_DGRAM, 0);
1711
1712         if (s < 0)
1713           continue;
1714
1715         /* Turn off interrupts here -- see comments below.  There used to
1716            be code which called bind_polling_period() to slow the polling
1717            period down rather than turn it off, but that seems rather
1718            bogus to me.  Best thing here is to use a non-blocking connect
1719            or something, to check for QUIT. */
1720
1721         /* Comments that are not quite valid: */
1722
1723         /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
1724            when connect is interrupted.  So let's not let it get interrupted.
1725            Note we do not turn off polling, because polling is only used
1726            when not interrupt_input, and thus not normally used on the systems
1727            which have this bug.  On systems which use polling, there's no way
1728            to quit if polling is turned off.  */
1729
1730         /* Slow down polling.  Some kernels have a bug which causes retrying
1731            connect to fail after a connect.  */
1732
1733         slow_down_interrupts ();
1734
1735       loop:
1736
1737         /* A system call interrupted with a SIGALRM or SIGIO comes back
1738            here, with can_break_system_calls reset to 0. */
1739         SETJMP (break_system_call_jump);
1740         if (QUITP)
1741           {
1742             speed_up_interrupts ();
1743             REALLY_QUIT;
1744             /* In case something really weird happens ... */
1745             slow_down_interrupts ();
1746           }
1747
1748         /* Break out of connect with a signal (it isn't otherwise possible).
1749            Thus you don't get screwed with a hung network. */
1750         can_break_system_calls = 1;
1751         retval = connect (s, lres->ai_addr, lres->ai_addrlen);
1752         can_break_system_calls = 0;
1753         if (retval == -1)
1754           {
1755             xerrno = errno;
1756             if (errno != EISCONN)
1757               {
1758                 if (errno == EINTR)
1759                   goto loop;
1760                 if (errno == EADDRINUSE && retry < 20)
1761                   {
1762                     /* A delay here is needed on some FreeBSD systems,
1763                        and it is harmless, since this retrying takes time anyway
1764                        and should be infrequent.
1765                        `sleep-for' allowed for quitting this loop with interrupts
1766                        slowed down so it can't be used here.  Async timers should
1767                        already be disabled at this point so we can use `sleep'. */
1768                     sleep (1);
1769                     retry++;
1770                     goto loop;
1771                   }
1772               }
1773
1774             failed_connect = 1;
1775             close (s);
1776             s = -1;
1777
1778             speed_up_interrupts ();
1779
1780             continue;
1781           }
1782
1783         if (port == 0)
1784           {
1785             int gni;
1786             char servbuf[NI_MAXSERV];
1787
1788             if (EQ (protocol, Qtcp))
1789               gni = getnameinfo (lres->ai_addr, lres->ai_addrlen,
1790                                  NULL, 0, servbuf, sizeof(servbuf),
1791                                  NI_NUMERICSERV);
1792             else /* EQ (protocol, Qudp) */
1793               gni = getnameinfo (lres->ai_addr, lres->ai_addrlen,
1794                                  NULL, 0, servbuf, sizeof(servbuf),
1795                                  NI_NUMERICSERV | NI_DGRAM);
1796
1797             if (gni == 0)
1798               port = strtol (servbuf, NULL, 10);
1799           }
1800
1801         break;
1802       } /* address loop */
1803
1804     speed_up_interrupts ();
1805
1806     freeaddrinfo (res);
1807     if (s < 0)
1808       {
1809         errno = xerrno;
1810
1811         if (failed_connect)
1812           report_file_error ("connection failed", list2 (host, name));
1813         else
1814           report_file_error ("error creating socket", list1 (name));
1815       }
1816 #else /* ! HAVE_GETADDRINFO */
1817     struct sockaddr_in address;
1818
1819     if (INTP (service))
1820       port = htons ((unsigned short) XINT (service));
1821     else
1822       {
1823         struct servent *svc_info;
1824         CHECK_STRING (service);
1825
1826         if (EQ (protocol, Qtcp))
1827           svc_info = getservbyname ((char *) XSTRING_DATA (service), "tcp");
1828         else /* EQ (protocol, Qudp) */
1829           svc_info = getservbyname ((char *) XSTRING_DATA (service), "udp");
1830
1831         if (svc_info == 0)
1832           invalid_argument ("Unknown service", service);
1833         port = svc_info->s_port;
1834       }
1835
1836     get_internet_address (host, &address, ERROR_ME);
1837     address.sin_port = port;
1838
1839     if (EQ (protocol, Qtcp))
1840       s = socket (address.sin_family, SOCK_STREAM, 0);
1841     else /* EQ (protocol, Qudp) */
1842       s = socket (address.sin_family, SOCK_DGRAM, 0);
1843
1844     if (s < 0)
1845       report_file_error ("error creating socket", list1 (name));
1846
1847     /* Turn off interrupts here -- see comments below.  There used to
1848        be code which called bind_polling_period() to slow the polling
1849        period down rather than turn it off, but that seems rather
1850        bogus to me.  Best thing here is to use a non-blocking connect
1851        or something, to check for QUIT. */
1852
1853     /* Comments that are not quite valid: */
1854
1855     /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
1856        when connect is interrupted.  So let's not let it get interrupted.
1857        Note we do not turn off polling, because polling is only used
1858        when not interrupt_input, and thus not normally used on the systems
1859        which have this bug.  On systems which use polling, there's no way
1860        to quit if polling is turned off.  */
1861
1862     /* Slow down polling.  Some kernels have a bug which causes retrying
1863        connect to fail after a connect.  */
1864
1865     slow_down_interrupts ();
1866
1867   loop:
1868
1869     /* A system call interrupted with a SIGALRM or SIGIO comes back
1870        here, with can_break_system_calls reset to 0. */
1871     SETJMP (break_system_call_jump);
1872     if (QUITP)
1873       {
1874         speed_up_interrupts ();
1875         REALLY_QUIT;
1876         /* In case something really weird happens ... */
1877         slow_down_interrupts ();
1878       }
1879
1880     /* Break out of connect with a signal (it isn't otherwise possible).
1881        Thus you don't get screwed with a hung network. */
1882     can_break_system_calls = 1;
1883     retval = connect (s, (struct sockaddr *) &address, sizeof (address));
1884     can_break_system_calls = 0;
1885     if (retval == -1 && errno != EISCONN)
1886       {
1887         int xerrno = errno;
1888         if (errno == EINTR)
1889           goto loop;
1890         if (errno == EADDRINUSE && retry < 20)
1891           {
1892             /* A delay here is needed on some FreeBSD systems,
1893                and it is harmless, since this retrying takes time anyway
1894                and should be infrequent.
1895                `sleep-for' allowed for quitting this loop with interrupts
1896                slowed down so it can't be used here.  Async timers should
1897                already be disabled at this point so we can use `sleep'. */
1898             sleep (1);
1899             retry++;
1900             goto loop;
1901           }
1902
1903         close (s);
1904
1905         speed_up_interrupts ();
1906
1907         errno = xerrno;
1908         report_file_error ("connection failed", list2 (host, name));
1909       }
1910
1911     speed_up_interrupts ();
1912 #endif /* ! HAVE_GETADDRINFO */
1913   }
1914
1915   inch = s;
1916   outch = dup (s);
1917   if (outch < 0)
1918     {
1919       close (s); /* this used to be leaked; from Kyle Jones */
1920       report_file_error ("error duplicating socket", list1 (name));
1921     }
1922
1923   set_socket_nonblocking_maybe (inch, port, "tcp");
1924
1925   *vinfd = (void*)inch;
1926   *voutfd = (void*)outch;
1927 }
1928
1929
1930 #ifdef HAVE_MULTICAST
1931
1932 /* Didier Verna <didier@xemacs.org> Nov. 28 1997.
1933
1934    This function is similar to open-network-stream-internal, but provides a
1935    mean to open an UDP multicast connection instead of a TCP one. Like in the
1936    TCP case, the multicast connection will be seen as a sub-process,
1937
1938    Some notes:
1939    - Normally, we should use sendto and recvfrom with non connected
1940    sockets. The current code doesn't allow us to do this. In the future, it
1941    would be a good idea to extend the process data structure in order to deal
1942    properly with the different types network connections.
1943    - For the same reason, when leaving a multicast group, it is better to make
1944    a setsockopt - IP_DROP_MEMBERSHIP before closing the descriptors.
1945    Unfortunately, this can't be done here because delete_process doesn't know
1946    about the kind of connection we have. However, this is not such an
1947    important issue.
1948 */
1949
1950 static void
1951 unix_open_multicast_group (Lisp_Object name, Lisp_Object dest,
1952                            Lisp_Object port, Lisp_Object ttl, void** vinfd,
1953                            void** voutfd)
1954 {
1955   struct ip_mreq imr;
1956   struct sockaddr_in sa;
1957   struct protoent *udp;
1958   int ws, rs;
1959   int theport;
1960   unsigned char thettl;
1961   int one = 1; /* For REUSEADDR */
1962   int ret;
1963   volatile int retry = 0;
1964
1965   CHECK_STRING (dest);
1966
1967   CHECK_NATNUM (port);
1968   theport = htons ((unsigned short) XINT (port));
1969
1970   CHECK_NATNUM (ttl);
1971   thettl = (unsigned char) XINT (ttl);
1972
1973   if ((udp = getprotobyname ("udp")) == NULL)
1974     type_error (Qinvalid_operation, "No info available for UDP protocol");
1975
1976   /* Init the sockets. Yes, I need 2 sockets. I couldn't duplicate one. */
1977   if ((rs = socket (PF_INET, SOCK_DGRAM, udp->p_proto)) < 0)
1978     report_file_error ("error creating socket", list1(name));
1979   if ((ws = socket (PF_INET, SOCK_DGRAM, udp->p_proto)) < 0)
1980     {
1981       close (rs);
1982       report_file_error ("error creating socket", list1(name));
1983     }
1984
1985   /* This will be used for both sockets */
1986   memset (&sa, 0, sizeof(sa));
1987   sa.sin_family = AF_INET;
1988   sa.sin_port = theport;
1989   sa.sin_addr.s_addr = inet_addr ((char *) XSTRING_DATA (dest));
1990
1991   /* Socket configuration for reading ------------------------ */
1992
1993   /* Multiple connections from the same machine. This must be done before
1994      bind. If it fails, it shouldn't be fatal. The only consequence is that
1995      people won't be able to connect twice from the same machine. */
1996   if (setsockopt (rs, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof (one))
1997       < 0)
1998     warn_when_safe (Qmulticast, Qwarning, "Cannot reuse socket address");
1999
2000   /* bind socket name */
2001   if (bind (rs, (struct sockaddr *)&sa, sizeof(sa)))
2002     {
2003       close (rs);
2004       close (ws);
2005       report_file_error ("error binding socket", list2(name, port));
2006     }
2007
2008   /* join multicast group */
2009   imr.imr_multiaddr.s_addr = inet_addr ((char *) XSTRING_DATA (dest));
2010   imr.imr_interface.s_addr = htonl (INADDR_ANY);
2011   if (setsockopt (rs, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2012                   &imr, sizeof (struct ip_mreq)) < 0)
2013     {
2014       close (ws);
2015       close (rs);
2016       report_file_error ("error adding membership", list2(name, dest));
2017     }
2018
2019   /* Socket configuration for writing ----------------------- */
2020
2021   /* Normally, there's no 'connect' in multicast, since we prefer to use
2022      'sendto' and 'recvfrom'. However, in order to handle this connection in
2023      the process-like way it is done for TCP, we must be able to use 'write'
2024      instead of 'sendto'. Consequently, we 'connect' this socket. */
2025
2026   /* See open-network-stream-internal for comments on this part of the code */
2027   slow_down_interrupts ();
2028
2029  loop:
2030
2031   /* A system call interrupted with a SIGALRM or SIGIO comes back
2032      here, with can_break_system_calls reset to 0. */
2033   SETJMP (break_system_call_jump);
2034   if (QUITP)
2035     {
2036       speed_up_interrupts ();
2037       REALLY_QUIT;
2038       /* In case something really weird happens ... */
2039       slow_down_interrupts ();
2040     }
2041
2042   /* Break out of connect with a signal (it isn't otherwise possible).
2043      Thus you don't get screwed with a hung network. */
2044   can_break_system_calls = 1;
2045   ret = connect (ws, (struct sockaddr *) &sa, sizeof (sa));
2046   can_break_system_calls = 0;
2047   if (ret == -1 && errno != EISCONN)
2048     {
2049       int xerrno = errno;
2050
2051       if (errno == EINTR)
2052         goto loop;
2053       if (errno == EADDRINUSE && retry < 20)
2054         {
2055           /* A delay here is needed on some FreeBSD systems,
2056              and it is harmless, since this retrying takes time anyway
2057              and should be infrequent.
2058              `sleep-for' allowed for quitting this loop with interrupts
2059              slowed down so it can't be used here.  Async timers should
2060              already be disabled at this point so we can use `sleep'. */
2061           sleep (1);
2062           retry++;
2063           goto loop;
2064         }
2065
2066       close (rs);
2067       close (ws);
2068       speed_up_interrupts ();
2069
2070       errno = xerrno;
2071       report_file_error ("error connecting socket", list2(name, port));
2072     }
2073
2074   speed_up_interrupts ();
2075
2076   /* scope */
2077   if (setsockopt (ws, IPPROTO_IP, IP_MULTICAST_TTL,
2078                   &thettl, sizeof (thettl)) < 0)
2079     {
2080       close (rs);
2081       close (ws);
2082       report_file_error ("error setting ttl", list2(name, ttl));
2083     }
2084
2085   set_socket_nonblocking_maybe (rs, theport, "udp");
2086
2087   *vinfd = (void*)rs;
2088   *voutfd = (void*)ws;
2089 }
2090
2091 #endif /* HAVE_MULTICAST */
2092
2093 #endif /* HAVE_SOCKETS */
2094
2095 \f
2096 /**********************************************************************/
2097 /*                            Initialization                          */
2098 /**********************************************************************/
2099
2100 void
2101 process_type_create_unix (void)
2102 {
2103   PROCESS_HAS_METHOD (unix, alloc_process_data);
2104   PROCESS_HAS_METHOD (unix, mark_process_data);
2105 #ifdef SIGCHLD
2106   PROCESS_HAS_METHOD (unix, init_process);
2107   PROCESS_HAS_METHOD (unix, reap_exited_processes);
2108 #endif
2109   PROCESS_HAS_METHOD (unix, init_process_io_handles);
2110   PROCESS_HAS_METHOD (unix, create_process);
2111   PROCESS_HAS_METHOD (unix, tooltalk_connection_p);
2112   PROCESS_HAS_METHOD (unix, set_window_size);
2113 #ifdef HAVE_WAITPID
2114   PROCESS_HAS_METHOD (unix, update_status_if_terminated);
2115 #endif
2116   PROCESS_HAS_METHOD (unix, send_process);
2117   PROCESS_HAS_METHOD (unix, process_send_eof);
2118   PROCESS_HAS_METHOD (unix, deactivate_process);
2119   PROCESS_HAS_METHOD (unix, kill_child_process);
2120   PROCESS_HAS_METHOD (unix, kill_process_by_pid);
2121   PROCESS_HAS_METHOD (unix, get_tty_name);
2122 #ifdef HAVE_SOCKETS
2123   PROCESS_HAS_METHOD (unix, canonicalize_host_name);
2124   PROCESS_HAS_METHOD (unix, open_network_stream);
2125 #ifdef HAVE_MULTICAST
2126   PROCESS_HAS_METHOD (unix, open_multicast_group);
2127 #endif
2128 #endif
2129 }
2130
2131 void
2132 vars_of_process_unix (void)
2133 {
2134   Fprovide (intern ("unix-processes"));
2135 }
2136
2137 #endif /* !defined (NO_SUBPROCESSES) */