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 */
373 #ifdef PTY_NAME_SPRINTF
376 sprintf(pty_name, "/dev/pty%c%x", c, i);
377 #endif /* no PTY_NAME_SPRINTF */
379 if (sxemacs_stat(pty_name, &stb) < 0) {
380 if (++failed_count >= 3)
384 fd = open(pty_name, O_RDWR | O_NONBLOCK | OPEN_BINARY,
388 #ifdef PTY_TTY_NAME_SPRINTF
391 sprintf(pty_name, "/dev/tty%c%x", c, i);
392 #endif /* no PTY_TTY_NAME_SPRINTF */
393 if (access(pty_name, R_OK | W_OK) == 0) {
402 #endif /* HAVE_PTYS */
405 create_bidirectional_pipe(long int *inchannel, long int *outchannel,
406 volatile int *forkin, volatile int *forkout)
411 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) < 0)
413 *outchannel = *inchannel = sv[0];
414 *forkout = *forkin = sv[1];
415 #else /* not SKTPAIR */
427 #endif /* not SKTPAIR */
433 #if !(defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO))
435 get_internet_address(Lisp_Object host, struct sockaddr_in *address,
438 struct hostent *host_info_ptr = NULL;
451 /* Some systems can't handle SIGIO/SIGALARM in gethostbyname. */
452 slow_down_interrupts();
453 host_info_ptr = gethostbyname((char *)XSTRING_DATA(host));
454 speed_up_interrupts();
456 if (!(host_info_ptr == 0 && h_errno == TRY_AGAIN))
459 Fsleep_for(make_int(1));
462 address->sin_family = host_info_ptr->h_addrtype;
463 memcpy(&address->sin_addr, host_info_ptr->h_addr,
464 host_info_ptr->h_length);
466 IN_ADDR numeric_addr;
467 /* Attempt to interpret host as numeric inet address */
468 numeric_addr = inet_addr((char *)XSTRING_DATA(host));
469 if (NUMERIC_ADDR_ERROR) {
470 maybe_error(Qprocess, errb,
471 "Unknown host \"%s\"", XSTRING_DATA(host));
475 /* There was some broken code here that called strlen() here
476 on (char *) &numeric_addr and even sometimes accessed
477 uninitialized data. */
478 address->sin_family = AF_INET;
479 *(IN_ADDR *) & address->sin_addr = numeric_addr;
484 #endif /* !(HAVE_GETADDRINFO && HAVE_GETNAMEINFO) */
486 static void set_socket_nonblocking_maybe(int fd, int port, const char *proto)
488 #ifdef PROCESS_IO_BLOCKING
491 for (tail = network_stream_blocking_port_list; CONSP(tail);
493 Lisp_Object tail_port = XCAR(tail);
495 if (STRINGP(tail_port)) {
496 struct servent *svc_info;
497 CHECK_STRING(tail_port);
499 getservbyname((char *)XSTRING_DATA(tail_port),
501 if ((svc_info != 0) && (svc_info->s_port == port))
505 } else if (INTP(tail_port)
506 && (htons((unsigned short)XINT(tail_port)) == port))
511 set_descriptor_non_blocking(fd);
514 set_descriptor_non_blocking(fd);
515 #endif /* PROCESS_IO_BLOCKING */
518 #endif /* HAVE_SOCKETS */
520 /* Compute the Lisp form of the process status from
521 the numeric status that was returned by `wait'. */
523 static void update_status_from_wait_code(Lisp_Process * p, int *w_fmh)
525 /* C compiler lossage when attempting to pass w directly */
529 p->status_symbol = Qstop;
530 p->exit_code = WSTOPSIG(w);
532 } else if (WIFEXITED(w)) {
533 p->status_symbol = Qexit;
534 p->exit_code = WEXITSTATUS(w);
536 } else if (WIFSIGNALED(w)) {
537 p->status_symbol = Qsignal;
538 p->exit_code = WTERMSIG(w);
539 p->core_dumped = WCOREDUMP(w);
541 p->status_symbol = Qrun;
548 #define MAX_EXITED_PROCESSES 1000
549 static volatile pid_t exited_processes[MAX_EXITED_PROCESSES];
550 static volatile int exited_processes_status[MAX_EXITED_PROCESSES];
551 static volatile int exited_processes_index;
553 static volatile int sigchld_happened;
555 /* On receipt of a signal that a child status has changed,
556 loop asking about children with changed statuses until
557 the system says there are no more. All we do is record
558 the processes and wait status.
560 This function could be called from within the SIGCHLD
561 handler, so it must be completely reentrant. When
562 not called from a SIGCHLD handler, BLOCK_SIGCHLD should
563 be non-zero so that SIGCHLD is blocked while this
564 function is running. (This is necessary so avoid
565 race conditions with the SIGCHLD_HAPPENED flag). */
567 static void record_exited_processes(int block_sigchld)
569 if (!sigchld_happened) {
572 #ifdef EMACS_BLOCK_SIGNAL
574 EMACS_BLOCK_SIGNAL(SIGCHLD);
577 while (sigchld_happened) {
581 /* Keep trying to get a status until we get a definitive result. */
587 # endif /* not WUNTRACED */
589 pid = waitpid((pid_t) - 1, &w, WNOHANG | WUNTRACED);
591 pid = wait3(&w, WNOHANG | WUNTRACED, 0);
593 #else /* not WNOHANG */
595 #endif /* not WNOHANG */
597 while (pid <= 0 && errno == EINTR);
602 if (exited_processes_index < MAX_EXITED_PROCESSES) {
603 exited_processes[exited_processes_index] = pid;
604 exited_processes_status[exited_processes_index] = w;
605 exited_processes_index++;
608 /* On systems with WNOHANG, we just ignore the number
609 of times that SIGCHLD was signalled, and keep looping
610 until there are no more processes to wait on. If we
611 don't have WNOHANG, we have to rely on the count in
615 #endif /* not WNOHANG */
618 sigchld_happened = 0;
621 EMACS_UNBLOCK_SIGNAL(SIGCHLD);
624 /* For any processes that have changed status and are recorded
625 and such, update the corresponding Lisp_Process.
626 We separate this from record_exited_processes() so that
627 we never have to call this function from within a signal
628 handler. We block SIGCHLD in case record_exited_processes()
629 is called from a signal handler. */
631 /** USG WARNING: Although it is not obvious from the documentation
632 in signal(2), on a USG system the SIGCLD handler MUST NOT call
633 signal() before executing at least one wait(), otherwise the handler
634 will be called again, resulting in an infinite loop. The relevant
635 portion of the documentation reads "SIGCLD signals will be queued
636 and the signal-catching function will be continually reentered until
637 the queue is empty". Invoking signal() causes the kernel to reexamine
638 the SIGCLD queue. Fred Fish, UniSoft Systems Inc.
640 (Note that now this only applies in SYS V Release 2 and before.
641 On SYS V Release 3, we use sigset() to set the signal handler for
642 the first time, and so we don't have to reestablish the signal handler
643 in the handler below. On SYS V Release 4, we don't get this weirdo
644 behavior when we use sigaction(), which we do use.) */
646 static SIGTYPE sigchld_handler(int signo)
648 #ifdef OBNOXIOUS_SYSV_SIGCLD_BEHAVIOR
649 int old_errno = errno;
652 record_exited_processes(0);
657 #ifdef HAVE_UNIXOID_EVENT_LOOP
660 /* WARNING - must come after wait3() for USG systems */
661 EMACS_REESTABLISH_SIGNAL(signo, sigchld_handler);
667 #ifdef SIGNALS_VIA_CHARACTERS
668 /* Get signal character to send to process if SIGNALS_VIA_CHARACTERS */
670 static int process_signal_char(int tty_fd, int signo)
672 /* If it's not a tty, pray that these default values work */
673 if (!isatty(tty_fd)) {
674 #define CNTL(ch) (037 & (ch))
689 /* TERMIOS is the latest and bestest, and seems most likely to work.
690 If the system has it, use it. */
693 tcgetattr(tty_fd, &t);
696 return t.c_cc[VINTR];
698 return t.c_cc[VQUIT];
699 #if defined(SIGTSTP) && defined(VSUSP)
701 return t.c_cc[VSUSP];
708 # elif defined (TIOCGLTC) && defined (TIOCGETC) /* not HAVE_TERMIOS */
710 /* On Berkeley descendants, the following IOCTL's retrieve the
711 current control characters. */
716 ioctl(tty_fd, TIOCGETC, &c);
719 ioctl(tty_fd, TIOCGETC, &c);
723 ioctl(tty_fd, TIOCGLTC, &lc);
725 # endif /* SIGTSTP */
729 # elif defined (TCGETA) /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
731 /* On SYSV descendants, the TCGETA ioctl retrieves the current
732 control characters. */
734 ioctl(tty_fd, TCGETA, &t);
737 return t.c_cc[VINTR];
739 return t.c_cc[VQUIT];
742 return t.c_cc[VSWTCH];
743 # endif /* SIGTSTP */
746 # else /* ! defined (TCGETA) */
747 #error ERROR! Using SIGNALS_VIA_CHARACTERS, but not HAVE_TERMIOS || (TIOCGLTC && TIOCGETC) || TCGETA
748 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
749 you'd better be using one of the alternatives above! */
750 # endif /* ! defined (TCGETA) */
753 #endif /* SIGNALS_VIA_CHARACTERS */
755 /**********************************************************************/
756 /* Process implementation methods */
757 /**********************************************************************/
760 * Allocate and initialize Lisp_Process->process_data
763 static void unix_alloc_process_data(Lisp_Process * p)
765 p->process_data = xnew(struct unix_process_data);
767 UNIX_DATA(p)->connected_via_filedesc_p = 0;
768 UNIX_DATA(p)->infd = -1;
769 UNIX_DATA(p)->subtty = -1;
770 UNIX_DATA(p)->tty_name = Qnil;
771 UNIX_DATA(p)->pty_flag = 0;
775 * Mark any Lisp objects in Lisp_Process->process_data
778 static void unix_mark_process_data(Lisp_Process * proc)
780 mark_object(UNIX_DATA(proc)->tty_name);
784 * Initialize SXEmacs process implementation once
788 static void unix_init_process(void)
791 if (!noninteractive || initialized)
793 signal(SIGCHLD, sigchld_handler);
798 * Initialize any process local data. This is called when newly
799 * created process is connected to real OS file handles. The
800 * handles are generally represented by void* type, but are
801 * of type int (file descriptors) for UNIX.
805 unix_init_process_io_handles(Lisp_Process * p, void *in, void *out, int flags)
807 Lisp_Object process = Qnil;
808 USID usid = FD_TO_USID((EMACS_INT)in);
809 XSETPROCESS(process, p);
810 puthash((const void *)usid, LISP_TO_VOID(process),
812 UNIX_DATA(p)->infd = (EMACS_INT)in;
816 * Fork off a subprocess. P is a pointer to a newly created subprocess
817 * object. If this function signals, the caller is responsible for
818 * deleting (and finalizing) the process object.
820 * The method must return PID of the new process, a (positive??? ####) number
821 * which fits into Lisp_Int. No return value indicates an error, the method
822 * must signal an error instead.
826 unix_create_process(Lisp_Process * p,
827 Lisp_Object * argv, int nargv,
828 Lisp_Object program, Lisp_Object cur_dir)
831 long int inchannel = -1;
832 long int outchannel = -1;
833 /* Use volatile to protect variables from being clobbered by longjmp. */
834 volatile int forkin = -1;
835 volatile int forkout = -1;
836 volatile int pty_flag = 0;
839 if (!NILP(Vprocess_connection_type)) {
840 /* find a new pty, open the master side, return the opened
841 file handle, and store the name of the corresponding slave
842 side in global variable pty_name. */
843 outchannel = inchannel = allocate_pty();
846 if (inchannel >= 0) {
847 /* You're "supposed" to now open the slave in the child.
848 On some systems, we can open it here; this allows for
849 better error checking. */
851 /* On USG systems it does not work to open the pty's tty here
852 and then close and reopen it in the child. */
854 /* Don't let this terminal become our controlling terminal
855 (in case we don't have one). */
857 open(pty_name, O_RDWR | O_NOCTTY | OPEN_BINARY, 0);
859 forkout = forkin = open(pty_name, O_RDWR | OPEN_BINARY, 0);
864 UNIX_DATA(p)->pty_flag = pty_flag = 1;
866 #endif /* HAVE_PTYS */
867 if (create_bidirectional_pipe(
868 (void*)&inchannel, (void*)&outchannel,
869 &forkin, &forkout) < 0)
873 /* Replaced by close_process_descs */
874 set_exclusive_use(inchannel);
875 set_exclusive_use(outchannel);
878 set_descriptor_non_blocking(inchannel);
879 set_descriptor_non_blocking(outchannel);
881 /* Record this as an active process, with its channels.
882 As a result, child_setup will close Emacs's side of the pipes. */
883 init_process_io_handles(p, (void *)inchannel, (void *)outchannel,
884 pty_flag ? STREAM_PTY_FLUSHING : 0);
885 /* Record the tty descriptor used in the subprocess. */
886 UNIX_DATA(p)->subtty = forkin;
889 /* child_setup must clobber environ on systems with true vfork.
890 Protect it from permanent change. */
891 char **save_environ = environ;
895 /**** Now we're in the child process ****/
896 int xforkin = forkin;
897 int xforkout = forkout;
899 /* Checking for quit in the child is bad because that will
900 cause I/O, and that, in turn, can confuse the X connection. */
901 begin_dont_check_for_quit();
903 /* Disconnect the current controlling terminal, pursuant to
904 making the pty be the controlling terminal of the process.
905 Also put us in our own process group. */
907 disconnect_controlling_terminal();
911 /* Open the pty connection and make the pty's terminal
912 our controlling terminal.
914 On systems with TIOCSCTTY, we just use it to set
915 the controlling terminal. On other systems, the
916 first TTY we open becomes the controlling terminal.
917 So, we end up with four possibilities:
919 (1) on USG and TIOCSCTTY systems, we open the pty
921 (2) on other USG systems, we just open the pty.
922 (3) on non-USG systems with TIOCSCTTY, we
923 just use TIOCSCTTY. (On non-USG systems, we
924 already opened the pty in the parent process.)
925 (4) on non-USG systems without TIOCSCTTY, we
926 close the pty and reopen it.
928 This would be cleaner if we didn't open the pty
929 in the parent process, but doing it that way
930 makes it possible to trap error conditions.
931 It's harder to convey an error from the child
932 process, and I don't feel like messing with
935 /* There was some weirdo, probably wrong,
936 conditionalization on RTU and UNIPLUS here.
937 I deleted it. So sue me. */
939 /* SunOS has TIOCSCTTY but the close/open method
942 # if defined (USG) || !defined (TIOCSCTTY)
943 /* Now close the pty (if we had it open) and reopen it.
944 This makes the pty the controlling terminal of the
946 /* I wonder if close (open (pty_name, ...)) would work? */
950 open(pty_name, O_RDWR | OPEN_BINARY, 0);
953 "Couldn't open the pty terminal ",
955 write(1, pty_name, strlen(pty_name));
959 # endif /* USG or not TIOCSCTTY */
961 /* Miscellaneous setup required for some systems.
962 Must be done before using tc* functions on xforkin.
963 This guarantees that isatty(xforkin) is true. */
965 # if defined (HAVE_ISASTREAM) && defined (I_PUSH)
966 if (isastream(xforkin)) {
967 # if defined (I_FIND)
968 # define stream_module_pushed(fd, module) (ioctl (fd, I_FIND, module) == 1)
970 # define stream_module_pushed(fd, module) 0
972 if (!stream_module_pushed
974 ioctl(xforkin, I_PUSH, "ptem");
975 if (!stream_module_pushed
977 ioctl(xforkin, I_PUSH,
979 if (!stream_module_pushed
980 (xforkin, "ttcompat"))
981 ioctl(xforkin, I_PUSH,
984 # endif /* HAVE_ISASTREAM */
987 /* We ignore the return value
988 because faith@cs.unc.edu says that is necessary on Linux. */
989 assert(isatty(xforkin));
990 ioctl(xforkin, TIOCSCTTY, 0);
991 # endif /* TIOCSCTTY */
993 /* Change the line discipline. */
995 # if defined (HAVE_TERMIOS) && defined (LDISC1)
998 assert(isatty(xforkin));
999 tcgetattr(xforkin, &t);
1001 if (tcsetattr(xforkin, TCSANOW, &t) < 0)
1003 ("create_process/tcsetattr LDISC1 failed\n");
1005 # elif defined (NTTYDISC) && defined (TIOCSETD)
1007 /* Use new line discipline. TIOCSETD is accepted and
1008 ignored on Sys5.4 systems with ttcompat. */
1009 int ldisc = NTTYDISC;
1010 assert(isatty(xforkin));
1011 ioctl(xforkin, TIOCSETD, &ldisc);
1013 # endif /* TIOCSETD & NTTYDISC */
1015 /* Make our process group be the foreground group
1016 of our new controlling terminal. */
1020 EMACS_GET_PROCESS_GROUP();
1021 EMACS_SET_TTY_PROCESS_GROUP(xforkin,
1025 /* On AIX, we've disabled SIGHUP above once we start a
1026 child on a pty. Now reenable it in the child, so it
1027 will die when we want it to.
1028 JV: This needs to be done ALWAYS as we might have inherited
1029 a SIG_IGN handling from our parent (nohup) and we are in new
1032 signal(SIGHUP, SIG_DFL);
1036 /* Set up the terminal characteristics of the pty. */
1037 child_setup_tty(xforkout);
1039 #endif /* HAVE_PTYS */
1041 signal(SIGINT, SIG_DFL);
1042 signal(SIGQUIT, SIG_DFL);
1047 alloca_array(char *, nargv + 2);
1050 /* Nothing below here GCs so our string pointers shouldn't move. */
1051 new_argv[0] = (char *)XSTRING_DATA(program);
1052 for (i = 0; i < nargv; i++) {
1053 CHECK_STRING(argv[i]);
1055 (char *)XSTRING_DATA(argv[i]);
1057 new_argv[i + 1] = 0;
1059 LISP_STRING_TO_EXTERNAL(cur_dir, current_dir,
1062 child_setup(xforkin, xforkout, xforkout,
1063 new_argv, current_dir);
1068 /**** End of child code ****/
1069 /**** Back in parent process ****/
1070 environ = save_environ;
1074 int save_errno = errno;
1075 close_descriptor_pair(forkin, forkout);
1077 report_file_error("Doing fork", Qnil);
1080 /* #### dmoore - why is this commented out, otherwise we leave
1081 subtty = forkin, but then we close forkin just below. */
1082 /* UNIX_DATA(p)->subtty = -1; */
1084 /* If the subfork execv fails, and it exits,
1085 this close hangs. I don't know why.
1086 So have an interrupt jar it loose. */
1088 close_safely(forkin);
1089 if (forkin != forkout && forkout >= 0)
1094 UNIX_DATA(p)->tty_name = build_string(pty_name);
1097 UNIX_DATA(p)->tty_name = Qnil;
1099 /* Notice that SIGCHLD was not blocked. (This is not possible on
1100 some systems.) No biggie if SIGCHLD occurs right around the
1101 time that this call happens, because SIGCHLD() does not actually
1102 deselect the process (that doesn't occur until the next time
1103 we're waiting for an event, when status_notify() is called). */
1108 int save_errno = errno;
1109 close_descriptor_pair(forkin, forkout);
1110 close_descriptor_pair(inchannel, outchannel);
1112 report_file_error("Opening pty or pipe", Qnil);
1113 return 0; /* not reached */
1117 /* This is called to set process' virtual terminal size */
1119 static int unix_set_window_size(Lisp_Process * p, int cols, int rows)
1121 return set_window_size(UNIX_DATA(p)->infd, cols, rows);
1125 * This method is called to update status fields of the process
1126 * structure. If the process has not existed, this method is
1127 * expected to do nothing.
1129 * The method is called only for real child processes.
1133 static void unix_update_status_if_terminated(Lisp_Process * p)
1137 EMACS_BLOCK_SIGNAL(SIGCHLD);
1139 if (waitpid(XINT(p->pid), &w, WNOHANG) == XINT(p->pid)) {
1141 update_status_from_wait_code(p, &w);
1144 EMACS_UNBLOCK_SIGNAL(SIGCHLD);
1150 * Update status of all exited processes. Called when SIGCLD has signaled.
1154 static void unix_reap_exited_processes(void)
1159 #ifndef OBNOXIOUS_SYSV_SIGCLD_BEHAVIOR
1160 record_exited_processes(1);
1163 if (exited_processes_index <= 0) {
1166 #ifdef EMACS_BLOCK_SIGNAL
1167 EMACS_BLOCK_SIGNAL(SIGCHLD);
1169 for (i = 0; i < exited_processes_index; i++) {
1170 int pid = exited_processes[i];
1171 int w = exited_processes_status[i];
1173 /* Find the process that signaled us, and record its status. */
1178 LIST_LOOP(tail, Vprocess_list) {
1179 Lisp_Object proc = XCAR(tail);
1181 if (INTP(p->pid) && XINT(p->pid) == pid)
1188 /* Change the status of the process that was found. */
1191 update_status_from_wait_code(p, &w);
1193 /* If process has terminated, stop waiting for its output. */
1194 if (WIFSIGNALED(w) || WIFEXITED(w)) {
1195 if (!NILP(p->pipe_instream)) {
1196 /* We can't just call event_stream->unselect_process_cb (p)
1197 here, because that calls XtRemoveInput, which is not
1198 necessarily reentrant, so we can't call this at interrupt
1204 /* There was no asynchronous process found for that id. Check
1205 if we have a synchronous process. Only set sync process status
1206 if there is one, so we work OK with the waitpid() call in
1207 wait_for_termination(). */
1208 if (synch_process_alive != 0) { /* Set the global sync process status variables. */
1209 synch_process_alive = 0;
1211 /* Report the status of the synchronous process. */
1213 synch_process_retcode = WEXITSTATUS(w);
1214 else if (WIFSIGNALED(w))
1215 synch_process_death =
1216 signal_name(WTERMSIG(w));
1221 exited_processes_index = 0;
1223 EMACS_UNBLOCK_SIGNAL(SIGCHLD);
1225 #endif /* SIGCHLD */
1228 * Stuff the entire contents of LSTREAM to the process output pipe
1231 static JMP_BUF send_process_frame;
1233 static SIGTYPE send_process_trap(int signum)
1235 EMACS_REESTABLISH_SIGNAL(signum, send_process_trap);
1236 EMACS_UNBLOCK_SIGNAL(signum);
1237 LONGJMP(send_process_frame, 1);
1241 unix_send_process(Lisp_Object proc, lstream_t lstream)
1243 /* Use volatile to protect variables from being clobbered by longjmp. */
1244 SIGTYPE(*volatile old_sigpipe) (int) = 0;
1245 volatile Lisp_Object vol_proc = proc;
1246 Lisp_Process *volatile p = XPROCESS(proc);
1248 /* #### JV: layering violation?
1250 This function knows too much about the relation between the encoding
1251 stream (DATA_OUTSTREAM) and the actual output stream p->output_stream.
1253 If encoding streams properly forwarded all calls, we could simply
1254 use DATA_OUTSTREAM everywhere. */
1256 if (!SETJMP(send_process_frame)) {
1257 /* use a reasonable-sized buffer (somewhere around the size of the
1258 stream buffer) so as to avoid inundating the stream with blocked
1260 Bufbyte chunkbuf[512];
1261 Bytecount chunklen = 0;
1264 Lstream_data_count writeret;
1265 if (p->process_type!=PROCESS_TYPE_NETWORK_SERVER_LISTEN) {
1266 chunklen = Lstream_read(lstream, chunkbuf, 512);
1269 (SIGTYPE(*)(int))signal(SIGPIPE, send_process_trap);
1273 switch (p->process_type) {
1274 case PROCESS_TYPE_NETWORK_SERVER_LISTEN:
1275 report_file_error ("no writing to listen process possible",
1278 case PROCESS_TYPE_SSL:
1279 case PROCESS_TYPE_PROC:
1280 case PROCESS_TYPE_NETWORK:
1281 case PROCESS_TYPE_MULTICAST:
1283 /* Lstream_write() will never successfully write less than
1284 * the amount sent in. In the worst case, it just buffers
1285 * the unwritten data. */
1286 writeret = Lstream_write
1287 (XLSTREAM (DATA_OUTSTREAM(p)),
1288 chunkbuf, chunklen);
1292 signal (SIGPIPE, old_sigpipe);
1295 /* This is a real error. Blocking errors are handled
1296 * specially inside of the filedesc stream.
1298 report_file_error ("writing to process",
1301 /* Need to make sure that everything up to and including the
1302 * last chunk is flushed, even when the pipe is currently
1304 Lstream_flush (XLSTREAM (DATA_OUTSTREAM(p)));
1305 signal (SIGPIPE, old_sigpipe);
1307 while (Lstream_was_blocked_p
1308 (XLSTREAM(p->pipe_outstream))) {
1309 /* Buffer is full. Wait, accepting input;
1310 * that may allow the program
1311 * to finish doing output and read more.
1313 Faccept_process_output(Qnil, make_int(1), Qnil);
1314 /* It could have *really* finished,
1315 * deleting the process */
1316 if (NILP(p->pipe_outstream))
1318 old_sigpipe = (SIGTYPE(*)(int))signal(
1321 Lstream_flush(XLSTREAM(p->pipe_outstream));
1322 signal(SIGPIPE, old_sigpipe);
1324 /* Perhaps should abort() if < 0?
1325 * This should never happen.
1328 while (chunklen > 0);
1329 } else { /* We got here from a longjmp() from the SIGPIPE handler */
1330 signal(SIGPIPE, old_sigpipe);
1331 /* Close the file lstream so we don't attempt to write to it further */
1332 /* #### There is controversy over whether this might cause fd leakage */
1333 /* my tests say no. -slb */
1334 XLSTREAM(p->pipe_outstream)->flags &= ~LSTREAM_FL_IS_OPEN;
1336 XLSTREAM(p->coding_outstream)->flags &= ~LSTREAM_FL_IS_OPEN;
1338 p->status_symbol = Qexit;
1339 p->exit_code = 256; /* #### SIGPIPE ??? */
1343 deactivate_process(vol_proc);
1344 invalid_operation("SIGPIPE raised on process; closed it",
1348 old_sigpipe = (SIGTYPE(*)(int))signal(SIGPIPE, send_process_trap);
1349 Lstream_flush(XLSTREAM(DATA_OUTSTREAM(p)));
1350 signal(SIGPIPE, old_sigpipe);
1354 * Send EOF to the process. The default implementation simply
1355 * closes the output stream. The method must return 0 to call
1356 * the default implementation, or 1 if it has taken all care about
1357 * sending EOF to the process.
1360 static int unix_process_send_eof(Lisp_Object proc)
1362 if (!UNIX_DATA(XPROCESS(proc))->pty_flag)
1365 /* #### get_eof_char simply doesn't return the correct character
1366 here. Maybe it is needed to determine the right eof
1367 character in init_process_io_handles but here it simply screws
1370 Bufbyte eof_char = get_eof_char(XPROCESS(proc));
1371 send_process(proc, Qnil, &eof_char, 0, 1);
1373 send_process(proc, Qnil, (const Bufbyte *)"\004", 0, 1);
1379 * Called before the process is deactivated. The process object
1380 * is not immediately finalized, just undergoes a transition to
1383 * The return value is a unique stream ID, as returned by
1384 * event_stream_delete_stream_pair
1386 * In the lack of this method, only event_stream_delete_stream_pair
1387 * is called on both I/O streams of the process.
1389 * The UNIX version guards this by ignoring possible SIGPIPE.
1392 static USID unix_deactivate_process(Lisp_Process * p)
1394 SIGTYPE(*old_sigpipe) (int) = 0;
1397 if (UNIX_DATA(p)->infd >= 0)
1398 flush_pending_output(UNIX_DATA(p)->infd);
1400 /* closing the outstream could result in SIGPIPE, so ignore it. */
1401 old_sigpipe = (SIGTYPE(*)(int))signal(SIGPIPE, SIG_IGN);
1402 usid = FD_TO_USID(UNIX_DATA(p)->infd);
1403 event_stream_delete_stream_pair(p->pipe_instream,
1406 signal(SIGPIPE, old_sigpipe);
1408 UNIX_DATA(p)->infd = -1;
1413 /* If the subtty field of the process data is not filled in, do so now. */
1414 static void try_to_initialize_subtty(struct unix_process_data *upd)
1416 if (upd->pty_flag && (upd->subtty == -1 || !isatty(upd->subtty))
1417 && STRINGP(upd->tty_name))
1419 open((char *)XSTRING_DATA(upd->tty_name), O_RDWR, 0);
1422 /* Send signal number SIGNO to PROCESS.
1423 CURRENT_GROUP means send to the process group that currently owns
1424 the terminal being used to communicate with PROCESS.
1425 This is used for various commands in shell mode.
1426 If NOMSG is zero, insert signal-announcements into process's buffers
1429 If we can, we try to signal PROCESS by sending control characters
1430 down the pty. This allows us to signal inferiors who have changed
1431 their uid, for which killpg would return an EPERM error,
1432 or processes running on other machines via remote login.
1434 The method signals an error if the given SIGNO is not valid. */
1437 unix_kill_child_process(Lisp_Object proc, int signo,
1438 int current_group, int nomsg)
1441 Lisp_Process *p = XPROCESS(proc);
1442 struct unix_process_data *d = UNIX_DATA(p);
1447 p->status_symbol = Qrun;
1454 #endif /* ! defined (SIGCONT) */
1458 flush_pending_output(d->infd);
1467 /* If current_group is true, we want to send a signal to the
1468 foreground process group of the terminal our child process is
1469 running on. You would think that would be easy.
1471 The BSD people invented the TIOCPGRP ioctl to get the foreground
1472 process group of a tty. That, combined with killpg, gives us
1475 However, the POSIX standards people, in their infinite wisdom,
1476 have seen fit to only allow this for processes which have the
1477 terminal as controlling terminal, which doesn't apply to us.
1479 Sooo..., we have to do something non-standard. The ioctls
1480 TIOCSIGNAL, TIOCSIG, and TIOCSIGSEND send the signal directly on
1481 many systems. POSIX tcgetpgrp(), since it is *documented* as not
1482 doing what we want, is actually less likely to work than the BSD
1483 ioctl TIOCGPGRP it is supposed to obsolete. Sometimes we have to
1484 use TIOCGPGRP on the master end, sometimes the slave end
1485 (probably an AIX bug). So we better get a fd for the slave if we
1488 Anal operating systems like SGI Irix and Compaq Tru64 adhere
1489 strictly to the letter of the law, so our hack doesn't work.
1490 The following fragment from an Irix header file is suggestive:
1493 // this is not currently supported
1494 #define TIOCSIGNAL (tIOC|31) // pty: send signal to slave
1497 On those systems where none of our tricks work, we just fall back
1498 to the non-current_group behavior and kill the process group of
1501 if (current_group) {
1502 try_to_initialize_subtty(d);
1504 #ifdef SIGNALS_VIA_CHARACTERS
1505 /* If possible, send signals to the entire pgrp
1506 by sending an input character to it. */
1508 char sigchar = process_signal_char(d->subtty, signo);
1510 send_process(proc, Qnil, (Bufbyte *) & sigchar,
1515 #endif /* SIGNALS_VIA_CHARACTERS */
1519 ioctl(d->infd, TIOCGPGRP, &pgid); /* BSD */
1520 if (pgid == -1 && d->subtty != -1)
1521 ioctl(d->subtty, TIOCGPGRP, &pgid); /* Only this works on AIX! */
1522 #endif /* TIOCGPGRP */
1525 /* Many systems provide an ioctl to send a signal directly */
1526 #ifdef TIOCSIGNAL /* Solaris, HP-UX */
1527 if (ioctl(d->infd, TIOCSIGNAL, signo) != -1)
1529 #endif /* TIOCSIGNAL */
1531 #ifdef TIOCSIG /* BSD */
1532 if (ioctl(d->infd, TIOCSIG, signo) != -1)
1534 #endif /* TIOCSIG */
1539 /* Either current_group is 0, or we failed to get the foreground
1540 process group using the trickery above. So we fall back to
1541 sending the signal to the process group of our child process.
1542 Since this is often a shell that ignores signals like SIGINT,
1543 the shell's subprocess is killed, which is the desired effect.
1544 The process group of p->pid is always p->pid, since it was
1545 created as a process group leader. */
1546 pgid = XINT(p->pid);
1548 /* Finally send the signal. */
1549 if (EMACS_KILLPG(pgid, signo) == -1) {
1550 /* It's not an error if our victim is already dead.
1551 And we can't rely on the result of killing a zombie, since
1552 XPG 4.2 requires that killing a zombie fail with ESRCH,
1553 while FIPS 151-2 requires that it succeeds! */
1557 error("kill (%ld, %ld) failed: %s",
1558 (long)pgid, (long)signo, strerror(errno));
1562 /* Send signal SIGCODE to any process in the system given its PID.
1563 Return zero if successful, a negative number upon failure. */
1565 static int unix_kill_process_by_pid(int pid, int sigcode)
1567 return kill(pid, sigcode);
1570 /* Return TTY name used to communicate with subprocess. */
1572 static Lisp_Object unix_get_tty_name(Lisp_Process * p)
1574 return UNIX_DATA(p)->tty_name;
1577 /* Canonicalize host name HOST, and return its canonical form.
1578 The default implementation just takes HOST for a canonical name. */
1581 static Lisp_Object unix_canonicalize_host_name(Lisp_Object host)
1583 #if defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO)
1584 struct addrinfo hints, *res;
1585 static char addrbuf[NI_MAXHOST];
1586 Lisp_Object canonname;
1591 hints.ai_flags = AI_CANONNAME;
1592 #ifdef IPV6_CANONICALIZE
1593 hints.ai_family = AF_UNSPEC;
1595 hints.ai_family = PF_INET;
1597 hints.ai_socktype = SOCK_STREAM;
1598 hints.ai_protocol = 0;
1599 LISP_STRING_TO_EXTERNAL(host, ext_host, Qnative);
1600 retval = getaddrinfo(ext_host, NULL, &hints, &res);
1604 EXTERNAL_TO_C_STRING(gai_strerror(retval),
1605 gai_error_l, Qnative);
1606 maybe_error(Qprocess, ERROR_ME_NOT,
1607 "%s \"%s\"", gai_error_l, XSTRING_DATA(host));
1610 int gni = getnameinfo(res->ai_addr, res->ai_addrlen,
1611 addrbuf, sizeof(addrbuf),
1612 NULL, 0, NI_NUMERICHOST);
1613 canonname = gni ? host : build_ext_string(addrbuf, Qnative);
1619 #else /* ! HAVE_GETADDRINFO */
1620 struct sockaddr_in address;
1622 if (!get_internet_address(host, &address, ERROR_ME_NOT))
1625 if (address.sin_family == AF_INET)
1626 return build_string(inet_ntoa(address.sin_addr));
1628 /* #### any clue what to do here? */
1630 #endif /* ! HAVE_GETADDRINFO */
1633 /* Open a TCP network connection to a given HOST/SERVICE.
1634 Treated exactly like a normal process when reading and writing.
1635 Only differences are in status display and process deletion.
1636 A network connection has no PID; you cannot signal it. All you can
1637 do is deactivate and close it via delete-process. */
1640 unix_open_network_stream(Lisp_Object name, Lisp_Object host,
1641 Lisp_Object service, Lisp_Object protocol,
1642 void **vinfd, void **voutfd)
1648 volatile int retry = 0;
1653 if (!EQ(protocol, Qtcp) && !EQ(protocol, Qudp))
1654 invalid_argument("Unsupported protocol", protocol);
1657 #if defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO)
1658 struct addrinfo hints, *res;
1659 struct addrinfo *volatile lres;
1661 volatile int xerrno = 0;
1662 volatile int failed_connect = 0;
1664 char portbuf[sizeof(long)*3 + 2];
1666 * Caution: service can either be a string or int.
1667 * Convert to a C string for later use by getaddrinfo.
1669 if (INTP(service)) {
1670 snprintf(portbuf, sizeof(portbuf), "%ld",
1671 (long)XINT(service));
1672 portstring = portbuf;
1673 port = htons((unsigned short)XINT(service));
1675 CHECK_STRING(service);
1676 LISP_STRING_TO_EXTERNAL(service, portstring, Qnative);
1682 hints.ai_family = AF_UNSPEC;
1683 if (EQ(protocol, Qtcp))
1684 hints.ai_socktype = SOCK_STREAM;
1685 else /* EQ (protocol, Qudp) */
1686 hints.ai_socktype = SOCK_DGRAM;
1687 hints.ai_protocol = 0;
1688 LISP_STRING_TO_EXTERNAL(host, ext_host, Qnative);
1689 retval = getaddrinfo(ext_host, portstring, &hints, &res);
1693 EXTERNAL_TO_C_STRING(gai_strerror(retval),
1694 gai_error_l, Qnative);
1695 error("%s/%s %s", XSTRING_DATA(host), portstring,
1700 for (lres = res; lres; lres = lres->ai_next) {
1701 if (EQ(protocol, Qtcp))
1702 s = socket(lres->ai_family, SOCK_STREAM, 0);
1703 else /* EQ (protocol, Qudp) */
1704 s = socket(lres->ai_family, SOCK_DGRAM, 0);
1709 /* Turn off interrupts here -- see comments below.
1710 There used to be code which called
1711 bind_polling_period() to slow the polling period down
1712 rather than turn it off, but that seems rather bogus
1713 to me. Best thing here is to use a non-blocking
1714 connect or something, to check for QUIT. */
1716 /* Comments that are not quite valid: */
1718 /* Kernel bugs (on Ultrix at least) cause lossage (not
1719 just EINTR) when connect is interrupted. So let's
1720 not let it get interrupted. Note we do not turn off
1721 polling, because polling is only used when not
1722 interrupt_input, and thus not normally used on the
1723 systems which have this bug. On systems which use
1724 polling, there's no way to quit if polling is turned
1727 /* Slow down polling. Some kernels have a bug which
1728 causes retrying connect to fail after a connect. */
1730 slow_down_interrupts();
1734 /* A system call interrupted with a SIGALRM or SIGIO
1735 comes back here, with can_break_system_calls reset to
1737 SETJMP(break_system_call_jump);
1739 speed_up_interrupts();
1741 /* In case something really weird happens ... */
1742 slow_down_interrupts();
1745 /* Break out of connect with a signal (it isn't
1746 otherwise possible). Thus you don't get screwed with
1748 can_break_system_calls = 1;
1749 retval = connect(s, lres->ai_addr, lres->ai_addrlen);
1750 can_break_system_calls = 0;
1753 if (errno != EISCONN) {
1756 if (errno == EADDRINUSE && retry < 20) {
1757 /* A delay here is needed on
1758 some FreeBSD systems, and
1759 it is harmless, since this
1760 retrying takes time anyway
1761 and should be infrequent.
1762 `sleep-for' allowed for
1763 quitting this loop with
1764 interrupts slowed down so
1765 it can't be used here.
1766 Async timers should already
1767 be disabled at this point
1768 so we can use `sleep'. */
1778 speed_up_interrupts();
1785 char servbuf[NI_MAXSERV];
1787 if (EQ(protocol, Qtcp))
1789 getnameinfo(lres->ai_addr,
1790 lres->ai_addrlen, NULL,
1794 else /* EQ (protocol, Qudp) */
1796 getnameinfo(lres->ai_addr,
1797 lres->ai_addrlen, NULL,
1804 port = strtol(servbuf, NULL, 10);
1808 } /* address loop */
1810 speed_up_interrupts();
1817 report_file_error("connection failed",
1820 report_file_error("error creating socket",
1823 #else /* ! HAVE_GETADDRINFO */
1824 struct sockaddr_in address;
1827 port = htons((unsigned short)XINT(service));
1829 struct servent *svc_info;
1830 CHECK_STRING(service);
1832 if (EQ(protocol, Qtcp))
1834 getservbyname((char *)XSTRING_DATA(service),
1836 else /* EQ (protocol, Qudp) */
1838 getservbyname((char *)XSTRING_DATA(service),
1842 invalid_argument("Unknown service", service);
1843 port = svc_info->s_port;
1846 get_internet_address(host, &address, ERROR_ME);
1847 address.sin_port = port;
1849 if (EQ(protocol, Qtcp))
1850 s = socket(address.sin_family, SOCK_STREAM, 0);
1851 else /* EQ (protocol, Qudp) */
1852 s = socket(address.sin_family, SOCK_DGRAM, 0);
1855 report_file_error("error creating socket", list1(name));
1857 /* Turn off interrupts here -- see comments below. There used to
1858 be code which called bind_polling_period() to slow the polling
1859 period down rather than turn it off, but that seems rather
1860 bogus to me. Best thing here is to use a non-blocking connect
1861 or something, to check for QUIT. */
1863 /* Comments that are not quite valid: */
1865 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
1866 when connect is interrupted. So let's not let it get interrupted.
1867 Note we do not turn off polling, because polling is only used
1868 when not interrupt_input, and thus not normally used on the systems
1869 which have this bug. On systems which use polling, there's no way
1870 to quit if polling is turned off. */
1872 /* Slow down polling. Some kernels have a bug which causes retrying
1873 connect to fail after a connect. */
1875 slow_down_interrupts();
1879 /* A system call interrupted with a SIGALRM or SIGIO comes back
1880 here, with can_break_system_calls reset to 0. */
1881 SETJMP(break_system_call_jump);
1883 speed_up_interrupts();
1885 /* In case something really weird happens ... */
1886 slow_down_interrupts();
1889 /* Break out of connect with a signal (it isn't otherwise possible).
1890 Thus you don't get screwed with a hung network. */
1891 can_break_system_calls = 1;
1893 connect(s, (struct sockaddr *)&address, sizeof(address));
1894 can_break_system_calls = 0;
1895 if (retval == -1 && errno != EISCONN) {
1899 if (errno == EADDRINUSE && retry < 20) {
1900 /* A delay here is needed on some FreeBSD
1901 systems, and it is harmless, since this
1902 retrying takes time anyway and should
1903 be infrequent. `sleep-for' allowed for
1904 quitting this loop with interrupts
1905 slowed down so it can't be used here.
1906 Async timers should already be disabled
1907 at this point so we can use `sleep'. */
1914 speed_up_interrupts();
1917 report_file_error("connection failed",
1921 speed_up_interrupts();
1922 #endif /* ! HAVE_GETADDRINFO */
1928 close(s); /* this used to be leaked; from Kyle Jones */
1929 report_file_error("error duplicating socket", list1(name));
1932 set_socket_nonblocking_maybe(inch, port, "tcp");
1934 *vinfd = (void *)inch;
1935 *voutfd = (void *)outch;
1940 Return the listener process of the accepted listened process
1942 static Lisp_Object unix_network_process_listener(Lisp_Object process)
1944 Lisp_Process *listener = 0,
1945 *p = XPROCESS(process);
1946 Lisp_Object ret = Qnil;
1948 struct gcpro ngcpro1;
1950 if (!PROCESS_READABLE_P(p))
1953 if (!CONSP(p->pid) || NILP(XCDR(XCDR(p->pid))))
1957 sock = XINT(XCAR(XCDR(p->pid)));
1958 listener = get_process_from_usid(FD_TO_USID(sock));
1959 ret = listener ? (Lisp_Object)listener : Qnil;
1965 Unwind a call to the network server stream accept below
1967 static Lisp_Object exec_acceptor_unwind(Lisp_Object datum)
1969 Lisp_Cons *d = XCONS(datum);
1976 Accept a connection being listened in the given network server
1978 Create a new network stream for the accepted connection.
1979 Call the acceptor callback and setup the sentinel and filter functions
1981 static void unix_network_server_accept(Lisp_Object process)
1983 Lisp_Process *p = XPROCESS(process);
1984 Lisp_Object np = Qnil;
1985 Lisp_Object acceptor = Qnil, filter = Qnil, sentinel = Qnil;
1986 Lisp_Object bufname = Qnil;
1987 Lisp_Object buffer = Qnil;
1988 long int ns, inch, outch;
1989 struct sockaddr_in sa;
1990 int sa_size = sizeof(sa);
1991 struct gcpro ngcpro1, ngcpro2, ngcpro3, ngcpro4, ngcpro5;
1993 if (!PROCESS_READABLE_P(p))
1996 /* Make sure the listen process is not disconnected
1997 afterwards. We have to make this here because in process.c
1998 we should not have any knowledge we need to do this, and in
1999 unix_open_network_server_stream we have no access to the
2000 process struct. It works, so I'm not complaining...
2002 UNIX_DATA(p)->connected_via_filedesc_p = 1;
2004 errno = 0; /* if we got an error, let it be from the accept call */
2005 ns = accept((int)UNIX_DATA(p)->infd, (struct sockaddr*)(&sa),
2006 (socklen_t*)&sa_size);
2010 NGCPRO5(np,bufname,acceptor,filter,sentinel);
2011 if (CONSP(p->process_type_data)) {
2012 acceptor = XCAR(p->process_type_data);
2013 filter = XCDR(p->process_type_data);
2014 if (CONSP(filter)) {
2015 sentinel = XCDR(filter);
2016 filter = XCAR(filter);
2018 if (CONSP(sentinel)) {
2019 bufname = XCDR(sentinel);
2020 sentinel = XCAR(sentinel);
2022 if (CONSP(bufname)) {
2023 bufname = XCAR(bufname);
2026 if (!NILP(bufname)) {
2027 Lisp_Object args[] = {
2028 build_string("<server port:%S listened_on:%S>"),
2029 make_int(sa.sin_port), bufname
2031 bufname = Fformat( 3, args );
2033 Lisp_Object args[] = {
2034 build_string("<server proc:%S pid:%S service:%S>"),
2035 p->name, p->pid, make_int(sa.sin_port)
2037 bufname = Fformat( 5, args );
2039 if (!NILP(bufname) ) {
2040 bufname = Fgenerate_new_buffer_name(bufname,Qnil);
2041 buffer = Fget_buffer_create(bufname);
2043 np = make_process_internal(p->name);
2044 XPROCESS(np)->pid = Fcons( make_int(sa.sin_port),
2045 Fcons(make_int(UNIX_DATA(p)->infd),p->pid));
2046 XPROCESS(np)->process_type = PROCESS_TYPE_NETWORK;
2047 XPROCESS(np)->buffer = buffer;
2050 set_socket_nonblocking_maybe(inch, sa.sin_port, "tcp");
2051 init_process_io_handles(XPROCESS(np), (void *)inch, (void *)outch,
2052 STREAM_NETWORK_CONNECTION);
2053 /* Process the call backs.. */
2054 if (CONSP(p->process_type_data)) {
2055 if (!NILP(filter)) {
2056 XPROCESS(np)->filter = filter;
2058 if (!NILP(sentinel)) {
2059 XPROCESS(np)->sentinel = sentinel;
2061 if (!NILP(acceptor)) {
2062 int speccount = specpdl_depth();
2063 record_unwind_protect(exec_acceptor_unwind,
2064 noseeum_cons(process, acceptor));
2065 running_asynch_code = 1;
2066 call1_trapping_errors("Error in server stream acceptor",
2068 running_asynch_code = 0;
2069 restore_match_data();
2070 unbind_to(speccount, Qnil);
2074 /* We have to log something here... */
2076 event_stream_select_process(XPROCESS(np));
2080 /* Open a TCP network connection to a given HOST/SERVICE.
2081 Treated exactly like a normal process when reading and writing.
2082 Only differences are in status display and process deletion.
2083 A network connection has no PID; you cannot signal it. All you can
2084 do is deactivate and close it via delete-process. */
2087 unix_open_network_server_stream(Lisp_Object name, Lisp_Object host,
2088 Lisp_Object service, Lisp_Object protocol,
2089 void **vinfd, void **voutfd)
2095 volatile int retry = 0;
2097 /* FIXME: Limited to 5 since it is the maximum for several BSD
2098 based implementations of sockets, and it is an acceptable
2099 value for a low rate of service purpose like this facility
2100 was designed for. */
2104 if (!EQ(protocol, Qtcp) && !EQ(protocol, Qudp))
2105 invalid_argument("Unsupported protocol", protocol);
2108 #if defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO)
2109 struct addrinfo hints, *res;
2110 struct addrinfo *volatile lres;
2112 volatile int xerrno = 0;
2113 volatile int failed_connect = 0;
2115 char portbuf[sizeof(long)*3 + 2];
2117 * Caution: service can either be a string or int.
2118 * Convert to a C string for later use by getaddrinfo.
2120 if (INTP(service)) {
2121 snprintf(portbuf, sizeof(portbuf), "%ld",
2122 (long)XINT(service));
2123 portstring = portbuf;
2124 port = htons((unsigned short)XINT(service));
2126 CHECK_STRING(service);
2127 LISP_STRING_TO_EXTERNAL(service, portstring, Qnative);
2133 hints.ai_family = AF_UNSPEC;
2134 if (EQ(protocol, Qtcp))
2135 hints.ai_socktype = SOCK_STREAM;
2136 else /* EQ (protocol, Qudp) */
2137 hints.ai_socktype = SOCK_DGRAM;
2138 hints.ai_protocol = 0;
2139 if (SYMBOLP(host) ) {
2140 if (EQ(host,Qip_any)) {
2141 hints.ai_flags |= AI_PASSIVE;
2142 } else if (!EQ(host,Qlocalhost)) {
2143 invalid_argument("invalid host ",host);
2145 /* If using localhost, not passing
2146 AI_PASSIVE will cause getaddrinfo
2147 to return a proper addr spec for
2148 listening only to local
2151 retval = getaddrinfo(NULL, portstring, &hints, &res);
2154 LISP_STRING_TO_EXTERNAL(host, ext_host, Qnative);
2155 retval = getaddrinfo(ext_host, portstring, &hints, &res);
2160 EXTERNAL_TO_C_STRING(gai_strerror(retval),
2161 gai_error_l, Qnative);
2162 error("%s/%s %s", XSTRING_DATA(host), portstring,
2167 for (lres = res; lres; lres = lres->ai_next) {
2168 if (EQ(protocol, Qtcp))
2169 s = socket(lres->ai_family, SOCK_STREAM, 0);
2170 else /* EQ (protocol, Qudp) */
2171 s = socket(lres->ai_family, SOCK_DGRAM, 0);
2176 /* Turn off interrupts here -- see comments below.
2177 There used to be code which called
2178 bind_polling_period() to slow the polling period down
2179 rather than turn it off, but that seems rather bogus
2180 to me. Best thing here is to use a non-blocking
2181 connect or something, to check for QUIT. */
2183 /* Comments that are not quite valid: */
2185 /* Kernel bugs (on Ultrix at least) cause lossage (not
2186 just EINTR) when connect is interrupted. So let's
2187 not let it get interrupted. Note we do not turn off
2188 polling, because polling is only used when not
2189 interrupt_input, and thus not normally used on the
2190 systems which have this bug. On systems which use
2191 polling, there's no way to quit if polling is turned
2194 /* Slow down polling. Some kernels have a bug which
2195 causes retrying connect to fail after a connect. */
2197 slow_down_interrupts();
2201 /* A system call interrupted with a SIGALRM or SIGIO
2202 comes back here, with can_break_system_calls reset to
2204 SETJMP(break_system_call_jump);
2206 speed_up_interrupts();
2208 /* In case something really weird happens ... */
2209 slow_down_interrupts();
2212 /* Break out of connect with a signal (it isn't
2213 otherwise possible). Thus you don't get screwed with
2215 can_break_system_calls = 1;
2216 retval = bind(s, lres->ai_addr, lres->ai_addrlen);
2218 retval = listen(s, listenQ);
2219 can_break_system_calls = 0;
2222 if (errno != EISCONN) {
2225 if (errno == EADDRINUSE && retry < 20) {
2226 /* A delay here is needed on
2227 some FreeBSD systems, and it
2228 is harmless, since this
2229 retrying takes time anyway
2230 and should be infrequent.
2231 `sleep-for' allowed for
2232 quitting this loop with
2233 interrupts slowed down so it
2234 can't be used here. Async
2235 timers should already be
2236 disabled at this point so we
2247 speed_up_interrupts();
2254 char servbuf[NI_MAXSERV];
2256 if (EQ(protocol, Qtcp))
2258 getnameinfo(lres->ai_addr,
2259 lres->ai_addrlen, NULL,
2263 else /* EQ (protocol, Qudp) */
2265 getnameinfo(lres->ai_addr,
2266 lres->ai_addrlen, NULL,
2273 port = strtol(servbuf, NULL, 10);
2277 } /* address loop */
2279 speed_up_interrupts();
2286 report_file_error("bind failed",
2289 report_file_error("error creating socket",
2292 #else /* ! HAVE_GETADDRINFO */
2293 struct sockaddr_in address;
2296 port = htons((unsigned short)XINT(service));
2298 struct servent *svc_info;
2299 CHECK_STRING(service);
2301 if (EQ(protocol, Qtcp))
2303 getservbyname((char *)XSTRING_DATA(service),
2305 else /* EQ (protocol, Qudp) */
2307 getservbyname((char *)XSTRING_DATA(service),
2311 invalid_argument("Unknown service", service);
2312 port = svc_info->s_port;
2314 if (SYMBOLP(host)) {
2315 if (EQ(host,Qip_any)) {
2316 address.sin_addr.s_host = htonl(INADDR_ANY);
2317 } else if (EQ(host,Qlocalhost)) {
2318 address.sin_addr.s_host = htonl(INADDR_LOOPBACK);
2320 invalid_argument("invalid host ",host);
2323 get_internet_address(host, &address, ERROR_ME);
2325 address.sin_port = port;
2327 if (EQ(protocol, Qtcp))
2328 s = socket(address.sin_family, SOCK_STREAM, 0);
2329 else /* EQ (protocol, Qudp) */
2330 s = socket(address.sin_family, SOCK_DGRAM, 0);
2333 report_file_error("error creating socket", list1(name));
2335 /* Turn off interrupts here -- see comments below. There used to
2336 be code which called bind_polling_period() to slow the polling
2337 period down rather than turn it off, but that seems rather
2338 bogus to me. Best thing here is to use a non-blocking connect
2339 or something, to check for QUIT. */
2341 /* Comments that are not quite valid: */
2343 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
2344 when connect is interrupted. So let's not let it get interrupted.
2345 Note we do not turn off polling, because polling is only used
2346 when not interrupt_input, and thus not normally used on the systems
2347 which have this bug. On systems which use polling, there's no way
2348 to quit if polling is turned off. */
2350 /* Slow down polling. Some kernels have a bug which causes retrying
2351 connect to fail after a connect. */
2353 slow_down_interrupts();
2357 /* A system call interrupted with a SIGALRM or SIGIO comes back
2358 here, with can_break_system_calls reset to 0. */
2359 SETJMP(break_system_call_jump);
2361 speed_up_interrupts();
2363 /* In case something really weird happens ... */
2364 slow_down_interrupts();
2367 /* Break out of connect with a signal (it isn't otherwise possible).
2368 Thus you don't get screwed with a hung network. */
2369 can_break_system_calls = 1;
2371 bind(s, (struct sockaddr *)&address, sizeof(address));
2373 listen( s, listenQ ); /* @@@ FIXME: This should be a parameter */
2374 can_break_system_calls = 0;
2375 if (retval == -1 && errno != EISCONN) {
2379 if (errno == EADDRINUSE && retry < 20) {
2380 /* A delay here is needed on some FreeBSD
2381 systems, and it is harmless, since this
2382 retrying takes time anyway and should be
2383 infrequent. `sleep-for' allowed for quitting
2384 this loop with interrupts slowed down so it
2385 can't be used here. Async timers should
2386 already be disabled at this point so we can
2394 speed_up_interrupts();
2397 report_file_error("connection failed",
2401 speed_up_interrupts();
2402 #endif /* ! HAVE_GETADDRINFO */
2408 close(s); /* this used to be leaked; from Kyle Jones */
2409 report_file_error("error duplicating socket", list1(name));
2412 set_socket_nonblocking_maybe(inch, port, "tcp");
2414 *vinfd = (void *)inch;
2415 *voutfd = (void *)outch;
2419 #ifdef HAVE_MULTICAST
2421 /* Didier Verna <didier@xemacs.org> Nov. 28 1997.
2423 This function is similar to open-network-stream-internal, but provides a
2424 mean to open an UDP multicast connection instead of a TCP one. Like in the
2425 TCP case, the multicast connection will be seen as a sub-process,
2428 - Normally, we should use sendto and recvfrom with non connected
2429 sockets. The current code doesn't allow us to do this. In the future, it
2430 would be a good idea to extend the process data structure in order to deal
2431 properly with the different types network connections.
2432 - For the same reason, when leaving a multicast group, it is better to make
2433 a setsockopt - IP_DROP_MEMBERSHIP before closing the descriptors.
2434 Unfortunately, this can't be done here because delete_process doesn't know
2435 about the kind of connection we have. However, this is not such an
2440 unix_open_multicast_group(Lisp_Object name, Lisp_Object dest,
2441 Lisp_Object port, Lisp_Object ttl, void **vinfd,
2445 struct sockaddr_in sa;
2446 struct protoent *udp;
2449 unsigned char thettl;
2450 int one = 1; /* For REUSEADDR */
2452 volatile int retry = 0;
2457 theport = htons((unsigned short)XINT(port));
2460 thettl = (unsigned char)XINT(ttl);
2462 if ((udp = getprotobyname("udp")) == NULL)
2463 type_error(Qinvalid_operation,
2464 "No info available for UDP protocol");
2466 /* Init the sockets. Yes, I need 2 sockets. I couldn't duplicate one. */
2467 if ((rs = socket(PF_INET, SOCK_DGRAM, udp->p_proto)) < 0)
2468 report_file_error("error creating socket", list1(name));
2469 if ((ws = socket(PF_INET, SOCK_DGRAM, udp->p_proto)) < 0) {
2471 report_file_error("error creating socket", list1(name));
2474 /* This will be used for both sockets */
2475 memset(&sa, 0, sizeof(sa));
2476 sa.sin_family = AF_INET;
2477 sa.sin_port = theport;
2478 sa.sin_addr.s_addr = inet_addr((char *)XSTRING_DATA(dest));
2480 /* Socket configuration for reading ------------------------ */
2482 /* Multiple connections from the same machine. This must be done before
2483 bind. If it fails, it shouldn't be fatal. The only consequence is that
2484 people won't be able to connect twice from the same machine. */
2485 if (setsockopt(rs, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one))
2487 warn_when_safe(Qmulticast, Qwarning,
2488 "Cannot reuse socket address");
2490 /* bind socket name */
2491 if (bind(rs, (struct sockaddr *)&sa, sizeof(sa))) {
2494 report_file_error("error binding socket", list2(name, port));
2497 /* join multicast group */
2498 imr.imr_multiaddr.s_addr = inet_addr((char *)XSTRING_DATA(dest));
2499 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2500 if (setsockopt(rs, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2501 &imr, sizeof(struct ip_mreq)) < 0) {
2504 report_file_error("error adding membership", list2(name, dest));
2507 /* Socket configuration for writing ----------------------- */
2509 /* Normally, there's no 'connect' in multicast, since we prefer to use
2510 'sendto' and 'recvfrom'. However, in order to handle this connection
2511 in the process-like way it is done for TCP, we must be able to use
2512 'write' instead of 'sendto'. Consequently, we 'connect' this
2515 /* See open-network-stream-internal for comments on this part of the
2517 slow_down_interrupts();
2521 /* A system call interrupted with a SIGALRM or SIGIO comes back
2522 here, with can_break_system_calls reset to 0. */
2523 SETJMP(break_system_call_jump);
2525 speed_up_interrupts();
2527 /* In case something really weird happens ... */
2528 slow_down_interrupts();
2531 /* Break out of connect with a signal (it isn't otherwise possible).
2532 Thus you don't get screwed with a hung network. */
2533 can_break_system_calls = 1;
2534 ret = connect(ws, (struct sockaddr *)&sa, sizeof(sa));
2535 can_break_system_calls = 0;
2536 if (ret == -1 && errno != EISCONN) {
2541 if (errno == EADDRINUSE && retry < 20) {
2542 /* A delay here is needed on some FreeBSD systems, and
2543 it is harmless, since this retrying takes time anyway
2544 and should be infrequent. `sleep-for' allowed for
2545 quitting this loop with interrupts slowed down so it
2546 can't be used here. Async timers should already be
2547 disabled at this point so we can use `sleep'. */
2554 speed_up_interrupts();
2557 report_file_error("error connecting socket", list2(name, port));
2560 speed_up_interrupts();
2563 if (setsockopt(ws, IPPROTO_IP, IP_MULTICAST_TTL,
2564 &thettl, sizeof(thettl)) < 0) {
2567 report_file_error("error setting ttl", list2(name, ttl));
2570 set_socket_nonblocking_maybe(rs, theport, "udp");
2572 *vinfd = (void *)rs;
2573 *voutfd = (void *)ws;
2576 #endif /* HAVE_MULTICAST */
2578 #endif /* HAVE_SOCKETS */
2580 /**********************************************************************/
2581 /* Initialization */
2582 /**********************************************************************/
2584 void process_type_create_unix(void)
2586 PROCESS_HAS_METHOD(unix, alloc_process_data);
2587 PROCESS_HAS_METHOD(unix, mark_process_data);
2589 PROCESS_HAS_METHOD(unix, init_process);
2590 PROCESS_HAS_METHOD(unix, reap_exited_processes);
2592 PROCESS_HAS_METHOD(unix, init_process_io_handles);
2593 PROCESS_HAS_METHOD(unix, create_process);
2594 PROCESS_HAS_METHOD(unix, set_window_size);
2596 PROCESS_HAS_METHOD(unix, update_status_if_terminated);
2598 PROCESS_HAS_METHOD(unix, send_process);
2599 PROCESS_HAS_METHOD(unix, process_send_eof);
2600 PROCESS_HAS_METHOD(unix, deactivate_process);
2601 PROCESS_HAS_METHOD(unix, kill_child_process);
2602 PROCESS_HAS_METHOD(unix, kill_process_by_pid);
2603 PROCESS_HAS_METHOD(unix, get_tty_name);
2605 PROCESS_HAS_METHOD(unix, canonicalize_host_name);
2606 PROCESS_HAS_METHOD(unix, open_network_stream);
2607 PROCESS_HAS_METHOD(unix, open_network_server_stream);
2608 PROCESS_HAS_METHOD(unix, network_server_accept);
2609 PROCESS_HAS_METHOD(unix, network_process_listener);
2610 #ifdef HAVE_MULTICAST
2611 PROCESS_HAS_METHOD(unix, open_multicast_group);
2616 void vars_of_process_unix(void)
2618 Fprovide(intern("unix-processes"));
2621 #endif /* !defined (NO_SUBPROCESSES) */