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.
7 This file is part of SXEmacs
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.
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.
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/>. */
23 /* This file has been Mule-ized except for `start-process-internal',
24 `open-network-stream-internal' and `open-multicast-group-internal'. */
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) */
30 /* The IPv6 support is derived from the code for GNU Emacs-20.3
31 written by Wolfgang S. Rupprecht */
35 #if !defined (NO_SUBPROCESSES)
37 /* The entire file is within this conditional */
42 #include "events/events.h"
50 #include "ui/window.h"
52 #include "mule/file-coding.h"
59 #include "syssignal.h" /* Always include before systty.h */
60 #include "ui/TTY/systty.h"
64 #include <grp.h> /* See grantpt fixups for HPUX below. */
67 #if defined(HAVE_OPENSSL) && defined(OPENSSL_SSL)
73 * Implementation-specific data. Pointed to by Lisp_Process->process_data
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 */
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). */
84 /* Name of subprocess terminal. */
86 /* Non-false if communicating through a pty. */
91 extern struct hash_table *usid_to_process;
94 #define UNIX_DATA(p) ((struct unix_process_data*)((p)->process_data))
96 /**********************************************************************/
97 /* Static helper routines */
98 /**********************************************************************/
100 static SIGTYPE close_safely_handler(int signo)
102 EMACS_REESTABLISH_SIGNAL(signo, close_safely_handler);
106 static void close_safely(int fd)
109 signal(SIGALRM, close_safely_handler);
116 static void close_descriptor_pair(int in, int out)
120 if (out != in && out >= 0)
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. */
129 close_process_descs_mapfun(const void *key, void *contents, void *arg)
132 CVOID_TO_LISP(proc, contents);
133 event_stream_delete_stream_pair(XPROCESS(proc)->pipe_instream,
134 XPROCESS(proc)->pipe_outstream);
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)
142 maphash(close_process_descs_mapfun, usid_to_process, 0);
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
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:
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
163 INFD and OUTFD specify the file descriptors to use for input and
164 output, respectively."
168 connect_to_file_descriptor(Lisp_Object name, Lisp_Object buffer,
169 Lisp_Object infd, Lisp_Object outfd)
171 /* This function can GC */
173 EMACS_INT inch, outch;
181 if (get_process_from_usid(FD_TO_USID(inch)))
182 invalid_operation("There is already a process connected to fd",
185 buffer = Fget_buffer_create(buffer);
186 proc = make_process_internal(name);
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;
193 event_stream_select_process(XPROCESS(proc));
199 static int allocate_pty_the_old_fashioned_way(void);
201 /* The file name of the (slave) pty opened by allocate_pty(). */
202 #ifndef MAX_PTYNAME_LEN
203 #define MAX_PTYNAME_LEN 64
205 static char pty_name[MAX_PTYNAME_LEN];
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'. */
212 static int allocate_pty(void)
214 /* Unix98 standardized grantpt, unlockpt, and ptsname, but not the
215 functions required to open a master pty in the first place :-(
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.
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
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 */
236 #ifdef HAVE_GETPT /* glibc */
240 #endif /* HAVE_GETPT */
242 #if defined(HAVE_OPENPTY) /* BSD, Tru64, glibc */
246 EMACS_BLOCK_SIGNAL(SIGCHLD);
247 rc = openpty(&master_fd, &slave_fd, NULL, NULL, NULL);
248 EMACS_UNBLOCK_SIGNAL(SIGCHLD);
250 slave_name = ttyname(slave_fd);
252 goto have_slave_name;
260 #endif /* HAVE_OPENPTY */
262 #if defined(HAVE__GETPTY) && defined (O_NDELAY) /* SGI */
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 */
271 /* Master clone devices are available on most systems */
274 for (i = 0; i < countof(clones); i++) {
277 open(_clone_, O_RDWR | O_NONBLOCK | OPEN_BINARY, 0);
288 #if defined (HAVE_PTSNAME)
289 slave_name = ptsname(master_fd);
291 goto have_slave_name;
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;
302 if( slave_name != NULL )
303 strncpy(pty_name, slave_name, sizeof(pty_name));
305 strncpy(pty_name, "<NULL ttyname>", sizeof(pty_name));
306 pty_name[sizeof(pty_name) - 1] = '\0';
307 setup_pty(master_fd);
309 /* We jump through some hoops to frob the pty.
310 It's not obvious that checking the return code here is useful. */
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
316 #if defined (HAVE_GRANTPT) || defined (HAVE_UNLOCKPT)
317 EMACS_BLOCK_SIGNAL(SIGCHLD);
319 #if defined (HAVE_GRANTPT)
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. */
326 struct group *tty_group = getgrnam("tty");
327 if (tty_group != NULL)
328 chown(pty_name, (uid_t) - 1, tty_group->gr_gid);
330 #endif /* HPUX has broken grantpt() */
331 #endif /* HAVE_GRANTPT */
333 #if defined (HAVE_UNLOCKPT)
337 EMACS_UNBLOCK_SIGNAL(SIGCHLD);
338 #endif /* HAVE_GRANTPT || HAVE_UNLOCKPT */
345 #endif /* ndef FORCE_ALLOCATE_PTY_THE_OLD_FASHIONED_WAY */
346 return allocate_pty_the_old_fashioned_way();
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)
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
360 int failed_count = 0;
368 # ifndef FIRST_PTY_LETTER
369 # define FIRST_PTY_LETTER 'p'
371 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
372 for (i = 0; i < 16; i++)
373 #endif /* PTY_ITERATION */
378 #ifdef PTY_NAME_SPRINTF
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 */
385 if (sxemacs_stat(pty_name, &stb) < 0) {
386 if (++failed_count >= 3)
390 fd = open(pty_name, O_RDWR | O_NONBLOCK | OPEN_BINARY,
394 #ifdef PTY_TTY_NAME_SPRINTF
395 PTY_TTY_NAME_SPRINTF;
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) {
410 #endif /* HAVE_PTYS */
413 create_bidirectional_pipe(long int *inchannel, long int *outchannel,
414 volatile int *forkin, volatile int *forkout)
419 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) < 0)
421 *outchannel = *inchannel = sv[0];
422 *forkout = *forkin = sv[1];
423 #else /* not SKTPAIR */
435 #endif /* not SKTPAIR */
441 #if !(defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO))
443 get_internet_address(Lisp_Object host, struct sockaddr_in *address,
446 struct hostent *host_info_ptr = NULL;
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();
464 if (!(host_info_ptr == 0 && h_errno == TRY_AGAIN))
467 Fsleep_for(make_int(1));
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);
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));
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;
492 #endif /* !(HAVE_GETADDRINFO && HAVE_GETNAMEINFO) */
494 static void set_socket_nonblocking_maybe(int fd, int port, const char *proto)
496 #ifdef PROCESS_IO_BLOCKING
499 for (tail = network_stream_blocking_port_list; CONSP(tail);
501 Lisp_Object tail_port = XCAR(tail);
503 if (STRINGP(tail_port)) {
504 struct servent *svc_info;
505 CHECK_STRING(tail_port);
507 getservbyname((char *)XSTRING_DATA(tail_port),
509 if ((svc_info != 0) && (svc_info->s_port == port))
513 } else if (INTP(tail_port)
514 && (htons((unsigned short)XINT(tail_port)) == port))
519 set_descriptor_non_blocking(fd);
522 set_descriptor_non_blocking(fd);
523 #endif /* PROCESS_IO_BLOCKING */
526 #endif /* HAVE_SOCKETS */
528 /* Compute the Lisp form of the process status from
529 the numeric status that was returned by `wait'. */
531 static void update_status_from_wait_code(Lisp_Process * p, int *w_fmh)
533 /* C compiler lossage when attempting to pass w directly */
537 p->status_symbol = Qstop;
538 p->exit_code = WSTOPSIG(w);
540 } else if (WIFEXITED(w)) {
541 p->status_symbol = Qexit;
542 p->exit_code = WEXITSTATUS(w);
544 } else if (WIFSIGNALED(w)) {
545 p->status_symbol = Qsignal;
546 p->exit_code = WTERMSIG(w);
547 p->core_dumped = WCOREDUMP(w);
549 p->status_symbol = Qrun;
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;
561 static volatile int sigchld_happened;
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.
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). */
575 static void record_exited_processes(int block_sigchld)
577 if (!sigchld_happened) {
580 #ifdef EMACS_BLOCK_SIGNAL
582 EMACS_BLOCK_SIGNAL(SIGCHLD);
585 while (sigchld_happened) {
589 /* Keep trying to get a status until we get a definitive result. */
595 # endif /* not WUNTRACED */
597 pid = waitpid((pid_t) - 1, &w, WNOHANG | WUNTRACED);
599 pid = wait3(&w, WNOHANG | WUNTRACED, 0);
601 #else /* not WNOHANG */
603 #endif /* not WNOHANG */
605 while (pid <= 0 && errno == EINTR);
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++;
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
623 #endif /* not WNOHANG */
626 sigchld_happened = 0;
629 EMACS_UNBLOCK_SIGNAL(SIGCHLD);
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. */
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.
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.) */
654 static SIGTYPE sigchld_handler(int signo)
656 #ifdef OBNOXIOUS_SYSV_SIGCLD_BEHAVIOR
657 int old_errno = errno;
660 record_exited_processes(0);
665 #ifdef HAVE_UNIXOID_EVENT_LOOP
668 /* WARNING - must come after wait3() for USG systems */
669 EMACS_REESTABLISH_SIGNAL(signo, sigchld_handler);
675 #ifdef SIGNALS_VIA_CHARACTERS
676 /* Get signal character to send to process if SIGNALS_VIA_CHARACTERS */
678 static int process_signal_char(int tty_fd, int signo)
680 /* Invalid tty_fd ... */
684 /* If it's not a tty, pray that these default values work */
685 if (!isatty(tty_fd)) {
686 #define CNTL(ch) (037 & (ch))
701 /* TERMIOS is the latest and bestest, and seems most likely to work.
702 If the system has it, use it. */
705 tcgetattr(tty_fd, &t);
708 return t.c_cc[VINTR];
710 return t.c_cc[VQUIT];
711 #if defined(SIGTSTP) && defined(VSUSP)
713 return t.c_cc[VSUSP];
720 # elif defined (TIOCGLTC) && defined (TIOCGETC) /* not HAVE_TERMIOS */
722 /* On Berkeley descendants, the following IOCTL's retrieve the
723 current control characters. */
728 ioctl(tty_fd, TIOCGETC, &c);
731 ioctl(tty_fd, TIOCGETC, &c);
735 ioctl(tty_fd, TIOCGLTC, &lc);
737 # endif /* SIGTSTP */
741 # elif defined (TCGETA) /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
743 /* On SYSV descendants, the TCGETA ioctl retrieves the current
744 control characters. */
746 ioctl(tty_fd, TCGETA, &t);
749 return t.c_cc[VINTR];
751 return t.c_cc[VQUIT];
754 return t.c_cc[VSWTCH];
755 # endif /* SIGTSTP */
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) */
765 #endif /* SIGNALS_VIA_CHARACTERS */
767 /**********************************************************************/
768 /* Process implementation methods */
769 /**********************************************************************/
772 * Allocate and initialize Lisp_Process->process_data
775 static void unix_alloc_process_data(Lisp_Process * p)
777 p->process_data = xnew(struct unix_process_data);
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;
787 * Mark any Lisp objects in Lisp_Process->process_data
790 static void unix_mark_process_data(Lisp_Process * proc)
792 mark_object(UNIX_DATA(proc)->tty_name);
796 * Initialize SXEmacs process implementation once
800 static void unix_init_process(void)
803 if (!noninteractive || initialized)
805 signal(SIGCHLD, sigchld_handler);
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.
817 unix_init_process_io_handles(Lisp_Process * p, void *in, void *out, int flags)
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),
824 UNIX_DATA(p)->infd = (EMACS_INT)in;
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.
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.
838 unix_create_process(Lisp_Process * p,
839 Lisp_Object * argv, int nargv,
840 Lisp_Object program, Lisp_Object cur_dir)
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;
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();
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. */
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. */
866 /* Don't let this terminal become our controlling terminal
867 (in case we don't have one). */
869 open(pty_name, O_RDWR | O_NOCTTY | OPEN_BINARY, 0);
871 forkout = forkin = open(pty_name, O_RDWR | OPEN_BINARY, 0);
876 UNIX_DATA(p)->pty_flag = pty_flag = 1;
878 #endif /* HAVE_PTYS */
879 if (create_bidirectional_pipe(
880 (void*)&inchannel, (void*)&outchannel,
881 &forkin, &forkout) < 0)
885 /* Replaced by close_process_descs */
886 set_exclusive_use(inchannel);
887 set_exclusive_use(outchannel);
890 set_descriptor_non_blocking(inchannel);
891 set_descriptor_non_blocking(outchannel);
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;
901 /* child_setup must clobber environ on systems with true vfork.
902 Protect it from permanent change. */
903 char **save_environ = environ;
907 /**** Now we're in the child process ****/
908 int xforkin = forkin;
909 int xforkout = forkout;
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();
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. */
919 disconnect_controlling_terminal();
923 /* Open the pty connection and make the pty's terminal
924 our controlling terminal.
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:
931 (1) on USG and TIOCSCTTY systems, we open the pty
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.
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
947 /* There was some weirdo, probably wrong,
948 conditionalization on RTU and UNIPLUS here.
949 I deleted it. So sue me. */
951 /* SunOS has TIOCSCTTY but the close/open method
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
958 /* I wonder if close (open (pty_name, ...)) would work? */
962 open(pty_name, O_RDWR | OPEN_BINARY, 0);
965 "Couldn't open the pty terminal ",
967 write(1, pty_name, strlen(pty_name));
971 # endif /* USG or not TIOCSCTTY */
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. */
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)
982 # define stream_module_pushed(fd, module) 0
984 if (!stream_module_pushed
986 ioctl(xforkin, I_PUSH, "ptem");
987 if (!stream_module_pushed
989 ioctl(xforkin, I_PUSH,
991 if (!stream_module_pushed
992 (xforkin, "ttcompat"))
993 ioctl(xforkin, I_PUSH,
996 # endif /* HAVE_ISASTREAM */
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 */
1005 /* Change the line discipline. */
1007 # if defined (HAVE_TERMIOS) && defined (LDISC1)
1010 assert(isatty(xforkin));
1011 tcgetattr(xforkin, &t);
1013 if (tcsetattr(xforkin, TCSANOW, &t) < 0)
1015 ("create_process/tcsetattr LDISC1 failed\n");
1017 # elif defined (NTTYDISC) && defined (TIOCSETD)
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);
1025 # endif /* TIOCSETD & NTTYDISC */
1027 /* Make our process group be the foreground group
1028 of our new controlling terminal. */
1032 EMACS_GET_PROCESS_GROUP();
1033 EMACS_SET_TTY_PROCESS_GROUP(xforkin,
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
1044 signal(SIGHUP, SIG_DFL);
1048 /* Set up the terminal characteristics of the pty. */
1049 child_setup_tty(xforkout);
1051 #endif /* HAVE_PTYS */
1053 signal(SIGINT, SIG_DFL);
1054 signal(SIGQUIT, SIG_DFL);
1059 alloca_array(char *, nargv + 2);
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]);
1067 (char *)XSTRING_DATA(argv[i]);
1069 new_argv[i + 1] = 0;
1071 LISP_STRING_TO_EXTERNAL(cur_dir, current_dir,
1074 child_setup(xforkin, xforkout, xforkout,
1075 new_argv, current_dir);
1080 /**** End of child code ****/
1081 /**** Back in parent process ****/
1082 environ = save_environ;
1086 int save_errno = errno;
1087 close_descriptor_pair(forkin, forkout);
1089 report_file_error("Doing fork", Qnil);
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; */
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. */
1100 close_safely(forkin);
1101 if (forkin != forkout && forkout >= 0)
1106 UNIX_DATA(p)->tty_name = build_string(pty_name);
1109 UNIX_DATA(p)->tty_name = Qnil;
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). */
1120 int save_errno = errno;
1121 close_descriptor_pair(forkin, forkout);
1122 close_descriptor_pair(inchannel, outchannel);
1124 report_file_error("Opening pty or pipe", Qnil);
1125 return 0; /* not reached */
1129 /* This is called to set process' virtual terminal size */
1131 static int unix_set_window_size(Lisp_Process * p, int cols, int rows)
1133 return set_window_size(UNIX_DATA(p)->infd, cols, rows);
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.
1141 * The method is called only for real child processes.
1145 static void unix_update_status_if_terminated(Lisp_Process * p)
1149 EMACS_BLOCK_SIGNAL(SIGCHLD);
1151 if (waitpid(XINT(p->pid), &w, WNOHANG) == XINT(p->pid)) {
1153 update_status_from_wait_code(p, &w);
1156 EMACS_UNBLOCK_SIGNAL(SIGCHLD);
1162 * Update status of all exited processes. Called when SIGCLD has signaled.
1166 static void unix_reap_exited_processes(void)
1171 #ifndef OBNOXIOUS_SYSV_SIGCLD_BEHAVIOR
1172 record_exited_processes(1);
1175 if (exited_processes_index <= 0) {
1178 #ifdef EMACS_BLOCK_SIGNAL
1179 EMACS_BLOCK_SIGNAL(SIGCHLD);
1181 for (i = 0; i < exited_processes_index; i++) {
1182 int pid = exited_processes[i];
1183 int w = exited_processes_status[i];
1185 /* Find the process that signaled us, and record its status. */
1190 LIST_LOOP(tail, Vprocess_list) {
1191 Lisp_Object proc = XCAR(tail);
1193 if (INTP(p->pid) && XINT(p->pid) == pid)
1200 /* Change the status of the process that was found. */
1203 update_status_from_wait_code(p, &w);
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
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;
1223 /* Report the status of the synchronous process. */
1225 synch_process_retcode = WEXITSTATUS(w);
1226 else if (WIFSIGNALED(w))
1227 synch_process_death =
1228 signal_name(WTERMSIG(w));
1233 exited_processes_index = 0;
1235 EMACS_UNBLOCK_SIGNAL(SIGCHLD);
1237 #endif /* SIGCHLD */
1240 * Stuff the entire contents of LSTREAM to the process output pipe
1243 static JMP_BUF send_process_frame;
1245 static SIGTYPE send_process_trap(int signum)
1247 EMACS_REESTABLISH_SIGNAL(signum, send_process_trap);
1248 EMACS_UNBLOCK_SIGNAL(signum);
1249 LONGJMP(send_process_frame, 1);
1253 unix_send_process(Lisp_Object proc, lstream_t lstream)
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);
1260 /* #### JV: layering violation?
1262 This function knows too much about the relation between the encoding
1263 stream (DATA_OUTSTREAM) and the actual output stream p->output_stream.
1265 If encoding streams properly forwarded all calls, we could simply
1266 use DATA_OUTSTREAM everywhere. */
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
1272 Bufbyte chunkbuf[512];
1273 Bytecount chunklen = 0;
1276 Lstream_data_count writeret;
1277 if (p->process_type!=PROCESS_TYPE_NETWORK_SERVER_LISTEN) {
1278 chunklen = Lstream_read(lstream, chunkbuf, 512);
1281 (SIGTYPE(*)(int))signal(SIGPIPE, send_process_trap);
1285 switch (p->process_type) {
1286 case PROCESS_TYPE_NETWORK_SERVER_LISTEN:
1287 report_file_error ("no writing to listen process possible",
1290 case PROCESS_TYPE_SSL:
1291 case PROCESS_TYPE_PROC:
1292 case PROCESS_TYPE_NETWORK:
1293 case PROCESS_TYPE_MULTICAST:
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);
1304 signal (SIGPIPE, old_sigpipe);
1307 /* This is a real error. Blocking errors are handled
1308 * specially inside of the filedesc stream.
1310 report_file_error ("writing to process",
1313 /* Need to make sure that everything up to and including the
1314 * last chunk is flushed, even when the pipe is currently
1316 Lstream_flush (XLSTREAM (DATA_OUTSTREAM(p)));
1317 signal (SIGPIPE, old_sigpipe);
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.
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))
1330 old_sigpipe = (SIGTYPE(*)(int))signal(
1333 Lstream_flush(XLSTREAM(p->pipe_outstream));
1334 signal(SIGPIPE, old_sigpipe);
1336 /* Perhaps should abort() if < 0?
1337 * This should never happen.
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;
1348 XLSTREAM(p->coding_outstream)->flags &= ~LSTREAM_FL_IS_OPEN;
1350 p->status_symbol = Qexit;
1351 p->exit_code = 256; /* #### SIGPIPE ??? */
1355 deactivate_process(vol_proc);
1356 invalid_operation("SIGPIPE raised on process; closed it",
1360 old_sigpipe = (SIGTYPE(*)(int))signal(SIGPIPE, send_process_trap);
1361 Lstream_flush(XLSTREAM(DATA_OUTSTREAM(p)));
1362 signal(SIGPIPE, old_sigpipe);
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.
1372 static int unix_process_send_eof(Lisp_Object proc)
1374 if (!UNIX_DATA(XPROCESS(proc))->pty_flag)
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
1382 Bufbyte eof_char = get_eof_char(XPROCESS(proc));
1383 send_process(proc, Qnil, &eof_char, 0, 1);
1385 send_process(proc, Qnil, (const Bufbyte *)"\004", 0, 1);
1391 * Called before the process is deactivated. The process object
1392 * is not immediately finalized, just undergoes a transition to
1395 * The return value is a unique stream ID, as returned by
1396 * event_stream_delete_stream_pair
1398 * In the lack of this method, only event_stream_delete_stream_pair
1399 * is called on both I/O streams of the process.
1401 * The UNIX version guards this by ignoring possible SIGPIPE.
1404 static USID unix_deactivate_process(Lisp_Process * p)
1406 SIGTYPE(*old_sigpipe) (int) = 0;
1409 if (UNIX_DATA(p)->infd >= 0)
1410 flush_pending_output(UNIX_DATA(p)->infd);
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,
1418 signal(SIGPIPE, old_sigpipe);
1420 UNIX_DATA(p)->infd = -1;
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)
1428 if (upd->pty_flag && (upd->subtty == -1 || !isatty(upd->subtty))
1429 && STRINGP(upd->tty_name))
1431 open((char *)XSTRING_DATA(upd->tty_name), O_RDWR, 0);
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
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.
1446 The method signals an error if the given SIGNO is not valid. */
1449 unix_kill_child_process(Lisp_Object proc, int signo,
1450 int current_group, int nomsg)
1453 Lisp_Process *p = XPROCESS(proc);
1454 struct unix_process_data *d = UNIX_DATA(p);
1459 p->status_symbol = Qrun;
1466 #endif /* ! defined (SIGCONT) */
1470 flush_pending_output(d->infd);
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.
1483 The BSD people invented the TIOCPGRP ioctl to get the foreground
1484 process group of a tty. That, combined with killpg, gives us
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.
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