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
1500 Anal operating systems like SGI Irix and Compaq Tru64 adhere
1501 strictly to the letter of the law, so our hack doesn't work.
1502 The following fragment from an Irix header file is suggestive:
1505 // this is not currently supported
1506 #define TIOCSIGNAL (tIOC|31) // pty: send signal to slave
1509 On those systems where none of our tricks work, we just fall back
1510 to the non-current_group behavior and kill the process group of
1513 if (current_group) {
1514 try_to_initialize_subtty(d);
1516 #ifdef SIGNALS_VIA_CHARACTERS
1517 /* If possible, send signals to the entire pgrp
1518 by sending an input character to it. */
1521 char sigchar = process_signal_char(d->subtty, signo);
1523 send_process(proc, Qnil, (Bufbyte *) & sigchar,
1528 #endif /* SIGNALS_VIA_CHARACTERS */
1532 ioctl(d->infd, TIOCGPGRP, &pgid); /* BSD */
1533 if (pgid == -1 && d->subtty >= 0)
1534 /* Only this works on AIX! */
1535 ioctl(d->subtty, TIOCGPGRP, &pgid);
1536 #endif /* TIOCGPGRP */
1539 /* Many systems provide an ioctl to send a signal directly */
1540 #ifdef TIOCSIGNAL /* Solaris, HP-UX */
1541 if (ioctl(d->infd, TIOCSIGNAL, signo) != -1)
1543 #endif /* TIOCSIGNAL */
1545 #ifdef TIOCSIG /* BSD */
1546 if (ioctl(d->infd, TIOCSIG, signo) != -1)
1548 #endif /* TIOCSIG */
1553 /* Either current_group is 0, or we failed to get the foreground
1554 process group using the trickery above. So we fall back to
1555 sending the signal to the process group of our child process.
1556 Since this is often a shell that ignores signals like SIGINT,
1557 the shell's subprocess is killed, which is the desired effect.
1558 The process group of p->pid is always p->pid, since it was
1559 created as a process group leader. */
1560 pgid = XINT(p->pid);
1562 /* Finally send the signal. */
1563 if (EMACS_KILLPG(pgid, signo) == -1) {
1564 /* It's not an error if our victim is already dead.
1565 And we can't rely on the result of killing a zombie, since
1566 XPG 4.2 requires that killing a zombie fail with ESRCH,
1567 while FIPS 151-2 requires that it succeeds! */
1571 error("kill (%ld, %ld) failed: %s",
1572 (long)pgid, (long)signo, strerror(errno));
1576 /* Send signal SIGCODE to any process in the system given its PID.
1577 Return zero if successful, a negative number upon failure. */
1579 static int unix_kill_process_by_pid(int pid, int sigcode)
1581 return kill(pid, sigcode);
1584 /* Return TTY name used to communicate with subprocess. */
1586 static Lisp_Object unix_get_tty_name(Lisp_Process * p)
1588 return UNIX_DATA(p)->tty_name;
1591 /* Canonicalize host name HOST, and return its canonical form.
1592 The default implementation just takes HOST for a canonical name. */
1595 static Lisp_Object unix_canonicalize_host_name(Lisp_Object host)
1597 #if defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO)
1598 struct addrinfo hints, *res;
1599 static char addrbuf[NI_MAXHOST];
1600 Lisp_Object canonname;
1605 hints.ai_flags = AI_CANONNAME;
1606 #ifdef IPV6_CANONICALIZE
1607 hints.ai_family = AF_UNSPEC;
1609 hints.ai_family = PF_INET;
1611 hints.ai_socktype = SOCK_STREAM;
1612 hints.ai_protocol = 0;
1613 LISP_STRING_TO_EXTERNAL(host, ext_host, Qnative);
1614 retval = getaddrinfo(ext_host, NULL, &hints, &res);
1618 EXTERNAL_TO_C_STRING(gai_strerror(retval),
1619 gai_error_l, Qnative);
1620 maybe_error(Qprocess, ERROR_ME_NOT,
1621 "%s \"%s\"", gai_error_l, XSTRING_DATA(host));
1624 int gni = getnameinfo(res->ai_addr, res->ai_addrlen,
1625 addrbuf, sizeof(addrbuf),
1626 NULL, 0, NI_NUMERICHOST);
1627 canonname = gni ? host : build_ext_string(addrbuf, Qnative);
1633 #else /* ! HAVE_GETADDRINFO */
1634 struct sockaddr_in address;
1636 if (!get_internet_address(host, &address, ERROR_ME_NOT))
1639 if (address.sin_family == AF_INET)
1640 return build_string(inet_ntoa(address.sin_addr));
1642 /* #### any clue what to do here? */
1644 #endif /* ! HAVE_GETADDRINFO */
1647 /* Open a TCP network connection to a given HOST/SERVICE.
1648 Treated exactly like a normal process when reading and writing.
1649 Only differences are in status display and process deletion.
1650 A network connection has no PID; you cannot signal it. All you can
1651 do is deactivate and close it via delete-process. */
1654 unix_open_network_stream(Lisp_Object name, Lisp_Object host,
1655 Lisp_Object service, Lisp_Object protocol,
1656 void **vinfd, void **voutfd)
1662 volatile int retry = 0;
1667 if (!EQ(protocol, Qtcp) && !EQ(protocol, Qudp))
1668 invalid_argument("Unsupported protocol", protocol);
1671 #if defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO)
1672 struct addrinfo hints, *res;
1673 struct addrinfo *volatile lres;
1675 volatile int xerrno = 0;
1676 volatile int failed_connect = 0;
1678 char portbuf[sizeof(long)*3 + 2];
1680 * Caution: service can either be a string or int.
1681 * Convert to a C string for later use by getaddrinfo.
1683 if (INTP(service)) {
1684 int sz= snprintf(portbuf, sizeof(portbuf), "%ld",
1685 (long)XINT(service));
1686 assert(sz >= 0 && (size_t)sz < sizeof(portbuf));
1687 portstring = portbuf;
1688 port = htons((unsigned short)XINT(service));
1690 CHECK_STRING(service);
1691 LISP_STRING_TO_EXTERNAL(service, portstring, Qnative);
1697 hints.ai_family = AF_UNSPEC;
1698 if (EQ(protocol, Qtcp))
1699 hints.ai_socktype = SOCK_STREAM;
1700 else /* EQ (protocol, Qudp) */
1701 hints.ai_socktype = SOCK_DGRAM;
1702 hints.ai_protocol = 0;
1703 LISP_STRING_TO_EXTERNAL(host, ext_host, Qnative);
1704 retval = getaddrinfo(ext_host, portstring, &hints, &res);
1708 EXTERNAL_TO_C_STRING(gai_strerror(retval),
1709 gai_error_l, Qnative);
1710 error("%s/%s %s", XSTRING_DATA(host), portstring,
1715 for (lres = res; lres; lres = lres->ai_next) {
1716 if (EQ(protocol, Qtcp))
1717 s = socket(lres->ai_family, SOCK_STREAM, 0);
1718 else /* EQ (protocol, Qudp) */
1719 s = socket(lres->ai_family, SOCK_DGRAM, 0);
1724 /* Turn off interrupts here -- see comments below.
1725 There used to be code which called
1726 bind_polling_period() to slow the polling period down
1727 rather than turn it off, but that seems rather bogus
1728 to me. Best thing here is to use a non-blocking
1729 connect or something, to check for QUIT. */
1731 /* Comments that are not quite valid: */
1733 /* Kernel bugs (on Ultrix at least) cause lossage (not
1734 just EINTR) when connect is interrupted. So let's
1735 not let it get interrupted. Note we do not turn off
1736 polling, because polling is only used when not
1737 interrupt_input, and thus not normally used on the
1738 systems which have this bug. On systems which use
1739 polling, there's no way to quit if polling is turned
1742 /* Slow down polling. Some kernels have a bug which
1743 causes retrying connect to fail after a connect. */
1745 slow_down_interrupts();
1749 /* A system call interrupted with a SIGALRM or SIGIO
1750 comes back here, with can_break_system_calls reset to
1752 SETJMP(break_system_call_jump);
1754 speed_up_interrupts();
1756 /* In case something really weird happens ... */
1757 slow_down_interrupts();
1760 /* Break out of connect with a signal (it isn't
1761 otherwise possible). Thus you don't get screwed with
1763 can_break_system_calls = 1;
1764 retval = connect(s, lres->ai_addr, lres->ai_addrlen);
1765 can_break_system_calls = 0;
1768 if (errno != EISCONN) {
1771 if (errno == EADDRINUSE && retry < 20) {
1772 /* A delay here is needed on
1773 some FreeBSD systems, and
1774 it is harmless, since this
1775 retrying takes time anyway
1776 and should be infrequent.
1777 `sleep-for' allowed for
1778 quitting this loop with
1779 interrupts slowed down so
1780 it can't be used here.
1781 Async timers should already
1782 be disabled at this point
1783 so we can use `sleep'. */
1793 speed_up_interrupts();
1800 char servbuf[NI_MAXSERV];
1802 if (EQ(protocol, Qtcp))
1804 getnameinfo(lres->ai_addr,
1805 lres->ai_addrlen, NULL,
1809 else /* EQ (protocol, Qudp) */
1811 getnameinfo(lres->ai_addr,
1812 lres->ai_addrlen, NULL,
1819 port = strtol(servbuf, NULL, 10);
1823 } /* address loop */
1825 speed_up_interrupts();
1832 report_file_error("connection failed",
1835 report_file_error("error creating socket",
1838 #else /* ! HAVE_GETADDRINFO */
1839 struct sockaddr_in address;
1842 port = htons((unsigned short)XINT(service));
1844 struct servent *svc_info;
1845 CHECK_STRING(service);
1847 if (EQ(protocol, Qtcp))
1849 getservbyname((char *)XSTRING_DATA(service),
1851 else /* EQ (protocol, Qudp) */
1853 getservbyname((char *)XSTRING_DATA(service),
1857 invalid_argument("Unknown service", service);
1858 port = svc_info->s_port;
1861 get_internet_address(host, &address, ERROR_ME);
1862 address.sin_port = port;
1864 if (EQ(protocol, Qtcp))
1865 s = socket(address.sin_family, SOCK_STREAM, 0);
1866 else /* EQ (protocol, Qudp) */
1867 s = socket(address.sin_family, SOCK_DGRAM, 0);
1870 report_file_error("error creating socket", list1(name));
1872 /* Turn off interrupts here -- see comments below. There used to
1873 be code which called bind_polling_period() to slow the polling
1874 period down rather than turn it off, but that seems rather
1875 bogus to me. Best thing here is to use a non-blocking connect
1876 or something, to check for QUIT. */
1878 /* Comments that are not quite valid: */
1880 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
1881 when connect is interrupted. So let's not let it get interrupted.
1882 Note we do not turn off polling, because polling is only used
1883 when not interrupt_input, and thus not normally used on the systems
1884 which have this bug. On systems which use polling, there's no way
1885 to quit if polling is turned off. */
1887 /* Slow down polling. Some kernels have a bug which causes retrying
1888 connect to fail after a connect. */
1890 slow_down_interrupts();
1894 /* A system call interrupted with a SIGALRM or SIGIO comes back
1895 here, with can_break_system_calls reset to 0. */
1896 SETJMP(break_system_call_jump);
1898 speed_up_interrupts();
1900 /* In case something really weird happens ... */
1901 slow_down_interrupts();
1904 /* Break out of connect with a signal (it isn't otherwise possible).
1905 Thus you don't get screwed with a hung network. */
1906 can_break_system_calls = 1;
1908 connect(s, (struct sockaddr *)&address, sizeof(address));
1909 can_break_system_calls = 0;
1910 if (retval == -1 && errno != EISCONN) {
1914 if (errno == EADDRINUSE && retry < 20) {
1915 /* A delay here is needed on some FreeBSD
1916 systems, and it is harmless, since this
1917 retrying takes time anyway and should
1918 be infrequent. `sleep-for' allowed for
1919 quitting this loop with interrupts
1920 slowed down so it can't be used here.
1921 Async timers should already be disabled
1922 at this point so we can use `sleep'. */
1929 speed_up_interrupts();
1932 report_file_error("connection failed",
1936 speed_up_interrupts();
1937 #endif /* ! HAVE_GETADDRINFO */
1943 close(s); /* this used to be leaked; from Kyle Jones */
1944 report_file_error("error duplicating socket", list1(name));
1947 set_socket_nonblocking_maybe(inch, port, "tcp");
1949 *vinfd = (void *)inch;
1950 *voutfd = (void *)outch;
1955 Return the listener process of the accepted listened process
1957 static Lisp_Object unix_network_process_listener(Lisp_Object process)
1959 Lisp_Process *listener = 0,
1960 *p = XPROCESS(process);
1961 Lisp_Object ret = Qnil;
1963 struct gcpro ngcpro1;
1965 if (!PROCESS_READABLE_P(p))
1968 if (!CONSP(p->pid) || NILP(XCDR(XCDR(p->pid))))
1972 sock = XINT(XCAR(XCDR(p->pid)));
1973 listener = get_process_from_usid(FD_TO_USID(sock));
1974 ret = listener ? (Lisp_Object)listener : Qnil;
1980 Unwind a call to the network server stream accept below
1982 static Lisp_Object exec_acceptor_unwind(Lisp_Object datum)
1984 Lisp_Cons *d = XCONS(datum);
1991 Accept a connection being listened in the given network server
1993 Create a new network stream for the accepted connection.
1994 Call the acceptor callback and setup the sentinel and filter functions
1996 static void unix_network_server_accept(Lisp_Object process)
1998 Lisp_Process *p = XPROCESS(process);
1999 Lisp_Object np = Qnil;
2000 Lisp_Object acceptor = Qnil, filter = Qnil, sentinel = Qnil;
2001 Lisp_Object bufname = Qnil;
2002 Lisp_Object buffer = Qnil;
2003 long int ns, inch, outch;
2004 struct sockaddr_in sa;
2005 int sa_size = sizeof(sa);
2006 struct gcpro ngcpro1, ngcpro2, ngcpro3, ngcpro4, ngcpro5;
2008 if (!PROCESS_READABLE_P(p))
2011 /* Make sure the listen process is not disconnected
2012 afterwards. We have to make this here because in process.c
2013 we should not have any knowledge we need to do this, and in
2014 unix_open_network_server_stream we have no access to the
2015 process struct. It works, so I'm not complaining...
2017 UNIX_DATA(p)->connected_via_filedesc_p = 1;
2019 errno = 0; /* if we got an error, let it be from the accept call */
2020 ns = accept((int)UNIX_DATA(p)->infd, (struct sockaddr*)(&sa),
2021 (socklen_t*)&sa_size);
2025 NGCPRO5(np,bufname,acceptor,filter,sentinel);
2026 if (CONSP(p->process_type_data)) {
2027 acceptor = XCAR(p->process_type_data);
2028 filter = XCDR(p->process_type_data);
2029 if (CONSP(filter)) {
2030 sentinel = XCDR(filter);
2031 filter = XCAR(filter);
2033 if (CONSP(sentinel)) {
2034 bufname = XCDR(sentinel);
2035 sentinel = XCAR(sentinel);
2037 if (CONSP(bufname)) {
2038 bufname = XCAR(bufname);
2041 if (!NILP(bufname)) {
2042 Lisp_Object args[] = {
2043 build_string("<server port:%S listened_on:%S>"),
2044 make_int(sa.sin_port), bufname
2046 bufname = Fformat( 3, args );
2048 Lisp_Object args[] = {
2049 build_string("<server proc:%S pid:%S service:%S>"),
2050 p->name, p->pid, make_int(sa.sin_port)
2052 bufname = Fformat( 5, args );
2054 if (!NILP(bufname) ) {
2055 bufname = Fgenerate_new_buffer_name(bufname,Qnil);
2056 buffer = Fget_buffer_create(bufname);
2058 np = make_process_internal(p->name);
2059 XPROCESS(np)->pid = Fcons( make_int(sa.sin_port),
2060 Fcons(make_int(UNIX_DATA(p)->infd),p->pid));
2061 XPROCESS(np)->process_type = PROCESS_TYPE_NETWORK;
2062 XPROCESS(np)->buffer = buffer;
2065 set_socket_nonblocking_maybe(inch, sa.sin_port, "tcp");
2066 init_process_io_handles(XPROCESS(np), (void *)inch, (void *)outch,
2067 STREAM_NETWORK_CONNECTION);
2068 /* Process the call backs.. */
2069 if (CONSP(p->process_type_data)) {
2070 if (!NILP(filter)) {
2071 XPROCESS(np)->filter = filter;
2073 if (!NILP(sentinel)) {
2074 XPROCESS(np)->sentinel = sentinel;
2076 if (!NILP(acceptor)) {
2077 int speccount = specpdl_depth();
2078 record_unwind_protect(exec_acceptor_unwind,
2079 noseeum_cons(process, acceptor));
2080 running_asynch_code = 1;
2081 call1_trapping_errors("Error in server stream acceptor",
2083 running_asynch_code = 0;
2084 restore_match_data();
2085 unbind_to(speccount, Qnil);
2089 /* We have to log something here... */
2091 event_stream_select_process(XPROCESS(np));
2095 /* Open a TCP network connection to a given HOST/SERVICE.
2096 Treated exactly like a normal process when reading and writing.
2097 Only differences are in status display and process deletion.
2098 A network connection has no PID; you cannot signal it. All you can
2099 do is deactivate and close it via delete-process. */
2102 unix_open_network_server_stream(Lisp_Object name, Lisp_Object host,
2103 Lisp_Object service, Lisp_Object protocol,
2104 void **vinfd, void **voutfd)
2110 volatile int retry = 0;
2112 /* FIXME: Limited to 5 since it is the maximum for several BSD
2113 based implementations of sockets, and it is an acceptable
2114 value for a low rate of service purpose like this facility
2115 was designed for. */
2119 if (!EQ(protocol, Qtcp) && !EQ(protocol, Qudp))
2120 invalid_argument("Unsupported protocol", protocol);
2123 #if defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO)
2124 struct addrinfo hints, *res;
2125 struct addrinfo *volatile lres;
2127 volatile int xerrno = 0;
2128 volatile int failed_connect = 0;
2130 char portbuf[sizeof(long)*3 + 2];
2132 * Caution: service can either be a string or int.
2133 * Convert to a C string for later use by getaddrinfo.
2135 if (INTP(service)) {
2136 int sz = snprintf(portbuf, sizeof(portbuf), "%ld",
2137 (long)XINT(service));
2138 assert(sz >= 0 && (size_t)sz < sizeof(portbuf));
2139 portstring = portbuf;
2140 port = htons((unsigned short)XINT(service));
2142 CHECK_STRING(service);
2143 LISP_STRING_TO_EXTERNAL(service, portstring, Qnative);
2149 hints.ai_family = AF_UNSPEC;
2150 if (EQ(protocol, Qtcp))
2151 hints.ai_socktype = SOCK_STREAM;
2152 else /* EQ (protocol, Qudp) */
2153 hints.ai_socktype = SOCK_DGRAM;
2154 hints.ai_protocol = 0;
2155 if (SYMBOLP(host) ) {
2156 if (EQ(host,Qip_any)) {
2157 hints.ai_flags |= AI_PASSIVE;
2158 } else if (!EQ(host,Qlocalhost)) {
2159 invalid_argument("invalid host ",host);
2161 /* If using localhost, not passing
2162 AI_PASSIVE will cause getaddrinfo
2163 to return a proper addr spec for
2164 listening only to local
2167 retval = getaddrinfo(NULL, portstring, &hints, &res);
2170 LISP_STRING_TO_EXTERNAL(host, ext_host, Qnative);
2171 retval = getaddrinfo(ext_host, portstring, &hints, &res);
2176 EXTERNAL_TO_C_STRING(gai_strerror(retval),
2177 gai_error_l, Qnative);
2178 error("%s/%s %s", XSTRING_DATA(host), portstring,
2183 for (lres = res; lres; lres = lres->ai_next) {
2184 if (EQ(protocol, Qtcp))
2185 s = socket(lres->ai_family, SOCK_STREAM, 0);
2186 else /* EQ (protocol, Qudp) */
2187 s = socket(lres->ai_family, SOCK_DGRAM, 0);
2192 /* Turn off interrupts here -- see comments below.
2193 There used to be code which called
2194 bind_polling_period() to slow the polling period down
2195 rather than turn it off, but that seems rather bogus
2196 to me. Best thing here is to use a non-blocking
2197 connect or something, to check for QUIT. */
2199 /* Comments that are not quite valid: */
2201 /* Kernel bugs (on Ultrix at least) cause lossage (not
2202 just EINTR) when connect is interrupted. So let's
2203 not let it get interrupted. Note we do not turn off
2204 polling, because polling is only used when not
2205 interrupt_input, and thus not normally used on the
2206 systems which have this bug. On systems which use
2207 polling, there's no way to quit if polling is turned
2210 /* Slow down polling. Some kernels have a bug which
2211 causes retrying connect to fail after a connect. */
2213 slow_down_interrupts();
2217 /* A system call interrupted with a SIGALRM or SIGIO
2218 comes back here, with can_break_system_calls reset to
2220 SETJMP(break_system_call_jump);
2222 speed_up_interrupts();
2224 /* In case something really weird happens ... */
2225 slow_down_interrupts();
2228 /* Break out of connect with a signal (it isn't
2229 otherwise possible). Thus you don't get screwed with
2231 can_break_system_calls = 1;
2232 retval = bind(s, lres->ai_addr, lres->ai_addrlen);
2234 retval = listen(s, listenQ);
2235 can_break_system_calls = 0;
2238 if (errno != EISCONN) {
2241 if (errno == EADDRINUSE && retry < 20) {
2242 /* A delay here is needed on
2243 some FreeBSD systems, and it
2244 is harmless, since this
2245 retrying takes time anyway
2246 and should be infrequent.
2247 `sleep-for' allowed for
2248 quitting this loop with
2249 interrupts slowed down so it
2250 can't be used here. Async
2251 timers should already be
2252 disabled at this point so we
2263 speed_up_interrupts();
2270 char servbuf[NI_MAXSERV];
2272 if (EQ(protocol, Qtcp))
2274 getnameinfo(lres->ai_addr,
2275 lres->ai_addrlen, NULL,
2279 else /* EQ (protocol, Qudp) */
2281 getnameinfo(lres->ai_addr,
2282 lres->ai_addrlen, NULL,
2289 port = strtol(servbuf, NULL, 10);
2293 } /* address loop */
2295 speed_up_interrupts();
2302 report_file_error("bind failed",
2305 report_file_error("error creating socket",
2308 #else /* ! HAVE_GETADDRINFO */
2309 struct sockaddr_in address;
2312 port = htons((unsigned short)XINT(service));
2314 struct servent *svc_info;
2315 CHECK_STRING(service);
2317 if (EQ(protocol, Qtcp))
2319 getservbyname((char *)XSTRING_DATA(service),
2321 else /* EQ (protocol, Qudp) */
2323 getservbyname((char *)XSTRING_DATA(service),
2327 invalid_argument("Unknown service", service);
2328 port = svc_info->s_port;
2330 if (SYMBOLP(host)) {
2331 if (EQ(host,Qip_any)) {
2332 address.sin_addr.s_host = htonl(INADDR_ANY);
2333 } else if (EQ(host,Qlocalhost)) {
2334 address.sin_addr.s_host = htonl(INADDR_LOOPBACK);
2336 invalid_argument("invalid host ",host);
2339 get_internet_address(host, &address, ERROR_ME);
2341 address.sin_port = port;
2343 if (EQ(protocol, Qtcp))
2344 s = socket(address.sin_family, SOCK_STREAM, 0);
2345 else /* EQ (protocol, Qudp) */
2346 s = socket(address.sin_family, SOCK_DGRAM, 0);
2349 report_file_error("error creating socket", list1(name));
2351 /* Turn off interrupts here -- see comments below. There used to
2352 be code which called bind_polling_period() to slow the polling
2353 period down rather than turn it off, but that seems rather
2354 bogus to me. Best thing here is to use a non-blocking connect
2355 or something, to check for QUIT. */
2357 /* Comments that are not quite valid: */
2359 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
2360 when connect is interrupted. So let's not let it get interrupted.
2361 Note we do not turn off polling, because polling is only used
2362 when not interrupt_input, and thus not normally used on the systems
2363 which have this bug. On systems which use polling, there's no way
2364 to quit if polling is turned off. */
2366 /* Slow down polling. Some kernels have a bug which causes retrying
2367 connect to fail after a connect. */
2369 slow_down_interrupts();
2373 /* A system call interrupted with a SIGALRM or SIGIO comes back
2374 here, with can_break_system_calls reset to 0. */
2375 SETJMP(break_system_call_jump);
2377 speed_up_interrupts();
2379 /* In case something really weird happens ... */
2380 slow_down_interrupts();
2383 /* Break out of connect with a signal (it isn't otherwise possible).
2384 Thus you don't get screwed with a hung network. */
2385 can_break_system_calls = 1;
2387 bind(s, (struct sockaddr *)&address, sizeof(address));
2389 listen( s, listenQ ); /* @@@ FIXME: This should be a parameter */
2390 can_break_system_calls = 0;
2391 if (retval == -1 && errno != EISCONN) {
2395 if (errno == EADDRINUSE && retry < 20) {
2396 /* A delay here is needed on some FreeBSD
2397 systems, and it is harmless, since this
2398 retrying takes time anyway and should be
2399 infrequent. `sleep-for' allowed for quitting
2400 this loop with interrupts slowed down so it
2401 can't be used here. Async timers should
2402 already be disabled at this point so we can
2410 speed_up_interrupts();
2413 report_file_error("connection failed",
2417 speed_up_interrupts();
2418 #endif /* ! HAVE_GETADDRINFO */
2424 close(s); /* this used to be leaked; from Kyle Jones */
2425 report_file_error("error duplicating socket", list1(name));
2428 set_socket_nonblocking_maybe(inch, port, "tcp");
2430 *vinfd = (void *)inch;
2431 *voutfd = (void *)outch;
2435 #ifdef HAVE_MULTICAST
2437 /* Didier Verna <didier@xemacs.org> Nov. 28 1997.
2439 This function is similar to open-network-stream-internal, but provides a
2440 mean to open an UDP multicast connection instead of a TCP one. Like in the
2441 TCP case, the multicast connection will be seen as a sub-process,
2444 - Normally, we should use sendto and recvfrom with non connected
2445 sockets. The current code doesn't allow us to do this. In the future, it
2446 would be a good idea to extend the process data structure in order to deal
2447 properly with the different types network connections.
2448 - For the same reason, when leaving a multicast group, it is better to make
2449 a setsockopt - IP_DROP_MEMBERSHIP before closing the descriptors.
2450 Unfortunately, this can't be done here because delete_process doesn't know
2451 about the kind of connection we have. However, this is not such an
2456 unix_open_multicast_group(Lisp_Object name, Lisp_Object dest,
2457 Lisp_Object port, Lisp_Object ttl, void **vinfd,
2461 struct sockaddr_in sa;
2462 struct protoent *udp;
2465 unsigned char thettl;
2466 int one = 1; /* For REUSEADDR */
2468 volatile int retry = 0;
2473 theport = htons((unsigned short)XINT(port));
2476 thettl = (unsigned char)XINT(ttl);
2478 if ((udp = getprotobyname("udp")) == NULL)
2479 type_error(Qinvalid_operation,
2480 "No info available for UDP protocol");
2482 /* Init the sockets. Yes, I need 2 sockets. I couldn't duplicate one. */
2483 if ((rs = socket(PF_INET, SOCK_DGRAM, udp->p_proto)) < 0)
2484 report_file_error("error creating socket", list1(name));
2485 if ((ws = socket(PF_INET, SOCK_DGRAM, udp->p_proto)) < 0) {
2487 report_file_error("error creating socket", list1(name));
2490 /* This will be used for both sockets */
2491 memset(&sa, 0, sizeof(sa));
2492 sa.sin_family = AF_INET;
2493 sa.sin_port = theport;
2494 sa.sin_addr.s_addr = inet_addr((char *)XSTRING_DATA(dest));
2496 /* Socket configuration for reading ------------------------ */
2498 /* Multiple connections from the same machine. This must be done before
2499 bind. If it fails, it shouldn't be fatal. The only consequence is that
2500 people won't be able to connect twice from the same machine. */
2501 if (setsockopt(rs, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one))
2503 warn_when_safe(Qmulticast, Qwarning,
2504 "Cannot reuse socket address");
2506 /* bind socket name */
2507 if (bind(rs, (struct sockaddr *)&sa, sizeof(sa))) {
2510 report_file_error("error binding socket", list2(name, port));
2513 /* join multicast group */
2514 imr.imr_multiaddr.s_addr = inet_addr((char *)XSTRING_DATA(dest));
2515 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2516 if (setsockopt(rs, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2517 &imr, sizeof(struct ip_mreq)) < 0) {
2520 report_file_error("error adding membership", list2(name, dest));
2523 /* Socket configuration for writing ----------------------- */
2525 /* Normally, there's no 'connect' in multicast, since we prefer to use
2526 'sendto' and 'recvfrom'. However, in order to handle this connection
2527 in the process-like way it is done for TCP, we must be able to use
2528 'write' instead of 'sendto'. Consequently, we 'connect' this
2531 /* See open-network-stream-internal for comments on this part of the
2533 slow_down_interrupts();
2537 /* A system call interrupted with a SIGALRM or SIGIO comes back
2538 here, with can_break_system_calls reset to 0. */
2539 SETJMP(break_system_call_jump);
2541 speed_up_interrupts();
2543 /* In case something really weird happens ... */
2544 slow_down_interrupts();
2547 /* Break out of connect with a signal (it isn't otherwise possible).
2548 Thus you don't get screwed with a hung network. */
2549 can_break_system_calls = 1;
2550 ret = connect(ws, (struct sockaddr *)&sa, sizeof(sa));
2551 can_break_system_calls = 0;
2552 if (ret == -1 && errno != EISCONN) {
2557 if (errno == EADDRINUSE && retry < 20) {
2558 /* A delay here is needed on some FreeBSD systems, and
2559 it is harmless, since this retrying takes time anyway
2560 and should be infrequent. `sleep-for' allowed for
2561 quitting this loop with interrupts slowed down so it
2562 can't be used here. Async timers should already be
2563 disabled at this point so we can use `sleep'. */
2570 speed_up_interrupts();
2573 report_file_error("error connecting socket", list2(name, port));
2576 speed_up_interrupts();
2579 if (setsockopt(ws, IPPROTO_IP, IP_MULTICAST_TTL,
2580 &thettl, sizeof(thettl)) < 0) {
2583 report_file_error("error setting ttl", list2(name, ttl));
2586 set_socket_nonblocking_maybe(rs, theport, "udp");
2588 *vinfd = (void *)rs;
2589 *voutfd = (void *)ws;
2592 #endif /* HAVE_MULTICAST */
2594 #endif /* HAVE_SOCKETS */
2596 /**********************************************************************/
2597 /* Initialization */
2598 /**********************************************************************/
2600 void process_type_create_unix(void)
2602 PROCESS_HAS_METHOD(unix, alloc_process_data);
2603 PROCESS_HAS_METHOD(unix, mark_process_data);
2605 PROCESS_HAS_METHOD(unix, init_process);
2606 PROCESS_HAS_METHOD(unix, reap_exited_processes);
2608 PROCESS_HAS_METHOD(unix, init_process_io_handles);
2609 PROCESS_HAS_METHOD(unix, create_process);
2610 PROCESS_HAS_METHOD(unix, set_window_size);
2612 PROCESS_HAS_METHOD(unix, update_status_if_terminated);
2614 PROCESS_HAS_METHOD(unix, send_process);
2615 PROCESS_HAS_METHOD(unix, process_send_eof);
2616 PROCESS_HAS_METHOD(unix, deactivate_process);
2617 PROCESS_HAS_METHOD(unix, kill_child_process);
2618 PROCESS_HAS_METHOD(unix, kill_process_by_pid);
2619 PROCESS_HAS_METHOD(unix, get_tty_name);
2621 PROCESS_HAS_METHOD(unix, canonicalize_host_name);
2622 PROCESS_HAS_METHOD(unix, open_network_stream);
2623 PROCESS_HAS_METHOD(unix, open_network_server_stream);
2624 PROCESS_HAS_METHOD(unix, network_server_accept);
2625 PROCESS_HAS_METHOD(unix, network_process_listener);
2626 #ifdef HAVE_MULTICAST
2627 PROCESS_HAS_METHOD(unix, open_multicast_group);
2632 void vars_of_process_unix(void)
2634 Fprovide(intern("unix-processes"));
2637 #endif /* !defined (NO_SUBPROCESSES) */