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 XEmacs.
9 XEmacs is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
14 XEmacs is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
19 You should have received a copy of the GNU General Public License
20 along with XEmacs; see the file COPYING. If not, write to
21 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 Boston, MA 02111-1307, USA. */
24 /* This file has been Mule-ized except for `start-process-internal',
25 `open-network-stream-internal' and `open-multicast-group-internal'. */
27 /* This file has been split into process.c and process-unix.c by
28 Kirill M. Katsnelson <kkm@kis.ru>, so please bash him and not
29 the original author(s) */
31 /* The IPv6 support is derived from the code for GNU Emacs-20.3
32 written by Wolfgang S. Rupprecht */
36 #if !defined (NO_SUBPROCESSES)
38 /* The entire file is within this conditional */
53 #include "file-coding.h"
60 #include "syssignal.h" /* Always include before systty.h */
65 #include <grp.h> /* See grantpt fixups for HPUX below. */
69 * Implementation-specific data. Pointed to by Lisp_Process->process_data
72 struct unix_process_data
74 /* Non-0 if this is really a ToolTalk channel. */
75 int connected_via_filedesc_p;
76 /* Descriptor by which we read from this process. -1 for dead process */
78 /* Descriptor for the tty which this process is using.
79 -1 if we didn't record it (on some systems, there's no need). */
81 /* Name of subprocess terminal. */
83 /* Non-false if communicating through a pty. */
87 #define UNIX_DATA(p) ((struct unix_process_data*)((p)->process_data))
91 /**********************************************************************/
92 /* Static helper routines */
93 /**********************************************************************/
96 close_safely_handler (int signo)
98 EMACS_REESTABLISH_SIGNAL (signo, close_safely_handler);
103 close_safely (int fd)
106 signal (SIGALRM, close_safely_handler);
114 close_descriptor_pair (int in, int out)
118 if (out != in && out >= 0)
122 /* Close all descriptors currently in use for communication
123 with subprocess. This is used in a newly-forked subprocess
124 to get rid of irrelevant descriptors. */
127 close_process_descs_mapfun (const void* key, void* contents, void* arg)
130 CVOID_TO_LISP (proc, contents);
131 event_stream_delete_stream_pair (XPROCESS(proc)->pipe_instream,
132 XPROCESS(proc)->pipe_outstream);
136 /* #### This function is currently called from child_setup
137 in callproc.c. It should become static though - kkm */
139 close_process_descs (void)
141 maphash (close_process_descs_mapfun, usid_to_process, 0);
144 /* connect to an existing file descriptor. This is very similar to
145 open-network-stream except that it assumes that the connection has
146 already been initialized. It is currently used for ToolTalk
149 /* This function used to be visible on the Lisp level, but there is no
150 real point in doing that. Here is the doc string:
152 "Connect to an existing file descriptor.
153 Return a subprocess-object to represent the connection.
154 Input and output work as for subprocesses; `delete-process' closes it.
155 Args are NAME BUFFER INFD OUTFD.
156 NAME is name for process. It is modified if necessary to make it unique.
157 BUFFER is the buffer (or buffer-name) to associate with the process.
158 Process output goes at end of that buffer, unless you specify
159 an output stream or filter function to handle the output.
160 BUFFER may also be nil, meaning that this process is not associated
162 INFD and OUTFD specify the file descriptors to use for input and
163 output, respectively."
167 connect_to_file_descriptor (Lisp_Object name, Lisp_Object buffer,
168 Lisp_Object infd, Lisp_Object outfd)
170 /* This function can GC */
179 if (get_process_from_usid (FD_TO_USID (inch)))
180 invalid_operation ("There is already a process connected to fd", infd);
182 buffer = Fget_buffer_create (buffer);
183 proc = make_process_internal (name);
185 XPROCESS (proc)->pid = Fcons (infd, name);
186 XPROCESS (proc)->buffer = buffer;
187 init_process_io_handles (XPROCESS (proc), (void*)inch, (void*)XINT (outfd),
189 UNIX_DATA (XPROCESS (proc))->connected_via_filedesc_p = 1;
191 event_stream_select_process (XPROCESS (proc));
197 static int allocate_pty_the_old_fashioned_way (void);
199 /* The file name of the (slave) pty opened by allocate_pty(). */
200 #ifndef MAX_PTYNAME_LEN
201 #define MAX_PTYNAME_LEN 64
203 static char pty_name[MAX_PTYNAME_LEN];
205 /* Open an available pty, returning a file descriptor.
206 Return -1 on failure.
207 The file name of the terminal corresponding to the pty
208 is left in the variable `pty_name'. */
213 /* Unix98 standardized grantpt, unlockpt, and ptsname, but not the
214 functions required to open a master pty in the first place :-(
216 Modern Unix systems all seems to have convenience methods to open
217 a master pty fd in one function call, but there is little
218 agreement on how to do it.
220 allocate_pty() tries all the different known easy ways of opening
221 a pty. In case of failure, we resort to the old BSD-style pty
222 grovelling code in allocate_pty_the_old_fashioned_way(). */
223 #ifndef FORCE_ALLOCATE_PTY_THE_OLD_FASHIONED_WAY
225 const char *slave_name = NULL;
226 const char *clone = NULL;
227 static const char * const clones[] = /* Different pty master clone devices */
229 "/dev/ptmx", /* Various systems */
230 "/dev/ptm/clone", /* HPUX */
231 "/dev/ptc", /* AIX */
232 "/dev/ptmx_bsd" /* Tru64 */
235 #ifdef HAVE_GETPT /* glibc */
236 master_fd = getpt ();
239 #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);
251 slave_name = ttyname (slave_fd);
253 goto have_slave_name;
263 #endif /* HAVE_OPENPTY */
265 #if defined(HAVE__GETPTY) && defined (O_NDELAY) /* SGI */
267 EMACS_BLOCK_SIGNAL (SIGCHLD);
268 slave_name = _getpty (&master_fd, O_RDWR | O_NDELAY, 0600, 0);
269 EMACS_UNBLOCK_SIGNAL (SIGCHLD);
270 if (master_fd >= 0 && slave_name != NULL)
271 goto have_slave_name;
272 #endif /* HAVE__GETPTY */
274 /* Master clone devices are available on most systems */
277 for (i = 0; i < countof (clones); i++)
280 master_fd = open (clone, O_RDWR | O_NONBLOCK | OPEN_BINARY, 0);
291 #if defined (HAVE_PTSNAME)
292 slave_name = ptsname (master_fd);
294 goto have_slave_name;
297 /* AIX docs say to use ttyname, not ptsname, to get slave_name */
299 && !strcmp (clone, "/dev/ptc")
300 && (slave_name = ttyname (master_fd)) != NULL)
301 goto have_slave_name;
306 strncpy (pty_name, slave_name, sizeof (pty_name));
307 pty_name[sizeof (pty_name) - 1] = '\0';
308 setup_pty (master_fd);
310 /* We jump through some hoops to frob the pty.
311 It's not obvious that checking the return code here is useful. */
313 /* "The grantpt() function will fail if it is unable to successfully
314 invoke the setuid root program. It may also fail if the
315 application has installed a signal handler to catch SIGCHLD
317 #if defined (HAVE_GRANTPT) || defined (HAVE_UNLOCKPT)
318 EMACS_BLOCK_SIGNAL (SIGCHLD);
320 #if defined (HAVE_GRANTPT)
323 /* grantpt() behavior on some versions of HP-UX differs from what's
324 specified in the man page: the group of the slave PTY is set to
325 the user's primary group, and we fix that. */
327 struct group *tty_group = getgrnam ("tty");
328 if (tty_group != NULL)
329 chown (pty_name, (uid_t) -1, tty_group->gr_gid);
331 #endif /* HPUX has broken grantpt() */
332 #endif /* HAVE_GRANTPT */
334 #if defined (HAVE_UNLOCKPT)
335 unlockpt (master_fd);
338 EMACS_UNBLOCK_SIGNAL (SIGCHLD);
339 #endif /* HAVE_GRANTPT || HAVE_UNLOCKPT */
346 #endif /* ndef FORCE_ALLOCATE_PTY_THE_OLD_FASHIONED_WAY */
347 return allocate_pty_the_old_fashioned_way ();
350 /* This function tries to allocate a pty by iterating through file
351 pairs with names like /dev/ptyp1 and /dev/ttyp1. */
353 allocate_pty_the_old_fashioned_way (void)
357 /* Some systems name their pseudoterminals so that there are gaps in
358 the usual sequence - for example, on HP9000/S700 systems, there
359 are no pseudoterminals with names ending in 'f'. So we wait for
360 three failures in a row before deciding that we've reached the
362 int failed_count = 0;
370 # ifndef FIRST_PTY_LETTER
371 # define FIRST_PTY_LETTER 'p'
373 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
374 for (i = 0; i < 16; i++)
375 #endif /* PTY_ITERATION */
378 #ifdef PTY_NAME_SPRINTF
381 sprintf (pty_name, "/dev/pty%c%x", c, i);
382 #endif /* no PTY_NAME_SPRINTF */
384 if (xemacs_stat (pty_name, &stb) < 0)
386 if (++failed_count >= 3)
391 fd = open (pty_name, O_RDWR | O_NONBLOCK | OPEN_BINARY, 0);
395 #ifdef PTY_TTY_NAME_SPRINTF
398 sprintf (pty_name, "/dev/tty%c%x", c, i);
399 #endif /* no PTY_TTY_NAME_SPRINTF */
400 if (access (pty_name, R_OK | W_OK) == 0)
410 #endif /* HAVE_PTYS */
413 create_bidirectional_pipe (int *inchannel, 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 */
426 if (temp < 0) return -1;
430 if (temp < 0) return -1;
433 #endif /* not SKTPAIR */
440 #if !(defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO))
442 get_internet_address (Lisp_Object host, struct sockaddr_in *address,
445 struct hostent *host_info_ptr = NULL;
455 if (count++ > 10) break;
456 #ifndef BROKEN_CYGWIN
460 /* Some systems can't handle SIGIO/SIGALARM in gethostbyname. */
461 slow_down_interrupts ();
462 host_info_ptr = gethostbyname ((char *) XSTRING_DATA (host));
463 speed_up_interrupts ();
465 if (! (host_info_ptr == 0 && h_errno == TRY_AGAIN))
468 Fsleep_for (make_int (1));
472 address->sin_family = host_info_ptr->h_addrtype;
473 memcpy (&address->sin_addr, host_info_ptr->h_addr, host_info_ptr->h_length);
477 IN_ADDR numeric_addr;
478 /* Attempt to interpret host as numeric inet address */
479 numeric_addr = inet_addr ((char *) XSTRING_DATA (host));
480 if (NUMERIC_ADDR_ERROR)
482 maybe_error (Qprocess, errb,
483 "Unknown host \"%s\"", XSTRING_DATA (host));
487 /* There was some broken code here that called strlen() here
488 on (char *) &numeric_addr and even sometimes accessed
489 uninitialized data. */
490 address->sin_family = AF_INET;
491 * (IN_ADDR *) &address->sin_addr = numeric_addr;
496 #endif /* !(HAVE_GETADDRINFO && HAVE_GETNAMEINFO) */
499 set_socket_nonblocking_maybe (int fd, int port, const char* proto)
501 #ifdef PROCESS_IO_BLOCKING
504 for (tail = network_stream_blocking_port_list; CONSP (tail); tail = XCDR (tail))
506 Lisp_Object tail_port = XCAR (tail);
508 if (STRINGP (tail_port))
510 struct servent *svc_info;
511 CHECK_STRING (tail_port);
512 svc_info = getservbyname ((char *) XSTRING_DATA (tail_port), proto);
513 if ((svc_info != 0) && (svc_info->s_port == port))
518 else if (INTP (tail_port) && (htons ((unsigned short) XINT (tail_port)) == port))
524 set_descriptor_non_blocking (fd);
527 set_descriptor_non_blocking (fd);
528 #endif /* PROCESS_IO_BLOCKING */
531 #endif /* HAVE_SOCKETS */
533 /* Compute the Lisp form of the process status from
534 the numeric status that was returned by `wait'. */
537 update_status_from_wait_code (Lisp_Process *p, int *w_fmh)
539 /* C compiler lossage when attempting to pass w directly */
544 p->status_symbol = Qstop;
545 p->exit_code = WSTOPSIG (w);
548 else if (WIFEXITED (w))
550 p->status_symbol = Qexit;
551 p->exit_code = WEXITSTATUS (w);
554 else if (WIFSIGNALED (w))
556 p->status_symbol = Qsignal;
557 p->exit_code = WTERMSIG (w);
558 p->core_dumped = WCOREDUMP (w);
562 p->status_symbol = Qrun;
569 #define MAX_EXITED_PROCESSES 1000
570 static volatile pid_t exited_processes[MAX_EXITED_PROCESSES];
571 static volatile int exited_processes_status[MAX_EXITED_PROCESSES];
572 static volatile int exited_processes_index;
574 static volatile int sigchld_happened;
576 /* On receipt of a signal that a child status has changed,
577 loop asking about children with changed statuses until
578 the system says there are no more. All we do is record
579 the processes and wait status.
581 This function could be called from within the SIGCHLD
582 handler, so it must be completely reentrant. When
583 not called from a SIGCHLD handler, BLOCK_SIGCHLD should
584 be non-zero so that SIGCHLD is blocked while this
585 function is running. (This is necessary so avoid
586 race conditions with the SIGCHLD_HAPPENED flag). */
589 record_exited_processes (int block_sigchld)
591 if (!sigchld_happened)
596 #ifdef EMACS_BLOCK_SIGNAL
598 EMACS_BLOCK_SIGNAL (SIGCHLD);
601 while (sigchld_happened)
606 /* Keep trying to get a status until we get a definitive result. */
613 # endif /* not WUNTRACED */
615 pid = waitpid ((pid_t) -1, &w, WNOHANG | WUNTRACED);
617 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
619 #else /* not WNOHANG */
621 #endif /* not WNOHANG */
623 while (pid <= 0 && errno == EINTR);
628 if (exited_processes_index < MAX_EXITED_PROCESSES)
630 exited_processes[exited_processes_index] = pid;
631 exited_processes_status[exited_processes_index] = w;
632 exited_processes_index++;
635 /* On systems with WNOHANG, we just ignore the number
636 of times that SIGCHLD was signalled, and keep looping
637 until there are no more processes to wait on. If we
638 don't have WNOHANG, we have to rely on the count in
642 #endif /* not WNOHANG */
645 sigchld_happened = 0;
648 EMACS_UNBLOCK_SIGNAL (SIGCHLD);
651 /* For any processes that have changed status and are recorded
652 and such, update the corresponding Lisp_Process.
653 We separate this from record_exited_processes() so that
654 we never have to call this function from within a signal
655 handler. We block SIGCHLD in case record_exited_processes()
656 is called from a signal handler. */
658 /** USG WARNING: Although it is not obvious from the documentation
659 in signal(2), on a USG system the SIGCLD handler MUST NOT call
660 signal() before executing at least one wait(), otherwise the handler
661 will be called again, resulting in an infinite loop. The relevant
662 portion of the documentation reads "SIGCLD signals will be queued
663 and the signal-catching function will be continually reentered until
664 the queue is empty". Invoking signal() causes the kernel to reexamine
665 the SIGCLD queue. Fred Fish, UniSoft Systems Inc.
667 (Note that now this only applies in SYS V Release 2 and before.
668 On SYS V Release 3, we use sigset() to set the signal handler for
669 the first time, and so we don't have to reestablish the signal handler
670 in the handler below. On SYS V Release 4, we don't get this weirdo
671 behavior when we use sigaction(), which we do use.) */
674 sigchld_handler (int signo)
676 #ifdef OBNOXIOUS_SYSV_SIGCLD_BEHAVIOR
677 int old_errno = errno;
680 record_exited_processes (0);
685 #ifdef HAVE_UNIXOID_EVENT_LOOP
686 signal_fake_event ();
688 /* WARNING - must come after wait3() for USG systems */
689 EMACS_REESTABLISH_SIGNAL (signo, sigchld_handler);
695 #ifdef SIGNALS_VIA_CHARACTERS
696 /* Get signal character to send to process if SIGNALS_VIA_CHARACTERS */
699 process_signal_char (int tty_fd, int signo)
701 /* If it's not a tty, pray that these default values work */
702 if (! isatty (tty_fd)) {
703 #define CNTL(ch) (037 & (ch))
706 case SIGINT: return CNTL ('C');
707 case SIGQUIT: return CNTL ('\\');
709 case SIGTSTP: return CNTL ('Z');
715 /* TERMIOS is the latest and bestest, and seems most likely to work.
716 If the system has it, use it. */
719 tcgetattr (tty_fd, &t);
722 case SIGINT: return t.c_cc[VINTR];
723 case SIGQUIT: return t.c_cc[VQUIT];
724 #if defined(SIGTSTP) && defined(VSUSP)
725 case SIGTSTP: return t.c_cc[VSUSP];
730 # elif defined (TIOCGLTC) && defined (TIOCGETC) /* not HAVE_TERMIOS */
732 /* On Berkeley descendants, the following IOCTL's retrieve the
733 current control characters. */
738 case SIGINT: ioctl (tty_fd, TIOCGETC, &c); return c.t_intrc;
739 case SIGQUIT: ioctl (tty_fd, TIOCGETC, &c); return c.t_quitc;
741 case SIGTSTP: ioctl (tty_fd, TIOCGLTC, &lc); return lc.t_suspc;
742 # endif /* SIGTSTP */
746 # elif defined (TCGETA) /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
748 /* On SYSV descendants, the TCGETA ioctl retrieves the current
749 control characters. */
751 ioctl (tty_fd, TCGETA, &t);
753 case SIGINT: return t.c_cc[VINTR];
754 case SIGQUIT: return t.c_cc[VQUIT];
756 case SIGTSTP: return t.c_cc[VSWTCH];
757 # endif /* SIGTSTP */
760 # else /* ! defined (TCGETA) */
761 #error ERROR! Using SIGNALS_VIA_CHARACTERS, but not HAVE_TERMIOS || (TIOCGLTC && TIOCGETC) || TCGETA
762 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
763 you'd better be using one of the alternatives above! */
764 # endif /* ! defined (TCGETA) */
767 #endif /* SIGNALS_VIA_CHARACTERS */
772 /**********************************************************************/
773 /* Process implementation methods */
774 /**********************************************************************/
777 * Allocate and initialize Lisp_Process->process_data
781 unix_alloc_process_data (Lisp_Process *p)
783 p->process_data = xnew (struct unix_process_data);
785 UNIX_DATA(p)->connected_via_filedesc_p = 0;
786 UNIX_DATA(p)->infd = -1;
787 UNIX_DATA(p)->subtty = -1;
788 UNIX_DATA(p)->tty_name = Qnil;
789 UNIX_DATA(p)->pty_flag = 0;
793 * Mark any Lisp objects in Lisp_Process->process_data
797 unix_mark_process_data (Lisp_Process *proc)
799 mark_object (UNIX_DATA(proc)->tty_name);
803 * Initialize XEmacs process implementation once
808 unix_init_process (void)
811 if (! noninteractive || initialized)
813 signal (SIGCHLD, sigchld_handler);
818 * Initialize any process local data. This is called when newly
819 * created process is connected to real OS file handles. The
820 * handles are generally represented by void* type, but are
821 * of type int (file descriptors) for UNIX.
825 unix_init_process_io_handles (Lisp_Process *p, void* in, void* out, int flags)
827 UNIX_DATA(p)->infd = (int)in;
831 * Fork off a subprocess. P is a pointer to a newly created subprocess
832 * object. If this function signals, the caller is responsible for
833 * deleting (and finalizing) the process object.
835 * The method must return PID of the new process, a (positive??? ####) number
836 * which fits into Lisp_Int. No return value indicates an error, the method
837 * must signal an error instead.
841 unix_create_process (Lisp_Process *p,
842 Lisp_Object *argv, int nargv,
843 Lisp_Object program, Lisp_Object cur_dir)
848 /* Use volatile to protect variables from being clobbered by longjmp. */
849 volatile int forkin = -1;
850 volatile int forkout = -1;
851 volatile int pty_flag = 0;
854 if (!NILP (Vprocess_connection_type))
856 /* find a new pty, open the master side, return the opened
857 file handle, and store the name of the corresponding slave
858 side in global variable pty_name. */
859 outchannel = inchannel = allocate_pty ();
864 /* You're "supposed" to now open the slave in the child.
865 On some systems, we can open it here; this allows for
866 better error checking. */
868 /* On USG systems it does not work to open the pty's tty here
869 and then close and reopen it in the child. */
871 /* Don't let this terminal become our controlling terminal
872 (in case we don't have one). */
873 forkout = forkin = open (pty_name, O_RDWR | O_NOCTTY | OPEN_BINARY, 0);
875 forkout = forkin = open (pty_name, O_RDWR | OPEN_BINARY, 0);
880 UNIX_DATA(p)->pty_flag = pty_flag = 1;
883 #endif /* HAVE_PTYS */
884 if (create_bidirectional_pipe (&inchannel, &outchannel,
885 &forkin, &forkout) < 0)
889 /* Replaced by close_process_descs */
890 set_exclusive_use (inchannel);
891 set_exclusive_use (outchannel);
894 set_descriptor_non_blocking (inchannel);
895 set_descriptor_non_blocking (outchannel);
897 /* Record this as an active process, with its channels.
898 As a result, child_setup will close Emacs's side of the pipes. */
899 init_process_io_handles (p, (void*)inchannel, (void*)outchannel,
900 pty_flag ? STREAM_PTY_FLUSHING : 0);
901 /* Record the tty descriptor used in the subprocess. */
902 UNIX_DATA(p)->subtty = forkin;
906 /* child_setup must clobber environ on systems with true vfork.
907 Protect it from permanent change. */
908 char **save_environ = environ;
914 /**** Now we're in the child process ****/
915 int xforkin = forkin;
916 int xforkout = forkout;
918 /* Checking for quit in the child is bad because that will
919 cause I/O, and that, in turn, can confuse the X connection. */
920 begin_dont_check_for_quit();
922 /* Disconnect the current controlling terminal, pursuant to
923 making the pty be the controlling terminal of the process.
924 Also put us in our own process group. */
926 disconnect_controlling_terminal ();
931 /* Open the pty connection and make the pty's terminal
932 our controlling terminal.
934 On systems with TIOCSCTTY, we just use it to set
935 the controlling terminal. On other systems, the
936 first TTY we open becomes the controlling terminal.
937 So, we end up with four possibilities:
939 (1) on USG and TIOCSCTTY systems, we open the pty
941 (2) on other USG systems, we just open the pty.
942 (3) on non-USG systems with TIOCSCTTY, we
943 just use TIOCSCTTY. (On non-USG systems, we
944 already opened the pty in the parent process.)
945 (4) on non-USG systems without TIOCSCTTY, we
946 close the pty and reopen it.
948 This would be cleaner if we didn't open the pty
949 in the parent process, but doing it that way
950 makes it possible to trap error conditions.
951 It's harder to convey an error from the child
952 process, and I don't feel like messing with
955 /* There was some weirdo, probably wrong,
956 conditionalization on RTU and UNIPLUS here.
957 I deleted it. So sue me. */
959 /* SunOS has TIOCSCTTY but the close/open method
962 # if defined (USG) || !defined (TIOCSCTTY)
963 /* Now close the pty (if we had it open) and reopen it.
964 This makes the pty the controlling terminal of the
966 /* I wonder if close (open (pty_name, ...)) would work? */
969 xforkout = xforkin = open (pty_name, O_RDWR | OPEN_BINARY, 0);
972 write (1, "Couldn't open the pty terminal ", 31);
973 write (1, pty_name, strlen (pty_name));
977 # endif /* USG or not TIOCSCTTY */
979 /* Miscellaneous setup required for some systems.
980 Must be done before using tc* functions on xforkin.
981 This guarantees that isatty(xforkin) is true. */
983 # if defined (HAVE_ISASTREAM) && defined (I_PUSH)
984 if (isastream (xforkin))
986 # if defined (I_FIND)
987 # define stream_module_pushed(fd, module) (ioctl (fd, I_FIND, module) == 1)
989 # define stream_module_pushed(fd, module) 0
991 if (! stream_module_pushed (xforkin, "ptem"))
992 ioctl (xforkin, I_PUSH, "ptem");
993 if (! stream_module_pushed (xforkin, "ldterm"))
994 ioctl (xforkin, I_PUSH, "ldterm");
995 if (! stream_module_pushed (xforkin, "ttcompat"))
996 ioctl (xforkin, I_PUSH, "ttcompat");
998 # endif /* HAVE_ISASTREAM */
1001 /* We ignore the return value
1002 because faith@cs.unc.edu says that is necessary on Linux. */
1003 assert (isatty (xforkin));
1004 ioctl (xforkin, TIOCSCTTY, 0);
1005 # endif /* TIOCSCTTY */
1007 /* Change the line discipline. */
1009 # if defined (HAVE_TERMIOS) && defined (LDISC1)
1012 assert (isatty (xforkin));
1013 tcgetattr (xforkin, &t);
1015 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1016 perror ("create_process/tcsetattr LDISC1 failed\n");
1018 # elif defined (NTTYDISC) && defined (TIOCSETD)
1020 /* Use new line discipline. TIOCSETD is accepted and
1021 ignored on Sys5.4 systems with ttcompat. */
1022 int ldisc = NTTYDISC;
1023 assert (isatty (xforkin));
1024 ioctl (xforkin, TIOCSETD, &ldisc);
1026 # endif /* TIOCSETD & NTTYDISC */
1028 /* Make our process group be the foreground group
1029 of our new controlling terminal. */
1032 pid_t piddly = EMACS_GET_PROCESS_GROUP ();
1033 EMACS_SET_TTY_PROCESS_GROUP (xforkin, &piddly);
1036 /* On AIX, we've disabled SIGHUP above once we start a
1037 child on a pty. Now reenable it in the child, so it
1038 will die when we want it to.
1039 JV: This needs to be done ALWAYS as we might have inherited
1040 a SIG_IGN handling from our parent (nohup) and we are in new
1043 signal (SIGHUP, SIG_DFL);
1047 /* Set up the terminal characteristics of the pty. */
1048 child_setup_tty (xforkout);
1050 #endif /* HAVE_PTYS */
1052 signal (SIGINT, SIG_DFL);
1053 signal (SIGQUIT, SIG_DFL);
1057 char **new_argv = alloca_array (char *, nargv + 2);
1060 /* Nothing below here GCs so our string pointers shouldn't move. */
1061 new_argv[0] = (char *) XSTRING_DATA (program);
1062 for (i = 0; i < nargv; i++)
1064 CHECK_STRING (argv[i]);
1065 new_argv[i + 1] = (char *) XSTRING_DATA (argv[i]);
1067 new_argv[i + 1] = 0;
1069 LISP_STRING_TO_EXTERNAL (cur_dir, current_dir, Qfile_name);
1071 child_setup (xforkin, xforkout, xforkout, new_argv, current_dir);
1074 } /**** End of child code ****/
1076 /**** Back in parent process ****/
1077 #if !defined(CYGWIN)
1078 environ = save_environ;
1084 int save_errno = errno;
1085 close_descriptor_pair (forkin, forkout);
1087 report_file_error ("Doing fork", Qnil);
1090 /* #### dmoore - why is this commented out, otherwise we leave
1091 subtty = forkin, but then we close forkin just below. */
1092 /* UNIX_DATA(p)->subtty = -1; */
1094 /* If the subfork execv fails, and it exits,
1095 this close hangs. I don't know why.
1096 So have an interrupt jar it loose. */
1098 close_safely (forkin);
1099 if (forkin != forkout && forkout >= 0)
1104 UNIX_DATA (p)->tty_name = build_string (pty_name);
1107 UNIX_DATA (p)->tty_name = Qnil;
1109 /* Notice that SIGCHLD was not blocked. (This is not possible on
1110 some systems.) No biggie if SIGCHLD occurs right around the
1111 time that this call happens, because SIGCHLD() does not actually
1112 deselect the process (that doesn't occur until the next time
1113 we're waiting for an event, when status_notify() is called). */
1118 int save_errno = errno;
1119 close_descriptor_pair (forkin, forkout);
1120 close_descriptor_pair (inchannel, outchannel);
1122 report_file_error ("Opening pty or pipe", Qnil);
1123 return 0; /* not reached */
1127 /* Return nonzero if this process is a ToolTalk connection. */
1130 unix_tooltalk_connection_p (Lisp_Process *p)
1132 return UNIX_DATA(p)->connected_via_filedesc_p;
1135 /* This is called to set process' virtual terminal size */
1138 unix_set_window_size (Lisp_Process* p, int cols, int rows)
1140 return set_window_size (UNIX_DATA(p)->infd, cols, rows);
1144 * This method is called to update status fields of the process
1145 * structure. If the process has not existed, this method is
1146 * expected to do nothing.
1148 * The method is called only for real child processes.
1153 unix_update_status_if_terminated (Lisp_Process* p)
1157 EMACS_BLOCK_SIGNAL (SIGCHLD);
1159 if (waitpid (XINT (p->pid), &w, WNOHANG) == XINT (p->pid))
1162 update_status_from_wait_code (p, &w);
1165 EMACS_UNBLOCK_SIGNAL (SIGCHLD);
1171 * Update status of all exited processes. Called when SIGCLD has signaled.
1176 unix_reap_exited_processes (void)
1181 #ifndef OBNOXIOUS_SYSV_SIGCLD_BEHAVIOR
1182 record_exited_processes (1);
1185 if (exited_processes_index <= 0)
1190 #ifdef EMACS_BLOCK_SIGNAL
1191 EMACS_BLOCK_SIGNAL (SIGCHLD);
1193 for (i = 0; i < exited_processes_index; i++)
1195 int pid = exited_processes[i];
1196 int w = exited_processes_status[i];
1198 /* Find the process that signaled us, and record its status. */
1203 LIST_LOOP (tail, Vprocess_list)
1205 Lisp_Object proc = XCAR (tail);
1206 p = XPROCESS (proc);
1207 if (INTP (p->pid) && XINT (p->pid) == pid)
1215 /* Change the status of the process that was found. */
1218 update_status_from_wait_code (p, &w);
1220 /* If process has terminated, stop waiting for its output. */
1221 if (WIFSIGNALED (w) || WIFEXITED (w))
1223 if (!NILP(p->pipe_instream))
1225 /* We can't just call event_stream->unselect_process_cb (p)
1226 here, because that calls XtRemoveInput, which is not
1227 necessarily reentrant, so we can't call this at interrupt
1235 /* There was no asynchronous process found for that id. Check
1236 if we have a synchronous process. Only set sync process status
1237 if there is one, so we work OK with the waitpid() call in
1238 wait_for_termination(). */
1239 if (synch_process_alive != 0)
1240 { /* Set the global sync process status variables. */
1241 synch_process_alive = 0;
1243 /* Report the status of the synchronous process. */
1245 synch_process_retcode = WEXITSTATUS (w);
1246 else if (WIFSIGNALED (w))
1247 synch_process_death = signal_name (WTERMSIG (w));
1252 exited_processes_index = 0;
1254 EMACS_UNBLOCK_SIGNAL (SIGCHLD);
1256 #endif /* SIGCHLD */
1259 * Stuff the entire contents of LSTREAM to the process output pipe
1262 static JMP_BUF send_process_frame;
1265 send_process_trap (int signum)
1267 EMACS_REESTABLISH_SIGNAL (signum, send_process_trap);
1268 EMACS_UNBLOCK_SIGNAL (signum);
1269 LONGJMP (send_process_frame, 1);
1273 unix_send_process (Lisp_Object proc, struct lstream* lstream)
1275 /* Use volatile to protect variables from being clobbered by longjmp. */
1276 SIGTYPE (*volatile old_sigpipe) (int) = 0;
1277 volatile Lisp_Object vol_proc = proc;
1278 Lisp_Process *volatile p = XPROCESS (proc);
1280 /* #### JV: layering violation?
1282 This function knows too much about the relation between the encoding
1283 stream (DATA_OUTSTREAM) and the actual output stream p->output_stream.
1285 If encoding streams properly forwarded all calls, we could simply
1286 use DATA_OUTSTREAM everywhere. */
1288 if (!SETJMP (send_process_frame))
1290 /* use a reasonable-sized buffer (somewhere around the size of the
1291 stream buffer) so as to avoid inundating the stream with blocked
1293 Bufbyte chunkbuf[512];
1298 Lstream_data_count writeret;
1300 chunklen = Lstream_read (lstream, chunkbuf, 512);
1302 break; /* perhaps should abort() if < 0?
1303 This should never happen. */
1305 (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
1306 /* Lstream_write() will never successfully write less than
1307 the amount sent in. In the worst case, it just buffers
1308 the unwritten data. */
1309 writeret = Lstream_write (XLSTREAM (DATA_OUTSTREAM(p)), chunkbuf,
1311 signal (SIGPIPE, old_sigpipe);
1313 /* This is a real error. Blocking errors are handled
1314 specially inside of the filedesc stream. */
1315 report_file_error ("writing to process", list1 (proc));
1316 while (Lstream_was_blocked_p (XLSTREAM (p->pipe_outstream)))
1318 /* Buffer is full. Wait, accepting input;
1319 that may allow the program
1320 to finish doing output and read more. */
1321 Faccept_process_output (Qnil, make_int (1), Qnil);
1322 /* It could have *really* finished, deleting the process */
1323 if (NILP(p->pipe_outstream))
1326 (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
1327 Lstream_flush (XLSTREAM (p->pipe_outstream));
1328 signal (SIGPIPE, old_sigpipe);
1333 { /* We got here from a longjmp() from the SIGPIPE handler */
1334 signal (SIGPIPE, old_sigpipe);
1335 /* Close the file lstream so we don't attempt to write to it further */
1336 /* #### There is controversy over whether this might cause fd leakage */
1337 /* my tests say no. -slb */
1338 XLSTREAM (p->pipe_outstream)->flags &= ~LSTREAM_FL_IS_OPEN;
1340 XLSTREAM (p->coding_outstream)->flags &= ~LSTREAM_FL_IS_OPEN;
1342 p->status_symbol = Qexit;
1343 p->exit_code = 256; /* #### SIGPIPE ??? */
1347 deactivate_process (*((Lisp_Object *) (&vol_proc)));
1348 invalid_operation ("SIGPIPE raised on process; closed it", p->name);
1351 old_sigpipe = (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
1352 Lstream_flush (XLSTREAM (DATA_OUTSTREAM(p)));
1353 signal (SIGPIPE, old_sigpipe);
1357 * Send EOF to the process. The default implementation simply
1358 * closes the output stream. The method must return 0 to call
1359 * the default implementation, or 1 if it has taken all care about
1360 * sending EOF to the process.
1364 unix_process_send_eof (Lisp_Object proc)
1366 if (!UNIX_DATA (XPROCESS (proc))->pty_flag)
1369 /* #### get_eof_char simply doesn't return the correct character
1370 here. Maybe it is needed to determine the right eof
1371 character in init_process_io_handles but here it simply screws
1374 Bufbyte eof_char = get_eof_char (XPROCESS (proc));
1375 send_process (proc, Qnil, &eof_char, 0, 1);
1377 send_process (proc, Qnil, (const Bufbyte *) "\004", 0, 1);
1383 * Called before the process is deactivated. The process object
1384 * is not immediately finalized, just undergoes a transition to
1387 * The return value is a unique stream ID, as returned by
1388 * event_stream_delete_stream_pair
1390 * In the lack of this method, only event_stream_delete_stream_pair
1391 * is called on both I/O streams of the process.
1393 * The UNIX version guards this by ignoring possible SIGPIPE.
1397 unix_deactivate_process (Lisp_Process *p)
1399 SIGTYPE (*old_sigpipe) (int) = 0;
1402 if (UNIX_DATA(p)->infd >= 0)
1403 flush_pending_output (UNIX_DATA(p)->infd);
1405 /* closing the outstream could result in SIGPIPE, so ignore it. */
1406 old_sigpipe = (SIGTYPE (*) (int)) signal (SIGPIPE, SIG_IGN);
1407 usid = event_stream_delete_stream_pair (p->pipe_instream, p->pipe_outstream);
1408 signal (SIGPIPE, old_sigpipe);
1410 UNIX_DATA(p)->infd = -1;
1415 /* If the subtty field of the process data is not filled in, do so now. */
1417 try_to_initialize_subtty (struct unix_process_data *upd)
1420 && (upd->subtty == -1 || ! isatty (upd->subtty))
1421 && STRINGP (upd->tty_name))
1422 upd->subtty = open ((char *) XSTRING_DATA (upd->tty_name), O_RDWR, 0);
1425 /* Send signal number SIGNO to PROCESS.
1426 CURRENT_GROUP means send to the process group that currently owns
1427 the terminal being used to communicate with PROCESS.
1428 This is used for various commands in shell mode.
1429 If NOMSG is zero, insert signal-announcements into process's buffers
1432 If we can, we try to signal PROCESS by sending control characters
1433 down the pty. This allows us to signal inferiors who have changed
1434 their uid, for which killpg would return an EPERM error,
1435 or processes running on other machines via remote login.
1437 The method signals an error if the given SIGNO is not valid. */
1440 unix_kill_child_process (Lisp_Object proc, int signo,
1441 int current_group, int nomsg)
1444 Lisp_Process *p = XPROCESS (proc);
1445 struct unix_process_data *d = UNIX_DATA (p);
1451 p->status_symbol = Qrun;
1458 #endif /* ! defined (SIGCONT) */
1462 flush_pending_output (d->infd);
1469 /* If current_group is true, we want to send a signal to the
1470 foreground process group of the terminal our child process is
1471 running on. You would think that would be easy.
1473 The BSD people invented the TIOCPGRP ioctl to get the foreground
1474 process group of a tty. That, combined with killpg, gives us
1477 However, the POSIX standards people, in their infinite wisdom,
1478 have seen fit to only allow this for processes which have the
1479 terminal as controlling terminal, which doesn't apply to us.
1481 Sooo..., we have to do something non-standard. The ioctls
1482 TIOCSIGNAL, TIOCSIG, and TIOCSIGSEND send the signal directly on
1483 many systems. POSIX tcgetpgrp(), since it is *documented* as not
1484 doing what we want, is actually less likely to work than the BSD
1485 ioctl TIOCGPGRP it is supposed to obsolete. Sometimes we have to
1486 use TIOCGPGRP on the master end, sometimes the slave end
1487 (probably an AIX bug). So we better get a fd for the slave if we
1490 Anal operating systems like SGI Irix and Compaq Tru64 adhere
1491 strictly to the letter of the law, so our hack doesn't work.
1492 The following fragment from an Irix header file is suggestive:
1495 // this is not currently supported
1496 #define TIOCSIGNAL (tIOC|31) // pty: send signal to slave
1499 On those systems where none of our tricks work, we just fall back
1500 to the non-current_group behavior and kill the process group of
1505 try_to_initialize_subtty (d);
1507 #ifdef SIGNALS_VIA_CHARACTERS
1508 /* If possible, send signals to the entire pgrp
1509 by sending an input character to it. */
1511 char sigchar = process_signal_char (d->subtty, signo);
1514 send_process (proc, Qnil, (Bufbyte *) &sigchar, 0, 1);
1518 #endif /* SIGNALS_VIA_CHARACTERS */
1522 ioctl (d->infd, TIOCGPGRP, &pgid); /* BSD */
1523 if (pgid == -1 && d->subtty != -1)
1524 ioctl (d->subtty, TIOCGPGRP, &pgid); /* Only this works on AIX! */
1525 #endif /* TIOCGPGRP */
1529 /* Many systems provide an ioctl to send a signal directly */
1530 #ifdef TIOCSIGNAL /* Solaris, HP-UX */
1531 if (ioctl (d->infd, TIOCSIGNAL, signo) != -1)
1533 #endif /* TIOCSIGNAL */
1535 #ifdef TIOCSIG /* BSD */
1536 if (ioctl (d->infd, TIOCSIG, signo) != -1)
1538 #endif /* TIOCSIG */
1540 } /* current_group */
1543 /* Either current_group is 0, or we failed to get the foreground
1544 process group using the trickery above. So we fall back to
1545 sending the signal to the process group of our child process.
1546 Since this is often a shell that ignores signals like SIGINT,
1547 the shell's subprocess is killed, which is the desired effect.
1548 The process group of p->pid is always p->pid, since it was
1549 created as a process group leader. */
1550 pgid = XINT (p->pid);
1552 /* Finally send the signal. */
1553 if (EMACS_KILLPG (pgid, signo) == -1)
1555 /* It's not an error if our victim is already dead.
1556 And we can't rely on the result of killing a zombie, since
1557 XPG 4.2 requires that killing a zombie fail with ESRCH,
1558 while FIPS 151-2 requires that it succeeds! */
1562 error ("kill (%ld, %ld) failed: %s",
1563 (long) pgid, (long) signo, strerror (errno));
1567 /* Send signal SIGCODE to any process in the system given its PID.
1568 Return zero if successful, a negative number upon failure. */
1571 unix_kill_process_by_pid (int pid, int sigcode)
1573 return kill (pid, sigcode);
1576 /* Return TTY name used to communicate with subprocess. */
1579 unix_get_tty_name (Lisp_Process *p)
1581 return UNIX_DATA (p)->tty_name;
1584 /* Canonicalize host name HOST, and return its canonical form.
1585 The default implementation just takes HOST for a canonical name. */
1589 unix_canonicalize_host_name (Lisp_Object host)
1591 #if defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO)
1592 struct addrinfo hints, *res;
1593 static char addrbuf[NI_MAXHOST];
1594 Lisp_Object canonname;
1599 hints.ai_flags = AI_CANONNAME;
1600 #ifdef IPV6_CANONICALIZE
1601 hints.ai_family = AF_UNSPEC;
1603 hints.ai_family = PF_INET;
1605 hints.ai_socktype = SOCK_STREAM;
1606 hints.ai_protocol = 0;
1607 LISP_STRING_TO_EXTERNAL (host, ext_host, Qnative);
1608 retval = getaddrinfo (ext_host, NULL, &hints, &res);
1613 EXTERNAL_TO_C_STRING (gai_strerror (retval), gai_error, Qnative);
1614 maybe_error (Qprocess, ERROR_ME_NOT,
1615 "%s \"%s\"", gai_error, XSTRING_DATA (host));
1620 int gni = getnameinfo (res->ai_addr, res->ai_addrlen,
1621 addrbuf, sizeof(addrbuf),
1622 NULL, 0, NI_NUMERICHOST);
1623 canonname = gni ? host : build_ext_string (addrbuf, Qnative);
1629 #else /* ! HAVE_GETADDRINFO */
1630 struct sockaddr_in address;
1632 if (!get_internet_address (host, &address, ERROR_ME_NOT))
1635 if (address.sin_family == AF_INET)
1636 return build_string (inet_ntoa (address.sin_addr));
1638 /* #### any clue what to do here? */
1640 #endif /* ! HAVE_GETADDRINFO */
1643 /* Open a TCP network connection to a given HOST/SERVICE.
1644 Treated exactly like a normal process when reading and writing.
1645 Only differences are in status display and process deletion.
1646 A network connection has no PID; you cannot signal it. All you can
1647 do is deactivate and close it via delete-process. */
1650 unix_open_network_stream (Lisp_Object name, Lisp_Object host, Lisp_Object service,
1651 Lisp_Object protocol, void** vinfd, void** voutfd)
1657 volatile int retry = 0;
1660 CHECK_STRING (host);
1662 if (!EQ (protocol, Qtcp) && !EQ (protocol, Qudp))
1663 invalid_argument ("Unsupported protocol", protocol);
1666 #if defined(HAVE_GETADDRINFO) && defined(HAVE_GETNAMEINFO)
1667 struct addrinfo hints, *res;
1668 struct addrinfo * volatile lres;
1670 volatile int xerrno = 0;
1671 volatile int failed_connect = 0;
1674 * Caution: service can either be a string or int.
1675 * Convert to a C string for later use by getaddrinfo.
1680 snprintf (portbuf, sizeof (portbuf), "%ld", (long) XINT (service));
1681 portstring = portbuf;
1682 port = htons ((unsigned short) XINT (service));
1686 CHECK_STRING (service);
1687 LISP_STRING_TO_EXTERNAL (service, portstring, Qnative);
1693 hints.ai_family = AF_UNSPEC;
1694 if (EQ (protocol, Qtcp))
1695 hints.ai_socktype = SOCK_STREAM;
1696 else /* EQ (protocol, Qudp) */
1697 hints.ai_socktype = SOCK_DGRAM;
1698 hints.ai_protocol = 0;
1699 LISP_STRING_TO_EXTERNAL (host, ext_host, Qnative);
1700 retval = getaddrinfo (ext_host, portstring, &hints, &res);
1705 EXTERNAL_TO_C_STRING (gai_strerror (retval), gai_error, Qnative);
1706 error ("%s/%s %s", XSTRING_DATA (host), portstring, gai_error);
1710 for (lres = res; lres ; lres = lres->ai_next)
1712 if (EQ (protocol, Qtcp))
1713 s = socket (lres->ai_family, SOCK_STREAM, 0);
1714 else /* EQ (protocol, Qudp) */
1715 s = socket (lres->ai_family, SOCK_DGRAM, 0);
1720 /* Turn off interrupts here -- see comments below. There used to
1721 be code which called bind_polling_period() to slow the polling
1722 period down rather than turn it off, but that seems rather
1723 bogus to me. Best thing here is to use a non-blocking connect
1724 or something, to check for QUIT. */
1726 /* Comments that are not quite valid: */
1728 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
1729 when connect is interrupted. So let's not let it get interrupted.
1730 Note we do not turn off polling, because polling is only used
1731 when not interrupt_input, and thus not normally used on the systems
1732 which have this bug. On systems which use polling, there's no way
1733 to quit if polling is turned off. */
1735 /* Slow down polling. Some kernels have a bug which causes retrying
1736 connect to fail after a connect. */
1738 slow_down_interrupts ();
1742 /* A system call interrupted with a SIGALRM or SIGIO comes back
1743 here, with can_break_system_calls reset to 0. */
1744 SETJMP (break_system_call_jump);
1747 speed_up_interrupts ();
1749 /* In case something really weird happens ... */
1750 slow_down_interrupts ();
1753 /* Break out of connect with a signal (it isn't otherwise possible).
1754 Thus you don't get screwed with a hung network. */
1755 can_break_system_calls = 1;
1756 retval = connect (s, lres->ai_addr, lres->ai_addrlen);
1757 can_break_system_calls = 0;
1761 if (errno != EISCONN)
1765 if (errno == EADDRINUSE && retry < 20)
1767 /* A delay here is needed on some FreeBSD systems,
1768 and it is harmless, since this retrying takes time anyway
1769 and should be infrequent.
1770 `sleep-for' allowed for quitting this loop with interrupts
1771 slowed down so it can't be used here. Async timers should
1772 already be disabled at this point so we can use `sleep'. */
1783 speed_up_interrupts ();
1791 char servbuf[NI_MAXSERV];
1793 if (EQ (protocol, Qtcp))
1794 gni = getnameinfo (lres->ai_addr, lres->ai_addrlen,
1795 NULL, 0, servbuf, sizeof(servbuf),
1797 else /* EQ (protocol, Qudp) */
1798 gni = getnameinfo (lres->ai_addr, lres->ai_addrlen,
1799 NULL, 0, servbuf, sizeof(servbuf),
1800 NI_NUMERICSERV | NI_DGRAM);
1803 port = strtol (servbuf, NULL, 10);
1807 } /* address loop */
1809 speed_up_interrupts ();
1817 report_file_error ("connection failed", list2 (host, name));
1819 report_file_error ("error creating socket", list1 (name));
1821 #else /* ! HAVE_GETADDRINFO */
1822 struct sockaddr_in address;
1825 port = htons ((unsigned short) XINT (service));
1828 struct servent *svc_info;
1829 CHECK_STRING (service);
1831 if (EQ (protocol, Qtcp))
1832 svc_info = getservbyname ((char *) XSTRING_DATA (service), "tcp");
1833 else /* EQ (protocol, Qudp) */
1834 svc_info = getservbyname ((char *) XSTRING_DATA (service), "udp");
1837 invalid_argument ("Unknown service", service);
1838 port = svc_info->s_port;
1841 get_internet_address (host, &address, ERROR_ME);
1842 address.sin_port = port;
1844 if (EQ (protocol, Qtcp))
1845 s = socket (address.sin_family, SOCK_STREAM, 0);
1846 else /* EQ (protocol, Qudp) */
1847 s = socket (address.sin_family, SOCK_DGRAM, 0);
1850 report_file_error ("error creating socket", list1 (name));
1852 /* Turn off interrupts here -- see comments below. There used to
1853 be code which called bind_polling_period() to slow the polling
1854 period down rather than turn it off, but that seems rather
1855 bogus to me. Best thing here is to use a non-blocking connect
1856 or something, to check for QUIT. */
1858 /* Comments that are not quite valid: */
1860 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
1861 when connect is interrupted. So let's not let it get interrupted.
1862 Note we do not turn off polling, because polling is only used
1863 when not interrupt_input, and thus not normally used on the systems
1864 which have this bug. On systems which use polling, there's no way
1865 to quit if polling is turned off. */
1867 /* Slow down polling. Some kernels have a bug which causes retrying
1868 connect to fail after a connect. */
1870 slow_down_interrupts ();
1874 /* A system call interrupted with a SIGALRM or SIGIO comes back
1875 here, with can_break_system_calls reset to 0. */
1876 SETJMP (break_system_call_jump);
1879 speed_up_interrupts ();
1881 /* In case something really weird happens ... */
1882 slow_down_interrupts ();
1885 /* Break out of connect with a signal (it isn't otherwise possible).
1886 Thus you don't get screwed with a hung network. */
1887 can_break_system_calls = 1;
1888 retval = connect (s, (struct sockaddr *) &address, sizeof (address));
1889 can_break_system_calls = 0;
1890 if (retval == -1 && errno != EISCONN)
1895 if (errno == EADDRINUSE && retry < 20)
1897 /* A delay here is needed on some FreeBSD systems,
1898 and it is harmless, since this retrying takes time anyway
1899 and should be infrequent.
1900 `sleep-for' allowed for quitting this loop with interrupts
1901 slowed down so it can't be used here. Async timers should
1902 already be disabled at this point so we can use `sleep'. */
1910 speed_up_interrupts ();
1913 report_file_error ("connection failed", list2 (host, name));
1916 speed_up_interrupts ();
1917 #endif /* ! HAVE_GETADDRINFO */
1924 close (s); /* this used to be leaked; from Kyle Jones */
1925 report_file_error ("error duplicating socket", list1 (name));
1928 set_socket_nonblocking_maybe (inch, port, "tcp");
1930 *vinfd = (void*)inch;
1931 *voutfd = (void*)outch;
1935 #ifdef HAVE_MULTICAST
1937 /* Didier Verna <didier@xemacs.org> Nov. 28 1997.
1939 This function is similar to open-network-stream-internal, but provides a
1940 mean to open an UDP multicast connection instead of a TCP one. Like in the
1941 TCP case, the multicast connection will be seen as a sub-process,
1944 - Normally, we should use sendto and recvfrom with non connected
1945 sockets. The current code doesn't allow us to do this. In the future, it
1946 would be a good idea to extend the process data structure in order to deal
1947 properly with the different types network connections.
1948 - For the same reason, when leaving a multicast group, it is better to make
1949 a setsockopt - IP_DROP_MEMBERSHIP before closing the descriptors.
1950 Unfortunately, this can't be done here because delete_process doesn't know
1951 about the kind of connection we have. However, this is not such an
1956 unix_open_multicast_group (Lisp_Object name, Lisp_Object dest,
1957 Lisp_Object port, Lisp_Object ttl, void** vinfd,
1961 struct sockaddr_in sa;
1962 struct protoent *udp;
1965 unsigned char thettl;
1966 int one = 1; /* For REUSEADDR */
1968 volatile int retry = 0;
1970 CHECK_STRING (dest);
1972 CHECK_NATNUM (port);
1973 theport = htons ((unsigned short) XINT (port));
1976 thettl = (unsigned char) XINT (ttl);
1978 if ((udp = getprotobyname ("udp")) == NULL)
1979 type_error (Qinvalid_operation, "No info available for UDP protocol");
1981 /* Init the sockets. Yes, I need 2 sockets. I couldn't duplicate one. */
1982 if ((rs = socket (PF_INET, SOCK_DGRAM, udp->p_proto)) < 0)
1983 report_file_error ("error creating socket", list1(name));
1984 if ((ws = socket (PF_INET, SOCK_DGRAM, udp->p_proto)) < 0)
1987 report_file_error ("error creating socket", list1(name));
1990 /* This will be used for both sockets */
1991 memset (&sa, 0, sizeof(sa));
1992 sa.sin_family = AF_INET;
1993 sa.sin_port = theport;
1994 sa.sin_addr.s_addr = inet_addr ((char *) XSTRING_DATA (dest));
1996 /* Socket configuration for reading ------------------------ */
1998 /* Multiple connections from the same machine. This must be done before
1999 bind. If it fails, it shouldn't be fatal. The only consequence is that
2000 people won't be able to connect twice from the same machine. */
2001 if (setsockopt (rs, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof (one))
2003 warn_when_safe (Qmulticast, Qwarning, "Cannot reuse socket address");
2005 /* bind socket name */
2006 if (bind (rs, (struct sockaddr *)&sa, sizeof(sa)))
2010 report_file_error ("error binding socket", list2(name, port));
2013 /* join multicast group */
2014 imr.imr_multiaddr.s_addr = inet_addr ((char *) XSTRING_DATA (dest));
2015 imr.imr_interface.s_addr = htonl (INADDR_ANY);
2016 if (setsockopt (rs, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2017 &imr, sizeof (struct ip_mreq)) < 0)
2021 report_file_error ("error adding membership", list2(name, dest));
2024 /* Socket configuration for writing ----------------------- */
2026 /* Normally, there's no 'connect' in multicast, since we prefer to use
2027 'sendto' and 'recvfrom'. However, in order to handle this connection in
2028 the process-like way it is done for TCP, we must be able to use 'write'
2029 instead of 'sendto'. Consequently, we 'connect' this socket. */
2031 /* See open-network-stream-internal for comments on this part of the code */
2032 slow_down_interrupts ();
2036 /* A system call interrupted with a SIGALRM or SIGIO comes back
2037 here, with can_break_system_calls reset to 0. */
2038 SETJMP (break_system_call_jump);
2041 speed_up_interrupts ();
2043 /* In case something really weird happens ... */
2044 slow_down_interrupts ();
2047 /* Break out of connect with a signal (it isn't otherwise possible).
2048 Thus you don't get screwed with a hung network. */
2049 can_break_system_calls = 1;
2050 ret = connect (ws, (struct sockaddr *) &sa, sizeof (sa));
2051 can_break_system_calls = 0;
2052 if (ret == -1 && errno != EISCONN)
2058 if (errno == EADDRINUSE && retry < 20)
2060 /* A delay here is needed on some FreeBSD systems,
2061 and it is harmless, since this retrying takes time anyway
2062 and should be infrequent.
2063 `sleep-for' allowed for quitting this loop with interrupts
2064 slowed down so it can't be used here. Async timers should
2065 already be disabled at this point so we can use `sleep'. */
2073 speed_up_interrupts ();
2076 report_file_error ("error connecting socket", list2(name, port));
2079 speed_up_interrupts ();
2082 if (setsockopt (ws, IPPROTO_IP, IP_MULTICAST_TTL,
2083 &thettl, sizeof (thettl)) < 0)
2087 report_file_error ("error setting ttl", list2(name, ttl));
2090 set_socket_nonblocking_maybe (rs, theport, "udp");
2093 *voutfd = (void*)ws;
2096 #endif /* HAVE_MULTICAST */
2098 #endif /* HAVE_SOCKETS */
2101 /**********************************************************************/
2102 /* Initialization */
2103 /**********************************************************************/
2106 process_type_create_unix (void)
2108 PROCESS_HAS_METHOD (unix, alloc_process_data);
2109 PROCESS_HAS_METHOD (unix, mark_process_data);
2111 PROCESS_HAS_METHOD (unix, init_process);
2112 PROCESS_HAS_METHOD (unix, reap_exited_processes);
2114 PROCESS_HAS_METHOD (unix, init_process_io_handles);
2115 PROCESS_HAS_METHOD (unix, create_process);
2116 PROCESS_HAS_METHOD (unix, tooltalk_connection_p);
2117 PROCESS_HAS_METHOD (unix, set_window_size);
2119 PROCESS_HAS_METHOD (unix, update_status_if_terminated);
2121 PROCESS_HAS_METHOD (unix, send_process);
2122 PROCESS_HAS_METHOD (unix, process_send_eof);
2123 PROCESS_HAS_METHOD (unix, deactivate_process);
2124 PROCESS_HAS_METHOD (unix, kill_child_process);
2125 PROCESS_HAS_METHOD (unix, kill_process_by_pid);
2126 PROCESS_HAS_METHOD (unix, get_tty_name);
2128 PROCESS_HAS_METHOD (unix, canonicalize_host_name);
2129 PROCESS_HAS_METHOD (unix, open_network_stream);
2130 #ifdef HAVE_MULTICAST
2131 PROCESS_HAS_METHOD (unix, open_multicast_group);
2137 vars_of_process_unix (void)
2139 Fprovide (intern ("unix-processes"));
2142 #endif /* !defined (NO_SUBPROCESSES) */