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/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 strncpy(pty_name, slave_name, sizeof(pty_name));
303 pty_name[sizeof(pty_name) - 1] = '\0';
304 setup_pty(master_fd);
306 /* We jump through some hoops to frob the pty.
307 It's not obvious that checking the return code here is useful. */
309 /* "The grantpt() function will fail if it is unable to successfully
310 invoke the setuid root program. It may also fail if the
311 application has installed a signal handler to catch SIGCHLD
313 #if defined (HAVE_GRANTPT) || defined (HAVE_UNLOCKPT)
314 EMACS_BLOCK_SIGNAL(SIGCHLD);
316 #if defined (HAVE_GRANTPT)
319 /* grantpt() behavior on some versions of HP-UX differs from what's
320 specified in the man page: the group of the slave PTY is set to
321 the user's primary group, and we fix that. */
323 struct group *tty_group = getgrnam("tty");
324 if (tty_group != NULL)
325 chown(pty_name, (uid_t) - 1, tty_group->gr_gid);
327 #endif /* HPUX has broken grantpt() */
328 #endif /* HAVE_GRANTPT */
330 #if defined (HAVE_UNLOCKPT)
334 EMACS_UNBLOCK_SIGNAL(SIGCHLD);
335 #endif /* HAVE_GRANTPT || HAVE_UNLOCKPT */
342 #endif /* ndef FORCE_ALLOCATE_PTY_THE_OLD_FASHIONED_WAY */
343 return allocate_pty_the_old_fashioned_way();
346 /* This function tries to allocate a pty by iterating through file
347 pairs with names like /dev/ptyp1 and /dev/ttyp1. */
348 static int allocate_pty_the_old_fashioned_way(void)
352 /* Some systems name their pseudoterminals so that there are gaps in
353 the usual sequence - for example, on HP9000/S700 systems, there
354 are no pseudoterminals with names ending in 'f'. So we wait for
355 three failures in a row before deciding that we've reached the
357 int failed_count = 0;
365 # ifndef FIRST_PTY_LETTER
366 # define FIRST_PTY_LETTER 'p'
368 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
369 for (i = 0; i < 16; i++)
370 #endif /* PTY_ITERATION */
375 #ifdef PTY_NAME_SPRINTF
378 sz = snprintf(pty_name, sizeof(pty_name), "/dev/pty%c%x", c, i);
379 assert(sz >= 0 && sz < sizeof(pty_name));
380 #endif /* no PTY_NAME_SPRINTF */
382 if (sxemacs_stat(pty_name, &stb) < 0) {
383 if (++failed_count >= 3)
387 fd = open(pty_name, O_RDWR | O_NONBLOCK | OPEN_BINARY,
391 #ifdef PTY_TTY_NAME_SPRINTF
392 PTY_TTY_NAME_SPRINTF;
394 int sz = snprintf(pty_name, sizeof(pty_name),
395 "/dev/tty%c%x", c, i);
396 assert(sz >= 0 && sz < sizeof(pty_name));
397 #endif /* no PTY_TTY_NAME_SPRINTF */
398 if (access(pty_name, R_OK | W_OK) == 0) {
407 #endif /* HAVE_PTYS */
410 create_bidirectional_pipe(long int *inchannel, long int *outchannel,
411 volatile int *forkin, volatile int *forkout)
416 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) < 0)
418 *outchannel = *inchannel = sv[0];
419 *forkout = *forkin = sv[1];
420 #else /* not SKTPAIR */
432 #endif /* not SKTPAIR */
438 #if !(defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO))
440 get_internet_address(Lisp_Object host, struct sockaddr_in *address,
443 struct hostent *host_info_ptr = NULL;
456 /* Some systems can't handle SIGIO/SIGALARM in gethostbyname. */
457 slow_down_interrupts();
458 host_info_ptr = gethostbyname((char *)XSTRING_DATA(host));
459 speed_up_interrupts();
461 if (!(host_info_ptr == 0 && h_errno == TRY_AGAIN))
464 Fsleep_for(make_int(1));
467 address->sin_family = host_info_ptr->h_addrtype;
468 memcpy(&address->sin_addr, host_info_ptr->h_addr,
469 host_info_ptr->h_length);
471 IN_ADDR numeric_addr;
472 /* Attempt to interpret host as numeric inet address */
473 numeric_addr = inet_addr((char *)XSTRING_DATA(host));
474 if (NUMERIC_ADDR_ERROR) {
475 maybe_error(Qprocess, errb,
476 "Unknown host \"%s\"", XSTRING_DATA(host));
480 /* There was some broken code here that called strlen() here
481 on (char *) &numeric_addr and even sometimes accessed
482 uninitialized data. */
483 address->sin_family = AF_INET;
484 *(IN_ADDR *) & address->sin_addr = numeric_addr;
489 #endif /* !(HAVE_GETADDRINFO && HAVE_GETNAMEINFO) */
491 static void set_socket_nonblocking_maybe(int fd, int port, const char *proto)
493 #ifdef PROCESS_IO_BLOCKING
496 for (tail = network_stream_blocking_port_list; CONSP(tail);
498 Lisp_Object tail_port = XCAR(tail);
500 if (STRINGP(tail_port)) {
501 struct servent *svc_info;
502 CHECK_STRING(tail_port);
504 getservbyname((char *)XSTRING_DATA(tail_port),
506 if ((svc_info != 0) && (svc_info->s_port == port))
510 } else if (INTP(tail_port)
511 && (htons((unsigned short)XINT(tail_port)) == port))
516 set_descriptor_non_blocking(fd);
519 set_descriptor_non_blocking(fd);
520 #endif /* PROCESS_IO_BLOCKING */
523 #endif /* HAVE_SOCKETS */
525 /* Compute the Lisp form of the process status from
526 the numeric status that was returned by `wait'. */
528 static void update_status_from_wait_code(Lisp_Process * p, int *w_fmh)
530 /* C compiler lossage when attempting to pass w directly */
534 p->status_symbol = Qstop;
535 p->exit_code = WSTOPSIG(w);
537 } else if (WIFEXITED(w)) {
538 p->status_symbol = Qexit;
539 p->exit_code = WEXITSTATUS(w);
541 } else if (WIFSIGNALED(w)) {
542 p->status_symbol = Qsignal;
543 p->exit_code = WTERMSIG(w);
544 p->core_dumped = WCOREDUMP(w);
546 p->status_symbol = Qrun;
553 #define MAX_EXITED_PROCESSES 1000
554 static volatile pid_t exited_processes[MAX_EXITED_PROCESSES];
555 static volatile int exited_processes_status[MAX_EXITED_PROCESSES];
556 static volatile int exited_processes_index;
558 static volatile int sigchld_happened;
560 /* On receipt of a signal that a child status has changed,
561 loop asking about children with changed statuses until
562 the system says there are no more. All we do is record
563 the processes and wait status.
565 This function could be called from within the SIGCHLD
566 handler, so it must be completely reentrant. When
567 not called from a SIGCHLD handler, BLOCK_SIGCHLD should
568 be non-zero so that SIGCHLD is blocked while this
569 function is running. (This is necessary so avoid
570 race conditions with the SIGCHLD_HAPPENED flag). */
572 static void record_exited_processes(int block_sigchld)
574 if (!sigchld_happened) {
577 #ifdef EMACS_BLOCK_SIGNAL
579 EMACS_BLOCK_SIGNAL(SIGCHLD);
582 while (sigchld_happened) {
586 /* Keep trying to get a status until we get a definitive result. */
592 # endif /* not WUNTRACED */
594 pid = waitpid((pid_t) - 1, &w, WNOHANG | WUNTRACED);
596 pid = wait3(&w, WNOHANG | WUNTRACED, 0);
598 #else /* not WNOHANG */
600 #endif /* not WNOHANG */
602 while (pid <= 0 && errno == EINTR);
607 if (exited_processes_index < MAX_EXITED_PROCESSES) {
608 exited_processes[exited_processes_index] = pid;
609 exited_processes_status[exited_processes_index] = w;
610 exited_processes_index++;
613 /* On systems with WNOHANG, we just ignore the number
614 of times that SIGCHLD was signalled, and keep looping
615 until there are no more processes to wait on. If we
616 don't have WNOHANG, we have to rely on the count in
620 #endif /* not WNOHANG */
623 sigchld_happened = 0;
626 EMACS_UNBLOCK_SIGNAL(SIGCHLD);
629 /* For any processes that have changed status and are recorded
630 and such, update the corresponding Lisp_Process.
631 We separate this from record_exited_processes() so that
632 we never have to call this function from within a signal
633 handler. We block SIGCHLD in case record_exited_processes()
634 is called from a signal handler. */
636 /** USG WARNING: Although it is not obvious from the documentation
637 in signal(2), on a USG system the SIGCLD handler MUST NOT call
638 signal() before executing at least one wait(), otherwise the handler
639 will be called again, resulting in an infinite loop. The relevant
640 portion of the documentation reads "SIGCLD signals will be queued
641 and the signal-catching function will be continually reentered until
642 the queue is empty". Invoking signal() causes the kernel to reexamine
643 the SIGCLD queue. Fred Fish, UniSoft Systems Inc.
645 (Note that now this only applies in SYS V Release 2 and before.
646 On SYS V Release 3, we use sigset() to set the signal handler for
647 the first time, and so we don't have to reestablish the signal handler
648 in the handler below. On SYS V Release 4, we don't get this weirdo
649 behavior when we use sigaction(), which we do use.) */
651 static SIGTYPE sigchld_handler(int signo)
653 #ifdef OBNOXIOUS_SYSV_SIGCLD_BEHAVIOR
654 int old_errno = errno;
657 record_exited_processes(0);
662 #ifdef HAVE_UNIXOID_EVENT_LOOP
665 /* WARNING - must come after wait3() for USG systems */
666 EMACS_REESTABLISH_SIGNAL(signo, sigchld_handler);
672 #ifdef SIGNALS_VIA_CHARACTERS
673 /* Get signal character to send to process if SIGNALS_VIA_CHARACTERS */
675 static int process_signal_char(int tty_fd, int signo)
677 /* If it's not a tty, pray that these default values work */
678 if (!isatty(tty_fd)) {
679 #define CNTL(ch) (037 & (ch))
694 /* TERMIOS is the latest and bestest, and seems most likely to work.
695 If the system has it, use it. */
698 tcgetattr(tty_fd, &t);
701 return t.c_cc[VINTR];
703 return t.c_cc[VQUIT];
704 #if defined(SIGTSTP) && defined(VSUSP)
706 return t.c_cc[VSUSP];
713 # elif defined (TIOCGLTC) && defined (TIOCGETC) /* not HAVE_TERMIOS */
715 /* On Berkeley descendants, the following IOCTL's retrieve the
716 current control characters. */
721 ioctl(tty_fd, TIOCGETC, &c);
724 ioctl(tty_fd, TIOCGETC, &c);
728 ioctl(tty_fd, TIOCGLTC, &lc);
730 # endif /* SIGTSTP */
734 # elif defined (TCGETA) /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
736 /* On SYSV descendants, the TCGETA ioctl retrieves the current
737 control characters. */
739 ioctl(tty_fd, TCGETA, &t);
742 return t.c_cc[VINTR];
744 return t.c_cc[VQUIT];
747 return t.c_cc[VSWTCH];
748 # endif /* SIGTSTP */
751 # else /* ! defined (TCGETA) */
752 #error ERROR! Using SIGNALS_VIA_CHARACTERS, but not HAVE_TERMIOS || (TIOCGLTC && TIOCGETC) || TCGETA
753 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
754 you'd better be using one of the alternatives above! */
755 # endif /* ! defined (TCGETA) */
758 #endif /* SIGNALS_VIA_CHARACTERS */
760 /**********************************************************************/
761 /* Process implementation methods */
762 /**********************************************************************/
765 * Allocate and initialize Lisp_Process->process_data
768 static void unix_alloc_process_data(Lisp_Process * p)
770 p->process_data = xnew(struct unix_process_data);
772 UNIX_DATA(p)->connected_via_filedesc_p = 0;
773 UNIX_DATA(p)->infd = -1;
774 UNIX_DATA(p)->subtty = -1;
775 UNIX_DATA(p)->tty_name = Qnil;
776 UNIX_DATA(p)->pty_flag = 0;
780 * Mark any Lisp objects in Lisp_Process->process_data
783 static void unix_mark_process_data(Lisp_Process * proc)
785 mark_object(UNIX_DATA(proc)->tty_name);
789 * Initialize SXEmacs process implementation once
793 static void unix_init_process(void)
796 if (!noninteractive || initialized)
798 signal(SIGCHLD, sigchld_handler);
803 * Initialize any process local data. This is called when newly
804 * created process is connected to real OS file handles. The
805 * handles are generally represented by void* type, but are
806 * of type int (file descriptors) for UNIX.
810 unix_init_process_io_handles(Lisp_Process * p, void *in, void *out, int flags)
812 Lisp_Object process = Qnil;
813 USID usid = FD_TO_USID((EMACS_INT)in);
814 XSETPROCESS(process, p);
815 puthash((const void *)usid, LISP_TO_VOID(process),
817 UNIX_DATA(p)->infd = (EMACS_INT)in;
821 * Fork off a subprocess. P is a pointer to a newly created subprocess
822 * object. If this function signals, the caller is responsible for
823 * deleting (and finalizing) the process object.
825 * The method must return PID of the new process, a (positive??? ####) number
826 * which fits into Lisp_Int. No return value indicates an error, the method
827 * must signal an error instead.
831 unix_create_process(Lisp_Process * p,
832 Lisp_Object * argv, int nargv,
833 Lisp_Object program, Lisp_Object cur_dir)
836 long int inchannel = -1;
837 long int outchannel = -1;
838 /* Use volatile to protect variables from being clobbered by longjmp. */
839 volatile int forkin = -1;
840 volatile int forkout = -1;
841 volatile int pty_flag = 0;
844 if (!NILP(Vprocess_connection_type)) {
845 /* find a new pty, open the master side, return the opened
846 file handle, and store the name of the corresponding slave
847 side in global variable pty_name. */
848 outchannel = inchannel = allocate_pty();
851 if (inchannel >= 0) {
852 /* You're "supposed" to now open the slave in the child.
853 On some systems, we can open it here; this allows for
854 better error checking. */
856 /* On USG systems it does not work to open the pty's tty here
857 and then close and reopen it in the child. */
859 /* Don't let this terminal become our controlling terminal
860 (in case we don't have one). */
862 open(pty_name, O_RDWR | O_NOCTTY | OPEN_BINARY, 0);
864 forkout = forkin = open(pty_name, O_RDWR | OPEN_BINARY, 0);
869 UNIX_DATA(p)->pty_flag = pty_flag = 1;
871 #endif /* HAVE_PTYS */
872 if (create_bidirectional_pipe(
873 (void*)&inchannel, (void*)&outchannel,
874 &forkin, &forkout) < 0)
878 /* Replaced by close_process_descs */
879 set_exclusive_use(inchannel);
880 set_exclusive_use(outchannel);
883 set_descriptor_non_blocking(inchannel);
884 set_descriptor_non_blocking(outchannel);
886 /* Record this as an active process, with its channels.
887 As a result, child_setup will close Emacs's side of the pipes. */
888 init_process_io_handles(p, (void *)inchannel, (void *)outchannel,
889 pty_flag ? STREAM_PTY_FLUSHING : 0);
890 /* Record the tty descriptor used in the subprocess. */
891 UNIX_DATA(p)->subtty = forkin;
894 /* child_setup must clobber environ on systems with true vfork.
895 Protect it from permanent change. */
896 char **save_environ = environ;
900 /**** Now we're in the child process ****/
901 int xforkin = forkin;
902 int xforkout = forkout;
904 /* Checking for quit in the child is bad because that will
905 cause I/O, and that, in turn, can confuse the X connection. */
906 begin_dont_check_for_quit();
908 /* Disconnect the current controlling terminal, pursuant to
909 making the pty be the controlling terminal of the process.
910 Also put us in our own process group. */
912 disconnect_controlling_terminal();
916 /* Open the pty connection and make the pty's terminal
917 our controlling terminal.
919 On systems with TIOCSCTTY, we just use it to set
920 the controlling terminal. On other systems, the
921 first TTY we open becomes the controlling terminal.
922 So, we end up with four possibilities:
924 (1) on USG and TIOCSCTTY systems, we open the pty
926 (2) on other USG systems, we just open the pty.
927 (3) on non-USG systems with TIOCSCTTY, we
928 just use TIOCSCTTY. (On non-USG systems, we
929 already opened the pty in the parent process.)
930 (4) on non-USG systems without TIOCSCTTY, we
931 close the pty and reopen it.
933 This would be cleaner if we didn't open the pty
934 in the parent process, but doing it that way
935 makes it possible to trap error conditions.
936 It's harder to convey an error from the child
937 process, and I don't feel like messing with
940 /* There was some weirdo, probably wrong,
941 conditionalization on RTU and UNIPLUS here.
942 I deleted it. So sue me. */
944 /* SunOS has TIOCSCTTY but the close/open method
947 # if defined (USG) || !defined (TIOCSCTTY)
948 /* Now close the pty (if we had it open) and reopen it.
949 This makes the pty the controlling terminal of the
951 /* I wonder if close (open (pty_name, ...)) would work? */
955 open(pty_name, O_RDWR | OPEN_BINARY, 0);
958 "Couldn't open the pty terminal ",
960 write(1, pty_name, strlen(pty_name));
964 # endif /* USG or not TIOCSCTTY */
966 /* Miscellaneous setup required for some systems.
967 Must be done before using tc* functions on xforkin.
968 This guarantees that isatty(xforkin) is true. */
970 # if defined (HAVE_ISASTREAM) && defined (I_PUSH)
971 if (isastream(xforkin)) {
972 # if defined (I_FIND)
973 # define stream_module_pushed(fd, module) (ioctl (fd, I_FIND, module) == 1)
975 # define stream_module_pushed(fd, module) 0
977 if (!stream_module_pushed
979 ioctl(xforkin, I_PUSH, "ptem");
980 if (!stream_module_pushed
982 ioctl(xforkin, I_PUSH,
984 if (!stream_module_pushed
985 (xforkin, "ttcompat"))
986 ioctl(xforkin, I_PUSH,
989 # endif /* HAVE_ISASTREAM */
992 /* We ignore the return value
993 because faith@cs.unc.edu says that is necessary on Linux. */
994 assert(isatty(xforkin));
995 ioctl(xforkin, TIOCSCTTY, 0);
996 # endif /* TIOCSCTTY */
998 /* Change the line discipline. */
1000 # if defined (HAVE_TERMIOS) && defined (LDISC1)
1003 assert(isatty(xforkin));
1004 tcgetattr(xforkin, &t);
1006 if (tcsetattr(xforkin, TCSANOW, &t) < 0)
1008 ("create_process/tcsetattr LDISC1 failed\n");
1010 # elif defined (NTTYDISC) && defined (TIOCSETD)
1012 /* Use new line discipline. TIOCSETD is accepted and
1013 ignored on Sys5.4 systems with ttcompat. */
1014 int ldisc = NTTYDISC;
1015 assert(isatty(xforkin));
1016 ioctl(xforkin, TIOCSETD, &ldisc);
1018 # endif /* TIOCSETD & NTTYDISC */
1020 /* Make our process group be the foreground group
1021 of our new controlling terminal. */
1025 EMACS_GET_PROCESS_GROUP();
1026 EMACS_SET_TTY_PROCESS_GROUP(xforkin,
1030 /* On AIX, we've disabled SIGHUP above once we start a
1031 child on a pty. Now reenable it in the child, so it
1032 will die when we want it to.
1033 JV: This needs to be done ALWAYS as we might have inherited
1034 a SIG_IGN handling from our parent (nohup) and we are in new
1037 signal(SIGHUP, SIG_DFL);
1041 /* Set up the terminal characteristics of the pty. */
1042 child_setup_tty(xforkout);
1044 #endif /* HAVE_PTYS */
1046 signal(SIGINT, SIG_DFL);
1047 signal(SIGQUIT, SIG_DFL);
1052 alloca_array(char *, nargv + 2);
1055 /* Nothing below here GCs so our string pointers shouldn't move. */
1056 new_argv[0] = (char *)XSTRING_DATA(program);
1057 for (i = 0; i < nargv; i++) {
1058 CHECK_STRING(argv[i]);
1060 (char *)XSTRING_DATA(argv[i]);
1062 new_argv[i + 1] = 0;
1064 LISP_STRING_TO_EXTERNAL(cur_dir, current_dir,
1067 child_setup(xforkin, xforkout, xforkout,
1068 new_argv, current_dir);
1073 /**** End of child code ****/
1074 /**** Back in parent process ****/
1075 environ = save_environ;
1079 int save_errno = errno;
1080 close_descriptor_pair(forkin, forkout);
1082 report_file_error("Doing fork", Qnil);
1085 /* #### dmoore - why is this commented out, otherwise we leave
1086 subtty = forkin, but then we close forkin just below. */
1087 /* UNIX_DATA(p)->subtty = -1; */
1089 /* If the subfork execv fails, and it exits,
1090 this close hangs. I don't know why.
1091 So have an interrupt jar it loose. */
1093 close_safely(forkin);
1094 if (forkin != forkout && forkout >= 0)
1099 UNIX_DATA(p)->tty_name = build_string(pty_name);
1102 UNIX_DATA(p)->tty_name = Qnil;
1104 /* Notice that SIGCHLD was not blocked. (This is not possible on
1105 some systems.) No biggie if SIGCHLD occurs right around the
1106 time that this call happens, because SIGCHLD() does not actually
1107 deselect the process (that doesn't occur until the next time
1108 we're waiting for an event, when status_notify() is called). */
1113 int save_errno = errno;
1114 close_descriptor_pair(forkin, forkout);
1115 close_descriptor_pair(inchannel, outchannel);
1117 report_file_error("Opening pty or pipe", Qnil);
1118 return 0; /* not reached */
1122 /* This is called to set process' virtual terminal size */
1124 static int unix_set_window_size(Lisp_Process * p, int cols, int rows)
1126 return set_window_size(UNIX_DATA(p)->infd, cols, rows);
1130 * This method is called to update status fields of the process
1131 * structure. If the process has not existed, this method is
1132 * expected to do nothing.
1134 * The method is called only for real child processes.
1138 static void unix_update_status_if_terminated(Lisp_Process * p)
1142 EMACS_BLOCK_SIGNAL(SIGCHLD);
1144 if (waitpid(XINT(p->pid), &w, WNOHANG) == XINT(p->pid)) {
1146 update_status_from_wait_code(p, &w);
1149 EMACS_UNBLOCK_SIGNAL(SIGCHLD);
1155 * Update status of all exited processes. Called when SIGCLD has signaled.
1159 static void unix_reap_exited_processes(void)
1164 #ifndef OBNOXIOUS_SYSV_SIGCLD_BEHAVIOR
1165 record_exited_processes(1);
1168 if (exited_processes_index <= 0) {
1171 #ifdef EMACS_BLOCK_SIGNAL
1172 EMACS_BLOCK_SIGNAL(SIGCHLD);
1174 for (i = 0; i < exited_processes_index; i++) {
1175 int pid = exited_processes[i];
1176 int w = exited_processes_status[i];
1178 /* Find the process that signaled us, and record its status. */
1183 LIST_LOOP(tail, Vprocess_list) {
1184 Lisp_Object proc = XCAR(tail);
1186 if (INTP(p->pid) && XINT(p->pid) == pid)
1193 /* Change the status of the process that was found. */
1196 update_status_from_wait_code(p, &w);
1198 /* If process has terminated, stop waiting for its output. */
1199 if (WIFSIGNALED(w) || WIFEXITED(w)) {
1200 if (!NILP(p->pipe_instream)) {
1201 /* We can't just call event_stream->unselect_process_cb (p)
1202 here, because that calls XtRemoveInput, which is not
1203 necessarily reentrant, so we can't call this at interrupt
1209 /* There was no asynchronous process found for that id. Check
1210 if we have a synchronous process. Only set sync process status
1211 if there is one, so we work OK with the waitpid() call in
1212 wait_for_termination(). */
1213 if (synch_process_alive != 0) { /* Set the global sync process status variables. */
1214 synch_process_alive = 0;
1216 /* Report the status of the synchronous process. */
1218 synch_process_retcode = WEXITSTATUS(w);
1219 else if (WIFSIGNALED(w))
1220 synch_process_death =
1221 signal_name(WTERMSIG(w));
1226 exited_processes_index = 0;
1228 EMACS_UNBLOCK_SIGNAL(SIGCHLD);
1230 #endif /* SIGCHLD */
1233 * Stuff the entire contents of LSTREAM to the process output pipe
1236 static JMP_BUF send_process_frame;
1238 static SIGTYPE send_process_trap(int signum)
1240 EMACS_REESTABLISH_SIGNAL(signum, send_process_trap);
1241 EMACS_UNBLOCK_SIGNAL(signum);
1242 LONGJMP(send_process_frame, 1);
1246 unix_send_process(Lisp_Object proc, lstream_t lstream)
1248 /* Use volatile to protect variables from being clobbered by longjmp. */
1249 SIGTYPE(*volatile old_sigpipe) (int) = 0;
1250 volatile Lisp_Object vol_proc = proc;
1251 Lisp_Process *volatile p = XPROCESS(proc);
1253 /* #### JV: layering violation?
1255 This function knows too much about the relation between the encoding
1256 stream (DATA_OUTSTREAM) and the actual output stream p->output_stream.
1258 If encoding streams properly forwarded all calls, we could simply
1259 use DATA_OUTSTREAM everywhere. */
1261 if (!SETJMP(send_process_frame)) {
1262 /* use a reasonable-sized buffer (somewhere around the size of the
1263 stream buffer) so as to avoid inundating the stream with blocked
1265 Bufbyte chunkbuf[512];
1266 Bytecount chunklen = 0;
1269 Lstream_data_count writeret;
1270 if (p->process_type!=PROCESS_TYPE_NETWORK_SERVER_LISTEN) {
1271 chunklen = Lstream_read(lstream, chunkbuf, 512);
1274 (SIGTYPE(*)(int))signal(SIGPIPE, send_process_trap);
1278 switch (p->process_type) {
1279 case PROCESS_TYPE_NETWORK_SERVER_LISTEN:
1280 report_file_error ("no writing to listen process possible",
1283 case PROCESS_TYPE_SSL:
1284 case PROCESS_TYPE_PROC:
1285 case PROCESS_TYPE_NETWORK:
1286 case PROCESS_TYPE_MULTICAST:
1288 /* Lstream_write() will never successfully write less than
1289 * the amount sent in. In the worst case, it just buffers
1290 * the unwritten data. */
1291 writeret = Lstream_write
1292 (XLSTREAM (DATA_OUTSTREAM(p)),
1293 chunkbuf, chunklen);
1297 signal (SIGPIPE, old_sigpipe);
1300 /* This is a real error. Blocking errors are handled
1301 * specially inside of the filedesc stream.
1303 report_file_error ("writing to process",
1306 /* Need to make sure that everything up to and including the
1307 * last chunk is flushed, even when the pipe is currently
1309 Lstream_flush (XLSTREAM (DATA_OUTSTREAM(p)));
1310 signal (SIGPIPE, old_sigpipe);
1312 while (Lstream_was_blocked_p
1313 (XLSTREAM(p->pipe_outstream))) {
1314 /* Buffer is full. Wait, accepting input;
1315 * that may allow the program
1316 * to finish doing output and read more.
1318 Faccept_process_output(Qnil, make_int(1), Qnil);
1319 /* It could have *really* finished,
1320 * deleting the process */
1321 if (NILP(p->pipe_outstream))
1323 old_sigpipe = (SIGTYPE(*)(int))signal(
1326 Lstream_flush(XLSTREAM(p->pipe_outstream));
1327 signal(SIGPIPE, old_sigpipe);
1329 /* Perhaps should abort() if < 0?
1330 * This should never happen.
1333 while (chunklen > 0);
1334 } else { /* We got here from a longjmp() from the SIGPIPE handler */
1335 signal(SIGPIPE, old_sigpipe);
1336 /* Close the file lstream so we don't attempt to write to it further */
1337 /* #### There is controversy over whether this might cause fd leakage */
1338 /* my tests say no. -slb */
1339 XLSTREAM(p->pipe_outstream)->flags &= ~LSTREAM_FL_IS_OPEN;
1341 XLSTREAM(p->coding_outstream)->flags &= ~LSTREAM_FL_IS_OPEN;
1343 p->status_symbol = Qexit;
1344 p->exit_code = 256; /* #### SIGPIPE ??? */
1348 deactivate_process(vol_proc);
1349 invalid_operation("SIGPIPE raised on process; closed it",
1353 old_sigpipe = (SIGTYPE(*)(int))signal(SIGPIPE, send_process_trap);
1354 Lstream_flush(XLSTREAM(DATA_OUTSTREAM(p)));
1355 signal(SIGPIPE, old_sigpipe);
1359 * Send EOF to the process. The default implementation simply
1360 * closes the output stream. The method must return 0 to call
1361 * the default implementation, or 1 if it has taken all care about
1362 * sending EOF to the process.
1365 static int unix_process_send_eof(Lisp_Object proc)
1367 if (!UNIX_DATA(XPROCESS(proc))->pty_flag)
1370 /* #### get_eof_char simply doesn't return the correct character
1371 here. Maybe it is needed to determine the right eof
1372 character in init_process_io_handles but here it simply screws
1375 Bufbyte eof_char = get_eof_char(XPROCESS(proc));
1376 send_process(proc, Qnil, &eof_char, 0, 1);
1378 send_process(proc, Qnil, (const Bufbyte *)"\004", 0, 1);
1384 * Called before the process is deactivated. The process object
1385 * is not immediately finalized, just undergoes a transition to
1388 * The return value is a unique stream ID, as returned by
1389 * event_stream_delete_stream_pair
1391 * In the lack of this method, only event_stream_delete_stream_pair
1392 * is called on both I/O streams of the process.
1394 * The UNIX version guards this by ignoring possible SIGPIPE.
1397 static USID unix_deactivate_process(Lisp_Process * p)
1399 SIGTYPE(*old_sigpipe) (int) = 0;
1402 if (UNIX_DATA(p)->infd >= 0)
1403 flush_pending_output(UNIX_DATA(p)->infd);
1405 /* closing the outstream could result in SIGPIPE, so ignore it. */
1406 old_sigpipe = (SIGTYPE(*)(int))signal(SIGPIPE, SIG_IGN);
1407 usid = FD_TO_USID(UNIX_DATA(p)->infd);
1408 event_stream_delete_stream_pair(p->pipe_instream,
1411 signal(SIGPIPE, old_sigpipe);
1413 UNIX_DATA(p)->infd = -1;
1418 /* If the subtty field of the process data is not filled in, do so now. */
1419 static void try_to_initialize_subtty(struct unix_process_data *upd)
1421 if (upd->pty_flag && (upd->subtty == -1 || !isatty(upd->subtty))
1422 && STRINGP(upd->tty_name))
1424 open((char *)XSTRING_DATA(upd->tty_name), O_RDWR, 0);
1427 /* Send signal number SIGNO to PROCESS.
1428 CURRENT_GROUP means send to the process group that currently owns
1429 the terminal being used to communicate with PROCESS.
1430 This is used for various commands in shell mode.
1431 If NOMSG is zero, insert signal-announcements into process's buffers
1434 If we can, we try to signal PROCESS by sending control characters
1435 down the pty. This allows us to signal inferiors who have changed
1436 their uid, for which killpg would return an EPERM error,
1437 or processes running on other machines via remote login.
1439 The method signals an error if the given SIGNO is not valid. */
1442 unix_kill_child_process(Lisp_Object proc, int signo,
1443 int current_group, int nomsg)
1446 Lisp_Process *p = XPROCESS(proc);
1447 struct unix_process_data *d = UNIX_DATA(p);
1452 p->status_symbol = Qrun;
1459 #endif /* ! defined (SIGCONT) */
1463 flush_pending_output(d->infd);
1472 /* If current_group is true, we want to send a signal to the
1473 foreground process group of the terminal our child process is
1474 running on. You would think that would be easy.
1476 The BSD people invented the TIOCPGRP ioctl to get the foreground
1477 process group of a tty. That, combined with killpg, gives us
1480 However, the POSIX standards people, in their infinite wisdom,
1481 have seen fit to only allow this for processes which have the
1482 terminal as controlling terminal, which doesn't apply to us.
1484 Sooo..., we have to do something non-standard. The ioctls
1485 TIOCSIGNAL, TIOCSIG, and TIOCSIGSEND send the signal directly on
1486 many systems. POSIX tcgetpgrp(), since it is *documented* as not
1487 doing what we want, is actually less likely to work than the BSD
1488 ioctl TIOCGPGRP it is supposed to obsolete. Sometimes we have to
1489 use TIOCGPGRP on the master end, sometimes the slave end
1490 (probably an AIX bug). So we better get a fd for the slave if we
1493 Anal operating systems like SGI Irix and Compaq Tru64 adhere
1494 strictly to the letter of the law, so our hack doesn't work.
1495 The following fragment from an Irix header file is suggestive:
1498 // this is not currently supported
1499 #define TIOCSIGNAL (tIOC|31) // pty: send signal to slave
1502 On those systems where none of our tricks work, we just fall back
1503 to the non-current_group behavior and kill the process group of
1506 if (current_group) {
1507 try_to_initialize_subtty(d);
1509 #ifdef SIGNALS_VIA_CHARACTERS
1510 /* If possible, send signals to the entire pgrp
1511 by sending an input character to it. */
1513 char sigchar = process_signal_char(d->subtty, signo);
1515 send_process(proc, Qnil, (Bufbyte *) & sigchar,
1520 #endif /* SIGNALS_VIA_CHARACTERS */
1524 ioctl(d->infd, TIOCGPGRP, &pgid); /* BSD */
1525 if (pgid == -1 && d->subtty != -1)
1526 ioctl(d->subtty, TIOCGPGRP, &pgid); /* Only this works on AIX! */
1527 #endif /* TIOCGPGRP */
1530 /* Many systems provide an ioctl to send a signal directly */
1531 #ifdef TIOCSIGNAL /* Solaris, HP-UX */
1532 if (ioctl(d->infd, TIOCSIGNAL, signo) != -1)
1534 #endif /* TIOCSIGNAL */
1536 #ifdef TIOCSIG /* BSD */
1537 if (ioctl(d->infd, TIOCSIG, signo) != -1)
1539 #endif /* TIOCSIG */
1544 /* Either current_group is 0, or we failed to get the foreground
1545 process group using the trickery above. So we fall back to
1546 sending the signal to the process group of our child process.
1547 Since this is often a shell that ignores signals like SIGINT,
1548 the shell's subprocess is killed, which is the desired effect.
1549 The process group of p->pid is always p->pid, since it was
1550 created as a process group leader. */
1551 pgid = XINT(p->pid);
1553 /* Finally send the signal. */
1554 if (EMACS_KILLPG(pgid, signo) == -1) {
1555 /* It's not an error if our victim is already dead.
1556 And we can't rely on the result of killing a zombie, since
1557 XPG 4.2 requires that killing a zombie fail with ESRCH,
1558 while FIPS 151-2 requires that it succeeds! */
1562 error("kill (%ld, %ld) failed: %s",
1563 (long)pgid, (long)signo, strerror(errno));
1567 /* Send signal SIGCODE to any process in the system given its PID.
1568 Return zero if successful, a negative number upon failure. */
1570 static int unix_kill_process_by_pid(int pid, int sigcode)
1572 return kill(pid, sigcode);
1575 /* Return TTY name used to communicate with subprocess. */
1577 static Lisp_Object unix_get_tty_name(Lisp_Process * p)
1579 return UNIX_DATA(p)->tty_name;
1582 /* Canonicalize host name HOST, and return its canonical form.
1583 The default implementation just takes HOST for a canonical name. */
1586 static Lisp_Object unix_canonicalize_host_name(Lisp_Object host)
1588 #if defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO)
1589 struct addrinfo hints, *res;
1590 static char addrbuf[NI_MAXHOST];
1591 Lisp_Object canonname;
1596 hints.ai_flags = AI_CANONNAME;
1597 #ifdef IPV6_CANONICALIZE
1598 hints.ai_family = AF_UNSPEC;
1600 hints.ai_family = PF_INET;
1602 hints.ai_socktype = SOCK_STREAM;
1603 hints.ai_protocol = 0;
1604 LISP_STRING_TO_EXTERNAL(host, ext_host, Qnative);
1605 retval = getaddrinfo(ext_host, NULL, &hints, &res);
1609 EXTERNAL_TO_C_STRING(gai_strerror(retval),
1610 gai_error_l, Qnative);
1611 maybe_error(Qprocess, ERROR_ME_NOT,
1612 "%s \"%s\"", gai_error_l, XSTRING_DATA(host));
1615 int gni = getnameinfo(res->ai_addr, res->ai_addrlen,
1616 addrbuf, sizeof(addrbuf),
1617 NULL, 0, NI_NUMERICHOST);
1618 canonname = gni ? host : build_ext_string(addrbuf, Qnative);
1624 #else /* ! HAVE_GETADDRINFO */
1625 struct sockaddr_in address;
1627 if (!get_internet_address(host, &address, ERROR_ME_NOT))
1630 if (address.sin_family == AF_INET)
1631 return build_string(inet_ntoa(address.sin_addr));
1633 /* #### any clue what to do here? */
1635 #endif /* ! HAVE_GETADDRINFO */
1638 /* Open a TCP network connection to a given HOST/SERVICE.
1639 Treated exactly like a normal process when reading and writing.
1640 Only differences are in status display and process deletion.
1641 A network connection has no PID; you cannot signal it. All you can
1642 do is deactivate and close it via delete-process. */
1645 unix_open_network_stream(Lisp_Object name, Lisp_Object host,
1646 Lisp_Object service, Lisp_Object protocol,
1647 void **vinfd, void **voutfd)
1653 volatile int retry = 0;
1658 if (!EQ(protocol, Qtcp) && !EQ(protocol, Qudp))
1659 invalid_argument("Unsupported protocol", protocol);
1662 #if defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO)
1663 struct addrinfo hints, *res;
1664 struct addrinfo *volatile lres;
1666 volatile int xerrno = 0;
1667 volatile int failed_connect = 0;
1669 char portbuf[sizeof(long)*3 + 2];
1671 * Caution: service can either be a string or int.
1672 * Convert to a C string for later use by getaddrinfo.
1674 if (INTP(service)) {
1675 int sz= snprintf(portbuf, sizeof(portbuf), "%ld",
1676 (long)XINT(service));
1677 assert(sz >= 0 && sz < sizeof(portbuf));
1678 portstring = portbuf;
1679 port = htons((unsigned short)XINT(service));
1681 CHECK_STRING(service);
1682 LISP_STRING_TO_EXTERNAL(service, portstring, Qnative);
1688 hints.ai_family = AF_UNSPEC;
1689 if (EQ(protocol, Qtcp))
1690 hints.ai_socktype = SOCK_STREAM;
1691 else /* EQ (protocol, Qudp) */
1692 hints.ai_socktype = SOCK_DGRAM;
1693 hints.ai_protocol = 0;
1694 LISP_STRING_TO_EXTERNAL(host, ext_host, Qnative);
1695 retval = getaddrinfo(ext_host, portstring, &hints, &res);
1699 EXTERNAL_TO_C_STRING(gai_strerror(retval),
1700 gai_error_l, Qnative);
1701 error("%s/%s %s", XSTRING_DATA(host), portstring,
1706 for (lres = res; lres; lres = lres->ai_next) {
1707 if (EQ(protocol, Qtcp))
1708 s = socket(lres->ai_family, SOCK_STREAM, 0);
1709 else /* EQ (protocol, Qudp) */
1710 s = socket(lres->ai_family, SOCK_DGRAM, 0);
1715 /* Turn off interrupts here -- see comments below.
1716 There used to be code which called
1717 bind_polling_period() to slow the polling period down
1718 rather than turn it off, but that seems rather bogus
1719 to me. Best thing here is to use a non-blocking
1720 connect or something, to check for QUIT. */
1722 /* Comments that are not quite valid: */
1724 /* Kernel bugs (on Ultrix at least) cause lossage (not
1725 just EINTR) when connect is interrupted. So let's
1726 not let it get interrupted. Note we do not turn off
1727 polling, because polling is only used when not
1728 interrupt_input, and thus not normally used on the
1729 systems which have this bug. On systems which use
1730 polling, there's no way to quit if polling is turned
1733 /* Slow down polling. Some kernels have a bug which
1734 causes retrying connect to fail after a connect. */
1736 slow_down_interrupts();
1740 /* A system call interrupted with a SIGALRM or SIGIO
1741 comes back here, with can_break_system_calls reset to
1743 SETJMP(break_system_call_jump);
1745 speed_up_interrupts();
1747 /* In case something really weird happens ... */
1748 slow_down_interrupts();
1751 /* Break out of connect with a signal (it isn't
1752 otherwise possible). Thus you don't get screwed with
1754 can_break_system_calls = 1;
1755 retval = connect(s, lres->ai_addr, lres->ai_addrlen);
1756 can_break_system_calls = 0;
1759 if (errno != EISCONN) {
1762 if (errno == EADDRINUSE && retry < 20) {
1763 /* A delay here is needed on
1764 some FreeBSD systems, and
1765 it is harmless, since this
1766 retrying takes time anyway
1767 and should be infrequent.
1768 `sleep-for' allowed for
1769 quitting this loop with
1770 interrupts slowed down so
1771 it can't be used here.
1772 Async timers should already
1773 be disabled at this point
1774 so we can use `sleep'. */
1784 speed_up_interrupts();
1791 char servbuf[NI_MAXSERV];
1793 if (EQ(protocol, Qtcp))
1795 getnameinfo(lres->ai_addr,
1796 lres->ai_addrlen, NULL,
1800 else /* EQ (protocol, Qudp) */
1802 getnameinfo(lres->ai_addr,
1803 lres->ai_addrlen, NULL,
1810 port = strtol(servbuf, NULL, 10);
1814 } /* address loop */
1816 speed_up_interrupts();
1823 report_file_error("connection failed",
1826 report_file_error("error creating socket",
1829 #else /* ! HAVE_GETADDRINFO */
1830 struct sockaddr_in address;
1833 port = htons((unsigned short)XINT(service));
1835 struct servent *svc_info;
1836 CHECK_STRING(service);
1838 if (EQ(protocol, Qtcp))
1840 getservbyname((char *)XSTRING_DATA(service),
1842 else /* EQ (protocol, Qudp) */
1844 getservbyname((char *)XSTRING_DATA(service),
1848 invalid_argument("Unknown service", service);
1849 port = svc_info->s_port;
1852 get_internet_address(host, &address, ERROR_ME);
1853 address.sin_port = port;
1855 if (EQ(protocol, Qtcp))
1856 s = socket(address.sin_family, SOCK_STREAM, 0);
1857 else /* EQ (protocol, Qudp) */
1858 s = socket(address.sin_family, SOCK_DGRAM, 0);
1861 report_file_error("error creating socket", list1(name));
1863 /* Turn off interrupts here -- see comments below. There used to
1864 be code which called bind_polling_period() to slow the polling
1865 period down rather than turn it off, but that seems rather
1866 bogus to me. Best thing here is to use a non-blocking connect
1867 or something, to check for QUIT. */
1869 /* Comments that are not quite valid: */
1871 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
1872 when connect is interrupted. So let's not let it get interrupted.
1873 Note we do not turn off polling, because polling is only used
1874 when not interrupt_input, and thus not normally used on the systems
1875 which have this bug. On systems which use polling, there's no way
1876 to quit if polling is turned off. */
1878 /* Slow down polling. Some kernels have a bug which causes retrying
1879 connect to fail after a connect. */
1881 slow_down_interrupts();
1885 /* A system call interrupted with a SIGALRM or SIGIO comes back
1886 here, with can_break_system_calls reset to 0. */
1887 SETJMP(break_system_call_jump);
1889 speed_up_interrupts();
1891 /* In case something really weird happens ... */
1892 slow_down_interrupts();
1895 /* Break out of connect with a signal (it isn't otherwise possible).
1896 Thus you don't get screwed with a hung network. */
1897 can_break_system_calls = 1;
1899 connect(s, (struct sockaddr *)&address, sizeof(address));
1900 can_break_system_calls = 0;
1901 if (retval == -1 && errno != EISCONN) {
1905 if (errno == EADDRINUSE && retry < 20) {
1906 /* A delay here is needed on some FreeBSD
1907 systems, and it is harmless, since this
1908 retrying takes time anyway and should
1909 be infrequent. `sleep-for' allowed for
1910 quitting this loop with interrupts
1911 slowed down so it can't be used here.
1912 Async timers should already be disabled
1913 at this point so we can use `sleep'. */
1920 speed_up_interrupts();
1923 report_file_error("connection failed",
1927 speed_up_interrupts();
1928 #endif /* ! HAVE_GETADDRINFO */
1934 close(s); /* this used to be leaked; from Kyle Jones */
1935 report_file_error("error duplicating socket", list1(name));
1938 set_socket_nonblocking_maybe(inch, port, "tcp");
1940 *vinfd = (void *)inch;
1941 *voutfd = (void *)outch;
1946 Return the listener process of the accepted listened process
1948 static Lisp_Object unix_network_process_listener(Lisp_Object process)
1950 Lisp_Process *listener = 0,
1951 *p = XPROCESS(process);
1952 Lisp_Object ret = Qnil;
1954 struct gcpro ngcpro1;
1956 if (!PROCESS_READABLE_P(p))
1959 if (!CONSP(p->pid) || NILP(XCDR(XCDR(p->pid))))
1963 sock = XINT(XCAR(XCDR(p->pid)));
1964 listener = get_process_from_usid(FD_TO_USID(sock));
1965 ret = listener ? (Lisp_Object)listener : Qnil;
1971 Unwind a call to the network server stream accept below
1973 static Lisp_Object exec_acceptor_unwind(Lisp_Object datum)
1975 Lisp_Cons *d = XCONS(datum);
1982 Accept a connection being listened in the given network server
1984 Create a new network stream for the accepted connection.
1985 Call the acceptor callback and setup the sentinel and filter functions
1987 static void unix_network_server_accept(Lisp_Object process)
1989 Lisp_Process *p = XPROCESS(process);
1990 Lisp_Object np = Qnil;
1991 Lisp_Object acceptor = Qnil, filter = Qnil, sentinel = Qnil;
1992 Lisp_Object bufname = Qnil;
1993 Lisp_Object buffer = Qnil;
1994 long int ns, inch, outch;
1995 struct sockaddr_in sa;
1996 int sa_size = sizeof(sa);
1997 struct gcpro ngcpro1, ngcpro2, ngcpro3, ngcpro4, ngcpro5;
1999 if (!PROCESS_READABLE_P(p))
2002 /* Make sure the listen process is not disconnected
2003 afterwards. We have to make this here because in process.c
2004 we should not have any knowledge we need to do this, and in
2005 unix_open_network_server_stream we have no access to the
2006 process struct. It works, so I'm not complaining...
2008 UNIX_DATA(p)->connected_via_filedesc_p = 1;
2010 errno = 0; /* if we got an error, let it be from the accept call */
2011 ns = accept((int)UNIX_DATA(p)->infd, (struct sockaddr*)(&sa),
2012 (socklen_t*)&sa_size);
2016 NGCPRO5(np,bufname,acceptor,filter,sentinel);
2017 if (CONSP(p->process_type_data)) {
2018 acceptor = XCAR(p->process_type_data);
2019 filter = XCDR(p->process_type_data);
2020 if (CONSP(filter)) {
2021 sentinel = XCDR(filter);
2022 filter = XCAR(filter);
2024 if (CONSP(sentinel)) {
2025 bufname = XCDR(sentinel);
2026 sentinel = XCAR(sentinel);
2028 if (CONSP(bufname)) {
2029 bufname = XCAR(bufname);
2032 if (!NILP(bufname)) {
2033 Lisp_Object args[] = {
2034 build_string("<server port:%S listened_on:%S>"),
2035 make_int(sa.sin_port), bufname
2037 bufname = Fformat( 3, args );
2039 Lisp_Object args[] = {
2040 build_string("<server proc:%S pid:%S service:%S>"),
2041 p->name, p->pid, make_int(sa.sin_port)
2043 bufname = Fformat( 5, args );
2045 if (!NILP(bufname) ) {
2046 bufname = Fgenerate_new_buffer_name(bufname,Qnil);
2047 buffer = Fget_buffer_create(bufname);
2049 np = make_process_internal(p->name);
2050 XPROCESS(np)->pid = Fcons( make_int(sa.sin_port),
2051 Fcons(make_int(UNIX_DATA(p)->infd),p->pid));
2052 XPROCESS(np)->process_type = PROCESS_TYPE_NETWORK;
2053 XPROCESS(np)->buffer = buffer;
2056 set_socket_nonblocking_maybe(inch, sa.sin_port, "tcp");
2057 init_process_io_handles(XPROCESS(np), (void *)inch, (void *)outch,
2058 STREAM_NETWORK_CONNECTION);
2059 /* Process the call backs.. */
2060 if (CONSP(p->process_type_data)) {
2061 if (!NILP(filter)) {
2062 XPROCESS(np)->filter = filter;
2064 if (!NILP(sentinel)) {
2065 XPROCESS(np)->sentinel = sentinel;
2067 if (!NILP(acceptor)) {
2068 int speccount = specpdl_depth();
2069 record_unwind_protect(exec_acceptor_unwind,
2070 noseeum_cons(process, acceptor));
2071 running_asynch_code = 1;
2072 call1_trapping_errors("Error in server stream acceptor",
2074 running_asynch_code = 0;
2075 restore_match_data();
2076 unbind_to(speccount, Qnil);
2080 /* We have to log something here... */
2082 event_stream_select_process(XPROCESS(np));
2086 /* Open a TCP network connection to a given HOST/SERVICE.
2087 Treated exactly like a normal process when reading and writing.
2088 Only differences are in status display and process deletion.
2089 A network connection has no PID; you cannot signal it. All you can
2090 do is deactivate and close it via delete-process. */
2093 unix_open_network_server_stream(Lisp_Object name, Lisp_Object host,
2094 Lisp_Object service, Lisp_Object protocol,
2095 void **vinfd, void **voutfd)
2101 volatile int retry = 0;
2103 /* FIXME: Limited to 5 since it is the maximum for several BSD
2104 based implementations of sockets, and it is an acceptable
2105 value for a low rate of service purpose like this facility
2106 was designed for. */
2110 if (!EQ(protocol, Qtcp) && !EQ(protocol, Qudp))
2111 invalid_argument("Unsupported protocol", protocol);
2114 #if defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO)
2115 struct addrinfo hints, *res;
2116 struct addrinfo *volatile lres;
2118 volatile int xerrno = 0;
2119 volatile int failed_connect = 0;
2121 char portbuf[sizeof(long)*3 + 2];
2123 * Caution: service can either be a string or int.
2124 * Convert to a C string for later use by getaddrinfo.
2126 if (INTP(service)) {
2127 int sz = snprintf(portbuf, sizeof(portbuf), "%ld",
2128 (long)XINT(service));
2129 assert(sz >= 0 && sz < sizeof(portbuf));
2130 portstring = portbuf;
2131 port = htons((unsigned short)XINT(service));
2133 CHECK_STRING(service);
2134 LISP_STRING_TO_EXTERNAL(service, portstring, Qnative);
2140 hints.ai_family = AF_UNSPEC;
2141 if (EQ(protocol, Qtcp))
2142 hints.ai_socktype = SOCK_STREAM;
2143 else /* EQ (protocol, Qudp) */
2144 hints.ai_socktype = SOCK_DGRAM;
2145 hints.ai_protocol = 0;
2146 if (SYMBOLP(host) ) {
2147 if (EQ(host,Qip_any)) {
2148 hints.ai_flags |= AI_PASSIVE;
2149 } else if (!EQ(host,Qlocalhost)) {
2150 invalid_argument("invalid host ",host);
2152 /* If using localhost, not passing
2153 AI_PASSIVE will cause getaddrinfo
2154 to return a proper addr spec for
2155 listening only to local
2158 retval = getaddrinfo(NULL, portstring, &hints, &res);
2161 LISP_STRING_TO_EXTERNAL(host, ext_host, Qnative);
2162 retval = getaddrinfo(ext_host, portstring, &hints, &res);
2167 EXTERNAL_TO_C_STRING(gai_strerror(retval),
2168 gai_error_l, Qnative);
2169 error("%s/%s %s", XSTRING_DATA(host), portstring,
2174 for (lres = res; lres; lres = lres->ai_next) {
2175 if (EQ(protocol, Qtcp))
2176 s = socket(lres->ai_family, SOCK_STREAM, 0);
2177 else /* EQ (protocol, Qudp) */
2178 s = socket(lres->ai_family, SOCK_DGRAM, 0);
2183 /* Turn off interrupts here -- see comments below.
2184 There used to be code which called
2185 bind_polling_period() to slow the polling period down
2186 rather than turn it off, but that seems rather bogus
2187 to me. Best thing here is to use a non-blocking
2188 connect or something, to check for QUIT. */
2190 /* Comments that are not quite valid: */
2192 /* Kernel bugs (on Ultrix at least) cause lossage (not
2193 just EINTR) when connect is interrupted. So let's
2194 not let it get interrupted. Note we do not turn off
2195 polling, because polling is only used when not
2196 interrupt_input, and thus not normally used on the
2197 systems which have this bug. On systems which use
2198 polling, there's no way to quit if polling is turned
2201 /* Slow down polling. Some kernels have a bug which
2202 causes retrying connect to fail after a connect. */
2204 slow_down_interrupts();
2208 /* A system call interrupted with a SIGALRM or SIGIO
2209 comes back here, with can_break_system_calls reset to
2211 SETJMP(break_system_call_jump);
2213 speed_up_interrupts();
2215 /* In case something really weird happens ... */
2216 slow_down_interrupts();
2219 /* Break out of connect with a signal (it isn't
2220 otherwise possible). Thus you don't get screwed with
2222 can_break_system_calls = 1;
2223 retval = bind(s, lres->ai_addr, lres->ai_addrlen);
2225 retval = listen(s, listenQ);
2226 can_break_system_calls = 0;
2229 if (errno != EISCONN) {
2232 if (errno == EADDRINUSE && retry < 20) {
2233 /* A delay here is needed on
2234 some FreeBSD systems, and it
2235 is harmless, since this
2236 retrying takes time anyway
2237 and should be infrequent.
2238 `sleep-for' allowed for
2239 quitting this loop with
2240 interrupts slowed down so it
2241 can't be used here. Async
2242 timers should already be
2243 disabled at this point so we
2254 speed_up_interrupts();
2261 char servbuf[NI_MAXSERV];
2263 if (EQ(protocol, Qtcp))
2265 getnameinfo(lres->ai_addr,
2266 lres->ai_addrlen, NULL,
2270 else /* EQ (protocol, Qudp) */
2272 getnameinfo(lres->ai_addr,
2273 lres->ai_addrlen, NULL,
2280 port = strtol(servbuf, NULL, 10);
2284 } /* address loop */
2286 speed_up_interrupts();
2293 report_file_error("bind failed",
2296 report_file_error("error creating socket",
2299 #else /* ! HAVE_GETADDRINFO */
2300 struct sockaddr_in address;
2303 port = htons((unsigned short)XINT(service));
2305 struct servent *svc_info;
2306 CHECK_STRING(service);
2308 if (EQ(protocol, Qtcp))
2310 getservbyname((char *)XSTRING_DATA(service),
2312 else /* EQ (protocol, Qudp) */
2314 getservbyname((char *)XSTRING_DATA(service),
2318 invalid_argument("Unknown service", service);
2319 port = svc_info->s_port;
2321 if (SYMBOLP(host)) {
2322 if (EQ(host,Qip_any)) {
2323 address.sin_addr.s_host = htonl(INADDR_ANY);
2324 } else if (EQ(host,Qlocalhost)) {
2325 address.sin_addr.s_host = htonl(INADDR_LOOPBACK);
2327 invalid_argument("invalid host ",host);
2330 get_internet_address(host, &address, ERROR_ME);
2332 address.sin_port = port;
2334 if (EQ(protocol, Qtcp))
2335 s = socket(address.sin_family, SOCK_STREAM, 0);
2336 else /* EQ (protocol, Qudp) */
2337 s = socket(address.sin_family, SOCK_DGRAM, 0);
2340 report_file_error("error creating socket", list1(name));
2342 /* Turn off interrupts here -- see comments below. There used to
2343 be code which called bind_polling_period() to slow the polling
2344 period down rather than turn it off, but that seems rather
2345 bogus to me. Best thing here is to use a non-blocking connect
2346 or something, to check for QUIT. */
2348 /* Comments that are not quite valid: */
2350 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
2351 when connect is interrupted. So let's not let it get interrupted.
2352 Note we do not turn off polling, because polling is only used
2353 when not interrupt_input, and thus not normally used on the systems
2354 which have this bug. On systems which use polling, there's no way
2355 to quit if polling is turned off. */
2357 /* Slow down polling. Some kernels have a bug which causes retrying
2358 connect to fail after a connect. */
2360 slow_down_interrupts();
2364 /* A system call interrupted with a SIGALRM or SIGIO comes back
2365 here, with can_break_system_calls reset to 0. */
2366 SETJMP(break_system_call_jump);
2368 speed_up_interrupts();
2370 /* In case something really weird happens ... */
2371 slow_down_interrupts();
2374 /* Break out of connect with a signal (it isn't otherwise possible).
2375 Thus you don't get screwed with a hung network. */
2376 can_break_system_calls = 1;
2378 bind(s, (struct sockaddr *)&address, sizeof(address));
2380 listen( s, listenQ ); /* @@@ FIXME: This should be a parameter */
2381 can_break_system_calls = 0;
2382 if (retval == -1 && errno != EISCONN) {
2386 if (errno == EADDRINUSE && retry < 20) {
2387 /* A delay here is needed on some FreeBSD
2388 systems, and it is harmless, since this
2389 retrying takes time anyway and should be
2390 infrequent. `sleep-for' allowed for quitting
2391 this loop with interrupts slowed down so it
2392 can't be used here. Async timers should
2393 already be disabled at this point so we can
2401 speed_up_interrupts();
2404 report_file_error("connection failed",
2408 speed_up_interrupts();
2409 #endif /* ! HAVE_GETADDRINFO */
2415 close(s); /* this used to be leaked; from Kyle Jones */
2416 report_file_error("error duplicating socket", list1(name));
2419 set_socket_nonblocking_maybe(inch, port, "tcp");
2421 *vinfd = (void *)inch;
2422 *voutfd = (void *)outch;
2426 #ifdef HAVE_MULTICAST
2428 /* Didier Verna <didier@xemacs.org> Nov. 28 1997.
2430 This function is similar to open-network-stream-internal, but provides a
2431 mean to open an UDP multicast connection instead of a TCP one. Like in the
2432 TCP case, the multicast connection will be seen as a sub-process,
2435 - Normally, we should use sendto and recvfrom with non connected
2436 sockets. The current code doesn't allow us to do this. In the future, it
2437 would be a good idea to extend the process data structure in order to deal
2438 properly with the different types network connections.
2439 - For the same reason, when leaving a multicast group, it is better to make
2440 a setsockopt - IP_DROP_MEMBERSHIP before closing the descriptors.
2441 Unfortunately, this can't be done here because delete_process doesn't know
2442 about the kind of connection we have. However, this is not such an
2447 unix_open_multicast_group(Lisp_Object name, Lisp_Object dest,
2448 Lisp_Object port, Lisp_Object ttl, void **vinfd,
2452 struct sockaddr_in sa;
2453 struct protoent *udp;
2456 unsigned char thettl;
2457 int one = 1; /* For REUSEADDR */
2459 volatile int retry = 0;
2464 theport = htons((unsigned short)XINT(port));
2467 thettl = (unsigned char)XINT(ttl);
2469 if ((udp = getprotobyname("udp")) == NULL)
2470 type_error(Qinvalid_operation,
2471 "No info available for UDP protocol");
2473 /* Init the sockets. Yes, I need 2 sockets. I couldn't duplicate one. */
2474 if ((rs = socket(PF_INET, SOCK_DGRAM, udp->p_proto)) < 0)
2475 report_file_error("error creating socket", list1(name));
2476 if ((ws = socket(PF_INET, SOCK_DGRAM, udp->p_proto)) < 0) {
2478 report_file_error("error creating socket", list1(name));
2481 /* This will be used for both sockets */
2482 memset(&sa, 0, sizeof(sa));
2483 sa.sin_family = AF_INET;
2484 sa.sin_port = theport;
2485 sa.sin_addr.s_addr = inet_addr((char *)XSTRING_DATA(dest));
2487 /* Socket configuration for reading ------------------------ */
2489 /* Multiple connections from the same machine. This must be done before
2490 bind. If it fails, it shouldn't be fatal. The only consequence is that
2491 people won't be able to connect twice from the same machine. */
2492 if (setsockopt(rs, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one))
2494 warn_when_safe(Qmulticast, Qwarning,
2495 "Cannot reuse socket address");
2497 /* bind socket name */
2498 if (bind(rs, (struct sockaddr *)&sa, sizeof(sa))) {
2501 report_file_error("error binding socket", list2(name, port));
2504 /* join multicast group */
2505 imr.imr_multiaddr.s_addr = inet_addr((char *)XSTRING_DATA(dest));
2506 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2507 if (setsockopt(rs, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2508 &imr, sizeof(struct ip_mreq)) < 0) {
2511 report_file_error("error adding membership", list2(name, dest));
2514 /* Socket configuration for writing ----------------------- */
2516 /* Normally, there's no 'connect' in multicast, since we prefer to use
2517 'sendto' and 'recvfrom'. However, in order to handle this connection
2518 in the process-like way it is done for TCP, we must be able to use
2519 'write' instead of 'sendto'. Consequently, we 'connect' this
2522 /* See open-network-stream-internal for comments on this part of the
2524 slow_down_interrupts();
2528 /* A system call interrupted with a SIGALRM or SIGIO comes back
2529 here, with can_break_system_calls reset to 0. */
2530 SETJMP(break_system_call_jump);
2532 speed_up_interrupts();
2534 /* In case something really weird happens ... */
2535 slow_down_interrupts();
2538 /* Break out of connect with a signal (it isn't otherwise possible).
2539 Thus you don't get screwed with a hung network. */
2540 can_break_system_calls = 1;
2541 ret = connect(ws, (struct sockaddr *)&sa, sizeof(sa));
2542 can_break_system_calls = 0;
2543 if (ret == -1 && errno != EISCONN) {
2548 if (errno == EADDRINUSE && retry < 20) {
2549 /* A delay here is needed on some FreeBSD systems, and
2550 it is harmless, since this retrying takes time anyway
2551 and should be infrequent. `sleep-for' allowed for
2552 quitting this loop with interrupts slowed down so it
2553 can't be used here. Async timers should already be
2554 disabled at this point so we can use `sleep'. */
2561 speed_up_interrupts();
2564 report_file_error("error connecting socket", list2(name, port));
2567 speed_up_interrupts();
2570 if (setsockopt(ws, IPPROTO_IP, IP_MULTICAST_TTL,
2571 &thettl, sizeof(thettl)) < 0) {
2574 report_file_error("error setting ttl", list2(name, ttl));
2577 set_socket_nonblocking_maybe(rs, theport, "udp");
2579 *vinfd = (void *)rs;
2580 *voutfd = (void *)ws;
2583 #endif /* HAVE_MULTICAST */
2585 #endif /* HAVE_SOCKETS */
2587 /**********************************************************************/
2588 /* Initialization */
2589 /**********************************************************************/
2591 void process_type_create_unix(void)
2593 PROCESS_HAS_METHOD(unix, alloc_process_data);
2594 PROCESS_HAS_METHOD(unix, mark_process_data);
2596 PROCESS_HAS_METHOD(unix, init_process);
2597 PROCESS_HAS_METHOD(unix, reap_exited_processes);
2599 PROCESS_HAS_METHOD(unix, init_process_io_handles);
2600 PROCESS_HAS_METHOD(unix, create_process);
2601 PROCESS_HAS_METHOD(unix, set_window_size);
2603 PROCESS_HAS_METHOD(unix, update_status_if_terminated);
2605 PROCESS_HAS_METHOD(unix, send_process);
2606 PROCESS_HAS_METHOD(unix, process_send_eof);
2607 PROCESS_HAS_METHOD(unix, deactivate_process);
2608 PROCESS_HAS_METHOD(unix, kill_child_process);
2609 PROCESS_HAS_METHOD(unix, kill_process_by_pid);
2610 PROCESS_HAS_METHOD(unix, get_tty_name);
2612 PROCESS_HAS_METHOD(unix, canonicalize_host_name);
2613 PROCESS_HAS_METHOD(unix, open_network_stream);
2614 PROCESS_HAS_METHOD(unix, open_network_server_stream);
2615 PROCESS_HAS_METHOD(unix, network_server_accept);
2616 PROCESS_HAS_METHOD(unix, network_process_listener);
2617 #ifdef HAVE_MULTICAST
2618 PROCESS_HAS_METHOD(unix, open_multicast_group);
2623 void vars_of_process_unix(void)
2625 Fprovide(intern("unix-processes"));
2628 #endif /* !defined (NO_SUBPROCESSES) */