Add logo XCF
[sxemacs] / 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 SXEmacs
8
9 SXEmacs is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13
14 SXEmacs is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program.  If not, see <http://www.gnu.org/licenses/>. */
21
22
23 /* This file has been Mule-ized except for `start-process-internal',
24    `open-network-stream-internal' and `open-multicast-group-internal'. */
25
26 /* This file has been split into process.c and process-unix.c by
27    Kirill M. Katsnelson <kkm@kis.ru>, so please bash him and not
28    the original author(s) */
29
30 /* The IPv6 support is derived from the code for GNU Emacs-20.3
31    written by Wolfgang S. Rupprecht */
32
33 #include <config.h>
34
35 #if !defined (NO_SUBPROCESSES)
36
37 /* The entire file is within this conditional */
38
39 #include "lisp.h"
40
41 #include "buffer.h"
42 #include "events/events.h"
43 #include "ui/frame.h"
44 #include "hash.h"
45 #include "lstream.h"
46 #include "opaque.h"
47 #include "process.h"
48 #include "procimpl.h"
49 #include "sysdep.h"
50 #include "ui/window.h"
51 #ifdef FILE_CODING
52 #include "mule/file-coding.h"
53 #endif
54
55 #include <setjmp.h>
56 #include "sysfile.h"
57 #include "sysproc.h"
58 #include "systime.h"
59 #include "syssignal.h"          /* Always include before systty.h */
60 #include "ui/TTY/systty.h"
61 #include "syswait.h"
62
63 #ifdef HPUX
64 #include <grp.h>                /* See grantpt fixups for HPUX below. */
65 #endif
66
67 #if defined(HAVE_OPENSSL) && defined(OPENSSL_SSL)
68 #include "openssl.h"
69 #endif
70
71
72 /*
73  * Implementation-specific data. Pointed to by Lisp_Process->process_data
74  */
75
76 struct unix_process_data {
77         /* Always 0.  Used to be for tooltalk only. */
78         int connected_via_filedesc_p;
79         /* Descriptor by which we read from this process.  -1 for dead process */
80         int infd;
81         /* Descriptor for the tty which this process is using.
82            -1 if we didn't record it (on some systems, there's no need).  */
83         int subtty;
84         /* Name of subprocess terminal. */
85         Lisp_Object tty_name;
86         /* Non-false if communicating through a pty.  */
87         char pty_flag;
88 };
89
90
91 extern struct hash_table *usid_to_process;
92
93
94 #define UNIX_DATA(p) ((struct unix_process_data*)((p)->process_data))
95 \f
96 /**********************************************************************/
97 /*                    Static helper routines                          */
98 /**********************************************************************/
99
100 static SIGTYPE close_safely_handler(int signo)
101 {
102         EMACS_REESTABLISH_SIGNAL(signo, close_safely_handler);
103         SIGRETURN;
104 }
105
106 static void close_safely(int fd)
107 {
108         stop_interrupts();
109         signal(SIGALRM, close_safely_handler);
110         alarm(1);
111         close(fd);
112         alarm(0);
113         start_interrupts();
114 }
115
116 static void close_descriptor_pair(int in, int out)
117 {
118         if (in >= 0)
119                 close(in);
120         if (out != in && out >= 0)
121                 close(out);
122 }
123
124 /* Close all descriptors currently in use for communication
125    with subprocess.  This is used in a newly-forked subprocess
126    to get rid of irrelevant descriptors.  */
127
128 static int
129 close_process_descs_mapfun(const void *key, void *contents, void *arg)
130 {
131         Lisp_Object proc;
132         CVOID_TO_LISP(proc, contents);
133         event_stream_delete_stream_pair(XPROCESS(proc)->pipe_instream,
134                                         XPROCESS(proc)->pipe_outstream);
135         return 0;
136 }
137
138 /* #### This function is currently called from child_setup
139    in callproc.c. It should become static though - kkm */
140 void close_process_descs(void)
141 {
142         maphash(close_process_descs_mapfun, usid_to_process, 0);
143 }
144
145 /* connect to an existing file descriptor.  This is very similar to
146    open-network-stream except that it assumes that the connection has
147    already been initialized.  It is currently used for ToolTalk
148    communication. */
149
150 /* This function used to be visible on the Lisp level, but there is no
151    real point in doing that.  Here is the doc string:
152
153   "Connect to an existing file descriptor.
154 Return a subprocess-object to represent the connection.
155 Input and output work as for subprocesses; `delete-process' closes it.
156 Args are NAME BUFFER INFD OUTFD.
157 NAME is name for process.  It is modified if necessary to make it unique.
158 BUFFER is the buffer (or buffer-name) to associate with the process.
159  Process output goes at end of that buffer, unless you specify
160  an output stream or filter function to handle the output.
161  BUFFER may also be nil, meaning that this process is not associated
162  with any buffer.
163 INFD and OUTFD specify the file descriptors to use for input and
164  output, respectively."
165 */
166
167 Lisp_Object
168 connect_to_file_descriptor(Lisp_Object name, Lisp_Object buffer,
169                            Lisp_Object infd, Lisp_Object outfd)
170 {
171         /* This function can GC */
172         Lisp_Object proc;
173         EMACS_INT inch, outch;
174
175         CHECK_STRING(name);
176         CHECK_INT(infd);
177         CHECK_INT(outfd);
178
179         inch = XINT(infd);
180         outch = XINT(outfd);
181         if (get_process_from_usid(FD_TO_USID(inch)))
182                 invalid_operation("There is already a process connected to fd",
183                                   infd);
184         if (!NILP(buffer))
185                 buffer = Fget_buffer_create(buffer);
186         proc = make_process_internal(name);
187
188         XPROCESS(proc)->pid = Fcons(infd, name);
189         XPROCESS(proc)->buffer = buffer;
190         init_process_io_handles(XPROCESS(proc), (void*)inch, (void*)outch, 0);
191         UNIX_DATA(XPROCESS(proc))->connected_via_filedesc_p = 1;
192
193         event_stream_select_process(XPROCESS(proc));
194
195         return proc;
196 }
197
198 #ifdef HAVE_PTYS
199 static int allocate_pty_the_old_fashioned_way(void);
200
201 /* The file name of the (slave) pty opened by allocate_pty().  */
202 #ifndef MAX_PTYNAME_LEN
203 #define MAX_PTYNAME_LEN 64
204 #endif
205 static char pty_name[MAX_PTYNAME_LEN];
206
207 /* Open an available pty, returning a file descriptor.
208    Return -1 on failure.
209    The file name of the terminal corresponding to the pty
210    is left in the variable `pty_name'.  */
211
212 static int allocate_pty(void)
213 {
214         /* Unix98 standardized grantpt, unlockpt, and ptsname, but not the
215            functions required to open a master pty in the first place :-(
216
217            Modern Unix systems all seems to have convenience methods to open
218            a master pty fd in one function call, but there is little
219            agreement on how to do it.
220
221            allocate_pty() tries all the different known easy ways of opening
222            a pty.  In case of failure, we resort to the old BSD-style pty
223            grovelling code in allocate_pty_the_old_fashioned_way(). */
224 #ifndef FORCE_ALLOCATE_PTY_THE_OLD_FASHIONED_WAY
225         int master_fd = -1;
226         const char *slave_name = NULL;
227         const char *_clone_ = NULL;
228         static const char *const clones[] = {
229                 /* Different pty master clone devices */
230                 "/dev/ptmx",    /* Various systems */
231                 "/dev/ptm/clone",       /* HPUX */
232                 "/dev/ptc",     /* AIX */
233                 "/dev/ptmx_bsd" /* Tru64 */
234         };
235
236 #ifdef HAVE_GETPT               /* glibc */
237         master_fd = getpt();
238         if (master_fd >= 0)
239                 goto have_master;
240 #endif                          /* HAVE_GETPT */
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                         slave_name = ttyname(slave_fd);
251                         close(slave_fd);
252                         goto have_slave_name;
253                 } else {
254                         if (master_fd >= 0)
255                                 close(master_fd);
256                         if (slave_fd >= 0)
257                                 close(slave_fd);
258                 }
259         }
260 #endif                          /* HAVE_OPENPTY */
261
262 #if defined(HAVE__GETPTY) && defined (O_NDELAY) /* SGI */
263         master_fd = -1;
264         EMACS_BLOCK_SIGNAL(SIGCHLD);
265         slave_name = _getpty(&master_fd, O_RDWR | O_NDELAY, 0600, 0);
266         EMACS_UNBLOCK_SIGNAL(SIGCHLD);
267         if (master_fd >= 0 && slave_name != NULL)
268                 goto have_slave_name;
269 #endif                          /* HAVE__GETPTY */
270
271         /* Master clone devices are available on most systems */
272         {
273                 int i;
274                 for (i = 0; i < countof(clones); i++) {
275                         _clone_ = clones[i];
276                         master_fd =
277                             open(_clone_, O_RDWR | O_NONBLOCK | OPEN_BINARY, 0);
278                         if (master_fd >= 0)
279                                 goto have_master;
280                 }
281                 _clone_ = NULL;
282         }
283
284         goto lose;
285
286       have_master:
287
288 #if defined (HAVE_PTSNAME)
289         slave_name = ptsname(master_fd);
290         if (slave_name)
291                 goto have_slave_name;
292 #endif
293
294         /* AIX docs say to use ttyname, not ptsname, to get slave_name */
295         if (_clone_ && !strcmp(_clone_, "/dev/ptc")
296             && (slave_name = ttyname(master_fd)) != NULL)
297                 goto have_slave_name;
298
299         goto lose;
300
301       have_slave_name:
302         if( slave_name != NULL )
303                 strncpy(pty_name, slave_name, sizeof(pty_name));
304         else
305                 strncpy(pty_name, "<NULL ttyname>", sizeof(pty_name));
306         pty_name[sizeof(pty_name) - 1] = '\0';
307         setup_pty(master_fd);
308
309         /* We jump through some hoops to frob the pty.
310            It's not obvious that checking the return code here is useful. */
311
312         /* "The grantpt() function will fail if it is unable to successfully
313            invoke the setuid root program.  It may also fail if the
314            application has installed a signal handler to catch SIGCHLD
315            signals." */
316 #if defined (HAVE_GRANTPT) || defined (HAVE_UNLOCKPT)
317         EMACS_BLOCK_SIGNAL(SIGCHLD);
318
319 #if defined (HAVE_GRANTPT)
320         grantpt(master_fd);
321 #ifdef HPUX
322         /* grantpt() behavior on some versions of HP-UX differs from what's
323            specified in the man page: the group of the slave PTY is set to
324            the user's primary group, and we fix that. */
325         {
326                 struct group *tty_group = getgrnam("tty");
327                 if (tty_group != NULL)
328                         chown(pty_name, (uid_t) - 1, tty_group->gr_gid);
329         }
330 #endif                          /* HPUX has broken grantpt() */
331 #endif                          /* HAVE_GRANTPT */
332
333 #if defined (HAVE_UNLOCKPT)
334         unlockpt(master_fd);
335 #endif
336
337         EMACS_UNBLOCK_SIGNAL(SIGCHLD);
338 #endif                          /* HAVE_GRANTPT || HAVE_UNLOCKPT */
339
340         return master_fd;
341
342       lose:
343         if (master_fd >= 0)
344                 close(master_fd);
345 #endif                          /* ndef FORCE_ALLOCATE_PTY_THE_OLD_FASHIONED_WAY */
346         return allocate_pty_the_old_fashioned_way();
347 }
348
349 /* This function tries to allocate a pty by iterating through file
350    pairs with names like /dev/ptyp1 and /dev/ttyp1. */
351 static int allocate_pty_the_old_fashioned_way(void)
352 {
353         struct stat stb;
354
355         /* Some systems name their pseudoterminals so that there are gaps in
356            the usual sequence - for example, on HP9000/S700 systems, there
357            are no pseudoterminals with names ending in 'f'.  So we wait for
358            three failures in a row before deciding that we've reached the
359            end of the ptys.  */
360         int failed_count = 0;
361         int fd;
362         int i;
363         int c;
364
365 #ifdef PTY_ITERATION
366         PTY_ITERATION
367 #else
368 # ifndef FIRST_PTY_LETTER
369 # define FIRST_PTY_LETTER 'p'
370 # endif
371         for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
372                 for (i = 0; i < 16; i++)
373 #endif                          /* PTY_ITERATION */
374
375                 {
376                         int sz;
377
378 #ifdef PTY_NAME_SPRINTF
379                         PTY_NAME_SPRINTF;
380 #else
381                         sz = snprintf(pty_name, sizeof(pty_name), "/dev/pty%c%x", c, i);
382                         assert(sz >= 0 && (size_t)sz < sizeof(pty_name));
383 #endif                          /* no PTY_NAME_SPRINTF */
384
385                         if (sxemacs_stat(pty_name, &stb) < 0) {
386                                 if (++failed_count >= 3)
387                                         return -1;
388                         } else
389                                 failed_count = 0;
390                         fd = open(pty_name, O_RDWR | O_NONBLOCK | OPEN_BINARY,
391                                   0);
392
393                         if (fd >= 0) {
394 #ifdef PTY_TTY_NAME_SPRINTF
395                                 PTY_TTY_NAME_SPRINTF;
396 #else
397                                 sz = snprintf(pty_name, sizeof(pty_name),
398                                                   "/dev/tty%c%x", c, i);
399                                 assert(sz >= 0 && (size_t)sz < sizeof(pty_name));
400 #endif                          /* no PTY_TTY_NAME_SPRINTF */
401                                 if (access(pty_name, R_OK | W_OK) == 0) {
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(long int *inchannel, long 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)
427                 return -1;
428         *inchannel = sv[0];
429         *forkout = sv[1];
430         temp = pipe(sv);
431         if (temp < 0)
432                 return -1;
433         *outchannel = sv[1];
434         *forkin = sv[0];
435 #endif                          /* not SKTPAIR */
436         return 0;
437 }
438
439 #ifdef HAVE_SOCKETS
440
441 #if !(defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO))
442 static int
443 get_internet_address(Lisp_Object host, struct sockaddr_in *address,
444                      Error_behavior errb)
445 {
446         struct hostent *host_info_ptr = NULL;
447 #ifdef TRY_AGAIN
448         int count = 0;
449 #endif
450
451         xzero(*address);
452
453         while (1) {
454 #ifdef TRY_AGAIN
455                 if (count++ > 10)
456                         break;
457                 h_errno = 0;
458 #endif
459                 /* Some systems can't handle SIGIO/SIGALARM in gethostbyname. */
460                 slow_down_interrupts();
461                 host_info_ptr = gethostbyname((char *)XSTRING_DATA(host));
462                 speed_up_interrupts();
463 #ifdef TRY_AGAIN
464                 if (!(host_info_ptr == 0 && h_errno == TRY_AGAIN))
465 #endif
466                         break;
467                 Fsleep_for(make_int(1));
468         }
469         if (host_info_ptr) {
470                 address->sin_family = host_info_ptr->h_addrtype;
471                 memcpy(&address->sin_addr, host_info_ptr->h_addr,
472                        host_info_ptr->h_length);
473         } else {
474                 IN_ADDR numeric_addr;
475                 /* Attempt to interpret host as numeric inet address */
476                 numeric_addr = inet_addr((char *)XSTRING_DATA(host));
477                 if (NUMERIC_ADDR_ERROR) {
478                         maybe_error(Qprocess, errb,
479                                     "Unknown host \"%s\"", XSTRING_DATA(host));
480                         return 0;
481                 }
482
483                 /* There was some broken code here that called strlen() here
484                    on (char *) &numeric_addr and even sometimes accessed
485                    uninitialized data. */
486                 address->sin_family = AF_INET;
487                 *(IN_ADDR *) & address->sin_addr = numeric_addr;
488         }
489
490         return 1;
491 }
492 #endif                          /*  !(HAVE_GETADDRINFO && HAVE_GETNAMEINFO) */
493
494 static void set_socket_nonblocking_maybe(int fd, int port, const char *proto)
495 {
496 #ifdef PROCESS_IO_BLOCKING
497         Lisp_Object tail;
498
499         for (tail = network_stream_blocking_port_list; CONSP(tail);
500              tail = XCDR(tail)) {
501                 Lisp_Object tail_port = XCAR(tail);
502
503                 if (STRINGP(tail_port)) {
504                         struct servent *svc_info;
505                         CHECK_STRING(tail_port);
506                         svc_info =
507                             getservbyname((char *)XSTRING_DATA(tail_port),
508                                           proto);
509                         if ((svc_info != 0) && (svc_info->s_port == port))
510                                 break;
511                         else
512                                 continue;
513                 } else if (INTP(tail_port)
514                            && (htons((unsigned short)XINT(tail_port)) == port))
515                         break;
516         }
517
518         if (!CONSP(tail)) {
519                 set_descriptor_non_blocking(fd);
520         }
521 #else
522         set_descriptor_non_blocking(fd);
523 #endif                          /* PROCESS_IO_BLOCKING */
524 }
525
526 #endif                          /* HAVE_SOCKETS */
527
528 /* Compute the Lisp form of the process status from
529    the numeric status that was returned by `wait'.  */
530
531 static void update_status_from_wait_code(Lisp_Process * p, int *w_fmh)
532 {
533         /* C compiler lossage when attempting to pass w directly */
534         int w = *w_fmh;
535
536         if (WIFSTOPPED(w)) {
537                 p->status_symbol = Qstop;
538                 p->exit_code = WSTOPSIG(w);
539                 p->core_dumped = 0;
540         } else if (WIFEXITED(w)) {
541                 p->status_symbol = Qexit;
542                 p->exit_code = WEXITSTATUS(w);
543                 p->core_dumped = 0;
544         } else if (WIFSIGNALED(w)) {
545                 p->status_symbol = Qsignal;
546                 p->exit_code = WTERMSIG(w);
547                 p->core_dumped = WCOREDUMP(w);
548         } else {
549                 p->status_symbol = Qrun;
550                 p->exit_code = 0;
551         }
552 }
553
554 #ifdef SIGCHLD
555
556 #define MAX_EXITED_PROCESSES 1000
557 static volatile pid_t exited_processes[MAX_EXITED_PROCESSES];
558 static volatile int exited_processes_status[MAX_EXITED_PROCESSES];
559 static volatile int exited_processes_index;
560
561 static volatile int sigchld_happened;
562
563 /* On receipt of a signal that a child status has changed,
564  loop asking about children with changed statuses until
565  the system says there are no more.  All we do is record
566  the processes and wait status.
567
568  This function could be called from within the SIGCHLD
569  handler, so it must be completely reentrant.  When
570  not called from a SIGCHLD handler, BLOCK_SIGCHLD should
571  be non-zero so that SIGCHLD is blocked while this
572  function is running. (This is necessary so avoid
573  race conditions with the SIGCHLD_HAPPENED flag). */
574
575 static void record_exited_processes(int block_sigchld)
576 {
577         if (!sigchld_happened) {
578                 return;
579         }
580 #ifdef EMACS_BLOCK_SIGNAL
581         if (block_sigchld)
582                 EMACS_BLOCK_SIGNAL(SIGCHLD);
583 #endif
584
585         while (sigchld_happened) {
586                 int pid;
587                 int w;
588
589                 /* Keep trying to get a status until we get a definitive result.  */
590                 do {
591                         errno = 0;
592 #ifdef WNOHANG
593 #  ifndef WUNTRACED
594 #    define WUNTRACED 0
595 #  endif                        /* not WUNTRACED */
596 #  ifdef HAVE_WAITPID
597                         pid = waitpid((pid_t) - 1, &w, WNOHANG | WUNTRACED);
598 #  else
599                         pid = wait3(&w, WNOHANG | WUNTRACED, 0);
600 #  endif
601 #else                           /* not WNOHANG */
602                         pid = wait(&w);
603 #endif                          /* not WNOHANG */
604                 }
605                 while (pid <= 0 && errno == EINTR);
606
607                 if (pid <= 0)
608                         break;
609
610                 if (exited_processes_index < MAX_EXITED_PROCESSES) {
611                         exited_processes[exited_processes_index] = pid;
612                         exited_processes_status[exited_processes_index] = w;
613                         exited_processes_index++;
614                 }
615
616                 /* On systems with WNOHANG, we just ignore the number
617                    of times that SIGCHLD was signalled, and keep looping
618                    until there are no more processes to wait on.  If we
619                    don't have WNOHANG, we have to rely on the count in
620                    SIGCHLD_HAPPENED. */
621 #ifndef WNOHANG
622                 sigchld_happened--;
623 #endif                          /* not WNOHANG */
624         }
625
626         sigchld_happened = 0;
627
628         if (block_sigchld)
629                 EMACS_UNBLOCK_SIGNAL(SIGCHLD);
630 }
631
632 /* For any processes that have changed status and are recorded
633    and such, update the corresponding Lisp_Process.
634    We separate this from record_exited_processes() so that
635    we never have to call this function from within a signal
636    handler.  We block SIGCHLD in case record_exited_processes()
637    is called from a signal handler. */
638
639 /** USG WARNING:  Although it is not obvious from the documentation
640  in signal(2), on a USG system the SIGCLD handler MUST NOT call
641  signal() before executing at least one wait(), otherwise the handler
642  will be called again, resulting in an infinite loop.  The relevant
643  portion of the documentation reads "SIGCLD signals will be queued
644  and the signal-catching function will be continually reentered until
645  the queue is empty".  Invoking signal() causes the kernel to reexamine
646  the SIGCLD queue.   Fred Fish, UniSoft Systems Inc.
647
648  (Note that now this only applies in SYS V Release 2 and before.
649  On SYS V Release 3, we use sigset() to set the signal handler for
650  the first time, and so we don't have to reestablish the signal handler
651  in the handler below.  On SYS V Release 4, we don't get this weirdo
652  behavior when we use sigaction(), which we do use.) */
653
654 static SIGTYPE sigchld_handler(int signo)
655 {
656 #ifdef OBNOXIOUS_SYSV_SIGCLD_BEHAVIOR
657         int old_errno = errno;
658
659         sigchld_happened++;
660         record_exited_processes(0);
661         errno = old_errno;
662 #else
663         sigchld_happened++;
664 #endif
665 #ifdef HAVE_UNIXOID_EVENT_LOOP
666         signal_fake_event();
667 #endif
668         /* WARNING - must come after wait3() for USG systems */
669         EMACS_REESTABLISH_SIGNAL(signo, sigchld_handler);
670         SIGRETURN;
671 }
672
673 #endif                          /* SIGCHLD */
674
675 #ifdef SIGNALS_VIA_CHARACTERS
676 /* Get signal character to send to process if SIGNALS_VIA_CHARACTERS */
677
678 static int process_signal_char(int tty_fd, int signo)
679 {
680         /* Invalid tty_fd ... */
681         if (tty_fd < 0)
682                 return '\0';
683
684         /* If it's not a tty, pray that these default values work */
685         if (!isatty(tty_fd)) {
686 #define CNTL(ch) (037 & (ch))
687                 switch (signo) {
688                 case SIGINT:
689                         return CNTL('C');
690                 case SIGQUIT:
691                         return CNTL('\\');
692 #ifdef SIGTSTP
693                 case SIGTSTP:
694                         return CNTL('Z');
695 #endif
696                 default:
697                         break;
698                 }
699         }
700 #ifdef HAVE_TERMIOS
701         /* TERMIOS is the latest and bestest, and seems most likely to work.
702            If the system has it, use it. */
703         {
704                 struct termios t;
705                 tcgetattr(tty_fd, &t);
706                 switch (signo) {
707                 case SIGINT:
708                         return t.c_cc[VINTR];
709                 case SIGQUIT:
710                         return t.c_cc[VQUIT];
711 #if defined(SIGTSTP) && defined(VSUSP)
712                 case SIGTSTP:
713                         return t.c_cc[VSUSP];
714 #endif
715                 default:
716                         break;
717                 }
718         }
719
720 # elif defined (TIOCGLTC) && defined (TIOCGETC) /* not HAVE_TERMIOS */
721         {
722                 /* On Berkeley descendants, the following IOCTL's retrieve the
723                    current control characters.  */
724                 struct tchars c;
725                 struct ltchars lc;
726                 switch (signo) {
727                 case SIGINT:
728                         ioctl(tty_fd, TIOCGETC, &c);
729                         return c.t_intrc;
730                 case SIGQUIT:
731                         ioctl(tty_fd, TIOCGETC, &c);
732                         return c.t_quitc;
733 #  ifdef SIGTSTP
734                 case SIGTSTP:
735                         ioctl(tty_fd, TIOCGLTC, &lc);
736                         return lc.t_suspc;
737 #  endif                        /* SIGTSTP */
738                 }
739         }
740
741 # elif defined (TCGETA)         /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
742         {
743                 /* On SYSV descendants, the TCGETA ioctl retrieves the current
744                    control characters.  */
745                 struct termio t;
746                 ioctl(tty_fd, TCGETA, &t);
747                 switch (signo) {
748                 case SIGINT:
749                         return t.c_cc[VINTR];
750                 case SIGQUIT:
751                         return t.c_cc[VQUIT];
752 #  ifdef SIGTSTP
753                 case SIGTSTP:
754                         return t.c_cc[VSWTCH];
755 #  endif                        /* SIGTSTP */
756                 }
757         }
758 # else                          /* ! defined (TCGETA) */
759 #error ERROR! Using SIGNALS_VIA_CHARACTERS, but not HAVE_TERMIOS || (TIOCGLTC && TIOCGETC) || TCGETA
760         /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
761            you'd better be using one of the alternatives above!  */
762 # endif                         /* ! defined (TCGETA) */
763         return '\0';
764 }
765 #endif                          /* SIGNALS_VIA_CHARACTERS */
766 \f
767 /**********************************************************************/
768 /*              Process implementation methods                        */
769 /**********************************************************************/
770
771 /*
772  * Allocate and initialize Lisp_Process->process_data
773  */
774
775 static void unix_alloc_process_data(Lisp_Process * p)
776 {
777         p->process_data = xnew(struct unix_process_data);
778
779         UNIX_DATA(p)->connected_via_filedesc_p = 0;
780         UNIX_DATA(p)->infd = -1;
781         UNIX_DATA(p)->subtty = -1;
782         UNIX_DATA(p)->tty_name = Qnil;
783         UNIX_DATA(p)->pty_flag = 0;
784 }
785
786 /*
787  * Mark any Lisp objects in Lisp_Process->process_data
788  */
789
790 static void unix_mark_process_data(Lisp_Process * proc)
791 {
792         mark_object(UNIX_DATA(proc)->tty_name);
793 }
794
795 /*
796  * Initialize SXEmacs process implementation once
797  */
798
799 #ifdef SIGCHLD
800 static void unix_init_process(void)
801 {
802 #ifndef CANNOT_DUMP
803         if (!noninteractive || initialized)
804 #endif
805                 signal(SIGCHLD, sigchld_handler);
806 }
807 #endif                          /* SIGCHLD */
808
809 /*
810  * Initialize any process local data. This is called when newly
811  * created process is connected to real OS file handles. The
812  * handles are generally represented by void* type, but are
813  * of type int (file descriptors) for UNIX.
814  */
815
816 static void
817 unix_init_process_io_handles(Lisp_Process * p, void *in, void *out, int flags)
818 {
819         Lisp_Object process = Qnil;
820         USID        usid = FD_TO_USID((EMACS_INT)in);
821         XSETPROCESS(process, p);
822         puthash((const void *)usid, LISP_TO_VOID(process),
823                 usid_to_process);
824         UNIX_DATA(p)->infd = (EMACS_INT)in;
825 }
826
827 /*
828  * Fork off a subprocess. P is a pointer to a newly created subprocess
829  * object. If this function signals, the caller is responsible for
830  * deleting (and finalizing) the process object.
831  *
832  * The method must return PID of the new process, a (positive??? ####) number
833  * which fits into Lisp_Int. No return value indicates an error, the method
834  * must signal an error instead.
835  */
836
837 static int
838 unix_create_process(Lisp_Process * p,
839                     Lisp_Object * argv, int nargv,
840                     Lisp_Object program, Lisp_Object cur_dir)
841 {
842         int pid;
843         long int inchannel = -1;
844         long int outchannel = -1;
845         /* Use volatile to protect variables from being clobbered by longjmp.  */
846         volatile int forkin = -1;
847         volatile int forkout = -1;
848         volatile int pty_flag = 0;
849
850 #ifdef HAVE_PTYS
851         if (!NILP(Vprocess_connection_type)) {
852                 /* find a new pty, open the master side, return the opened
853                    file handle, and store the name of the corresponding slave
854                    side in global variable pty_name. */
855                 outchannel = inchannel = allocate_pty();
856         }
857
858         if (inchannel >= 0) {
859                 /* You're "supposed" to now open the slave in the child.
860                    On some systems, we can open it here; this allows for
861                    better error checking. */
862 #if !defined(USG)
863                 /* On USG systems it does not work to open the pty's tty here
864                    and then close and reopen it in the child.  */
865 #ifdef O_NOCTTY
866                 /* Don't let this terminal become our controlling terminal
867                    (in case we don't have one).  */
868                 forkout = forkin =
869                     open(pty_name, O_RDWR | O_NOCTTY | OPEN_BINARY, 0);
870 #else
871                 forkout = forkin = open(pty_name, O_RDWR | OPEN_BINARY, 0);
872 #endif
873                 if (forkin < 0)
874                         goto io_failure;
875 #endif                          /* not USG */
876                 UNIX_DATA(p)->pty_flag = pty_flag = 1;
877         } else
878 #endif                          /* HAVE_PTYS */
879         if (create_bidirectional_pipe(
880                     (void*)&inchannel, (void*)&outchannel,
881                     &forkin, &forkout) < 0)
882                 goto io_failure;
883
884 #if 0
885         /* Replaced by close_process_descs */
886         set_exclusive_use(inchannel);
887         set_exclusive_use(outchannel);
888 #endif
889
890         set_descriptor_non_blocking(inchannel);
891         set_descriptor_non_blocking(outchannel);
892
893         /* Record this as an active process, with its channels.
894            As a result, child_setup will close Emacs's side of the pipes.  */
895         init_process_io_handles(p, (void *)inchannel, (void *)outchannel,
896                                 pty_flag ? STREAM_PTY_FLUSHING : 0);
897         /* Record the tty descriptor used in the subprocess.  */
898         UNIX_DATA(p)->subtty = forkin;
899
900         {
901                 /* child_setup must clobber environ on systems with true vfork.
902                    Protect it from permanent change.  */
903                 char **save_environ = environ;
904
905                 pid = fork();
906                 if (pid == 0) {
907         /**** Now we're in the child process ****/
908                         int xforkin = forkin;
909                         int xforkout = forkout;
910
911                         /* Checking for quit in the child is bad because that will
912                            cause I/O, and that, in turn, can confuse the X connection. */
913                         begin_dont_check_for_quit();
914
915                         /* Disconnect the current controlling terminal, pursuant to
916                            making the pty be the controlling terminal of the process.
917                            Also put us in our own process group. */
918
919                         disconnect_controlling_terminal();
920
921 #ifdef HAVE_PTYS
922                         if (pty_flag) {
923                                 /* Open the pty connection and make the pty's terminal
924                                    our controlling terminal.
925
926                                    On systems with TIOCSCTTY, we just use it to set
927                                    the controlling terminal.  On other systems, the
928                                    first TTY we open becomes the controlling terminal.
929                                    So, we end up with four possibilities:
930
931                                    (1) on USG and TIOCSCTTY systems, we open the pty
932                                    and use TIOCSCTTY.
933                                    (2) on other USG systems, we just open the pty.
934                                    (3) on non-USG systems with TIOCSCTTY, we
935                                    just use TIOCSCTTY. (On non-USG systems, we
936                                    already opened the pty in the parent process.)
937                                    (4) on non-USG systems without TIOCSCTTY, we
938                                    close the pty and reopen it.
939
940                                    This would be cleaner if we didn't open the pty
941                                    in the parent process, but doing it that way
942                                    makes it possible to trap error conditions.
943                                    It's harder to convey an error from the child
944                                    process, and I don't feel like messing with
945                                    this now. */
946
947                                 /* There was some weirdo, probably wrong,
948                                    conditionalization on RTU and UNIPLUS here.
949                                    I deleted it.  So sue me. */
950
951                                 /* SunOS has TIOCSCTTY but the close/open method
952                                    also works. */
953
954 #  if defined (USG) || !defined (TIOCSCTTY)
955                                 /* Now close the pty (if we had it open) and reopen it.
956                                    This makes the pty the controlling terminal of the
957                                    subprocess.  */
958                                 /* I wonder if close (open (pty_name, ...)) would work?  */
959                                 if (xforkin >= 0)
960                                         close(xforkin);
961                                 xforkout = xforkin =
962                                     open(pty_name, O_RDWR | OPEN_BINARY, 0);
963                                 if (xforkin < 0) {
964                                         write(1,
965                                               "Couldn't open the pty terminal ",
966                                               31);
967                                         write(1, pty_name, strlen(pty_name));
968                                         write(1, "\n", 1);
969                                         _exit(1);
970                                 }
971 #  endif                        /* USG or not TIOCSCTTY */
972
973                                 /* Miscellaneous setup required for some systems.
974                                    Must be done before using tc* functions on xforkin.
975                                    This guarantees that isatty(xforkin) is true. */
976
977 #  if defined (HAVE_ISASTREAM) && defined (I_PUSH)
978                                 if (isastream(xforkin)) {
979 #    if defined (I_FIND)
980 #      define stream_module_pushed(fd, module) (ioctl (fd, I_FIND, module) == 1)
981 #    else
982 #      define stream_module_pushed(fd, module) 0
983 #    endif
984                                         if (!stream_module_pushed
985                                             (xforkin, "ptem"))
986                                                 ioctl(xforkin, I_PUSH, "ptem");
987                                         if (!stream_module_pushed
988                                             (xforkin, "ldterm"))
989                                                 ioctl(xforkin, I_PUSH,
990                                                       "ldterm");
991                                         if (!stream_module_pushed
992                                             (xforkin, "ttcompat"))
993                                                 ioctl(xforkin, I_PUSH,
994                                                       "ttcompat");
995                                 }
996 #  endif                        /* HAVE_ISASTREAM */
997
998 #  ifdef TIOCSCTTY
999                                 /* We ignore the return value
1000                                    because faith@cs.unc.edu says that is necessary on Linux.  */
1001                                 assert(isatty(xforkin));
1002                                 ioctl(xforkin, TIOCSCTTY, 0);
1003 #  endif                        /* TIOCSCTTY */
1004
1005                                 /* Change the line discipline. */
1006
1007 # if defined (HAVE_TERMIOS) && defined (LDISC1)
1008                                 {
1009                                         struct termios t;
1010                                         assert(isatty(xforkin));
1011                                         tcgetattr(xforkin, &t);
1012                                         t.c_lflag = LDISC1;
1013                                         if (tcsetattr(xforkin, TCSANOW, &t) < 0)
1014                                                 perror
1015                                                     ("create_process/tcsetattr LDISC1 failed\n");
1016                                 }
1017 # elif defined (NTTYDISC) && defined (TIOCSETD)
1018                                 {
1019                                         /* Use new line discipline.  TIOCSETD is accepted and
1020                                            ignored on Sys5.4 systems with ttcompat. */
1021                                         int ldisc = NTTYDISC;
1022                                         assert(isatty(xforkin));
1023                                         ioctl(xforkin, TIOCSETD, &ldisc);
1024                                 }
1025 # endif                         /* TIOCSETD & NTTYDISC */
1026
1027                                 /* Make our process group be the foreground group
1028                                    of our new controlling terminal. */
1029
1030                                 {
1031                                         pid_t piddly =
1032                                             EMACS_GET_PROCESS_GROUP();
1033                                         EMACS_SET_TTY_PROCESS_GROUP(xforkin,
1034                                                                     &piddly);
1035                                 }
1036
1037                                 /* On AIX, we've disabled SIGHUP above once we start a
1038                                    child on a pty.  Now reenable it in the child, so it
1039                                    will die when we want it to.
1040                                    JV: This needs to be done ALWAYS as we might have inherited
1041                                    a SIG_IGN handling from our parent (nohup) and we are in new
1042                                    process group.
1043                                  */
1044                                 signal(SIGHUP, SIG_DFL);
1045                         }
1046
1047                         if (pty_flag)
1048                                 /* Set up the terminal characteristics of the pty. */
1049                                 child_setup_tty(xforkout);
1050
1051 #endif                          /* HAVE_PTYS */
1052
1053                         signal(SIGINT, SIG_DFL);
1054                         signal(SIGQUIT, SIG_DFL);
1055
1056                         {
1057                                 char *current_dir;
1058                                 char **new_argv =
1059                                     alloca_array(char *, nargv + 2);
1060                                 int i;
1061
1062                                 /* Nothing below here GCs so our string pointers shouldn't move. */
1063                                 new_argv[0] = (char *)XSTRING_DATA(program);
1064                                 for (i = 0; i < nargv; i++) {
1065                                         CHECK_STRING(argv[i]);
1066                                         new_argv[i + 1] =
1067                                             (char *)XSTRING_DATA(argv[i]);
1068                                 }
1069                                 new_argv[i + 1] = 0;
1070
1071                                 LISP_STRING_TO_EXTERNAL(cur_dir, current_dir,
1072                                                         Qfile_name);
1073
1074                                 child_setup(xforkin, xforkout, xforkout,
1075                                             new_argv, current_dir);
1076                         }
1077
1078                 }
1079
1080             /**** End of child code ****/
1081  /**** Back in parent process ****/
1082                 environ = save_environ;
1083         }
1084
1085         if (pid < 0) {
1086                 int save_errno = errno;
1087                 close_descriptor_pair(forkin, forkout);
1088                 errno = save_errno;
1089                 report_file_error("Doing fork", Qnil);
1090         }
1091
1092         /* #### dmoore - why is this commented out, otherwise we leave
1093            subtty = forkin, but then we close forkin just below. */
1094         /* UNIX_DATA(p)->subtty = -1; */
1095
1096         /* If the subfork execv fails, and it exits,
1097            this close hangs.  I don't know why.
1098            So have an interrupt jar it loose.  */
1099         if (forkin >= 0)
1100                 close_safely(forkin);
1101         if (forkin != forkout && forkout >= 0)
1102                 close(forkout);
1103
1104 #ifdef HAVE_PTYS
1105         if (pty_flag)
1106                 UNIX_DATA(p)->tty_name = build_string(pty_name);
1107         else
1108 #endif
1109                 UNIX_DATA(p)->tty_name = Qnil;
1110
1111         /* Notice that SIGCHLD was not blocked. (This is not possible on
1112            some systems.) No biggie if SIGCHLD occurs right around the
1113            time that this call happens, because SIGCHLD() does not actually
1114            deselect the process (that doesn't occur until the next time
1115            we're waiting for an event, when status_notify() is called). */
1116         return pid;
1117
1118       io_failure:
1119         {
1120                 int save_errno = errno;
1121                 close_descriptor_pair(forkin, forkout);
1122                 close_descriptor_pair(inchannel, outchannel);
1123                 errno = save_errno;
1124                 report_file_error("Opening pty or pipe", Qnil);
1125                 return 0;       /* not reached */
1126         }
1127 }
1128
1129 /* This is called to set process' virtual terminal size */
1130
1131 static int unix_set_window_size(Lisp_Process * p, int cols, int rows)
1132 {
1133         return set_window_size(UNIX_DATA(p)->infd, cols, rows);
1134 }
1135
1136 /*
1137  * This method is called to update status fields of the process
1138  * structure. If the process has not existed, this method is
1139  * expected to do nothing.
1140  *
1141  * The method is called only for real child processes.
1142  */
1143
1144 #ifdef HAVE_WAITPID
1145 static void unix_update_status_if_terminated(Lisp_Process * p)
1146 {
1147         int w;
1148 #ifdef SIGCHLD
1149         EMACS_BLOCK_SIGNAL(SIGCHLD);
1150 #endif
1151         if (waitpid(XINT(p->pid), &w, WNOHANG) == XINT(p->pid)) {
1152                 p->tick++;
1153                 update_status_from_wait_code(p, &w);
1154         }
1155 #ifdef SIGCHLD
1156         EMACS_UNBLOCK_SIGNAL(SIGCHLD);
1157 #endif
1158 }
1159 #endif
1160
1161 /*
1162  * Update status of all exited processes. Called when SIGCLD has signaled.
1163  */
1164
1165 #ifdef SIGCHLD
1166 static void unix_reap_exited_processes(void)
1167 {
1168         int i;
1169         Lisp_Process *p;
1170
1171 #ifndef OBNOXIOUS_SYSV_SIGCLD_BEHAVIOR
1172         record_exited_processes(1);
1173 #endif
1174
1175         if (exited_processes_index <= 0) {
1176                 return;
1177         }
1178 #ifdef  EMACS_BLOCK_SIGNAL
1179         EMACS_BLOCK_SIGNAL(SIGCHLD);
1180 #endif
1181         for (i = 0; i < exited_processes_index; i++) {
1182                 int pid = exited_processes[i];
1183                 int w = exited_processes_status[i];
1184
1185                 /* Find the process that signaled us, and record its status.  */
1186
1187                 p = 0;
1188                 {
1189                         Lisp_Object tail;
1190                         LIST_LOOP(tail, Vprocess_list) {
1191                                 Lisp_Object proc = XCAR(tail);
1192                                 p = XPROCESS(proc);
1193                                 if (INTP(p->pid) && XINT(p->pid) == pid)
1194                                         break;
1195                                 p = 0;
1196                         }
1197                 }
1198
1199                 if (p) {
1200                         /* Change the status of the process that was found.  */
1201                         p->tick++;
1202                         process_tick++;
1203                         update_status_from_wait_code(p, &w);
1204
1205                         /* If process has terminated, stop waiting for its output.  */
1206                         if (WIFSIGNALED(w) || WIFEXITED(w)) {
1207                                 if (!NILP(p->pipe_instream)) {
1208                                         /* We can't just call event_stream->unselect_process_cb (p)
1209                                            here, because that calls XtRemoveInput, which is not
1210                                            necessarily reentrant, so we can't call this at interrupt
1211                                            level.
1212                                          */
1213                                 }
1214                         }
1215                 } else {
1216                         /* There was no asynchronous process found for that id.  Check
1217                            if we have a synchronous process. Only set sync process status
1218                            if there is one, so we work OK with the waitpid() call in
1219                            wait_for_termination(). */
1220                         if (synch_process_alive != 0) { /* Set the global sync process status variables. */
1221                                 synch_process_alive = 0;
1222
1223                                 /* Report the status of the synchronous process.  */
1224                                 if (WIFEXITED(w))
1225                                         synch_process_retcode = WEXITSTATUS(w);
1226                                 else if (WIFSIGNALED(w))
1227                                         synch_process_death =
1228                                             signal_name(WTERMSIG(w));
1229                         }
1230                 }
1231         }
1232
1233         exited_processes_index = 0;
1234
1235         EMACS_UNBLOCK_SIGNAL(SIGCHLD);
1236 }
1237 #endif                          /* SIGCHLD */
1238
1239 /*
1240  * Stuff the entire contents of LSTREAM to the process output pipe
1241  */
1242
1243 static JMP_BUF send_process_frame;
1244
1245 static SIGTYPE send_process_trap(int signum)
1246 {
1247         EMACS_REESTABLISH_SIGNAL(signum, send_process_trap);
1248         EMACS_UNBLOCK_SIGNAL(signum);
1249         LONGJMP(send_process_frame, 1);
1250 }
1251
1252 static void
1253 unix_send_process(Lisp_Object proc, lstream_t lstream)
1254 {
1255         /* Use volatile to protect variables from being clobbered by longjmp.  */
1256         SIGTYPE(*volatile old_sigpipe) (int) = 0;
1257         volatile Lisp_Object vol_proc = proc;
1258         Lisp_Process *volatile p = XPROCESS(proc);
1259
1260         /* #### JV: layering violation?
1261
1262            This function knows too much about the relation between the encoding
1263            stream (DATA_OUTSTREAM) and the actual output stream p->output_stream.
1264
1265            If encoding streams properly forwarded all calls, we could simply
1266            use DATA_OUTSTREAM everywhere. */
1267
1268         if (!SETJMP(send_process_frame)) {
1269                 /* use a reasonable-sized buffer (somewhere around the size of the
1270                    stream buffer) so as to avoid inundating the stream with blocked
1271                    data. */
1272                 Bufbyte chunkbuf[512];
1273                 Bytecount chunklen = 0;
1274
1275                 do {
1276                         Lstream_data_count writeret;
1277                         if (p->process_type!=PROCESS_TYPE_NETWORK_SERVER_LISTEN) {
1278                                 chunklen = Lstream_read(lstream, chunkbuf, 512);
1279                         }
1280                         old_sigpipe =
1281                             (SIGTYPE(*)(int))signal(SIGPIPE, send_process_trap);
1282                         if (chunklen > 0) {
1283                                 int save_errno;
1284
1285                                 switch (p->process_type) {
1286                                 case PROCESS_TYPE_NETWORK_SERVER_LISTEN:
1287                                         report_file_error ("no writing to listen process possible",
1288                                                            list1 (proc));
1289                                         break;
1290                                 case PROCESS_TYPE_SSL:
1291                                 case PROCESS_TYPE_PROC:
1292                                 case PROCESS_TYPE_NETWORK:
1293                                 case PROCESS_TYPE_MULTICAST:
1294                                 default:
1295 /* Lstream_write() will never successfully write less than
1296  * the amount sent in.  In the worst case, it just buffers
1297  * the unwritten data. */
1298                                         writeret = Lstream_write
1299                                                 (XLSTREAM (DATA_OUTSTREAM(p)),
1300                                                  chunkbuf, chunklen);
1301                                         break;
1302                                 }
1303                                 save_errno = errno;
1304                                 signal (SIGPIPE, old_sigpipe);
1305                                 errno = save_errno;
1306                                 if (writeret < 0)
1307 /* This is a real error.  Blocking errors are handled
1308  * specially inside of the filedesc stream.
1309  */
1310                                         report_file_error ("writing to process",
1311                                                            list1 (proc));
1312                         } else {
1313 /* Need to make sure that everything up to and including the
1314  * last chunk is flushed, even when the pipe is currently
1315  * blocked. */
1316                                 Lstream_flush (XLSTREAM (DATA_OUTSTREAM(p)));
1317                                 signal (SIGPIPE, old_sigpipe);
1318                         }
1319                         while (Lstream_was_blocked_p
1320                                (XLSTREAM(p->pipe_outstream))) {
1321                                 /* Buffer is full.  Wait, accepting input;
1322                                  * that may allow the program
1323                                  * to finish doing output and read more.
1324                                  */
1325                                 Faccept_process_output(Qnil, make_int(1), Qnil);
1326                                 /* It could have *really* finished,
1327                                  * deleting the process */
1328                                 if (NILP(p->pipe_outstream))
1329                                         return;
1330                                 old_sigpipe = (SIGTYPE(*)(int))signal(
1331                                         SIGPIPE,
1332                                         send_process_trap);
1333                                 Lstream_flush(XLSTREAM(p->pipe_outstream));
1334                                 signal(SIGPIPE, old_sigpipe);
1335                         }
1336                         /* Perhaps should abort() if < 0?
1337                          * This should never happen.
1338                          */
1339                 }
1340                 while (chunklen > 0);
1341         } else {        /* We got here from a longjmp() from the SIGPIPE handler */
1342                 signal(SIGPIPE, old_sigpipe);
1343                 /* Close the file lstream so we don't attempt to write to it further */
1344                 /* #### There is controversy over whether this might cause fd leakage */
1345                 /*      my tests say no. -slb */
1346                 XLSTREAM(p->pipe_outstream)->flags &= ~LSTREAM_FL_IS_OPEN;
1347 #ifdef FILE_CODING
1348                 XLSTREAM(p->coding_outstream)->flags &= ~LSTREAM_FL_IS_OPEN;
1349 #endif
1350                 p->status_symbol = Qexit;
1351                 p->exit_code = 256;     /* #### SIGPIPE ??? */
1352                 p->core_dumped = 0;
1353                 p->tick++;
1354                 process_tick++;
1355                 deactivate_process(vol_proc);
1356                 invalid_operation("SIGPIPE raised on process; closed it",
1357                                   p->name);
1358         }
1359
1360         old_sigpipe = (SIGTYPE(*)(int))signal(SIGPIPE, send_process_trap);
1361         Lstream_flush(XLSTREAM(DATA_OUTSTREAM(p)));
1362         signal(SIGPIPE, old_sigpipe);
1363 }
1364
1365 /*
1366  * Send EOF to the process. The default implementation simply
1367  * closes the output stream. The method must return 0 to call
1368  * the default implementation, or 1 if it has taken all care about
1369  * sending EOF to the process.
1370  */
1371
1372 static int unix_process_send_eof(Lisp_Object proc)
1373 {
1374         if (!UNIX_DATA(XPROCESS(proc))->pty_flag)
1375                 return 0;
1376
1377         /* #### get_eof_char simply doesn't return the correct character
1378            here.  Maybe it is needed to determine the right eof
1379            character in init_process_io_handles but here it simply screws
1380            things up. */
1381 #if 0
1382         Bufbyte eof_char = get_eof_char(XPROCESS(proc));
1383         send_process(proc, Qnil, &eof_char, 0, 1);
1384 #else
1385         send_process(proc, Qnil, (const Bufbyte *)"\004", 0, 1);
1386 #endif
1387         return 1;
1388 }
1389
1390 /*
1391  * Called before the process is deactivated. The process object
1392  * is not immediately finalized, just undergoes a transition to
1393  * inactive state.
1394  *
1395  * The return value is a unique stream ID, as returned by
1396  * event_stream_delete_stream_pair
1397  *
1398  * In the lack of this method, only event_stream_delete_stream_pair
1399  * is called on both I/O streams of the process.
1400  *
1401  * The UNIX version guards this by ignoring possible SIGPIPE.
1402  */
1403
1404 static USID unix_deactivate_process(Lisp_Process * p)
1405 {
1406         SIGTYPE(*old_sigpipe) (int) = 0;
1407         USID usid;
1408
1409         if (UNIX_DATA(p)->infd >= 0)
1410                 flush_pending_output(UNIX_DATA(p)->infd);
1411
1412         /* closing the outstream could result in SIGPIPE, so ignore it. */
1413         old_sigpipe = (SIGTYPE(*)(int))signal(SIGPIPE, SIG_IGN);
1414         usid =  FD_TO_USID(UNIX_DATA(p)->infd);
1415         event_stream_delete_stream_pair(p->pipe_instream,
1416                                         p->pipe_outstream);
1417
1418         signal(SIGPIPE, old_sigpipe);
1419
1420         UNIX_DATA(p)->infd = -1;
1421
1422         return usid;
1423 }
1424
1425 /* If the subtty field of the process data is not filled in, do so now. */
1426 static void try_to_initialize_subtty(struct unix_process_data *upd)
1427 {
1428         if (upd->pty_flag && (upd->subtty == -1 || !isatty(upd->subtty))
1429             && STRINGP(upd->tty_name))
1430                 upd->subtty =
1431                     open((char *)XSTRING_DATA(upd->tty_name), O_RDWR, 0);
1432 }
1433
1434 /* Send signal number SIGNO to PROCESS.
1435    CURRENT_GROUP means send to the process group that currently owns
1436    the terminal being used to communicate with PROCESS.
1437    This is used for various commands in shell mode.
1438    If NOMSG is zero, insert signal-announcements into process's buffers
1439    right away.
1440
1441    If we can, we try to signal PROCESS by sending control characters
1442    down the pty.  This allows us to signal inferiors who have changed
1443    their uid, for which killpg would return an EPERM error,
1444    or processes running on other machines via remote login.
1445
1446    The method signals an error if the given SIGNO is not valid. */
1447
1448 static void
1449 unix_kill_child_process(Lisp_Object proc, int signo,
1450                         int current_group, int nomsg)
1451 {
1452         pid_t pgid = -1;
1453         Lisp_Process *p = XPROCESS(proc);
1454         struct unix_process_data *d = UNIX_DATA(p);
1455
1456         switch (signo) {
1457 #ifdef SIGCONT
1458         case SIGCONT:
1459                 p->status_symbol = Qrun;
1460                 p->exit_code = 0;
1461                 p->tick++;
1462                 process_tick++;
1463                 if (!nomsg)
1464                         status_notify();
1465                 break;
1466 #endif                          /* ! defined (SIGCONT) */
1467         case SIGINT:
1468         case SIGQUIT:
1469         case SIGKILL:
1470                 flush_pending_output(d->infd);
1471                 break;
1472         default:
1473                 break;
1474         }
1475
1476         if (!d->pty_flag)
1477                 current_group = 0;
1478
1479         /* If current_group is true, we want to send a signal to the
1480            foreground process group of the terminal our child process is
1481            running on.  You would think that would be easy.
1482
1483            The BSD people invented the TIOCPGRP ioctl to get the foreground
1484            process group of a tty.  That, combined with killpg, gives us
1485            what we want.
1486
1487            However, the POSIX standards people, in their infinite wisdom,
1488            have seen fit to only allow this for processes which have the
1489            terminal as controlling terminal, which doesn't apply to us.
1490
1491            Sooo..., we have to do something non-standard.  The ioctls
1492            TIOCSIGNAL, TIOCSIG, and TIOCSIGSEND send the signal directly on
1493            many systems.  POSIX tcgetpgrp(), since it is *documented* as not
1494            doing what we want, is actually less likely to work than the BSD
1495            ioctl TIOCGPGRP it is supposed to obsolete.  Sometimes we have to
1496            use TIOCGPGRP on the master end, sometimes the slave end
1497            (probably an AIX bug).  So we better get a fd for the slave if we
1498            haven't got it yet.
14