Remove the highlighting support for quoting 'like this' inside Lisp docstrings
[emacs.git] / src / process.c
blob1eac5e12663b70967fc921d2702cae9b1c66e133
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2016 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
27 #include <sys/file.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30 #include <fcntl.h>
32 #include "lisp.h"
34 /* Only MS-DOS does not define `subprocesses'. */
35 #ifdef subprocesses
37 #include <sys/socket.h>
38 #include <netdb.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
42 /* Are local (unix) sockets supported? */
43 #if defined (HAVE_SYS_UN_H)
44 #if !defined (AF_LOCAL) && defined (AF_UNIX)
45 #define AF_LOCAL AF_UNIX
46 #endif
47 #ifdef AF_LOCAL
48 #define HAVE_LOCAL_SOCKETS
49 #include <sys/un.h>
50 #endif
51 #endif
53 #include <sys/ioctl.h>
54 #if defined (HAVE_NET_IF_H)
55 #include <net/if.h>
56 #endif /* HAVE_NET_IF_H */
58 #if defined (HAVE_IFADDRS_H)
59 /* Must be after net/if.h */
60 #include <ifaddrs.h>
62 /* We only use structs from this header when we use getifaddrs. */
63 #if defined (HAVE_NET_IF_DL_H)
64 #include <net/if_dl.h>
65 #endif
67 #endif
69 #ifdef NEED_BSDTTY
70 #include <bsdtty.h>
71 #endif
73 #ifdef USG5_4
74 # include <sys/stream.h>
75 # include <sys/stropts.h>
76 #endif
78 #ifdef HAVE_RES_INIT
79 #include <arpa/nameser.h>
80 #include <resolv.h>
81 #endif
83 #ifdef HAVE_UTIL_H
84 #include <util.h>
85 #endif
87 #ifdef HAVE_PTY_H
88 #include <pty.h>
89 #endif
91 #include <c-ctype.h>
92 #include <sig2str.h>
93 #include <verify.h>
95 #endif /* subprocesses */
97 #include "systime.h"
98 #include "systty.h"
100 #include "window.h"
101 #include "character.h"
102 #include "buffer.h"
103 #include "coding.h"
104 #include "process.h"
105 #include "frame.h"
106 #include "termopts.h"
107 #include "keyboard.h"
108 #include "blockinput.h"
109 #include "atimer.h"
110 #include "sysselect.h"
111 #include "syssignal.h"
112 #include "syswait.h"
113 #ifdef HAVE_GNUTLS
114 #include "gnutls.h"
115 #endif
117 #ifdef HAVE_WINDOW_SYSTEM
118 #include TERM_HEADER
119 #endif /* HAVE_WINDOW_SYSTEM */
121 #ifdef HAVE_GLIB
122 #include "xgselect.h"
123 #ifndef WINDOWSNT
124 #include <glib.h>
125 #endif
126 #endif
128 #ifdef WINDOWSNT
129 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
130 struct timespec *, void *);
131 #endif
133 /* Work around GCC 4.7.0 bug with strict overflow checking; see
134 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
135 This bug appears to be fixed in GCC 5.1, so don't work around it there. */
136 #if __GNUC__ == 4 && __GNUC_MINOR__ >= 3
137 # pragma GCC diagnostic ignored "-Wstrict-overflow"
138 #endif
140 /* True if keyboard input is on hold, zero otherwise. */
142 static bool kbd_is_on_hold;
144 /* Nonzero means don't run process sentinels. This is used
145 when exiting. */
146 bool inhibit_sentinels;
148 #ifdef subprocesses
150 #ifndef SOCK_CLOEXEC
151 # define SOCK_CLOEXEC 0
152 #endif
154 #ifndef HAVE_ACCEPT4
156 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
158 static int
159 close_on_exec (int fd)
161 if (0 <= fd)
162 fcntl (fd, F_SETFD, FD_CLOEXEC);
163 return fd;
166 # undef accept4
167 # define accept4(sockfd, addr, addrlen, flags) \
168 process_accept4 (sockfd, addr, addrlen, flags)
169 static int
170 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
172 return close_on_exec (accept (sockfd, addr, addrlen));
175 static int
176 process_socket (int domain, int type, int protocol)
178 return close_on_exec (socket (domain, type, protocol));
180 # undef socket
181 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
182 #endif
184 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
185 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
186 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
187 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
188 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
189 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
191 /* Number of events of change of status of a process. */
192 static EMACS_INT process_tick;
193 /* Number of events for which the user or sentinel has been notified. */
194 static EMACS_INT update_tick;
196 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects.
197 The code can be simplified by assuming NON_BLOCKING_CONNECT once
198 Emacs starts assuming POSIX 1003.1-2001 or later. */
200 #if (defined HAVE_SELECT \
201 && (defined GNU_LINUX || defined HAVE_GETPEERNAME) \
202 && (defined EWOULDBLOCK || defined EINPROGRESS))
203 # define NON_BLOCKING_CONNECT
204 #endif
206 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
207 this system. We need to read full packets, so we need a
208 "non-destructive" select. So we require either native select,
209 or emulation of select using FIONREAD. */
211 #ifndef BROKEN_DATAGRAM_SOCKETS
212 # if defined HAVE_SELECT || defined USABLE_FIONREAD
213 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
214 # define DATAGRAM_SOCKETS
215 # endif
216 # endif
217 #endif
219 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
220 # define HAVE_SEQPACKET
221 #endif
223 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
224 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
225 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
227 /* Number of processes which have a non-zero read_output_delay,
228 and therefore might be delayed for adaptive read buffering. */
230 static int process_output_delay_count;
232 /* True if any process has non-nil read_output_skip. */
234 static bool process_output_skip;
236 static void create_process (Lisp_Object, char **, Lisp_Object);
237 #ifdef USABLE_SIGIO
238 static bool keyboard_bit_set (fd_set *);
239 #endif
240 static void deactivate_process (Lisp_Object);
241 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
242 static int read_process_output (Lisp_Object, int);
243 static void handle_child_signal (int);
244 static void create_pty (Lisp_Object);
246 static Lisp_Object get_process (register Lisp_Object name);
247 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
249 /* Mask of bits indicating the descriptors that we wait for input on. */
251 static fd_set input_wait_mask;
253 /* Mask that excludes keyboard input descriptor(s). */
255 static fd_set non_keyboard_wait_mask;
257 /* Mask that excludes process input descriptor(s). */
259 static fd_set non_process_wait_mask;
261 /* Mask for selecting for write. */
263 static fd_set write_mask;
265 #ifdef NON_BLOCKING_CONNECT
266 /* Mask of bits indicating the descriptors that we wait for connect to
267 complete on. Once they complete, they are removed from this mask
268 and added to the input_wait_mask and non_keyboard_wait_mask. */
270 static fd_set connect_wait_mask;
272 /* Number of bits set in connect_wait_mask. */
273 static int num_pending_connects;
274 #endif /* NON_BLOCKING_CONNECT */
276 /* The largest descriptor currently in use for a process object; -1 if none. */
277 static int max_process_desc;
279 /* The largest descriptor currently in use for input; -1 if none. */
280 static int max_input_desc;
282 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
283 static Lisp_Object chan_process[FD_SETSIZE];
285 /* Alist of elements (NAME . PROCESS). */
286 static Lisp_Object Vprocess_alist;
288 /* Buffered-ahead input char from process, indexed by channel.
289 -1 means empty (no char is buffered).
290 Used on sys V where the only way to tell if there is any
291 output from the process is to read at least one char.
292 Always -1 on systems that support FIONREAD. */
294 static int proc_buffered_char[FD_SETSIZE];
296 /* Table of `struct coding-system' for each process. */
297 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
298 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
300 #ifdef DATAGRAM_SOCKETS
301 /* Table of `partner address' for datagram sockets. */
302 static struct sockaddr_and_len {
303 struct sockaddr *sa;
304 int len;
305 } datagram_address[FD_SETSIZE];
306 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
307 #define DATAGRAM_CONN_P(proc) \
308 (PROCESSP (proc) && \
309 XPROCESS (proc)->infd >= 0 && \
310 datagram_address[XPROCESS (proc)->infd].sa != 0)
311 #else
312 #define DATAGRAM_CHAN_P(chan) (0)
313 #define DATAGRAM_CONN_P(proc) (0)
314 #endif
316 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
317 a `for' loop which iterates over processes from Vprocess_alist. */
319 #define FOR_EACH_PROCESS(list_var, proc_var) \
320 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
322 /* These setters are used only in this file, so they can be private. */
323 static void
324 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
326 p->buffer = val;
328 static void
329 pset_command (struct Lisp_Process *p, Lisp_Object val)
331 p->command = val;
333 static void
334 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
336 p->decode_coding_system = val;
338 static void
339 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
341 p->decoding_buf = val;
343 static void
344 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
346 p->encode_coding_system = val;
348 static void
349 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
351 p->encoding_buf = val;
353 static void
354 pset_filter (struct Lisp_Process *p, Lisp_Object val)
356 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
358 static void
359 pset_log (struct Lisp_Process *p, Lisp_Object val)
361 p->log = val;
363 static void
364 pset_mark (struct Lisp_Process *p, Lisp_Object val)
366 p->mark = val;
368 static void
369 pset_name (struct Lisp_Process *p, Lisp_Object val)
371 p->name = val;
373 static void
374 pset_plist (struct Lisp_Process *p, Lisp_Object val)
376 p->plist = val;
378 static void
379 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
381 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
383 static void
384 pset_status (struct Lisp_Process *p, Lisp_Object val)
386 p->status = val;
388 static void
389 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
391 p->tty_name = val;
393 static void
394 pset_type (struct Lisp_Process *p, Lisp_Object val)
396 p->type = val;
398 static void
399 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
401 p->write_queue = val;
403 static void
404 pset_stderrproc (struct Lisp_Process *p, Lisp_Object val)
406 p->stderrproc = val;
410 static Lisp_Object
411 make_lisp_proc (struct Lisp_Process *p)
413 return make_lisp_ptr (p, Lisp_Vectorlike);
416 static struct fd_callback_data
418 fd_callback func;
419 void *data;
420 #define FOR_READ 1
421 #define FOR_WRITE 2
422 int condition; /* Mask of the defines above. */
423 } fd_callback_info[FD_SETSIZE];
426 /* Add a file descriptor FD to be monitored for when read is possible.
427 When read is possible, call FUNC with argument DATA. */
429 void
430 add_read_fd (int fd, fd_callback func, void *data)
432 add_keyboard_wait_descriptor (fd);
434 fd_callback_info[fd].func = func;
435 fd_callback_info[fd].data = data;
436 fd_callback_info[fd].condition |= FOR_READ;
439 /* Stop monitoring file descriptor FD for when read is possible. */
441 void
442 delete_read_fd (int fd)
444 delete_keyboard_wait_descriptor (fd);
446 fd_callback_info[fd].condition &= ~FOR_READ;
447 if (fd_callback_info[fd].condition == 0)
449 fd_callback_info[fd].func = 0;
450 fd_callback_info[fd].data = 0;
454 /* Add a file descriptor FD to be monitored for when write is possible.
455 When write is possible, call FUNC with argument DATA. */
457 void
458 add_write_fd (int fd, fd_callback func, void *data)
460 FD_SET (fd, &write_mask);
461 if (fd > max_input_desc)
462 max_input_desc = fd;
464 fd_callback_info[fd].func = func;
465 fd_callback_info[fd].data = data;
466 fd_callback_info[fd].condition |= FOR_WRITE;
469 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
471 static void
472 delete_input_desc (int fd)
474 if (fd == max_input_desc)
477 fd--;
478 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
479 || FD_ISSET (fd, &write_mask)));
481 max_input_desc = fd;
485 /* Stop monitoring file descriptor FD for when write is possible. */
487 void
488 delete_write_fd (int fd)
490 FD_CLR (fd, &write_mask);
491 fd_callback_info[fd].condition &= ~FOR_WRITE;
492 if (fd_callback_info[fd].condition == 0)
494 fd_callback_info[fd].func = 0;
495 fd_callback_info[fd].data = 0;
496 delete_input_desc (fd);
501 /* Compute the Lisp form of the process status, p->status, from
502 the numeric status that was returned by `wait'. */
504 static Lisp_Object status_convert (int);
506 static void
507 update_status (struct Lisp_Process *p)
509 eassert (p->raw_status_new);
510 pset_status (p, status_convert (p->raw_status));
511 p->raw_status_new = 0;
514 /* Convert a process status word in Unix format to
515 the list that we use internally. */
517 static Lisp_Object
518 status_convert (int w)
520 if (WIFSTOPPED (w))
521 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
522 else if (WIFEXITED (w))
523 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
524 WCOREDUMP (w) ? Qt : Qnil));
525 else if (WIFSIGNALED (w))
526 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
527 WCOREDUMP (w) ? Qt : Qnil));
528 else
529 return Qrun;
532 /* Given a status-list, extract the three pieces of information
533 and store them individually through the three pointers. */
535 static void
536 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
538 Lisp_Object tem;
540 if (SYMBOLP (l))
542 *symbol = l;
543 *code = 0;
544 *coredump = 0;
546 else
548 *symbol = XCAR (l);
549 tem = XCDR (l);
550 *code = XFASTINT (XCAR (tem));
551 tem = XCDR (tem);
552 *coredump = !NILP (tem);
556 /* Return a string describing a process status list. */
558 static Lisp_Object
559 status_message (struct Lisp_Process *p)
561 Lisp_Object status = p->status;
562 Lisp_Object symbol;
563 int code;
564 bool coredump;
565 Lisp_Object string;
567 decode_status (status, &symbol, &code, &coredump);
569 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
571 char const *signame;
572 synchronize_system_messages_locale ();
573 signame = strsignal (code);
574 if (signame == 0)
575 string = build_string ("unknown");
576 else
578 int c1, c2;
580 string = build_unibyte_string (signame);
581 if (! NILP (Vlocale_coding_system))
582 string = (code_convert_string_norecord
583 (string, Vlocale_coding_system, 0));
584 c1 = STRING_CHAR (SDATA (string));
585 c2 = downcase (c1);
586 if (c1 != c2)
587 Faset (string, make_number (0), make_number (c2));
589 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
590 return concat2 (string, suffix);
592 else if (EQ (symbol, Qexit))
594 if (NETCONN1_P (p))
595 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
596 if (code == 0)
597 return build_string ("finished\n");
598 AUTO_STRING (prefix, "exited abnormally with code ");
599 string = Fnumber_to_string (make_number (code));
600 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
601 return concat3 (prefix, string, suffix);
603 else if (EQ (symbol, Qfailed))
605 AUTO_STRING (prefix, "failed with code ");
606 string = Fnumber_to_string (make_number (code));
607 AUTO_STRING (suffix, "\n");
608 return concat3 (prefix, string, suffix);
610 else
611 return Fcopy_sequence (Fsymbol_name (symbol));
614 enum { PTY_NAME_SIZE = 24 };
616 /* Open an available pty, returning a file descriptor.
617 Store into PTY_NAME the file name of the terminal corresponding to the pty.
618 Return -1 on failure. */
620 static int
621 allocate_pty (char pty_name[PTY_NAME_SIZE])
623 #ifdef HAVE_PTYS
624 int fd;
626 #ifdef PTY_ITERATION
627 PTY_ITERATION
628 #else
629 register int c, i;
630 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
631 for (i = 0; i < 16; i++)
632 #endif
634 #ifdef PTY_NAME_SPRINTF
635 PTY_NAME_SPRINTF
636 #else
637 sprintf (pty_name, "/dev/pty%c%x", c, i);
638 #endif /* no PTY_NAME_SPRINTF */
640 #ifdef PTY_OPEN
641 PTY_OPEN;
642 #else /* no PTY_OPEN */
643 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
644 #endif /* no PTY_OPEN */
646 if (fd >= 0)
648 #ifdef PTY_TTY_NAME_SPRINTF
649 PTY_TTY_NAME_SPRINTF
650 #else
651 sprintf (pty_name, "/dev/tty%c%x", c, i);
652 #endif /* no PTY_TTY_NAME_SPRINTF */
654 /* Set FD's close-on-exec flag. This is needed even if
655 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
656 doesn't require support for that combination.
657 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
658 doesn't work if the close-on-exec flag is set (Bug#20555).
659 Multithreaded platforms where posix_openpt ignores
660 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
661 have a race condition between the PTY_OPEN and here. */
662 fcntl (fd, F_SETFD, FD_CLOEXEC);
664 /* Check to make certain that both sides are available.
665 This avoids a nasty yet stupid bug in rlogins. */
666 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
668 emacs_close (fd);
669 # ifndef __sgi
670 continue;
671 # else
672 return -1;
673 # endif /* __sgi */
675 setup_pty (fd);
676 return fd;
679 #endif /* HAVE_PTYS */
680 return -1;
683 /* Allocate basically initialized process. */
685 static struct Lisp_Process *
686 allocate_process (void)
688 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
691 static Lisp_Object
692 make_process (Lisp_Object name)
694 register Lisp_Object val, tem, name1;
695 register struct Lisp_Process *p;
696 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
697 printmax_t i;
699 p = allocate_process ();
700 /* Initialize Lisp data. Note that allocate_process initializes all
701 Lisp data to nil, so do it only for slots which should not be nil. */
702 pset_status (p, Qrun);
703 pset_mark (p, Fmake_marker ());
705 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
706 non-Lisp data, so do it only for slots which should not be zero. */
707 p->infd = -1;
708 p->outfd = -1;
709 for (i = 0; i < PROCESS_OPEN_FDS; i++)
710 p->open_fd[i] = -1;
712 #ifdef HAVE_GNUTLS
713 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
714 #endif
716 /* If name is already in use, modify it until it is unused. */
718 name1 = name;
719 for (i = 1; ; i++)
721 tem = Fget_process (name1);
722 if (NILP (tem)) break;
723 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
725 name = name1;
726 pset_name (p, name);
727 pset_sentinel (p, Qinternal_default_process_sentinel);
728 pset_filter (p, Qinternal_default_process_filter);
729 XSETPROCESS (val, p);
730 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
731 return val;
734 static void
735 remove_process (register Lisp_Object proc)
737 register Lisp_Object pair;
739 pair = Frassq (proc, Vprocess_alist);
740 Vprocess_alist = Fdelq (pair, Vprocess_alist);
742 deactivate_process (proc);
746 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
747 doc: /* Return t if OBJECT is a process. */)
748 (Lisp_Object object)
750 return PROCESSP (object) ? Qt : Qnil;
753 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
754 doc: /* Return the process named NAME, or nil if there is none. */)
755 (register Lisp_Object name)
757 if (PROCESSP (name))
758 return name;
759 CHECK_STRING (name);
760 return Fcdr (Fassoc (name, Vprocess_alist));
763 /* This is how commands for the user decode process arguments. It
764 accepts a process, a process name, a buffer, a buffer name, or nil.
765 Buffers denote the first process in the buffer, and nil denotes the
766 current buffer. */
768 static Lisp_Object
769 get_process (register Lisp_Object name)
771 register Lisp_Object proc, obj;
772 if (STRINGP (name))
774 obj = Fget_process (name);
775 if (NILP (obj))
776 obj = Fget_buffer (name);
777 if (NILP (obj))
778 error ("Process %s does not exist", SDATA (name));
780 else if (NILP (name))
781 obj = Fcurrent_buffer ();
782 else
783 obj = name;
785 /* Now obj should be either a buffer object or a process object. */
786 if (BUFFERP (obj))
788 if (NILP (BVAR (XBUFFER (obj), name)))
789 error ("Attempt to get process for a dead buffer");
790 proc = Fget_buffer_process (obj);
791 if (NILP (proc))
792 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
794 else
796 CHECK_PROCESS (obj);
797 proc = obj;
799 return proc;
803 /* Fdelete_process promises to immediately forget about the process, but in
804 reality, Emacs needs to remember those processes until they have been
805 treated by the SIGCHLD handler and waitpid has been invoked on them;
806 otherwise they might fill up the kernel's process table.
808 Some processes created by call-process are also put onto this list.
810 Members of this list are (process-ID . filename) pairs. The
811 process-ID is a number; the filename, if a string, is a file that
812 needs to be removed after the process exits. */
813 static Lisp_Object deleted_pid_list;
815 void
816 record_deleted_pid (pid_t pid, Lisp_Object filename)
818 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
819 /* GC treated elements set to nil. */
820 Fdelq (Qnil, deleted_pid_list));
824 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
825 doc: /* Delete PROCESS: kill it and forget about it immediately.
826 PROCESS may be a process, a buffer, the name of a process or buffer, or
827 nil, indicating the current buffer's process. */)
828 (register Lisp_Object process)
830 register struct Lisp_Process *p;
832 process = get_process (process);
833 p = XPROCESS (process);
835 p->raw_status_new = 0;
836 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
838 pset_status (p, list2 (Qexit, make_number (0)));
839 p->tick = ++process_tick;
840 status_notify (p, NULL);
841 redisplay_preserve_echo_area (13);
843 else
845 if (p->alive)
846 record_kill_process (p, Qnil);
848 if (p->infd >= 0)
850 /* Update P's status, since record_kill_process will make the
851 SIGCHLD handler update deleted_pid_list, not *P. */
852 Lisp_Object symbol;
853 if (p->raw_status_new)
854 update_status (p);
855 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
856 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
857 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
859 p->tick = ++process_tick;
860 status_notify (p, NULL);
861 redisplay_preserve_echo_area (13);
864 remove_process (process);
865 return Qnil;
868 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
869 doc: /* Return the status of PROCESS.
870 The returned value is one of the following symbols:
871 run -- for a process that is running.
872 stop -- for a process stopped but continuable.
873 exit -- for a process that has exited.
874 signal -- for a process that has got a fatal signal.
875 open -- for a network stream connection that is open.
876 listen -- for a network stream server that is listening.
877 closed -- for a network stream connection that is closed.
878 connect -- when waiting for a non-blocking connection to complete.
879 failed -- when a non-blocking connection has failed.
880 nil -- if arg is a process name and no such process exists.
881 PROCESS may be a process, a buffer, the name of a process, or
882 nil, indicating the current buffer's process. */)
883 (register Lisp_Object process)
885 register struct Lisp_Process *p;
886 register Lisp_Object status;
888 if (STRINGP (process))
889 process = Fget_process (process);
890 else
891 process = get_process (process);
893 if (NILP (process))
894 return process;
896 p = XPROCESS (process);
897 if (p->raw_status_new)
898 update_status (p);
899 status = p->status;
900 if (CONSP (status))
901 status = XCAR (status);
902 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
904 if (EQ (status, Qexit))
905 status = Qclosed;
906 else if (EQ (p->command, Qt))
907 status = Qstop;
908 else if (EQ (status, Qrun))
909 status = Qopen;
911 return status;
914 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
915 1, 1, 0,
916 doc: /* Return the exit status of PROCESS or the signal number that killed it.
917 If PROCESS has not yet exited or died, return 0. */)
918 (register Lisp_Object process)
920 CHECK_PROCESS (process);
921 if (XPROCESS (process)->raw_status_new)
922 update_status (XPROCESS (process));
923 if (CONSP (XPROCESS (process)->status))
924 return XCAR (XCDR (XPROCESS (process)->status));
925 return make_number (0);
928 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
929 doc: /* Return the process id of PROCESS.
930 This is the pid of the external process which PROCESS uses or talks to.
931 For a network connection, this value is nil. */)
932 (register Lisp_Object process)
934 pid_t pid;
936 CHECK_PROCESS (process);
937 pid = XPROCESS (process)->pid;
938 return (pid ? make_fixnum_or_float (pid) : Qnil);
941 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
942 doc: /* Return the name of PROCESS, as a string.
943 This is the name of the program invoked in PROCESS,
944 possibly modified to make it unique among process names. */)
945 (register Lisp_Object process)
947 CHECK_PROCESS (process);
948 return XPROCESS (process)->name;
951 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
952 doc: /* Return the command that was executed to start PROCESS.
953 This is a list of strings, the first string being the program executed
954 and the rest of the strings being the arguments given to it.
955 For a network or serial process, this is nil (process is running) or t
956 (process is stopped). */)
957 (register Lisp_Object process)
959 CHECK_PROCESS (process);
960 return XPROCESS (process)->command;
963 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
964 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
965 This is the terminal that the process itself reads and writes on,
966 not the name of the pty that Emacs uses to talk with that terminal. */)
967 (register Lisp_Object process)
969 CHECK_PROCESS (process);
970 return XPROCESS (process)->tty_name;
973 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
974 2, 2, 0,
975 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
976 Return BUFFER. */)
977 (register Lisp_Object process, Lisp_Object buffer)
979 struct Lisp_Process *p;
981 CHECK_PROCESS (process);
982 if (!NILP (buffer))
983 CHECK_BUFFER (buffer);
984 p = XPROCESS (process);
985 pset_buffer (p, buffer);
986 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
987 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
988 setup_process_coding_systems (process);
989 return buffer;
992 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
993 1, 1, 0,
994 doc: /* Return the buffer PROCESS is associated with.
995 The default process filter inserts output from PROCESS into this buffer. */)
996 (register Lisp_Object process)
998 CHECK_PROCESS (process);
999 return XPROCESS (process)->buffer;
1002 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1003 1, 1, 0,
1004 doc: /* Return the marker for the end of the last output from PROCESS. */)
1005 (register Lisp_Object process)
1007 CHECK_PROCESS (process);
1008 return XPROCESS (process)->mark;
1011 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1012 2, 2, 0,
1013 doc: /* Give PROCESS the filter function FILTER; nil means default.
1014 A value of t means stop accepting output from the process.
1016 When a process has a non-default filter, its buffer is not used for output.
1017 Instead, each time it does output, the entire string of output is
1018 passed to the filter.
1020 The filter gets two arguments: the process and the string of output.
1021 The string argument is normally a multibyte string, except:
1022 - if the process's input coding system is no-conversion or raw-text,
1023 it is a unibyte string (the non-converted input), or else
1024 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1025 string (the result of converting the decoded input multibyte
1026 string to unibyte with `string-make-unibyte'). */)
1027 (register Lisp_Object process, Lisp_Object filter)
1029 struct Lisp_Process *p;
1031 CHECK_PROCESS (process);
1032 p = XPROCESS (process);
1034 /* Don't signal an error if the process's input file descriptor
1035 is closed. This could make debugging Lisp more difficult,
1036 for example when doing something like
1038 (setq process (start-process ...))
1039 (debug)
1040 (set-process-filter process ...) */
1042 if (NILP (filter))
1043 filter = Qinternal_default_process_filter;
1045 if (p->infd >= 0)
1047 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1049 FD_CLR (p->infd, &input_wait_mask);
1050 FD_CLR (p->infd, &non_keyboard_wait_mask);
1052 else if (EQ (p->filter, Qt)
1053 /* Network or serial process not stopped: */
1054 && !EQ (p->command, Qt))
1056 FD_SET (p->infd, &input_wait_mask);
1057 FD_SET (p->infd, &non_keyboard_wait_mask);
1061 pset_filter (p, filter);
1062 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1063 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1064 setup_process_coding_systems (process);
1065 return filter;
1068 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1069 1, 1, 0,
1070 doc: /* Return the filter function of PROCESS.
1071 See `set-process-filter' for more info on filter functions. */)
1072 (register Lisp_Object process)
1074 CHECK_PROCESS (process);
1075 return XPROCESS (process)->filter;
1078 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1079 2, 2, 0,
1080 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1081 The sentinel is called as a function when the process changes state.
1082 It gets two arguments: the process, and a string describing the change. */)
1083 (register Lisp_Object process, Lisp_Object sentinel)
1085 struct Lisp_Process *p;
1087 CHECK_PROCESS (process);
1088 p = XPROCESS (process);
1090 if (NILP (sentinel))
1091 sentinel = Qinternal_default_process_sentinel;
1093 pset_sentinel (p, sentinel);
1094 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1095 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1096 return sentinel;
1099 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1100 1, 1, 0,
1101 doc: /* Return the sentinel of PROCESS.
1102 See `set-process-sentinel' for more info on sentinels. */)
1103 (register Lisp_Object process)
1105 CHECK_PROCESS (process);
1106 return XPROCESS (process)->sentinel;
1109 DEFUN ("set-process-window-size", Fset_process_window_size,
1110 Sset_process_window_size, 3, 3, 0,
1111 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1112 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1114 CHECK_PROCESS (process);
1116 /* All known platforms store window sizes as 'unsigned short'. */
1117 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1118 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1120 if (XPROCESS (process)->infd < 0
1121 || (set_window_size (XPROCESS (process)->infd,
1122 XINT (height), XINT (width))
1123 < 0))
1124 return Qnil;
1125 else
1126 return Qt;
1129 DEFUN ("set-process-inherit-coding-system-flag",
1130 Fset_process_inherit_coding_system_flag,
1131 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1132 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1133 If the second argument FLAG is non-nil, then the variable
1134 `buffer-file-coding-system' of the buffer associated with PROCESS
1135 will be bound to the value of the coding system used to decode
1136 the process output.
1138 This is useful when the coding system specified for the process buffer
1139 leaves either the character code conversion or the end-of-line conversion
1140 unspecified, or if the coding system used to decode the process output
1141 is more appropriate for saving the process buffer.
1143 Binding the variable `inherit-process-coding-system' to non-nil before
1144 starting the process is an alternative way of setting the inherit flag
1145 for the process which will run.
1147 This function returns FLAG. */)
1148 (register Lisp_Object process, Lisp_Object flag)
1150 CHECK_PROCESS (process);
1151 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1152 return flag;
1155 DEFUN ("set-process-query-on-exit-flag",
1156 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1157 2, 2, 0,
1158 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1159 If the second argument FLAG is non-nil, Emacs will query the user before
1160 exiting or killing a buffer if PROCESS is running. This function
1161 returns FLAG. */)
1162 (register Lisp_Object process, Lisp_Object flag)
1164 CHECK_PROCESS (process);
1165 XPROCESS (process)->kill_without_query = NILP (flag);
1166 return flag;
1169 DEFUN ("process-query-on-exit-flag",
1170 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1171 1, 1, 0,
1172 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1173 (register Lisp_Object process)
1175 CHECK_PROCESS (process);
1176 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1179 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1180 1, 2, 0,
1181 doc: /* Return the contact info of PROCESS; t for a real child.
1182 For a network or serial connection, the value depends on the optional
1183 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1184 SERVICE) for a network connection or (PORT SPEED) for a serial
1185 connection. If KEY is t, the complete contact information for the
1186 connection is returned, else the specific value for the keyword KEY is
1187 returned. See `make-network-process' or `make-serial-process' for a
1188 list of keywords. */)
1189 (register Lisp_Object process, Lisp_Object key)
1191 Lisp_Object contact;
1193 CHECK_PROCESS (process);
1194 contact = XPROCESS (process)->childp;
1196 #ifdef DATAGRAM_SOCKETS
1197 if (DATAGRAM_CONN_P (process)
1198 && (EQ (key, Qt) || EQ (key, QCremote)))
1199 contact = Fplist_put (contact, QCremote,
1200 Fprocess_datagram_address (process));
1201 #endif
1203 if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1204 || EQ (key, Qt))
1205 return contact;
1206 if (NILP (key) && NETCONN_P (process))
1207 return list2 (Fplist_get (contact, QChost),
1208 Fplist_get (contact, QCservice));
1209 if (NILP (key) && SERIALCONN_P (process))
1210 return list2 (Fplist_get (contact, QCport),
1211 Fplist_get (contact, QCspeed));
1212 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1213 if the pipe process is useful for purposes other than receiving
1214 stderr. */
1215 if (NILP (key) && PIPECONN_P (process))
1216 return Qt;
1217 return Fplist_get (contact, key);
1220 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1221 1, 1, 0,
1222 doc: /* Return the plist of PROCESS. */)
1223 (register Lisp_Object process)
1225 CHECK_PROCESS (process);
1226 return XPROCESS (process)->plist;
1229 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1230 2, 2, 0,
1231 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1232 (register Lisp_Object process, Lisp_Object plist)
1234 CHECK_PROCESS (process);
1235 CHECK_LIST (plist);
1237 pset_plist (XPROCESS (process), plist);
1238 return plist;
1241 #if 0 /* Turned off because we don't currently record this info
1242 in the process. Perhaps add it. */
1243 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1244 doc: /* Return the connection type of PROCESS.
1245 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1246 a socket connection. */)
1247 (Lisp_Object process)
1249 return XPROCESS (process)->type;
1251 #endif
1253 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1254 doc: /* Return the connection type of PROCESS.
1255 The value is either the symbol `real', `network', or `serial'.
1256 PROCESS may be a process, a buffer, the name of a process or buffer, or
1257 nil, indicating the current buffer's process. */)
1258 (Lisp_Object process)
1260 Lisp_Object proc;
1261 proc = get_process (process);
1262 return XPROCESS (proc)->type;
1265 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1266 1, 2, 0,
1267 doc: /* Convert network ADDRESS from internal format to a string.
1268 A 4 or 5 element vector represents an IPv4 address (with port number).
1269 An 8 or 9 element vector represents an IPv6 address (with port number).
1270 If optional second argument OMIT-PORT is non-nil, don't include a port
1271 number in the string, even when present in ADDRESS.
1272 Returns nil if format of ADDRESS is invalid. */)
1273 (Lisp_Object address, Lisp_Object omit_port)
1275 if (NILP (address))
1276 return Qnil;
1278 if (STRINGP (address)) /* AF_LOCAL */
1279 return address;
1281 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1283 register struct Lisp_Vector *p = XVECTOR (address);
1284 ptrdiff_t size = p->header.size;
1285 Lisp_Object args[10];
1286 int nargs, i;
1287 char const *format;
1289 if (size == 4 || (size == 5 && !NILP (omit_port)))
1291 format = "%d.%d.%d.%d";
1292 nargs = 4;
1294 else if (size == 5)
1296 format = "%d.%d.%d.%d:%d";
1297 nargs = 5;
1299 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1301 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1302 nargs = 8;
1304 else if (size == 9)
1306 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1307 nargs = 9;
1309 else
1310 return Qnil;
1312 AUTO_STRING (format_obj, format);
1313 args[0] = format_obj;
1315 for (i = 0; i < nargs; i++)
1317 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1318 return Qnil;
1320 if (nargs <= 5 /* IPv4 */
1321 && i < 4 /* host, not port */
1322 && XINT (p->contents[i]) > 255)
1323 return Qnil;
1325 args[i + 1] = p->contents[i];
1328 return Fformat (nargs + 1, args);
1331 if (CONSP (address))
1333 AUTO_STRING (format, "<Family %d>");
1334 return CALLN (Fformat, format, Fcar (address));
1337 return Qnil;
1340 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1341 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1342 (void)
1344 return Fmapcar (Qcdr, Vprocess_alist);
1347 /* Starting asynchronous inferior processes. */
1349 static void start_process_unwind (Lisp_Object proc);
1351 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1352 doc: /* Start a program in a subprocess. Return the process object for it.
1354 This is similar to `start-process', but arguments are specified as
1355 keyword/argument pairs. The following arguments are defined:
1357 :name NAME -- NAME is name for process. It is modified if necessary
1358 to make it unique.
1360 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1361 with the process. Process output goes at end of that buffer, unless
1362 you specify an output stream or filter function to handle the output.
1363 BUFFER may be also nil, meaning that this process is not associated
1364 with any buffer.
1366 :command COMMAND -- COMMAND is a list starting with the program file
1367 name, followed by strings to give to the program as arguments.
1369 :coding CODING -- If CODING is a symbol, it specifies the coding
1370 system used for both reading and writing for this process. If CODING
1371 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1372 ENCODING is used for writing.
1374 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1375 the process is running. If BOOL is not given, query before exiting.
1377 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1378 In the stopped state, a process does not accept incoming data, but you
1379 can send outgoing data. The stopped state is cleared by
1380 `continue-process' and set by `stop-process'.
1382 :connection-type TYPE -- TYPE is control type of device used to
1383 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1384 to use a pty, or nil to use the default specified through
1385 `process-connection-type'.
1387 :filter FILTER -- Install FILTER as the process filter.
1389 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1391 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1392 to the standard error of subprocess. Specifying this implies
1393 `:connection-type' is set to `pipe'.
1395 usage: (make-process &rest ARGS) */)
1396 (ptrdiff_t nargs, Lisp_Object *args)
1398 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1399 Lisp_Object xstderr, stderrproc;
1400 ptrdiff_t count = SPECPDL_INDEX ();
1401 USE_SAFE_ALLOCA;
1403 if (nargs == 0)
1404 return Qnil;
1406 /* Save arguments for process-contact and clone-process. */
1407 contact = Flist (nargs, args);
1409 buffer = Fplist_get (contact, QCbuffer);
1410 if (!NILP (buffer))
1411 buffer = Fget_buffer_create (buffer);
1413 /* Make sure that the child will be able to chdir to the current
1414 buffer's current directory, or its unhandled equivalent. We
1415 can't just have the child check for an error when it does the
1416 chdir, since it's in a vfork. */
1417 current_dir = encode_current_directory ();
1419 name = Fplist_get (contact, QCname);
1420 CHECK_STRING (name);
1422 command = Fplist_get (contact, QCcommand);
1423 if (CONSP (command))
1424 program = XCAR (command);
1425 else
1426 program = Qnil;
1428 if (!NILP (program))
1429 CHECK_STRING (program);
1431 stderrproc = Qnil;
1432 xstderr = Fplist_get (contact, QCstderr);
1433 if (PROCESSP (xstderr))
1435 if (!PIPECONN_P (xstderr))
1436 error ("Process is not a pipe process");
1437 stderrproc = xstderr;
1439 else if (!NILP (xstderr))
1441 CHECK_STRING (program);
1442 stderrproc = CALLN (Fmake_pipe_process,
1443 QCname,
1444 concat2 (name, build_string (" stderr")),
1445 QCbuffer,
1446 Fget_buffer_create (xstderr));
1449 proc = make_process (name);
1450 /* If an error occurs and we can't start the process, we want to
1451 remove it from the process list. This means that each error
1452 check in create_process doesn't need to call remove_process
1453 itself; it's all taken care of here. */
1454 record_unwind_protect (start_process_unwind, proc);
1456 pset_childp (XPROCESS (proc), Qt);
1457 pset_plist (XPROCESS (proc), Qnil);
1458 pset_type (XPROCESS (proc), Qreal);
1459 pset_buffer (XPROCESS (proc), buffer);
1460 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1461 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1462 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1464 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
1465 XPROCESS (proc)->kill_without_query = 1;
1466 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1467 pset_command (XPROCESS (proc), Qt);
1469 tem = Fplist_get (contact, QCconnection_type);
1470 if (EQ (tem, Qpty))
1471 XPROCESS (proc)->pty_flag = true;
1472 else if (EQ (tem, Qpipe))
1473 XPROCESS (proc)->pty_flag = false;
1474 else if (NILP (tem))
1475 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1476 else
1477 report_file_error ("Unknown connection type", tem);
1479 if (!NILP (stderrproc))
1481 pset_stderrproc (XPROCESS (proc), stderrproc);
1483 XPROCESS (proc)->pty_flag = false;
1486 #ifdef HAVE_GNUTLS
1487 /* AKA GNUTLS_INITSTAGE(proc). */
1488 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1489 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1490 #endif
1492 XPROCESS (proc)->adaptive_read_buffering
1493 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1494 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1496 /* Make the process marker point into the process buffer (if any). */
1497 if (BUFFERP (buffer))
1498 set_marker_both (XPROCESS (proc)->mark, buffer,
1499 BUF_ZV (XBUFFER (buffer)),
1500 BUF_ZV_BYTE (XBUFFER (buffer)));
1503 /* Decide coding systems for communicating with the process. Here
1504 we don't setup the structure coding_system nor pay attention to
1505 unibyte mode. They are done in create_process. */
1507 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1508 Lisp_Object coding_systems = Qt;
1509 Lisp_Object val, *args2;
1511 tem = Fplist_get (contact, QCcoding);
1512 if (!NILP (tem))
1514 val = tem;
1515 if (CONSP (val))
1516 val = XCAR (val);
1518 else
1519 val = Vcoding_system_for_read;
1520 if (NILP (val))
1522 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1523 Lisp_Object tem2;
1524 SAFE_ALLOCA_LISP (args2, nargs2);
1525 ptrdiff_t i = 0;
1526 args2[i++] = Qstart_process;
1527 args2[i++] = name;
1528 args2[i++] = buffer;
1529 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1530 args2[i++] = XCAR (tem2);
1531 if (!NILP (program))
1532 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1533 if (CONSP (coding_systems))
1534 val = XCAR (coding_systems);
1535 else if (CONSP (Vdefault_process_coding_system))
1536 val = XCAR (Vdefault_process_coding_system);
1538 pset_decode_coding_system (XPROCESS (proc), val);
1540 if (!NILP (tem))
1542 val = tem;
1543 if (CONSP (val))
1544 val = XCDR (val);
1546 else
1547 val = Vcoding_system_for_write;
1548 if (NILP (val))
1550 if (EQ (coding_systems, Qt))
1552 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1553 Lisp_Object tem2;
1554 SAFE_ALLOCA_LISP (args2, nargs2);
1555 ptrdiff_t i = 0;
1556 args2[i++] = Qstart_process;
1557 args2[i++] = name;
1558 args2[i++] = buffer;
1559 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1560 args2[i++] = XCAR (tem2);
1561 if (!NILP (program))
1562 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1564 if (CONSP (coding_systems))
1565 val = XCDR (coding_systems);
1566 else if (CONSP (Vdefault_process_coding_system))
1567 val = XCDR (Vdefault_process_coding_system);
1569 pset_encode_coding_system (XPROCESS (proc), val);
1570 /* Note: At this moment, the above coding system may leave
1571 text-conversion or eol-conversion unspecified. They will be
1572 decided after we read output from the process and decode it by
1573 some coding system, or just before we actually send a text to
1574 the process. */
1578 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1579 XPROCESS (proc)->decoding_carryover = 0;
1580 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1582 XPROCESS (proc)->inherit_coding_system_flag
1583 = !(NILP (buffer) || !inherit_process_coding_system);
1585 if (!NILP (program))
1587 Lisp_Object program_args = XCDR (command);
1589 /* If program file name is not absolute, search our path for it.
1590 Put the name we will really use in TEM. */
1591 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1592 && !(SCHARS (program) > 1
1593 && IS_DEVICE_SEP (SREF (program, 1))))
1595 tem = Qnil;
1596 openp (Vexec_path, program, Vexec_suffixes, &tem,
1597 make_number (X_OK), false);
1598 if (NILP (tem))
1599 report_file_error ("Searching for program", program);
1600 tem = Fexpand_file_name (tem, Qnil);
1602 else
1604 if (!NILP (Ffile_directory_p (program)))
1605 error ("Specified program for new process is a directory");
1606 tem = program;
1609 /* Remove "/:" from TEM. */
1610 tem = remove_slash_colon (tem);
1612 Lisp_Object arg_encoding = Qnil;
1614 /* Encode the file name and put it in NEW_ARGV.
1615 That's where the child will use it to execute the program. */
1616 tem = list1 (ENCODE_FILE (tem));
1617 ptrdiff_t new_argc = 1;
1619 /* Here we encode arguments by the coding system used for sending
1620 data to the process. We don't support using different coding
1621 systems for encoding arguments and for encoding data sent to the
1622 process. */
1624 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1626 Lisp_Object arg = XCAR (tem2);
1627 CHECK_STRING (arg);
1628 if (STRING_MULTIBYTE (arg))
1630 if (NILP (arg_encoding))
1631 arg_encoding = (complement_process_encoding_system
1632 (XPROCESS (proc)->encode_coding_system));
1633 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1635 tem = Fcons (arg, tem);
1636 new_argc++;
1639 /* Now that everything is encoded we can collect the strings into
1640 NEW_ARGV. */
1641 char **new_argv;
1642 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1643 new_argv[new_argc] = 0;
1645 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1647 new_argv[i] = SSDATA (XCAR (tem));
1648 tem = XCDR (tem);
1651 create_process (proc, new_argv, current_dir);
1653 else
1654 create_pty (proc);
1656 SAFE_FREE ();
1657 return unbind_to (count, proc);
1660 /* This function is the unwind_protect form for Fstart_process. If
1661 PROC doesn't have its pid set, then we know someone has signaled
1662 an error and the process wasn't started successfully, so we should
1663 remove it from the process list. */
1664 static void
1665 start_process_unwind (Lisp_Object proc)
1667 if (!PROCESSP (proc))
1668 emacs_abort ();
1670 /* Was PROC started successfully?
1671 -2 is used for a pty with no process, eg for gdb. */
1672 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1673 remove_process (proc);
1676 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1678 static void
1679 close_process_fd (int *fd_addr)
1681 int fd = *fd_addr;
1682 if (0 <= fd)
1684 *fd_addr = -1;
1685 emacs_close (fd);
1689 /* Indexes of file descriptors in open_fds. */
1690 enum
1692 /* The pipe from Emacs to its subprocess. */
1693 SUBPROCESS_STDIN,
1694 WRITE_TO_SUBPROCESS,
1696 /* The main pipe from the subprocess to Emacs. */
1697 READ_FROM_SUBPROCESS,
1698 SUBPROCESS_STDOUT,
1700 /* The pipe from the subprocess to Emacs that is closed when the
1701 subprocess execs. */
1702 READ_FROM_EXEC_MONITOR,
1703 EXEC_MONITOR_OUTPUT
1706 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1708 static void
1709 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1711 struct Lisp_Process *p = XPROCESS (process);
1712 int inchannel, outchannel;
1713 pid_t pid;
1714 int vfork_errno;
1715 int forkin, forkout, forkerr = -1;
1716 bool pty_flag = 0;
1717 char pty_name[PTY_NAME_SIZE];
1718 Lisp_Object lisp_pty_name = Qnil;
1719 sigset_t oldset;
1721 inchannel = outchannel = -1;
1723 if (p->pty_flag)
1724 outchannel = inchannel = allocate_pty (pty_name);
1726 if (inchannel >= 0)
1728 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1729 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1730 /* On most USG systems it does not work to open the pty's tty here,
1731 then close it and reopen it in the child. */
1732 /* Don't let this terminal become our controlling terminal
1733 (in case we don't have one). */
1734 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1735 if (forkin < 0)
1736 report_file_error ("Opening pty", Qnil);
1737 p->open_fd[SUBPROCESS_STDIN] = forkin;
1738 #else
1739 forkin = forkout = -1;
1740 #endif /* not USG, or USG_SUBTTY_WORKS */
1741 pty_flag = 1;
1742 lisp_pty_name = build_string (pty_name);
1744 else
1746 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1747 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1748 report_file_error ("Creating pipe", Qnil);
1749 forkin = p->open_fd[SUBPROCESS_STDIN];
1750 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1751 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1752 forkout = p->open_fd[SUBPROCESS_STDOUT];
1754 if (!NILP (p->stderrproc))
1756 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
1758 forkerr = pp->open_fd[SUBPROCESS_STDOUT];
1760 /* Close unnecessary file descriptors. */
1761 close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
1762 close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
1766 #ifndef WINDOWSNT
1767 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1768 report_file_error ("Creating pipe", Qnil);
1769 #endif
1771 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1772 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1774 /* Record this as an active process, with its channels. */
1775 chan_process[inchannel] = process;
1776 p->infd = inchannel;
1777 p->outfd = outchannel;
1779 /* Previously we recorded the tty descriptor used in the subprocess.
1780 It was only used for getting the foreground tty process, so now
1781 we just reopen the device (see emacs_get_tty_pgrp) as this is
1782 more portable (see USG_SUBTTY_WORKS above). */
1784 p->pty_flag = pty_flag;
1785 pset_status (p, Qrun);
1787 if (!EQ (p->command, Qt))
1789 FD_SET (inchannel, &input_wait_mask);
1790 FD_SET (inchannel, &non_keyboard_wait_mask);
1793 if (inchannel > max_process_desc)
1794 max_process_desc = inchannel;
1796 /* This may signal an error. */
1797 setup_process_coding_systems (process);
1799 block_input ();
1800 block_child_signal (&oldset);
1802 #ifndef WINDOWSNT
1803 /* vfork, and prevent local vars from being clobbered by the vfork. */
1804 Lisp_Object volatile current_dir_volatile = current_dir;
1805 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1806 char **volatile new_argv_volatile = new_argv;
1807 int volatile forkin_volatile = forkin;
1808 int volatile forkout_volatile = forkout;
1809 int volatile forkerr_volatile = forkerr;
1810 struct Lisp_Process *p_volatile = p;
1812 pid = vfork ();
1814 current_dir = current_dir_volatile;
1815 lisp_pty_name = lisp_pty_name_volatile;
1816 new_argv = new_argv_volatile;
1817 forkin = forkin_volatile;
1818 forkout = forkout_volatile;
1819 forkerr = forkerr_volatile;
1820 p = p_volatile;
1822 pty_flag = p->pty_flag;
1824 if (pid == 0)
1825 #endif /* not WINDOWSNT */
1827 /* Make the pty be the controlling terminal of the process. */
1828 #ifdef HAVE_PTYS
1829 /* First, disconnect its current controlling terminal. */
1830 /* We tried doing setsid only if pty_flag, but it caused
1831 process_set_signal to fail on SGI when using a pipe. */
1832 setsid ();
1833 /* Make the pty's terminal the controlling terminal. */
1834 if (pty_flag && forkin >= 0)
1836 #ifdef TIOCSCTTY
1837 /* We ignore the return value
1838 because faith@cs.unc.edu says that is necessary on Linux. */
1839 ioctl (forkin, TIOCSCTTY, 0);
1840 #endif
1842 #if defined (LDISC1)
1843 if (pty_flag && forkin >= 0)
1845 struct termios t;
1846 tcgetattr (forkin, &t);
1847 t.c_lflag = LDISC1;
1848 if (tcsetattr (forkin, TCSANOW, &t) < 0)
1849 emacs_perror ("create_process/tcsetattr LDISC1");
1851 #else
1852 #if defined (NTTYDISC) && defined (TIOCSETD)
1853 if (pty_flag && forkin >= 0)
1855 /* Use new line discipline. */
1856 int ldisc = NTTYDISC;
1857 ioctl (forkin, TIOCSETD, &ldisc);
1859 #endif
1860 #endif
1861 #ifdef TIOCNOTTY
1862 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1863 can do TIOCSPGRP only to the process's controlling tty. */
1864 if (pty_flag)
1866 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1867 I can't test it since I don't have 4.3. */
1868 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1869 if (j >= 0)
1871 ioctl (j, TIOCNOTTY, 0);
1872 emacs_close (j);
1875 #endif /* TIOCNOTTY */
1877 #if !defined (DONT_REOPEN_PTY)
1878 /*** There is a suggestion that this ought to be a
1879 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1880 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1881 that system does seem to need this code, even though
1882 both TIOCSCTTY is defined. */
1883 /* Now close the pty (if we had it open) and reopen it.
1884 This makes the pty the controlling terminal of the subprocess. */
1885 if (pty_flag)
1888 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1889 would work? */
1890 if (forkin >= 0)
1891 emacs_close (forkin);
1892 forkout = forkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1894 if (forkin < 0)
1896 emacs_perror (SSDATA (lisp_pty_name));
1897 _exit (EXIT_CANCELED);
1901 #endif /* not DONT_REOPEN_PTY */
1903 #ifdef SETUP_SLAVE_PTY
1904 if (pty_flag)
1906 SETUP_SLAVE_PTY;
1908 #endif /* SETUP_SLAVE_PTY */
1909 #endif /* HAVE_PTYS */
1911 signal (SIGINT, SIG_DFL);
1912 signal (SIGQUIT, SIG_DFL);
1913 #ifdef SIGPROF
1914 signal (SIGPROF, SIG_DFL);
1915 #endif
1917 /* Emacs ignores SIGPIPE, but the child should not. */
1918 signal (SIGPIPE, SIG_DFL);
1920 /* Stop blocking SIGCHLD in the child. */
1921 unblock_child_signal (&oldset);
1923 if (pty_flag)
1924 child_setup_tty (forkout);
1926 if (forkerr < 0)
1927 forkerr = forkout;
1928 #ifdef WINDOWSNT
1929 pid = child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1930 #else /* not WINDOWSNT */
1931 child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1932 #endif /* not WINDOWSNT */
1935 /* Back in the parent process. */
1937 vfork_errno = errno;
1938 p->pid = pid;
1939 if (pid >= 0)
1940 p->alive = 1;
1942 /* Stop blocking in the parent. */
1943 unblock_child_signal (&oldset);
1944 unblock_input ();
1946 if (pid < 0)
1947 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1948 else
1950 /* vfork succeeded. */
1952 /* Close the pipe ends that the child uses, or the child's pty. */
1953 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
1954 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
1956 #ifdef WINDOWSNT
1957 register_child (pid, inchannel);
1958 #endif /* WINDOWSNT */
1960 pset_tty_name (p, lisp_pty_name);
1962 #ifndef WINDOWSNT
1963 /* Wait for child_setup to complete in case that vfork is
1964 actually defined as fork. The descriptor
1965 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1966 of a pipe is closed at the child side either by close-on-exec
1967 on successful execve or the _exit call in child_setup. */
1969 char dummy;
1971 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
1972 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
1973 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
1975 #endif
1976 if (!NILP (p->stderrproc))
1978 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
1979 close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
1984 static void
1985 create_pty (Lisp_Object process)
1987 struct Lisp_Process *p = XPROCESS (process);
1988 char pty_name[PTY_NAME_SIZE];
1989 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
1991 if (pty_fd >= 0)
1993 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
1994 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1995 /* On most USG systems it does not work to open the pty's tty here,
1996 then close it and reopen it in the child. */
1997 /* Don't let this terminal become our controlling terminal
1998 (in case we don't have one). */
1999 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2000 if (forkout < 0)
2001 report_file_error ("Opening pty", Qnil);
2002 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2003 #if defined (DONT_REOPEN_PTY)
2004 /* In the case that vfork is defined as fork, the parent process
2005 (Emacs) may send some data before the child process completes
2006 tty options setup. So we setup tty before forking. */
2007 child_setup_tty (forkout);
2008 #endif /* DONT_REOPEN_PTY */
2009 #endif /* not USG, or USG_SUBTTY_WORKS */
2011 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2013 /* Record this as an active process, with its channels.
2014 As a result, child_setup will close Emacs's side of the pipes. */
2015 chan_process[pty_fd] = process;
2016 p->infd = pty_fd;
2017 p->outfd = pty_fd;
2019 /* Previously we recorded the tty descriptor used in the subprocess.
2020 It was only used for getting the foreground tty process, so now
2021 we just reopen the device (see emacs_get_tty_pgrp) as this is
2022 more portable (see USG_SUBTTY_WORKS above). */
2024 p->pty_flag = 1;
2025 pset_status (p, Qrun);
2026 setup_process_coding_systems (process);
2028 FD_SET (pty_fd, &input_wait_mask);
2029 FD_SET (pty_fd, &non_keyboard_wait_mask);
2030 if (pty_fd > max_process_desc)
2031 max_process_desc = pty_fd;
2033 pset_tty_name (p, build_string (pty_name));
2036 p->pid = -2;
2039 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2040 0, MANY, 0,
2041 doc: /* Create and return a bidirectional pipe process.
2043 In Emacs, pipes are represented by process objects, so input and
2044 output work as for subprocesses, and `delete-process' closes a pipe.
2045 However, a pipe process has no process id, it cannot be signaled,
2046 and the status codes are different from normal processes.
2048 Arguments are specified as keyword/argument pairs. The following
2049 arguments are defined:
2051 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2053 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2054 with the process. Process output goes at the end of that buffer,
2055 unless you specify an output stream or filter function to handle the
2056 output. If BUFFER is not given, the value of NAME is used.
2058 :coding CODING -- If CODING is a symbol, it specifies the coding
2059 system used for both reading and writing for this process. If CODING
2060 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2061 ENCODING is used for writing.
2063 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2064 the process is running. If BOOL is not given, query before exiting.
2066 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2067 In the stopped state, a pipe process does not accept incoming data,
2068 but you can send outgoing data. The stopped state is cleared by
2069 `continue-process' and set by `stop-process'.
2071 :filter FILTER -- Install FILTER as the process filter.
2073 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2075 usage: (make-pipe-process &rest ARGS) */)
2076 (ptrdiff_t nargs, Lisp_Object *args)
2078 Lisp_Object proc, contact;
2079 struct Lisp_Process *p;
2080 Lisp_Object name, buffer;
2081 Lisp_Object tem;
2082 ptrdiff_t specpdl_count;
2083 int inchannel, outchannel;
2085 if (nargs == 0)
2086 return Qnil;
2088 contact = Flist (nargs, args);
2090 name = Fplist_get (contact, QCname);
2091 CHECK_STRING (name);
2092 proc = make_process (name);
2093 specpdl_count = SPECPDL_INDEX ();
2094 record_unwind_protect (remove_process, proc);
2095 p = XPROCESS (proc);
2097 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2098 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2099 report_file_error ("Creating pipe", Qnil);
2100 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2101 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2103 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2104 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2106 #ifdef WINDOWSNT
2107 register_aux_fd (inchannel);
2108 #endif
2110 /* Record this as an active process, with its channels. */
2111 chan_process[inchannel] = proc;
2112 p->infd = inchannel;
2113 p->outfd = outchannel;
2115 if (inchannel > max_process_desc)
2116 max_process_desc = inchannel;
2118 buffer = Fplist_get (contact, QCbuffer);
2119 if (NILP (buffer))
2120 buffer = name;
2121 buffer = Fget_buffer_create (buffer);
2122 pset_buffer (p, buffer);
2124 pset_childp (p, contact);
2125 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2126 pset_type (p, Qpipe);
2127 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2128 pset_filter (p, Fplist_get (contact, QCfilter));
2129 pset_log (p, Qnil);
2130 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2131 p->kill_without_query = 1;
2132 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2133 pset_command (p, Qt);
2134 eassert (! p->pty_flag);
2136 if (!EQ (p->command, Qt))
2138 FD_SET (inchannel, &input_wait_mask);
2139 FD_SET (inchannel, &non_keyboard_wait_mask);
2141 p->adaptive_read_buffering
2142 = (NILP (Vprocess_adaptive_read_buffering) ? 0
2143 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2145 /* Make the process marker point into the process buffer (if any). */
2146 if (BUFFERP (buffer))
2147 set_marker_both (p->mark, buffer,
2148 BUF_ZV (XBUFFER (buffer)),
2149 BUF_ZV_BYTE (XBUFFER (buffer)));
2152 /* Setup coding systems for communicating with the network stream. */
2154 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2155 Lisp_Object coding_systems = Qt;
2156 Lisp_Object val;
2158 tem = Fplist_get (contact, QCcoding);
2159 val = Qnil;
2160 if (!NILP (tem))
2162 val = tem;
2163 if (CONSP (val))
2164 val = XCAR (val);
2166 else if (!NILP (Vcoding_system_for_read))
2167 val = Vcoding_system_for_read;
2168 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2169 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2170 /* We dare not decode end-of-line format by setting VAL to
2171 Qraw_text, because the existing Emacs Lisp libraries
2172 assume that they receive bare code including a sequence of
2173 CR LF. */
2174 val = Qnil;
2175 else
2177 if (CONSP (coding_systems))
2178 val = XCAR (coding_systems);
2179 else if (CONSP (Vdefault_process_coding_system))
2180 val = XCAR (Vdefault_process_coding_system);
2181 else
2182 val = Qnil;
2184 pset_decode_coding_system (p, val);
2186 if (!NILP (tem))
2188 val = tem;
2189 if (CONSP (val))
2190 val = XCDR (val);
2192 else if (!NILP (Vcoding_system_for_write))
2193 val = Vcoding_system_for_write;
2194 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2195 val = Qnil;
2196 else
2198 if (CONSP (coding_systems))
2199 val = XCDR (coding_systems);
2200 else if (CONSP (Vdefault_process_coding_system))
2201 val = XCDR (Vdefault_process_coding_system);
2202 else
2203 val = Qnil;
2205 pset_encode_coding_system (p, val);
2207 /* This may signal an error. */
2208 setup_process_coding_systems (proc);
2210 specpdl_ptr = specpdl + specpdl_count;
2212 return proc;
2216 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2217 The address family of sa is not included in the result. */
2219 Lisp_Object
2220 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2222 Lisp_Object address;
2223 int i;
2224 unsigned char *cp;
2225 register struct Lisp_Vector *p;
2227 /* Workaround for a bug in getsockname on BSD: Names bound to
2228 sockets in the UNIX domain are inaccessible; getsockname returns
2229 a zero length name. */
2230 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2231 return empty_unibyte_string;
2233 switch (sa->sa_family)
2235 case AF_INET:
2237 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2238 len = sizeof (sin->sin_addr) + 1;
2239 address = Fmake_vector (make_number (len), Qnil);
2240 p = XVECTOR (address);
2241 p->contents[--len] = make_number (ntohs (sin->sin_port));
2242 cp = (unsigned char *) &sin->sin_addr;
2243 break;
2245 #ifdef AF_INET6
2246 case AF_INET6:
2248 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2249 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2250 len = sizeof (sin6->sin6_addr) / 2 + 1;
2251 address = Fmake_vector (make_number (len), Qnil);
2252 p = XVECTOR (address);
2253 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2254 for (i = 0; i < len; i++)
2255 p->contents[i] = make_number (ntohs (ip6[i]));
2256 return address;
2258 #endif
2259 #ifdef HAVE_LOCAL_SOCKETS
2260 case AF_LOCAL:
2262 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2263 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2264 /* If the first byte is NUL, the name is a Linux abstract
2265 socket name, and the name can contain embedded NULs. If
2266 it's not, we have a NUL-terminated string. Be careful not
2267 to walk past the end of the object looking for the name
2268 terminator, however. */
2269 if (name_length > 0 && sockun->sun_path[0] != '\0')
2271 const char *terminator
2272 = memchr (sockun->sun_path, '\0', name_length);
2274 if (terminator)
2275 name_length = terminator - (const char *) sockun->sun_path;
2278 return make_unibyte_string (sockun->sun_path, name_length);
2280 #endif
2281 default:
2282 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2283 address = Fcons (make_number (sa->sa_family),
2284 Fmake_vector (make_number (len), Qnil));
2285 p = XVECTOR (XCDR (address));
2286 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2287 break;
2290 i = 0;
2291 while (i < len)
2292 p->contents[i++] = make_number (*cp++);
2294 return address;
2298 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2300 static int
2301 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2303 register struct Lisp_Vector *p;
2305 if (VECTORP (address))
2307 p = XVECTOR (address);
2308 if (p->header.size == 5)
2310 *familyp = AF_INET;
2311 return sizeof (struct sockaddr_in);
2313 #ifdef AF_INET6
2314 else if (p->header.size == 9)
2316 *familyp = AF_INET6;
2317 return sizeof (struct sockaddr_in6);
2319 #endif
2321 #ifdef HAVE_LOCAL_SOCKETS
2322 else if (STRINGP (address))
2324 *familyp = AF_LOCAL;
2325 return sizeof (struct sockaddr_un);
2327 #endif
2328 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2329 && VECTORP (XCDR (address)))
2331 struct sockaddr *sa;
2332 p = XVECTOR (XCDR (address));
2333 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2334 return 0;
2335 *familyp = XINT (XCAR (address));
2336 return p->header.size + sizeof (sa->sa_family);
2338 return 0;
2341 /* Convert an address object (vector or string) to an internal sockaddr.
2343 The address format has been basically validated by
2344 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2345 it could have come from user data. So if FAMILY is not valid,
2346 we return after zeroing *SA. */
2348 static void
2349 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2351 register struct Lisp_Vector *p;
2352 register unsigned char *cp = NULL;
2353 register int i;
2354 EMACS_INT hostport;
2356 memset (sa, 0, len);
2358 if (VECTORP (address))
2360 p = XVECTOR (address);
2361 if (family == AF_INET)
2363 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2364 len = sizeof (sin->sin_addr) + 1;
2365 hostport = XINT (p->contents[--len]);
2366 sin->sin_port = htons (hostport);
2367 cp = (unsigned char *)&sin->sin_addr;
2368 sa->sa_family = family;
2370 #ifdef AF_INET6
2371 else if (family == AF_INET6)
2373 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2374 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2375 len = sizeof (sin6->sin6_addr) / 2 + 1;
2376 hostport = XINT (p->contents[--len]);
2377 sin6->sin6_port = htons (hostport);
2378 for (i = 0; i < len; i++)
2379 if (INTEGERP (p->contents[i]))
2381 int j = XFASTINT (p->contents[i]) & 0xffff;
2382 ip6[i] = ntohs (j);
2384 sa->sa_family = family;
2385 return;
2387 #endif
2388 else
2389 return;
2391 else if (STRINGP (address))
2393 #ifdef HAVE_LOCAL_SOCKETS
2394 if (family == AF_LOCAL)
2396 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2397 cp = SDATA (address);
2398 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2399 sockun->sun_path[i] = *cp++;
2400 sa->sa_family = family;
2402 #endif
2403 return;
2405 else
2407 p = XVECTOR (XCDR (address));
2408 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2411 for (i = 0; i < len; i++)
2412 if (INTEGERP (p->contents[i]))
2413 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2416 #ifdef DATAGRAM_SOCKETS
2417 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2418 1, 1, 0,
2419 doc: /* Get the current datagram address associated with PROCESS. */)
2420 (Lisp_Object process)
2422 int channel;
2424 CHECK_PROCESS (process);
2426 if (!DATAGRAM_CONN_P (process))
2427 return Qnil;
2429 channel = XPROCESS (process)->infd;
2430 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2431 datagram_address[channel].len);
2434 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2435 2, 2, 0,
2436 doc: /* Set the datagram address for PROCESS to ADDRESS.
2437 Returns nil upon error setting address, ADDRESS otherwise. */)
2438 (Lisp_Object process, Lisp_Object address)
2440 int channel;
2441 int family, len;
2443 CHECK_PROCESS (process);
2445 if (!DATAGRAM_CONN_P (process))
2446 return Qnil;
2448 channel = XPROCESS (process)->infd;
2450 len = get_lisp_to_sockaddr_size (address, &family);
2451 if (len == 0 || datagram_address[channel].len != len)
2452 return Qnil;
2453 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2454 return address;
2456 #endif
2459 static const struct socket_options {
2460 /* The name of this option. Should be lowercase version of option
2461 name without SO_ prefix. */
2462 const char *name;
2463 /* Option level SOL_... */
2464 int optlevel;
2465 /* Option number SO_... */
2466 int optnum;
2467 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2468 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2469 } socket_options[] =
2471 #ifdef SO_BINDTODEVICE
2472 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2473 #endif
2474 #ifdef SO_BROADCAST
2475 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2476 #endif
2477 #ifdef SO_DONTROUTE
2478 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2479 #endif
2480 #ifdef SO_KEEPALIVE
2481 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2482 #endif
2483 #ifdef SO_LINGER
2484 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2485 #endif
2486 #ifdef SO_OOBINLINE
2487 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2488 #endif
2489 #ifdef SO_PRIORITY
2490 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2491 #endif
2492 #ifdef SO_REUSEADDR
2493 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2494 #endif
2495 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2498 /* Set option OPT to value VAL on socket S.
2500 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2501 Signals an error if setting a known option fails.
2504 static int
2505 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2507 char *name;
2508 const struct socket_options *sopt;
2509 int ret = 0;
2511 CHECK_SYMBOL (opt);
2513 name = SSDATA (SYMBOL_NAME (opt));
2514 for (sopt = socket_options; sopt->name; sopt++)
2515 if (strcmp (name, sopt->name) == 0)
2516 break;
2518 switch (sopt->opttype)
2520 case SOPT_BOOL:
2522 int optval;
2523 optval = NILP (val) ? 0 : 1;
2524 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2525 &optval, sizeof (optval));
2526 break;
2529 case SOPT_INT:
2531 int optval;
2532 if (TYPE_RANGED_INTEGERP (int, val))
2533 optval = XINT (val);
2534 else
2535 error ("Bad option value for %s", name);
2536 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2537 &optval, sizeof (optval));
2538 break;
2541 #ifdef SO_BINDTODEVICE
2542 case SOPT_IFNAME:
2544 char devname[IFNAMSIZ + 1];
2546 /* This is broken, at least in the Linux 2.4 kernel.
2547 To unbind, the arg must be a zero integer, not the empty string.
2548 This should work on all systems. KFS. 2003-09-23. */
2549 memset (devname, 0, sizeof devname);
2550 if (STRINGP (val))
2552 char *arg = SSDATA (val);
2553 int len = min (strlen (arg), IFNAMSIZ);
2554 memcpy (devname, arg, len);
2556 else if (!NILP (val))
2557 error ("Bad option value for %s", name);
2558 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2559 devname, IFNAMSIZ);
2560 break;
2562 #endif
2564 #ifdef SO_LINGER
2565 case SOPT_LINGER:
2567 struct linger linger;
2569 linger.l_onoff = 1;
2570 linger.l_linger = 0;
2571 if (TYPE_RANGED_INTEGERP (int, val))
2572 linger.l_linger = XINT (val);
2573 else
2574 linger.l_onoff = NILP (val) ? 0 : 1;
2575 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2576 &linger, sizeof (linger));
2577 break;
2579 #endif
2581 default:
2582 return 0;
2585 if (ret < 0)
2587 int setsockopt_errno = errno;
2588 report_file_errno ("Cannot set network option", list2 (opt, val),
2589 setsockopt_errno);
2592 return (1 << sopt->optbit);
2596 DEFUN ("set-network-process-option",
2597 Fset_network_process_option, Sset_network_process_option,
2598 3, 4, 0,
2599 doc: /* For network process PROCESS set option OPTION to value VALUE.
2600 See `make-network-process' for a list of options and values.
2601 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2602 OPTION is not a supported option, return nil instead; otherwise return t. */)
2603 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2605 int s;
2606 struct Lisp_Process *p;
2608 CHECK_PROCESS (process);
2609 p = XPROCESS (process);
2610 if (!NETCONN1_P (p))
2611 error ("Process is not a network process");
2613 s = p->infd;
2614 if (s < 0)
2615 error ("Process is not running");
2617 if (set_socket_option (s, option, value))
2619 pset_childp (p, Fplist_put (p->childp, option, value));
2620 return Qt;
2623 if (NILP (no_error))
2624 error ("Unknown or unsupported option");
2626 return Qnil;
2630 DEFUN ("serial-process-configure",
2631 Fserial_process_configure,
2632 Sserial_process_configure,
2633 0, MANY, 0,
2634 doc: /* Configure speed, bytesize, etc. of a serial process.
2636 Arguments are specified as keyword/argument pairs. Attributes that
2637 are not given are re-initialized from the process's current
2638 configuration (available via the function `process-contact') or set to
2639 reasonable default values. The following arguments are defined:
2641 :process PROCESS
2642 :name NAME
2643 :buffer BUFFER
2644 :port PORT
2645 -- Any of these arguments can be given to identify the process that is
2646 to be configured. If none of these arguments is given, the current
2647 buffer's process is used.
2649 :speed SPEED -- SPEED is the speed of the serial port in bits per
2650 second, also called baud rate. Any value can be given for SPEED, but
2651 most serial ports work only at a few defined values between 1200 and
2652 115200, with 9600 being the most common value. If SPEED is nil, the
2653 serial port is not configured any further, i.e., all other arguments
2654 are ignored. This may be useful for special serial ports such as
2655 Bluetooth-to-serial converters which can only be configured through AT
2656 commands. A value of nil for SPEED can be used only when passed
2657 through `make-serial-process' or `serial-term'.
2659 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2660 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2662 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2663 `odd' (use odd parity), or the symbol `even' (use even parity). If
2664 PARITY is not given, no parity is used.
2666 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2667 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2668 is not given or nil, 1 stopbit is used.
2670 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2671 flowcontrol to be used, which is either nil (don't use flowcontrol),
2672 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2673 (use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2674 flowcontrol is used.
2676 `serial-process-configure' is called by `make-serial-process' for the
2677 initial configuration of the serial port.
2679 Examples:
2681 (serial-process-configure :process "/dev/ttyS0" :speed 1200)
2683 (serial-process-configure
2684 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2686 (serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2688 usage: (serial-process-configure &rest ARGS) */)
2689 (ptrdiff_t nargs, Lisp_Object *args)
2691 struct Lisp_Process *p;
2692 Lisp_Object contact = Qnil;
2693 Lisp_Object proc = Qnil;
2695 contact = Flist (nargs, args);
2697 proc = Fplist_get (contact, QCprocess);
2698 if (NILP (proc))
2699 proc = Fplist_get (contact, QCname);
2700 if (NILP (proc))
2701 proc = Fplist_get (contact, QCbuffer);
2702 if (NILP (proc))
2703 proc = Fplist_get (contact, QCport);
2704 proc = get_process (proc);
2705 p = XPROCESS (proc);
2706 if (!EQ (p->type, Qserial))
2707 error ("Not a serial process");
2709 if (NILP (Fplist_get (p->childp, QCspeed)))
2710 return Qnil;
2712 serial_configure (p, contact);
2713 return Qnil;
2716 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2717 0, MANY, 0,
2718 doc: /* Create and return a serial port process.
2720 In Emacs, serial port connections are represented by process objects,
2721 so input and output work as for subprocesses, and `delete-process'
2722 closes a serial port connection. However, a serial process has no
2723 process id, it cannot be signaled, and the status codes are different
2724 from normal processes.
2726 `make-serial-process' creates a process and a buffer, on which you
2727 probably want to use `process-send-string'. Try \\[serial-term] for
2728 an interactive terminal. See below for examples.
2730 Arguments are specified as keyword/argument pairs. The following
2731 arguments are defined:
2733 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2734 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2735 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2736 the backslashes in strings).
2738 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2739 which this function calls.
2741 :name NAME -- NAME is the name of the process. If NAME is not given,
2742 the value of PORT is used.
2744 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2745 with the process. Process output goes at the end of that buffer,
2746 unless you specify an output stream or filter function to handle the
2747 output. If BUFFER is not given, the value of NAME is used.
2749 :coding CODING -- If CODING is a symbol, it specifies the coding
2750 system used for both reading and writing for this process. If CODING
2751 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2752 ENCODING is used for writing.
2754 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2755 the process is running. If BOOL is not given, query before exiting.
2757 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2758 In the stopped state, a serial process does not accept incoming data,
2759 but you can send outgoing data. The stopped state is cleared by
2760 `continue-process' and set by `stop-process'.
2762 :filter FILTER -- Install FILTER as the process filter.
2764 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2766 :plist PLIST -- Install PLIST as the initial plist of the process.
2768 :bytesize
2769 :parity
2770 :stopbits
2771 :flowcontrol
2772 -- This function calls `serial-process-configure' to handle these
2773 arguments.
2775 The original argument list, possibly modified by later configuration,
2776 is available via the function `process-contact'.
2778 Examples:
2780 (make-serial-process :port "/dev/ttyS0" :speed 9600)
2782 (make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2784 (make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2786 (make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2788 usage: (make-serial-process &rest ARGS) */)
2789 (ptrdiff_t nargs, Lisp_Object *args)
2791 int fd = -1;
2792 Lisp_Object proc, contact, port;
2793 struct Lisp_Process *p;
2794 Lisp_Object name, buffer;
2795 Lisp_Object tem, val;
2796 ptrdiff_t specpdl_count;
2798 if (nargs == 0)
2799 return Qnil;
2801 contact = Flist (nargs, args);
2803 port = Fplist_get (contact, QCport);
2804 if (NILP (port))
2805 error ("No port specified");
2806 CHECK_STRING (port);
2808 if (NILP (Fplist_member (contact, QCspeed)))
2809 error (":speed not specified");
2810 if (!NILP (Fplist_get (contact, QCspeed)))
2811 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2813 name = Fplist_get (contact, QCname);
2814 if (NILP (name))
2815 name = port;
2816 CHECK_STRING (name);
2817 proc = make_process (name);
2818 specpdl_count = SPECPDL_INDEX ();
2819 record_unwind_protect (remove_process, proc);
2820 p = XPROCESS (proc);
2822 fd = serial_open (port);
2823 p->open_fd[SUBPROCESS_STDIN] = fd;
2824 p->infd = fd;
2825 p->outfd = fd;
2826 if (fd > max_process_desc)
2827 max_process_desc = fd;
2828 chan_process[fd] = proc;
2830 buffer = Fplist_get (contact, QCbuffer);
2831 if (NILP (buffer))
2832 buffer = name;
2833 buffer = Fget_buffer_create (buffer);
2834 pset_buffer (p, buffer);
2836 pset_childp (p, contact);
2837 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2838 pset_type (p, Qserial);
2839 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2840 pset_filter (p, Fplist_get (contact, QCfilter));
2841 pset_log (p, Qnil);
2842 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2843 p->kill_without_query = 1;
2844 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2845 pset_command (p, Qt);
2846 eassert (! p->pty_flag);
2848 if (!EQ (p->command, Qt))
2850 FD_SET (fd, &input_wait_mask);
2851 FD_SET (fd, &non_keyboard_wait_mask);
2854 if (BUFFERP (buffer))
2856 set_marker_both (p->mark, buffer,
2857 BUF_ZV (XBUFFER (buffer)),
2858 BUF_ZV_BYTE (XBUFFER (buffer)));
2861 tem = Fplist_member (contact, QCcoding);
2862 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2863 tem = Qnil;
2865 val = Qnil;
2866 if (!NILP (tem))
2868 val = XCAR (XCDR (tem));
2869 if (CONSP (val))
2870 val = XCAR (val);
2872 else if (!NILP (Vcoding_system_for_read))
2873 val = Vcoding_system_for_read;
2874 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2875 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2876 val = Qnil;
2877 pset_decode_coding_system (p, val);
2879 val = Qnil;
2880 if (!NILP (tem))
2882 val = XCAR (XCDR (tem));
2883 if (CONSP (val))
2884 val = XCDR (val);
2886 else if (!NILP (Vcoding_system_for_write))
2887 val = Vcoding_system_for_write;
2888 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2889 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2890 val = Qnil;
2891 pset_encode_coding_system (p, val);
2893 setup_process_coding_systems (proc);
2894 pset_decoding_buf (p, empty_unibyte_string);
2895 p->decoding_carryover = 0;
2896 pset_encoding_buf (p, empty_unibyte_string);
2897 p->inherit_coding_system_flag
2898 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2900 Fserial_process_configure (nargs, args);
2902 specpdl_ptr = specpdl + specpdl_count;
2904 return proc;
2907 /* Create a network stream/datagram client/server process. Treated
2908 exactly like a normal process when reading and writing. Primary
2909 differences are in status display and process deletion. A network
2910 connection has no PID; you cannot signal it. All you can do is
2911 stop/continue it and deactivate/close it via delete-process. */
2913 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2914 0, MANY, 0,
2915 doc: /* Create and return a network server or client process.
2917 In Emacs, network connections are represented by process objects, so
2918 input and output work as for subprocesses and `delete-process' closes
2919 a network connection. However, a network process has no process id,
2920 it cannot be signaled, and the status codes are different from normal
2921 processes.
2923 Arguments are specified as keyword/argument pairs. The following
2924 arguments are defined:
2926 :name NAME -- NAME is name for process. It is modified if necessary
2927 to make it unique.
2929 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2930 with the process. Process output goes at end of that buffer, unless
2931 you specify an output stream or filter function to handle the output.
2932 BUFFER may be also nil, meaning that this process is not associated
2933 with any buffer.
2935 :host HOST -- HOST is name of the host to connect to, or its IP
2936 address. The symbol `local' specifies the local host. If specified
2937 for a server process, it must be a valid name or address for the local
2938 host, and only clients connecting to that address will be accepted.
2940 :service SERVICE -- SERVICE is name of the service desired, or an
2941 integer specifying a port number to connect to. If SERVICE is t,
2942 a random port number is selected for the server. (If Emacs was
2943 compiled with getaddrinfo, a port number can also be specified as a
2944 string, e.g. "80", as well as an integer. This is not portable.)
2946 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2947 stream type connection, `datagram' creates a datagram type connection,
2948 `seqpacket' creates a reliable datagram connection.
2950 :family FAMILY -- FAMILY is the address (and protocol) family for the
2951 service specified by HOST and SERVICE. The default (nil) is to use
2952 whatever address family (IPv4 or IPv6) that is defined for the host
2953 and port number specified by HOST and SERVICE. Other address families
2954 supported are:
2955 local -- for a local (i.e. UNIX) address specified by SERVICE.
2956 ipv4 -- use IPv4 address family only.
2957 ipv6 -- use IPv6 address family only.
2959 :local ADDRESS -- ADDRESS is the local address used for the connection.
2960 This parameter is ignored when opening a client process. When specified
2961 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2963 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2964 connection. This parameter is ignored when opening a stream server
2965 process. For a datagram server process, it specifies the initial
2966 setting of the remote datagram address. When specified for a client
2967 process, the FAMILY, HOST, and SERVICE args are ignored.
2969 The format of ADDRESS depends on the address family:
2970 - An IPv4 address is represented as an vector of integers [A B C D P]
2971 corresponding to numeric IP address A.B.C.D and port number P.
2972 - A local address is represented as a string with the address in the
2973 local address space.
2974 - An "unsupported family" address is represented by a cons (F . AV)
2975 where F is the family number and AV is a vector containing the socket
2976 address data with one element per address data byte. Do not rely on
2977 this format in portable code, as it may depend on implementation
2978 defined constants, data sizes, and data structure alignment.
2980 :coding CODING -- If CODING is a symbol, it specifies the coding
2981 system used for both reading and writing for this process. If CODING
2982 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2983 ENCODING is used for writing.
2985 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2986 return without waiting for the connection to complete; instead, the
2987 sentinel function will be called with second arg matching "open" (if
2988 successful) or "failed" when the connect completes. Default is to use
2989 a blocking connect (i.e. wait) for stream type connections.
2991 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2992 running when Emacs is exited.
2994 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2995 In the stopped state, a server process does not accept new
2996 connections, and a client process does not handle incoming traffic.
2997 The stopped state is cleared by `continue-process' and set by
2998 `stop-process'.
3000 :filter FILTER -- Install FILTER as the process filter.
3002 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3003 process filter are multibyte, otherwise they are unibyte.
3004 If this keyword is not specified, the strings are multibyte if
3005 the default value of `enable-multibyte-characters' is non-nil.
3007 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3009 :log LOG -- Install LOG as the server process log function. This
3010 function is called when the server accepts a network connection from a
3011 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3012 is the server process, CLIENT is the new process for the connection,
3013 and MESSAGE is a string.
3015 :plist PLIST -- Install PLIST as the new process's initial plist.
3017 :server QLEN -- if QLEN is non-nil, create a server process for the
3018 specified FAMILY, SERVICE, and connection type (stream or datagram).
3019 If QLEN is an integer, it is used as the max. length of the server's
3020 pending connection queue (also known as the backlog); the default
3021 queue length is 5. Default is to create a client process.
3023 The following network options can be specified for this connection:
3025 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3026 :dontroute BOOL -- Only send to directly connected hosts.
3027 :keepalive BOOL -- Send keep-alive messages on network stream.
3028 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3029 :oobinline BOOL -- Place out-of-band data in receive data stream.
3030 :priority INT -- Set protocol defined priority for sent packets.
3031 :reuseaddr BOOL -- Allow reusing a recently used local address
3032 (this is allowed by default for a server process).
3033 :bindtodevice NAME -- bind to interface NAME. Using this may require
3034 special privileges on some systems.
3036 Consult the relevant system programmer's manual pages for more
3037 information on using these options.
3040 A server process will listen for and accept connections from clients.
3041 When a client connection is accepted, a new network process is created
3042 for the connection with the following parameters:
3044 - The client's process name is constructed by concatenating the server
3045 process's NAME and a client identification string.
3046 - If the FILTER argument is non-nil, the client process will not get a
3047 separate process buffer; otherwise, the client's process buffer is a newly
3048 created buffer named after the server process's BUFFER name or process
3049 NAME concatenated with the client identification string.
3050 - The connection type and the process filter and sentinel parameters are
3051 inherited from the server process's TYPE, FILTER and SENTINEL.
3052 - The client process's contact info is set according to the client's
3053 addressing information (typically an IP address and a port number).
3054 - The client process's plist is initialized from the server's plist.
3056 Notice that the FILTER and SENTINEL args are never used directly by
3057 the server process. Also, the BUFFER argument is not used directly by
3058 the server process, but via the optional :log function, accepted (and
3059 failed) connections may be logged in the server process's buffer.
3061 The original argument list, modified with the actual connection
3062 information, is available via the `process-contact' function.
3064 usage: (make-network-process &rest ARGS) */)
3065 (ptrdiff_t nargs, Lisp_Object *args)
3067 Lisp_Object proc;
3068 Lisp_Object contact;
3069 struct Lisp_Process *p;
3070 #ifdef HAVE_GETADDRINFO
3071 struct addrinfo ai, *res, *lres;
3072 struct addrinfo hints;
3073 const char *portstring;
3074 char portbuf[128];
3075 #else /* HAVE_GETADDRINFO */
3076 struct _emacs_addrinfo
3078 int ai_family;
3079 int ai_socktype;
3080 int ai_protocol;
3081 int ai_addrlen;
3082 struct sockaddr *ai_addr;
3083 struct _emacs_addrinfo *ai_next;
3084 } ai, *res, *lres;
3085 #endif /* HAVE_GETADDRINFO */
3086 struct sockaddr_in address_in;
3087 #ifdef HAVE_LOCAL_SOCKETS
3088 struct sockaddr_un address_un;
3089 #endif
3090 int port;
3091 int ret = 0;
3092 int xerrno = 0;
3093 int s = -1, outch, inch;
3094 ptrdiff_t count = SPECPDL_INDEX ();
3095 ptrdiff_t count1;
3096 Lisp_Object colon_address; /* Either QClocal or QCremote. */
3097 Lisp_Object tem;
3098 Lisp_Object name, buffer, host, service, address;
3099 Lisp_Object filter, sentinel;
3100 bool is_non_blocking_client = 0;
3101 bool is_server = 0;
3102 int backlog = 5;
3103 int socktype;
3104 int family = -1;
3106 if (nargs == 0)
3107 return Qnil;
3109 /* Save arguments for process-contact and clone-process. */
3110 contact = Flist (nargs, args);
3112 #ifdef WINDOWSNT
3113 /* Ensure socket support is loaded if available. */
3114 init_winsock (TRUE);
3115 #endif
3117 /* :type TYPE (nil: stream, datagram */
3118 tem = Fplist_get (contact, QCtype);
3119 if (NILP (tem))
3120 socktype = SOCK_STREAM;
3121 #ifdef DATAGRAM_SOCKETS
3122 else if (EQ (tem, Qdatagram))
3123 socktype = SOCK_DGRAM;
3124 #endif
3125 #ifdef HAVE_SEQPACKET
3126 else if (EQ (tem, Qseqpacket))
3127 socktype = SOCK_SEQPACKET;
3128 #endif
3129 else
3130 error ("Unsupported connection type");
3132 /* :server BOOL */
3133 tem = Fplist_get (contact, QCserver);
3134 if (!NILP (tem))
3136 /* Don't support network sockets when non-blocking mode is
3137 not available, since a blocked Emacs is not useful. */
3138 is_server = 1;
3139 if (TYPE_RANGED_INTEGERP (int, tem))
3140 backlog = XINT (tem);
3143 /* Make colon_address an alias for :local (server) or :remote (client). */
3144 colon_address = is_server ? QClocal : QCremote;
3146 /* :nowait BOOL */
3147 if (!is_server && socktype != SOCK_DGRAM
3148 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3150 #ifndef NON_BLOCKING_CONNECT
3151 error ("Non-blocking connect not supported");
3152 #else
3153 is_non_blocking_client = 1;
3154 #endif
3157 name = Fplist_get (contact, QCname);
3158 buffer = Fplist_get (contact, QCbuffer);
3159 filter = Fplist_get (contact, QCfilter);
3160 sentinel = Fplist_get (contact, QCsentinel);
3162 CHECK_STRING (name);
3164 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3165 ai.ai_socktype = socktype;
3166 ai.ai_protocol = 0;
3167 ai.ai_next = NULL;
3168 res = &ai;
3170 /* :local ADDRESS or :remote ADDRESS */
3171 address = Fplist_get (contact, colon_address);
3172 if (!NILP (address))
3174 host = service = Qnil;
3176 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3177 error ("Malformed :address");
3178 ai.ai_family = family;
3179 ai.ai_addr = alloca (ai.ai_addrlen);
3180 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3181 goto open_socket;
3184 /* :family FAMILY -- nil (for Inet), local, or integer. */
3185 tem = Fplist_get (contact, QCfamily);
3186 if (NILP (tem))
3188 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3189 family = AF_UNSPEC;
3190 #else
3191 family = AF_INET;
3192 #endif
3194 #ifdef HAVE_LOCAL_SOCKETS
3195 else if (EQ (tem, Qlocal))
3196 family = AF_LOCAL;
3197 #endif
3198 #ifdef AF_INET6
3199 else if (EQ (tem, Qipv6))
3200 family = AF_INET6;
3201 #endif
3202 else if (EQ (tem, Qipv4))
3203 family = AF_INET;
3204 else if (TYPE_RANGED_INTEGERP (int, tem))
3205 family = XINT (tem);
3206 else
3207 error ("Unknown address family");
3209 ai.ai_family = family;
3211 /* :service SERVICE -- string, integer (port number), or t (random port). */
3212 service = Fplist_get (contact, QCservice);
3214 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3215 host = Fplist_get (contact, QChost);
3216 if (!NILP (host))
3218 if (EQ (host, Qlocal))
3219 /* Depending on setup, "localhost" may map to different IPv4 and/or
3220 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3221 host = build_string ("127.0.0.1");
3222 CHECK_STRING (host);
3225 #ifdef HAVE_LOCAL_SOCKETS
3226 if (family == AF_LOCAL)
3228 if (!NILP (host))
3230 message (":family local ignores the :host property");
3231 contact = Fplist_put (contact, QChost, Qnil);
3232 host = Qnil;
3234 CHECK_STRING (service);
3235 memset (&address_un, 0, sizeof address_un);
3236 address_un.sun_family = AF_LOCAL;
3237 if (sizeof address_un.sun_path <= SBYTES (service))
3238 error ("Service name too long");
3239 lispstpcpy (address_un.sun_path, service);
3240 ai.ai_addr = (struct sockaddr *) &address_un;
3241 ai.ai_addrlen = sizeof address_un;
3242 goto open_socket;
3244 #endif
3246 /* Slow down polling to every ten seconds.
3247 Some kernels have a bug which causes retrying connect to fail
3248 after a connect. Polling can interfere with gethostbyname too. */
3249 #ifdef POLL_FOR_INPUT
3250 if (socktype != SOCK_DGRAM)
3252 record_unwind_protect_void (run_all_atimers);
3253 bind_polling_period (10);
3255 #endif
3257 #ifdef HAVE_GETADDRINFO
3258 /* If we have a host, use getaddrinfo to resolve both host and service.
3259 Otherwise, use getservbyname to lookup the service. */
3260 if (!NILP (host))
3263 /* SERVICE can either be a string or int.
3264 Convert to a C string for later use by getaddrinfo. */
3265 if (EQ (service, Qt))
3266 portstring = "0";
3267 else if (INTEGERP (service))
3269 sprintf (portbuf, "%"pI"d", XINT (service));
3270 portstring = portbuf;
3272 else
3274 CHECK_STRING (service);
3275 portstring = SSDATA (service);
3278 immediate_quit = 1;
3279 QUIT;
3280 memset (&hints, 0, sizeof (hints));
3281 hints.ai_flags = 0;
3282 hints.ai_family = family;
3283 hints.ai_socktype = socktype;
3284 hints.ai_protocol = 0;
3286 #ifdef HAVE_RES_INIT
3287 res_init ();
3288 #endif
3290 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3291 if (ret)
3292 #ifdef HAVE_GAI_STRERROR
3293 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3294 #else
3295 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3296 #endif
3297 immediate_quit = 0;
3299 goto open_socket;
3301 #endif /* HAVE_GETADDRINFO */
3303 /* We end up here if getaddrinfo is not defined, or in case no hostname
3304 has been specified (e.g. for a local server process). */
3306 if (EQ (service, Qt))
3307 port = 0;
3308 else if (INTEGERP (service))
3309 port = htons ((unsigned short) XINT (service));
3310 else
3312 struct servent *svc_info;
3313 CHECK_STRING (service);
3314 svc_info = getservbyname (SSDATA (service),
3315 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3316 if (svc_info == 0)
3317 error ("Unknown service: %s", SDATA (service));
3318 port = svc_info->s_port;
3321 memset (&address_in, 0, sizeof address_in);
3322 address_in.sin_family = family;
3323 address_in.sin_addr.s_addr = INADDR_ANY;
3324 address_in.sin_port = port;
3326 #ifndef HAVE_GETADDRINFO
3327 if (!NILP (host))
3329 struct hostent *host_info_ptr;
3331 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3332 as it may `hang' Emacs for a very long time. */
3333 immediate_quit = 1;
3334 QUIT;
3336 #ifdef HAVE_RES_INIT
3337 res_init ();
3338 #endif
3340 host_info_ptr = gethostbyname (SDATA (host));
3341 immediate_quit = 0;
3343 if (host_info_ptr)
3345 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3346 host_info_ptr->h_length);
3347 family = host_info_ptr->h_addrtype;
3348 address_in.sin_family = family;
3350 else
3351 /* Attempt to interpret host as numeric inet address. */
3353 unsigned long numeric_addr;
3354 numeric_addr = inet_addr (SSDATA (host));
3355 if (numeric_addr == -1)
3356 error ("Unknown host \"%s\"", SDATA (host));
3358 memcpy (&address_in.sin_addr, &numeric_addr,
3359 sizeof (address_in.sin_addr));
3363 #endif /* not HAVE_GETADDRINFO */
3365 ai.ai_family = family;
3366 ai.ai_addr = (struct sockaddr *) &address_in;
3367 ai.ai_addrlen = sizeof address_in;
3369 open_socket:
3371 /* Do this in case we never enter the for-loop below. */
3372 count1 = SPECPDL_INDEX ();
3373 s = -1;
3375 for (lres = res; lres; lres = lres->ai_next)
3377 ptrdiff_t optn;
3378 int optbits;
3380 #ifdef WINDOWSNT
3381 retry_connect:
3382 #endif
3384 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3385 lres->ai_protocol);
3386 if (s < 0)
3388 xerrno = errno;
3389 continue;
3392 #ifdef DATAGRAM_SOCKETS
3393 if (!is_server && socktype == SOCK_DGRAM)
3394 break;
3395 #endif /* DATAGRAM_SOCKETS */
3397 #ifdef NON_BLOCKING_CONNECT
3398 if (is_non_blocking_client)
3400 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3401 if (ret < 0)
3403 xerrno = errno;
3404 emacs_close (s);
3405 s = -1;
3406 continue;
3409 #endif
3411 /* Make us close S if quit. */
3412 record_unwind_protect_int (close_file_unwind, s);
3414 /* Parse network options in the arg list.
3415 We simply ignore anything which isn't a known option (including other keywords).
3416 An error is signaled if setting a known option fails. */
3417 for (optn = optbits = 0; optn < nargs - 1; optn += 2)
3418 optbits |= set_socket_option (s, args[optn], args[optn + 1]);
3420 if (is_server)
3422 /* Configure as a server socket. */
3424 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3425 explicit :reuseaddr key to override this. */
3426 #ifdef HAVE_LOCAL_SOCKETS
3427 if (family != AF_LOCAL)
3428 #endif
3429 if (!(optbits & (1 << OPIX_REUSEADDR)))
3431 int optval = 1;
3432 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3433 report_file_error ("Cannot set reuse option on server socket", Qnil);
3436 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3437 report_file_error ("Cannot bind server socket", Qnil);
3439 #ifdef HAVE_GETSOCKNAME
3440 if (EQ (service, Qt))
3442 struct sockaddr_in sa1;
3443 socklen_t len1 = sizeof (sa1);
3444 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3446 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3447 service = make_number (ntohs (sa1.sin_port));
3448 contact = Fplist_put (contact, QCservice, service);
3451 #endif
3453 if (socktype != SOCK_DGRAM && listen (s, backlog))
3454 report_file_error ("Cannot listen on server socket", Qnil);
3456 break;
3459 immediate_quit = 1;
3460 QUIT;
3462 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3463 xerrno = errno;
3465 if (ret == 0 || xerrno == EISCONN)
3467 /* The unwind-protect will be discarded afterwards.
3468 Likewise for immediate_quit. */
3469 break;
3472 #ifdef NON_BLOCKING_CONNECT
3473 #ifdef EINPROGRESS
3474 if (is_non_blocking_client && xerrno == EINPROGRESS)
3475 break;
3476 #else
3477 #ifdef EWOULDBLOCK
3478 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3479 break;
3480 #endif
3481 #endif
3482 #endif
3484 #ifndef WINDOWSNT
3485 if (xerrno == EINTR)
3487 /* Unlike most other syscalls connect() cannot be called
3488 again. (That would return EALREADY.) The proper way to
3489 wait for completion is pselect(). */
3490 int sc;
3491 socklen_t len;
3492 fd_set fdset;
3493 retry_select:
3494 FD_ZERO (&fdset);
3495 FD_SET (s, &fdset);
3496 QUIT;
3497 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3498 if (sc == -1)
3500 if (errno == EINTR)
3501 goto retry_select;
3502 else
3503 report_file_error ("Failed select", Qnil);
3505 eassert (sc > 0);
3507 len = sizeof xerrno;
3508 eassert (FD_ISSET (s, &fdset));
3509 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3510 report_file_error ("Failed getsockopt", Qnil);
3511 if (xerrno)
3512 report_file_errno ("Failed connect", Qnil, xerrno);
3513 break;
3515 #endif /* !WINDOWSNT */
3517 immediate_quit = 0;
3519 /* Discard the unwind protect closing S. */
3520 specpdl_ptr = specpdl + count1;
3521 emacs_close (s);
3522 s = -1;
3524 #ifdef WINDOWSNT
3525 if (xerrno == EINTR)
3526 goto retry_connect;
3527 #endif
3530 if (s >= 0)
3532 #ifdef DATAGRAM_SOCKETS
3533 if (socktype == SOCK_DGRAM)
3535 if (datagram_address[s].sa)
3536 emacs_abort ();
3537 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3538 datagram_address[s].len = lres->ai_addrlen;
3539 if (is_server)
3541 Lisp_Object remote;
3542 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3543 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3545 int rfamily, rlen;
3546 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3547 if (rlen != 0 && rfamily == lres->ai_family
3548 && rlen == lres->ai_addrlen)
3549 conv_lisp_to_sockaddr (rfamily, remote,
3550 datagram_address[s].sa, rlen);
3553 else
3554 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3556 #endif
3557 contact = Fplist_put (contact, colon_address,
3558 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3559 #ifdef HAVE_GETSOCKNAME
3560 if (!is_server)
3562 struct sockaddr_in sa1;
3563 socklen_t len1 = sizeof (sa1);
3564 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3565 contact = Fplist_put (contact, QClocal,
3566 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3568 #endif
3571 immediate_quit = 0;
3573 #ifdef HAVE_GETADDRINFO
3574 if (res != &ai)
3576 block_input ();
3577 freeaddrinfo (res);
3578 unblock_input ();
3580 #endif
3582 if (s < 0)
3584 /* If non-blocking got this far - and failed - assume non-blocking is
3585 not supported after all. This is probably a wrong assumption, but
3586 the normal blocking calls to open-network-stream handles this error
3587 better. */
3588 if (is_non_blocking_client)
3589 return Qnil;
3591 report_file_errno ((is_server
3592 ? "make server process failed"
3593 : "make client process failed"),
3594 contact, xerrno);
3597 inch = s;
3598 outch = s;
3600 if (!NILP (buffer))
3601 buffer = Fget_buffer_create (buffer);
3602 proc = make_process (name);
3604 chan_process[inch] = proc;
3606 fcntl (inch, F_SETFL, O_NONBLOCK);
3608 p = XPROCESS (proc);
3610 pset_childp (p, contact);
3611 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3612 pset_type (p, Qnetwork);
3614 pset_buffer (p, buffer);
3615 pset_sentinel (p, sentinel);
3616 pset_filter (p, filter);
3617 pset_log (p, Fplist_get (contact, QClog));
3618 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3619 p->kill_without_query = 1;
3620 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3621 pset_command (p, Qt);
3622 p->pid = 0;
3624 p->open_fd[SUBPROCESS_STDIN] = inch;
3625 p->infd = inch;
3626 p->outfd = outch;
3628 /* Discard the unwind protect for closing S, if any. */
3629 specpdl_ptr = specpdl + count1;
3631 /* Unwind bind_polling_period and request_sigio. */
3632 unbind_to (count, Qnil);
3634 if (is_server && socktype != SOCK_DGRAM)
3635 pset_status (p, Qlisten);
3637 /* Make the process marker point into the process buffer (if any). */
3638 if (BUFFERP (buffer))
3639 set_marker_both (p->mark, buffer,
3640 BUF_ZV (XBUFFER (buffer)),
3641 BUF_ZV_BYTE (XBUFFER (buffer)));
3643 #ifdef NON_BLOCKING_CONNECT
3644 if (is_non_blocking_client)
3646 /* We may get here if connect did succeed immediately. However,
3647 in that case, we still need to signal this like a non-blocking
3648 connection. */
3649 pset_status (p, Qconnect);
3650 if (!FD_ISSET (inch, &connect_wait_mask))
3652 FD_SET (inch, &connect_wait_mask);
3653 FD_SET (inch, &write_mask);
3654 num_pending_connects++;
3657 else
3658 #endif
3659 /* A server may have a client filter setting of Qt, but it must
3660 still listen for incoming connects unless it is stopped. */
3661 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3662 || (EQ (p->status, Qlisten) && NILP (p->command)))
3664 FD_SET (inch, &input_wait_mask);
3665 FD_SET (inch, &non_keyboard_wait_mask);
3668 if (inch > max_process_desc)
3669 max_process_desc = inch;
3671 tem = Fplist_member (contact, QCcoding);
3672 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3673 tem = Qnil; /* No error message (too late!). */
3676 /* Setup coding systems for communicating with the network stream. */
3677 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3678 Lisp_Object coding_systems = Qt;
3679 Lisp_Object val;
3681 if (!NILP (tem))
3683 val = XCAR (XCDR (tem));
3684 if (CONSP (val))
3685 val = XCAR (val);
3687 else if (!NILP (Vcoding_system_for_read))
3688 val = Vcoding_system_for_read;
3689 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3690 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3691 /* We dare not decode end-of-line format by setting VAL to
3692 Qraw_text, because the existing Emacs Lisp libraries
3693 assume that they receive bare code including a sequence of
3694 CR LF. */
3695 val = Qnil;
3696 else
3698 if (NILP (host) || NILP (service))
3699 coding_systems = Qnil;
3700 else
3701 coding_systems = CALLN (Ffind_operation_coding_system,
3702 Qopen_network_stream, name, buffer,
3703 host, service);
3704 if (CONSP (coding_systems))
3705 val = XCAR (coding_systems);
3706 else if (CONSP (Vdefault_process_coding_system))
3707 val = XCAR (Vdefault_process_coding_system);
3708 else
3709 val = Qnil;
3711 pset_decode_coding_system (p, val);
3713 if (!NILP (tem))
3715 val = XCAR (XCDR (tem));
3716 if (CONSP (val))
3717 val = XCDR (val);
3719 else if (!NILP (Vcoding_system_for_write))
3720 val = Vcoding_system_for_write;
3721 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3722 val = Qnil;
3723 else
3725 if (EQ (coding_systems, Qt))
3727 if (NILP (host) || NILP (service))
3728 coding_systems = Qnil;
3729 else
3730 coding_systems = CALLN (Ffind_operation_coding_system,
3731 Qopen_network_stream, name, buffer,
3732 host, service);
3734 if (CONSP (coding_systems))
3735 val = XCDR (coding_systems);
3736 else if (CONSP (Vdefault_process_coding_system))
3737 val = XCDR (Vdefault_process_coding_system);
3738 else
3739 val = Qnil;
3741 pset_encode_coding_system (p, val);
3743 setup_process_coding_systems (proc);
3745 pset_decoding_buf (p, empty_unibyte_string);
3746 p->decoding_carryover = 0;
3747 pset_encoding_buf (p, empty_unibyte_string);
3749 p->inherit_coding_system_flag
3750 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3752 return proc;
3756 #ifdef HAVE_NET_IF_H
3758 #ifdef SIOCGIFCONF
3759 static Lisp_Object
3760 network_interface_list (void)
3762 struct ifconf ifconf;
3763 struct ifreq *ifreq;
3764 void *buf = NULL;
3765 ptrdiff_t buf_size = 512;
3766 int s;
3767 Lisp_Object res;
3768 ptrdiff_t count;
3770 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3771 if (s < 0)
3772 return Qnil;
3773 count = SPECPDL_INDEX ();
3774 record_unwind_protect_int (close_file_unwind, s);
3778 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3779 ifconf.ifc_buf = buf;
3780 ifconf.ifc_len = buf_size;
3781 if (ioctl (s, SIOCGIFCONF, &ifconf))
3783 emacs_close (s);
3784 xfree (buf);
3785 return Qnil;
3788 while (ifconf.ifc_len == buf_size);
3790 res = unbind_to (count, Qnil);
3791 ifreq = ifconf.ifc_req;
3792 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3794 struct ifreq *ifq = ifreq;
3795 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3796 #define SIZEOF_IFREQ(sif) \
3797 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3798 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3800 int len = SIZEOF_IFREQ (ifq);
3801 #else
3802 int len = sizeof (*ifreq);
3803 #endif
3804 char namebuf[sizeof (ifq->ifr_name) + 1];
3805 ifreq = (struct ifreq *) ((char *) ifreq + len);
3807 if (ifq->ifr_addr.sa_family != AF_INET)
3808 continue;
3810 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3811 namebuf[sizeof (ifq->ifr_name)] = 0;
3812 res = Fcons (Fcons (build_string (namebuf),
3813 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3814 sizeof (struct sockaddr))),
3815 res);
3818 xfree (buf);
3819 return res;
3821 #endif /* SIOCGIFCONF */
3823 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3825 struct ifflag_def {
3826 int flag_bit;
3827 const char *flag_sym;
3830 static const struct ifflag_def ifflag_table[] = {
3831 #ifdef IFF_UP
3832 { IFF_UP, "up" },
3833 #endif
3834 #ifdef IFF_BROADCAST
3835 { IFF_BROADCAST, "broadcast" },
3836 #endif
3837 #ifdef IFF_DEBUG
3838 { IFF_DEBUG, "debug" },
3839 #endif
3840 #ifdef IFF_LOOPBACK
3841 { IFF_LOOPBACK, "loopback" },
3842 #endif
3843 #ifdef IFF_POINTOPOINT
3844 { IFF_POINTOPOINT, "pointopoint" },
3845 #endif
3846 #ifdef IFF_RUNNING
3847 { IFF_RUNNING, "running" },
3848 #endif
3849 #ifdef IFF_NOARP
3850 { IFF_NOARP, "noarp" },
3851 #endif
3852 #ifdef IFF_PROMISC
3853 { IFF_PROMISC, "promisc" },
3854 #endif
3855 #ifdef IFF_NOTRAILERS
3856 #ifdef NS_IMPL_COCOA
3857 /* Really means smart, notrailers is obsolete. */
3858 { IFF_NOTRAILERS, "smart" },
3859 #else
3860 { IFF_NOTRAILERS, "notrailers" },
3861 #endif
3862 #endif
3863 #ifdef IFF_ALLMULTI
3864 { IFF_ALLMULTI, "allmulti" },
3865 #endif
3866 #ifdef IFF_MASTER
3867 { IFF_MASTER, "master" },
3868 #endif
3869 #ifdef IFF_SLAVE
3870 { IFF_SLAVE, "slave" },
3871 #endif
3872 #ifdef IFF_MULTICAST
3873 { IFF_MULTICAST, "multicast" },
3874 #endif
3875 #ifdef IFF_PORTSEL
3876 { IFF_PORTSEL, "portsel" },
3877 #endif
3878 #ifdef IFF_AUTOMEDIA
3879 { IFF_AUTOMEDIA, "automedia" },
3880 #endif
3881 #ifdef IFF_DYNAMIC
3882 { IFF_DYNAMIC, "dynamic" },
3883 #endif
3884 #ifdef IFF_OACTIVE
3885 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
3886 #endif
3887 #ifdef IFF_SIMPLEX
3888 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
3889 #endif
3890 #ifdef IFF_LINK0
3891 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
3892 #endif
3893 #ifdef IFF_LINK1
3894 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
3895 #endif
3896 #ifdef IFF_LINK2
3897 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
3898 #endif
3899 { 0, 0 }
3902 static Lisp_Object
3903 network_interface_info (Lisp_Object ifname)
3905 struct ifreq rq;
3906 Lisp_Object res = Qnil;
3907 Lisp_Object elt;
3908 int s;
3909 bool any = 0;
3910 ptrdiff_t count;
3911 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3912 && defined HAVE_GETIFADDRS && defined LLADDR)
3913 struct ifaddrs *ifap;
3914 #endif
3916 CHECK_STRING (ifname);
3918 if (sizeof rq.ifr_name <= SBYTES (ifname))
3919 error ("interface name too long");
3920 lispstpcpy (rq.ifr_name, ifname);
3922 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3923 if (s < 0)
3924 return Qnil;
3925 count = SPECPDL_INDEX ();
3926 record_unwind_protect_int (close_file_unwind, s);
3928 elt = Qnil;
3929 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3930 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3932 int flags = rq.ifr_flags;
3933 const struct ifflag_def *fp;
3934 int fnum;
3936 /* If flags is smaller than int (i.e. short) it may have the high bit set
3937 due to IFF_MULTICAST. In that case, sign extending it into
3938 an int is wrong. */
3939 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3940 flags = (unsigned short) rq.ifr_flags;
3942 any = 1;
3943 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3945 if (flags & fp->flag_bit)
3947 elt = Fcons (intern (fp->flag_sym), elt);
3948 flags -= fp->flag_bit;
3951 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3953 if (flags & 1)
3955 elt = Fcons (make_number (fnum), elt);
3959 #endif
3960 res = Fcons (elt, res);
3962 elt = Qnil;
3963 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3964 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3966 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3967 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3968 int n;
3970 any = 1;
3971 for (n = 0; n < 6; n++)
3972 p->contents[n] = make_number (((unsigned char *)
3973 &rq.ifr_hwaddr.sa_data[0])
3974 [n]);
3975 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3977 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3978 if (getifaddrs (&ifap) != -1)
3980 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3981 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3982 struct ifaddrs *it;
3984 for (it = ifap; it != NULL; it = it->ifa_next)
3986 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3987 unsigned char linkaddr[6];
3988 int n;
3990 if (it->ifa_addr->sa_family != AF_LINK
3991 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3992 || sdl->sdl_alen != 6)
3993 continue;
3995 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3996 for (n = 0; n < 6; n++)
3997 p->contents[n] = make_number (linkaddr[n]);
3999 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4000 break;
4003 #ifdef HAVE_FREEIFADDRS
4004 freeifaddrs (ifap);
4005 #endif
4007 #endif /* HAVE_GETIFADDRS && LLADDR */
4009 res = Fcons (elt, res);
4011 elt = Qnil;
4012 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4013 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4015 any = 1;
4016 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4017 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4018 #else
4019 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4020 #endif
4022 #endif
4023 res = Fcons (elt, res);
4025 elt = Qnil;
4026 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4027 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4029 any = 1;
4030 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4032 #endif
4033 res = Fcons (elt, res);
4035 elt = Qnil;
4036 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4037 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4039 any = 1;
4040 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4042 #endif
4043 res = Fcons (elt, res);
4045 return unbind_to (count, any ? res : Qnil);
4047 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4048 #endif /* defined (HAVE_NET_IF_H) */
4050 DEFUN ("network-interface-list", Fnetwork_interface_list,
4051 Snetwork_interface_list, 0, 0, 0,
4052 doc: /* Return an alist of all network interfaces and their network address.
4053 Each element is a cons, the car of which is a string containing the
4054 interface name, and the cdr is the network address in internal
4055 format; see the description of ADDRESS in `make-network-process'.
4057 If the information is not available, return nil. */)
4058 (void)
4060 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4061 return network_interface_list ();
4062 #else
4063 return Qnil;
4064 #endif
4067 DEFUN ("network-interface-info", Fnetwork_interface_info,
4068 Snetwork_interface_info, 1, 1, 0,
4069 doc: /* Return information about network interface named IFNAME.
4070 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4071 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4072 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4073 FLAGS is the current flags of the interface.
4075 Data that is unavailable is returned as nil. */)
4076 (Lisp_Object ifname)
4078 #if ((defined HAVE_NET_IF_H \
4079 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4080 || defined SIOCGIFFLAGS)) \
4081 || defined WINDOWSNT)
4082 return network_interface_info (ifname);
4083 #else
4084 return Qnil;
4085 #endif
4088 /* If program file NAME starts with /: for quoting a magic
4089 name, remove that, preserving the multibyteness of NAME. */
4091 Lisp_Object
4092 remove_slash_colon (Lisp_Object name)
4094 return
4095 ((SBYTES (name) > 2 && SREF (name, 0) == '/' && SREF (name, 1) == ':')
4096 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
4097 SBYTES (name) - 2, STRING_MULTIBYTE (name))
4098 : name);
4101 /* Turn off input and output for process PROC. */
4103 static void
4104 deactivate_process (Lisp_Object proc)
4106 int inchannel;
4107 struct Lisp_Process *p = XPROCESS (proc);
4108 int i;
4110 #ifdef HAVE_GNUTLS
4111 /* Delete GnuTLS structures in PROC, if any. */
4112 emacs_gnutls_deinit (proc);
4113 #endif /* HAVE_GNUTLS */
4115 if (p->read_output_delay > 0)
4117 if (--process_output_delay_count < 0)
4118 process_output_delay_count = 0;
4119 p->read_output_delay = 0;
4120 p->read_output_skip = 0;
4123 /* Beware SIGCHLD hereabouts. */
4125 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4126 close_process_fd (&p->open_fd[i]);
4128 inchannel = p->infd;
4129 if (inchannel >= 0)
4131 p->infd = -1;
4132 p->outfd = -1;
4133 #ifdef DATAGRAM_SOCKETS
4134 if (DATAGRAM_CHAN_P (inchannel))
4136 xfree (datagram_address[inchannel].sa);
4137 datagram_address[inchannel].sa = 0;
4138 datagram_address[inchannel].len = 0;
4140 #endif
4141 chan_process[inchannel] = Qnil;
4142 FD_CLR (inchannel, &input_wait_mask);
4143 FD_CLR (inchannel, &non_keyboard_wait_mask);
4144 #ifdef NON_BLOCKING_CONNECT
4145 if (FD_ISSET (inchannel, &connect_wait_mask))
4147 FD_CLR (inchannel, &connect_wait_mask);
4148 FD_CLR (inchannel, &write_mask);
4149 if (--num_pending_connects < 0)
4150 emacs_abort ();
4152 #endif
4153 if (inchannel == max_process_desc)
4155 /* We just closed the highest-numbered process input descriptor,
4156 so recompute the highest-numbered one now. */
4157 int i = inchannel;
4159 i--;
4160 while (0 <= i && NILP (chan_process[i]));
4162 max_process_desc = i;
4168 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4169 0, 4, 0,
4170 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4171 It is given to their filter functions.
4172 Optional argument PROCESS means do not return until output has been
4173 received from PROCESS.
4175 Optional second argument SECONDS and third argument MILLISEC
4176 specify a timeout; return after that much time even if there is
4177 no subprocess output. If SECONDS is a floating point number,
4178 it specifies a fractional number of seconds to wait.
4179 The MILLISEC argument is obsolete and should be avoided.
4181 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4182 from PROCESS only, suspending reading output from other processes.
4183 If JUST-THIS-ONE is an integer, don't run any timers either.
4184 Return non-nil if we received any output from PROCESS (or, if PROCESS
4185 is nil, from any process) before the timeout expired. */)
4186 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4188 intmax_t secs;
4189 int nsecs;
4191 if (! NILP (process))
4192 CHECK_PROCESS (process);
4193 else
4194 just_this_one = Qnil;
4196 if (!NILP (millisec))
4197 { /* Obsolete calling convention using integers rather than floats. */
4198 CHECK_NUMBER (millisec);
4199 if (NILP (seconds))
4200 seconds = make_float (XINT (millisec) / 1000.0);
4201 else
4203 CHECK_NUMBER (seconds);
4204 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4208 secs = 0;
4209 nsecs = -1;
4211 if (!NILP (seconds))
4213 if (INTEGERP (seconds))
4215 if (XINT (seconds) > 0)
4217 secs = XINT (seconds);
4218 nsecs = 0;
4221 else if (FLOATP (seconds))
4223 if (XFLOAT_DATA (seconds) > 0)
4225 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4226 secs = min (t.tv_sec, WAIT_READING_MAX);
4227 nsecs = t.tv_nsec;
4230 else
4231 wrong_type_argument (Qnumberp, seconds);
4233 else if (! NILP (process))
4234 nsecs = 0;
4236 return
4237 ((wait_reading_process_output (secs, nsecs, 0, 0,
4238 Qnil,
4239 !NILP (process) ? XPROCESS (process) : NULL,
4240 (NILP (just_this_one) ? 0
4241 : !INTEGERP (just_this_one) ? 1 : -1))
4242 <= 0)
4243 ? Qnil : Qt);
4246 /* Accept a connection for server process SERVER on CHANNEL. */
4248 static EMACS_INT connect_counter = 0;
4250 static void
4251 server_accept_connection (Lisp_Object server, int channel)
4253 Lisp_Object proc, caller, name, buffer;
4254 Lisp_Object contact, host, service;
4255 struct Lisp_Process *ps = XPROCESS (server);
4256 struct Lisp_Process *p;
4257 int s;
4258 union u_sockaddr {
4259 struct sockaddr sa;
4260 struct sockaddr_in in;
4261 #ifdef AF_INET6
4262 struct sockaddr_in6 in6;
4263 #endif
4264 #ifdef HAVE_LOCAL_SOCKETS
4265 struct sockaddr_un un;
4266 #endif
4267 } saddr;
4268 socklen_t len = sizeof saddr;
4269 ptrdiff_t count;
4271 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4273 if (s < 0)
4275 int code = errno;
4277 if (code == EAGAIN)
4278 return;
4279 #ifdef EWOULDBLOCK
4280 if (code == EWOULDBLOCK)
4281 return;
4282 #endif
4284 if (!NILP (ps->log))
4285 call3 (ps->log, server, Qnil,
4286 concat3 (build_string ("accept failed with code"),
4287 Fnumber_to_string (make_number (code)),
4288 build_string ("\n")));
4289 return;
4292 count = SPECPDL_INDEX ();
4293 record_unwind_protect_int (close_file_unwind, s);
4295 connect_counter++;
4297 /* Setup a new process to handle the connection. */
4299 /* Generate a unique identification of the caller, and build contact
4300 information for this process. */
4301 host = Qt;
4302 service = Qnil;
4303 switch (saddr.sa.sa_family)
4305 case AF_INET:
4307 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4309 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4310 host = CALLN (Fformat, ipv4_format,
4311 make_number (ip[0]), make_number (ip[1]),
4312 make_number (ip[2]), make_number (ip[3]));
4313 service = make_number (ntohs (saddr.in.sin_port));
4314 AUTO_STRING (caller_format, " <%s:%d>");
4315 caller = CALLN (Fformat, caller_format, host, service);
4317 break;
4319 #ifdef AF_INET6
4320 case AF_INET6:
4322 Lisp_Object args[9];
4323 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4324 int i;
4326 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4327 args[0] = ipv6_format;
4328 for (i = 0; i < 8; i++)
4329 args[i + 1] = make_number (ntohs (ip6[i]));
4330 host = CALLMANY (Fformat, args);
4331 service = make_number (ntohs (saddr.in.sin_port));
4332 AUTO_STRING (caller_format, " <[%s]:%d>");
4333 caller = CALLN (Fformat, caller_format, host, service);
4335 break;
4336 #endif
4338 #ifdef HAVE_LOCAL_SOCKETS
4339 case AF_LOCAL:
4340 #endif
4341 default:
4342 caller = Fnumber_to_string (make_number (connect_counter));
4343 AUTO_STRING (space_less_than, " <");
4344 AUTO_STRING (greater_than, ">");
4345 caller = concat3 (space_less_than, caller, greater_than);
4346 break;
4349 /* Create a new buffer name for this process if it doesn't have a
4350 filter. The new buffer name is based on the buffer name or
4351 process name of the server process concatenated with the caller
4352 identification. */
4354 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4355 || EQ (ps->filter, Qt)))
4356 buffer = Qnil;
4357 else
4359 buffer = ps->buffer;
4360 if (!NILP (buffer))
4361 buffer = Fbuffer_name (buffer);
4362 else
4363 buffer = ps->name;
4364 if (!NILP (buffer))
4366 buffer = concat2 (buffer, caller);
4367 buffer = Fget_buffer_create (buffer);
4371 /* Generate a unique name for the new server process. Combine the
4372 server process name with the caller identification. */
4374 name = concat2 (ps->name, caller);
4375 proc = make_process (name);
4377 chan_process[s] = proc;
4379 fcntl (s, F_SETFL, O_NONBLOCK);
4381 p = XPROCESS (proc);
4383 /* Build new contact information for this setup. */
4384 contact = Fcopy_sequence (ps->childp);
4385 contact = Fplist_put (contact, QCserver, Qnil);
4386 contact = Fplist_put (contact, QChost, host);
4387 if (!NILP (service))
4388 contact = Fplist_put (contact, QCservice, service);
4389 contact = Fplist_put (contact, QCremote,
4390 conv_sockaddr_to_lisp (&saddr.sa, len));
4391 #ifdef HAVE_GETSOCKNAME
4392 len = sizeof saddr;
4393 if (getsockname (s, &saddr.sa, &len) == 0)
4394 contact = Fplist_put (contact, QClocal,
4395 conv_sockaddr_to_lisp (&saddr.sa, len));
4396 #endif
4398 pset_childp (p, contact);
4399 pset_plist (p, Fcopy_sequence (ps->plist));
4400 pset_type (p, Qnetwork);
4402 pset_buffer (p, buffer);
4403 pset_sentinel (p, ps->sentinel);
4404 pset_filter (p, ps->filter);
4405 pset_command (p, Qnil);
4406 p->pid = 0;
4408 /* Discard the unwind protect for closing S. */
4409 specpdl_ptr = specpdl + count;
4411 p->open_fd[SUBPROCESS_STDIN] = s;
4412 p->infd = s;
4413 p->outfd = s;
4414 pset_status (p, Qrun);
4416 /* Client processes for accepted connections are not stopped initially. */
4417 if (!EQ (p->filter, Qt))
4419 FD_SET (s, &input_wait_mask);
4420 FD_SET (s, &non_keyboard_wait_mask);
4423 if (s > max_process_desc)
4424 max_process_desc = s;
4426 /* Setup coding system for new process based on server process.
4427 This seems to be the proper thing to do, as the coding system
4428 of the new process should reflect the settings at the time the
4429 server socket was opened; not the current settings. */
4431 pset_decode_coding_system (p, ps->decode_coding_system);
4432 pset_encode_coding_system (p, ps->encode_coding_system);
4433 setup_process_coding_systems (proc);
4435 pset_decoding_buf (p, empty_unibyte_string);
4436 p->decoding_carryover = 0;
4437 pset_encoding_buf (p, empty_unibyte_string);
4439 p->inherit_coding_system_flag
4440 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4442 AUTO_STRING (dash, "-");
4443 AUTO_STRING (nl, "\n");
4444 Lisp_Object host_string = STRINGP (host) ? host : dash;
4446 if (!NILP (ps->log))
4448 AUTO_STRING (accept_from, "accept from ");
4449 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4452 AUTO_STRING (open_from, "open from ");
4453 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4456 /* This variable is different from waiting_for_input in keyboard.c.
4457 It is used to communicate to a lisp process-filter/sentinel (via the
4458 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4459 for user-input when that process-filter was called.
4460 waiting_for_input cannot be used as that is by definition 0 when
4461 lisp code is being evalled.
4462 This is also used in record_asynch_buffer_change.
4463 For that purpose, this must be 0
4464 when not inside wait_reading_process_output. */
4465 static int waiting_for_user_input_p;
4467 static void
4468 wait_reading_process_output_unwind (int data)
4470 waiting_for_user_input_p = data;
4473 /* This is here so breakpoints can be put on it. */
4474 static void
4475 wait_reading_process_output_1 (void)
4479 /* Read and dispose of subprocess output while waiting for timeout to
4480 elapse and/or keyboard input to be available.
4482 TIME_LIMIT is:
4483 timeout in seconds
4484 If negative, gobble data immediately available but don't wait for any.
4486 NSECS is:
4487 an additional duration to wait, measured in nanoseconds
4488 If TIME_LIMIT is zero, then:
4489 If NSECS == 0, there is no limit.
4490 If NSECS > 0, the timeout consists of NSECS only.
4491 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4493 READ_KBD is:
4494 0 to ignore keyboard input, or
4495 1 to return when input is available, or
4496 -1 meaning caller will actually read the input, so don't throw to
4497 the quit handler, or
4499 DO_DISPLAY means redisplay should be done to show subprocess
4500 output that arrives.
4502 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4503 (and gobble terminal input into the buffer if any arrives).
4505 If WAIT_PROC is specified, wait until something arrives from that
4506 process.
4508 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4509 (suspending output from other processes). A negative value
4510 means don't run any timers either.
4512 Return positive if we received input from WAIT_PROC (or from any
4513 process if WAIT_PROC is null), zero if we attempted to receive
4514 input but got none, and negative if we didn't even try. */
4517 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4518 bool do_display,
4519 Lisp_Object wait_for_cell,
4520 struct Lisp_Process *wait_proc, int just_wait_proc)
4522 int channel, nfds;
4523 fd_set Available;
4524 fd_set Writeok;
4525 bool check_write;
4526 int check_delay;
4527 bool no_avail;
4528 int xerrno;
4529 Lisp_Object proc;
4530 struct timespec timeout, end_time, timer_delay;
4531 struct timespec got_output_end_time = invalid_timespec ();
4532 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
4533 int got_some_output = -1;
4534 ptrdiff_t count = SPECPDL_INDEX ();
4536 /* Close to the current time if known, an invalid timespec otherwise. */
4537 struct timespec now = invalid_timespec ();
4539 FD_ZERO (&Available);
4540 FD_ZERO (&Writeok);
4542 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4543 && !(CONSP (wait_proc->status)
4544 && EQ (XCAR (wait_proc->status), Qexit)))
4545 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4547 record_unwind_protect_int (wait_reading_process_output_unwind,
4548 waiting_for_user_input_p);
4549 waiting_for_user_input_p = read_kbd;
4551 if (TYPE_MAXIMUM (time_t) < time_limit)
4552 time_limit = TYPE_MAXIMUM (time_t);
4554 if (time_limit < 0 || nsecs < 0)
4555 wait = MINIMUM;
4556 else if (time_limit > 0 || nsecs > 0)
4558 wait = TIMEOUT;
4559 now = current_timespec ();
4560 end_time = timespec_add (now, make_timespec (time_limit, nsecs));
4562 else
4563 wait = INFINITY;
4565 while (1)
4567 bool process_skipped = false;
4569 /* If calling from keyboard input, do not quit
4570 since we want to return C-g as an input character.
4571 Otherwise, do pending quit if requested. */
4572 if (read_kbd >= 0)
4573 QUIT;
4574 else if (pending_signals)
4575 process_pending_signals ();
4577 /* Exit now if the cell we're waiting for became non-nil. */
4578 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4579 break;
4581 /* Compute time from now till when time limit is up. */
4582 /* Exit if already run out. */
4583 if (wait == TIMEOUT)
4585 if (!timespec_valid_p (now))
4586 now = current_timespec ();
4587 if (timespec_cmp (end_time, now) <= 0)
4588 break;
4589 timeout = timespec_sub (end_time, now);
4591 else
4592 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
4594 /* Normally we run timers here.
4595 But not if wait_for_cell; in those cases,
4596 the wait is supposed to be short,
4597 and those callers cannot handle running arbitrary Lisp code here. */
4598 if (NILP (wait_for_cell)
4599 && just_wait_proc >= 0)
4603 unsigned old_timers_run = timers_run;
4604 struct buffer *old_buffer = current_buffer;
4605 Lisp_Object old_window = selected_window;
4607 timer_delay = timer_check ();
4609 /* If a timer has run, this might have changed buffers
4610 an alike. Make read_key_sequence aware of that. */
4611 if (timers_run != old_timers_run
4612 && (old_buffer != current_buffer
4613 || !EQ (old_window, selected_window))
4614 && waiting_for_user_input_p == -1)
4615 record_asynch_buffer_change ();
4617 if (timers_run != old_timers_run && do_display)
4618 /* We must retry, since a timer may have requeued itself
4619 and that could alter the time_delay. */
4620 redisplay_preserve_echo_area (9);
4621 else
4622 break;
4624 while (!detect_input_pending ());
4626 /* If there is unread keyboard input, also return. */
4627 if (read_kbd != 0
4628 && requeued_events_pending_p ())
4629 break;
4631 /* This is so a breakpoint can be put here. */
4632 if (!timespec_valid_p (timer_delay))
4633 wait_reading_process_output_1 ();
4636 /* Cause C-g and alarm signals to take immediate action,
4637 and cause input available signals to zero out timeout.
4639 It is important that we do this before checking for process
4640 activity. If we get a SIGCHLD after the explicit checks for
4641 process activity, timeout is the only way we will know. */
4642 if (read_kbd < 0)
4643 set_waiting_for_input (&timeout);
4645 /* If status of something has changed, and no input is
4646 available, notify the user of the change right away. After
4647 this explicit check, we'll let the SIGCHLD handler zap
4648 timeout to get our attention. */
4649 if (update_tick != process_tick)
4651 fd_set Atemp;
4652 fd_set Ctemp;
4654 if (kbd_on_hold_p ())
4655 FD_ZERO (&Atemp);
4656 else
4657 Atemp = input_wait_mask;
4658 Ctemp = write_mask;
4660 timeout = make_timespec (0, 0);
4661 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4662 &Atemp,
4663 #ifdef NON_BLOCKING_CONNECT
4664 (num_pending_connects > 0 ? &Ctemp : NULL),
4665 #else
4666 NULL,
4667 #endif
4668 NULL, &timeout, NULL)
4669 <= 0))
4671 /* It's okay for us to do this and then continue with
4672 the loop, since timeout has already been zeroed out. */
4673 clear_waiting_for_input ();
4674 got_some_output = status_notify (NULL, wait_proc);
4675 if (do_display) redisplay_preserve_echo_area (13);
4679 /* Don't wait for output from a non-running process. Just
4680 read whatever data has already been received. */
4681 if (wait_proc && wait_proc->raw_status_new)
4682 update_status (wait_proc);
4683 if (wait_proc
4684 && ! EQ (wait_proc->status, Qrun)
4685 && ! EQ (wait_proc->status, Qconnect))
4687 bool read_some_bytes = false;
4689 clear_waiting_for_input ();
4691 /* If data can be read from the process, do so until exhausted. */
4692 if (wait_proc->infd >= 0)
4694 XSETPROCESS (proc, wait_proc);
4696 while (true)
4698 int nread = read_process_output (proc, wait_proc->infd);
4699 if (nread < 0)
4701 if (errno == EIO || errno == EAGAIN)
4702 break;
4703 #ifdef EWOULDBLOCK
4704 if (errno == EWOULDBLOCK)
4705 break;
4706 #endif
4708 else
4710 if (got_some_output < nread)
4711 got_some_output = nread;
4712 if (nread == 0)
4713 break;
4714 read_some_bytes = true;
4719 if (read_some_bytes && do_display)
4720 redisplay_preserve_echo_area (10);
4722 break;
4725 /* Wait till there is something to do. */
4727 if (wait_proc && just_wait_proc)
4729 if (wait_proc->infd < 0) /* Terminated. */
4730 break;
4731 FD_SET (wait_proc->infd, &Available);
4732 check_delay = 0;
4733 check_write = 0;
4735 else if (!NILP (wait_for_cell))
4737 Available = non_process_wait_mask;
4738 check_delay = 0;
4739 check_write = 0;
4741 else
4743 if (! read_kbd)
4744 Available = non_keyboard_wait_mask;
4745 else
4746 Available = input_wait_mask;
4747 Writeok = write_mask;
4748 check_delay = wait_proc ? 0 : process_output_delay_count;
4749 check_write = true;
4752 /* If frame size has changed or the window is newly mapped,
4753 redisplay now, before we start to wait. There is a race
4754 condition here; if a SIGIO arrives between now and the select
4755 and indicates that a frame is trashed, the select may block
4756 displaying a trashed screen. */
4757 if (frame_garbaged && do_display)
4759 clear_waiting_for_input ();
4760 redisplay_preserve_echo_area (11);
4761 if (read_kbd < 0)
4762 set_waiting_for_input (&timeout);
4765 /* Skip the `select' call if input is available and we're
4766 waiting for keyboard input or a cell change (which can be
4767 triggered by processing X events). In the latter case, set
4768 nfds to 1 to avoid breaking the loop. */
4769 no_avail = 0;
4770 if ((read_kbd || !NILP (wait_for_cell))
4771 && detect_input_pending ())
4773 nfds = read_kbd ? 0 : 1;
4774 no_avail = 1;
4775 FD_ZERO (&Available);
4777 else
4779 /* Set the timeout for adaptive read buffering if any
4780 process has non-zero read_output_skip and non-zero
4781 read_output_delay, and we are not reading output for a
4782 specific process. It is not executed if
4783 Vprocess_adaptive_read_buffering is nil. */
4784 if (process_output_skip && check_delay > 0)
4786 int adaptive_nsecs = timeout.tv_nsec;
4787 if (timeout.tv_sec > 0 || adaptive_nsecs > READ_OUTPUT_DELAY_MAX)
4788 adaptive_nsecs = READ_OUTPUT_DELAY_MAX;
4789 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4791 proc = chan_process[channel];
4792 if (NILP (proc))
4793 continue;
4794 /* Find minimum non-zero read_output_delay among the
4795 processes with non-zero read_output_skip. */
4796 if (XPROCESS (proc)->read_output_delay > 0)
4798 check_delay--;
4799 if (!XPROCESS (proc)->read_output_skip)
4800 continue;
4801 FD_CLR (channel, &Available);
4802 process_skipped = true;
4803 XPROCESS (proc)->read_output_skip = 0;
4804 if (XPROCESS (proc)->read_output_delay < adaptive_nsecs)
4805 adaptive_nsecs = XPROCESS (proc)->read_output_delay;
4808 timeout = make_timespec (0, adaptive_nsecs);
4809 process_output_skip = 0;
4812 /* If we've got some output and haven't limited our timeout
4813 with adaptive read buffering, limit it. */
4814 if (got_some_output > 0 && !process_skipped
4815 && (timeout.tv_sec
4816 || timeout.tv_nsec > READ_OUTPUT_DELAY_INCREMENT))
4817 timeout = make_timespec (0, READ_OUTPUT_DELAY_INCREMENT);
4820 if (NILP (wait_for_cell) && just_wait_proc >= 0
4821 && timespec_valid_p (timer_delay)
4822 && timespec_cmp (timer_delay, timeout) < 0)
4824 if (!timespec_valid_p (now))
4825 now = current_timespec ();
4826 struct timespec timeout_abs = timespec_add (now, timeout);
4827 if (!timespec_valid_p (got_output_end_time)
4828 || timespec_cmp (timeout_abs, got_output_end_time) < 0)
4829 got_output_end_time = timeout_abs;
4830 timeout = timer_delay;
4832 else
4833 got_output_end_time = invalid_timespec ();
4835 /* NOW can become inaccurate if time can pass during pselect. */
4836 if (timeout.tv_sec > 0 || timeout.tv_nsec > 0)
4837 now = invalid_timespec ();
4839 #if defined (HAVE_NS)
4840 nfds = ns_select
4841 #elif defined (HAVE_GLIB)
4842 nfds = xg_select
4843 #else
4844 nfds = pselect
4845 #endif
4846 (max (max_process_desc, max_input_desc) + 1,
4847 &Available,
4848 (check_write ? &Writeok : 0),
4849 NULL, &timeout, NULL);
4851 #ifdef HAVE_GNUTLS
4852 /* GnuTLS buffers data internally. In lowat mode it leaves
4853 some data in the TCP buffers so that select works, but
4854 with custom pull/push functions we need to check if some
4855 data is available in the buffers manually. */
4856 if (nfds == 0)
4858 fd_set tls_available;
4859 int set = 0;
4861 FD_ZERO (&tls_available);
4862 if (! wait_proc)
4864 /* We're not waiting on a specific process, so loop
4865 through all the channels and check for data.
4866 This is a workaround needed for some versions of
4867 the gnutls library -- 2.12.14 has been confirmed
4868 to need it. See
4869 http://comments.gmane.org/gmane.emacs.devel/145074 */
4870 for (channel = 0; channel < FD_SETSIZE; ++channel)
4871 if (! NILP (chan_process[channel]))
4873 struct Lisp_Process *p =
4874 XPROCESS (chan_process[channel]);
4875 if (p && p->gnutls_p && p->gnutls_state
4876 && ((emacs_gnutls_record_check_pending
4877 (p->gnutls_state))
4878 > 0))
4880 nfds++;
4881 eassert (p->infd == channel);
4882 FD_SET (p->infd, &tls_available);
4883 set++;
4887 else
4889 /* Check this specific channel. */
4890 if (wait_proc->gnutls_p /* Check for valid process. */
4891 && wait_proc->gnutls_state
4892 /* Do we have pending data? */
4893 && ((emacs_gnutls_record_check_pending
4894 (wait_proc->gnutls_state))
4895 > 0))
4897 nfds = 1;
4898 eassert (0 <= wait_proc->infd);
4899 /* Set to Available. */
4900 FD_SET (wait_proc->infd, &tls_available);
4901 set++;
4904 if (set)
4905 Available = tls_available;
4907 #endif
4910 xerrno = errno;
4912 /* Make C-g and alarm signals set flags again. */
4913 clear_waiting_for_input ();
4915 /* If we woke up due to SIGWINCH, actually change size now. */
4916 do_pending_window_change (0);
4918 if (nfds == 0)
4920 /* Exit the main loop if we've passed the requested timeout,
4921 or aren't skipping processes and got some output and
4922 haven't lowered our timeout due to timers or SIGIO and
4923 have waited a long amount of time due to repeated
4924 timers. */
4925 if (wait < TIMEOUT)
4926 break;
4927 struct timespec cmp_time
4928 = (wait == TIMEOUT
4929 ? end_time
4930 : (!process_skipped && got_some_output > 0
4931 && (timeout.tv_sec > 0 || timeout.tv_nsec > 0))
4932 ? got_output_end_time
4933 : invalid_timespec ());
4934 if (timespec_valid_p (cmp_time))
4936 now = current_timespec ();
4937 if (timespec_cmp (cmp_time, now) <= 0)
4938 break;
4942 if (nfds < 0)
4944 if (xerrno == EINTR)
4945 no_avail = 1;
4946 else if (xerrno == EBADF)
4947 emacs_abort ();
4948 else
4949 report_file_errno ("Failed select", Qnil, xerrno);
4952 /* Check for keyboard input. */
4953 /* If there is any, return immediately
4954 to give it higher priority than subprocesses. */
4956 if (read_kbd != 0)
4958 unsigned old_timers_run = timers_run;
4959 struct buffer *old_buffer = current_buffer;
4960 Lisp_Object old_window = selected_window;
4961 bool leave = false;
4963 if (detect_input_pending_run_timers (do_display))
4965 swallow_events (do_display);
4966 if (detect_input_pending_run_timers (do_display))
4967 leave = true;
4970 /* If a timer has run, this might have changed buffers
4971 an alike. Make read_key_sequence aware of that. */
4972 if (timers_run != old_timers_run
4973 && waiting_for_user_input_p == -1
4974 && (old_buffer != current_buffer
4975 || !EQ (old_window, selected_window)))
4976 record_asynch_buffer_change ();
4978 if (leave)
4979 break;
4982 /* If there is unread keyboard input, also return. */
4983 if (read_kbd != 0
4984 && requeued_events_pending_p ())
4985 break;
4987 /* If we are not checking for keyboard input now,
4988 do process events (but don't run any timers).
4989 This is so that X events will be processed.
4990 Otherwise they may have to wait until polling takes place.
4991 That would causes delays in pasting selections, for example.
4993 (We used to do this only if wait_for_cell.) */
4994 if (read_kbd == 0 && detect_input_pending ())
4996 swallow_events (do_display);
4997 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4998 if (detect_input_pending ())
4999 break;
5000 #endif
5003 /* Exit now if the cell we're waiting for became non-nil. */
5004 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5005 break;
5007 #ifdef USABLE_SIGIO
5008 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5009 go read it. This can happen with X on BSD after logging out.
5010 In that case, there really is no input and no SIGIO,
5011 but select says there is input. */
5013 if (read_kbd && interrupt_input
5014 && keyboard_bit_set (&Available) && ! noninteractive)
5015 handle_input_available_signal (SIGIO);
5016 #endif
5018 /* If checking input just got us a size-change event from X,
5019 obey it now if we should. */
5020 if (read_kbd || ! NILP (wait_for_cell))
5021 do_pending_window_change (0);
5023 /* Check for data from a process. */
5024 if (no_avail || nfds == 0)
5025 continue;
5027 for (channel = 0; channel <= max_input_desc; ++channel)
5029 struct fd_callback_data *d = &fd_callback_info[channel];
5030 if (d->func
5031 && ((d->condition & FOR_READ
5032 && FD_ISSET (channel, &Available))
5033 || (d->condition & FOR_WRITE
5034 && FD_ISSET (channel, &write_mask))))
5035 d->func (channel, d->data);
5038 for (channel = 0; channel <= max_process_desc; channel++)
5040 if (FD_ISSET (channel, &Available)
5041 && FD_ISSET (channel, &non_keyboard_wait_mask)
5042 && !FD_ISSET (channel, &non_process_wait_mask))
5044 int nread;
5046 /* If waiting for this channel, arrange to return as
5047 soon as no more input to be processed. No more
5048 waiting. */
5049 proc = chan_process[channel];
5050 if (NILP (proc))
5051 continue;
5053 /* If this is a server stream socket, accept connection. */
5054 if (EQ (XPROCESS (proc)->status, Qlisten))
5056 server_accept_connection (proc, channel);
5057 continue;
5060 /* Read data from the process, starting with our
5061 buffered-ahead character if we have one. */
5063 nread = read_process_output (proc, channel);
5064 if ((!wait_proc || wait_proc == XPROCESS (proc))
5065 && got_some_output < nread)
5066 got_some_output = nread;
5067 if (nread > 0)
5069 /* Vacuum up any leftovers without waiting. */
5070 if (wait_proc == XPROCESS (proc))
5071 wait = MINIMUM;
5072 /* Since read_process_output can run a filter,
5073 which can call accept-process-output,
5074 don't try to read from any other processes
5075 before doing the select again. */
5076 FD_ZERO (&Available);
5078 if (do_display)
5079 redisplay_preserve_echo_area (12);
5081 #ifdef EWOULDBLOCK
5082 else if (nread == -1 && errno == EWOULDBLOCK)
5084 #endif
5085 else if (nread == -1 && errno == EAGAIN)
5087 #ifdef WINDOWSNT
5088 /* FIXME: Is this special case still needed? */
5089 /* Note that we cannot distinguish between no input
5090 available now and a closed pipe.
5091 With luck, a closed pipe will be accompanied by
5092 subprocess termination and SIGCHLD. */
5093 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5094 && !PIPECONN_P (proc))
5096 #endif
5097 #ifdef HAVE_PTYS
5098 /* On some OSs with ptys, when the process on one end of
5099 a pty exits, the other end gets an error reading with
5100 errno = EIO instead of getting an EOF (0 bytes read).
5101 Therefore, if we get an error reading and errno =
5102 EIO, just continue, because the child process has
5103 exited and should clean itself up soon (e.g. when we
5104 get a SIGCHLD). */
5105 else if (nread == -1 && errno == EIO)
5107 struct Lisp_Process *p = XPROCESS (proc);
5109 /* Clear the descriptor now, so we only raise the
5110 signal once. */
5111 FD_CLR (channel, &input_wait_mask);
5112 FD_CLR (channel, &non_keyboard_wait_mask);
5114 if (p->pid == -2)
5116 /* If the EIO occurs on a pty, the SIGCHLD handler's
5117 waitpid call will not find the process object to
5118 delete. Do it here. */
5119 p->tick = ++process_tick;
5120 pset_status (p, Qfailed);
5123 #endif /* HAVE_PTYS */
5124 /* If we can detect process termination, don't consider the
5125 process gone just because its pipe is closed. */
5126 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5127 && !PIPECONN_P (proc))
5129 else if (nread == 0 && PIPECONN_P (proc))
5131 /* Preserve status of processes already terminated. */
5132 XPROCESS (proc)->tick = ++process_tick;
5133 deactivate_process (proc);
5134 if (EQ (XPROCESS (proc)->status, Qrun))
5135 pset_status (XPROCESS (proc),
5136 list2 (Qexit, make_number (0)));
5138 else
5140 /* Preserve status of processes already terminated. */
5141 XPROCESS (proc)->tick = ++process_tick;
5142 deactivate_process (proc);
5143 if (XPROCESS (proc)->raw_status_new)
5144 update_status (XPROCESS (proc));
5145 if (EQ (XPROCESS (proc)->status, Qrun))
5146 pset_status (XPROCESS (proc),
5147 list2 (Qexit, make_number (256)));
5150 #ifdef NON_BLOCKING_CONNECT
5151 if (FD_ISSET (channel, &Writeok)
5152 && FD_ISSET (channel, &connect_wait_mask))
5154 struct Lisp_Process *p;
5156 FD_CLR (channel, &connect_wait_mask);
5157 FD_CLR (channel, &write_mask);
5158 if (--num_pending_connects < 0)
5159 emacs_abort ();
5161 proc = chan_process[channel];
5162 if (NILP (proc))
5163 continue;
5165 p = XPROCESS (proc);
5167 #ifdef GNU_LINUX
5168 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5169 So only use it on systems where it is known to work. */
5171 socklen_t xlen = sizeof (xerrno);
5172 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5173 xerrno = errno;
5175 #else
5177 struct sockaddr pname;
5178 socklen_t pnamelen = sizeof (pname);
5180 /* If connection failed, getpeername will fail. */
5181 xerrno = 0;
5182 if (getpeername (channel, &pname, &pnamelen) < 0)
5184 /* Obtain connect failure code through error slippage. */
5185 char dummy;
5186 xerrno = errno;
5187 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5188 xerrno = errno;
5191 #endif
5192 if (xerrno)
5194 p->tick = ++process_tick;
5195 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5196 deactivate_process (proc);
5198 else
5200 pset_status (p, Qrun);
5201 /* Execute the sentinel here. If we had relied on
5202 status_notify to do it later, it will read input
5203 from the process before calling the sentinel. */
5204 exec_sentinel (proc, build_string ("open\n"));
5205 if (0 <= p->infd && !EQ (p->filter, Qt)
5206 && !EQ (p->command, Qt))
5208 FD_SET (p->infd, &input_wait_mask);
5209 FD_SET (p->infd, &non_keyboard_wait_mask);
5213 #endif /* NON_BLOCKING_CONNECT */
5214 } /* End for each file descriptor. */
5215 } /* End while exit conditions not met. */
5217 unbind_to (count, Qnil);
5219 /* If calling from keyboard input, do not quit
5220 since we want to return C-g as an input character.
5221 Otherwise, do pending quit if requested. */
5222 if (read_kbd >= 0)
5224 /* Prevent input_pending from remaining set if we quit. */
5225 clear_input_pending ();
5226 QUIT;
5229 return got_some_output;
5232 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5234 static Lisp_Object
5235 read_process_output_call (Lisp_Object fun_and_args)
5237 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5240 static Lisp_Object
5241 read_process_output_error_handler (Lisp_Object error_val)
5243 cmd_error_internal (error_val, "error in process filter: ");
5244 Vinhibit_quit = Qt;
5245 update_echo_area ();
5246 Fsleep_for (make_number (2), Qnil);
5247 return Qt;
5250 static void
5251 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5252 ssize_t nbytes,
5253 struct coding_system *coding);
5255 /* Read pending output from the process channel,
5256 starting with our buffered-ahead character if we have one.
5257 Yield number of decoded characters read.
5259 This function reads at most 4096 characters.
5260 If you want to read all available subprocess output,
5261 you must call it repeatedly until it returns zero.
5263 The characters read are decoded according to PROC's coding-system
5264 for decoding. */
5266 static int
5267 read_process_output (Lisp_Object proc, int channel)
5269 ssize_t nbytes;
5270 struct Lisp_Process *p = XPROCESS (proc);
5271 struct coding_system *coding = proc_decode_coding_system[channel];
5272 int carryover = p->decoding_carryover;
5273 enum { readmax = 4096 };
5274 ptrdiff_t count = SPECPDL_INDEX ();
5275 Lisp_Object odeactivate;
5276 char chars[sizeof coding->carryover + readmax];
5278 if (carryover)
5279 /* See the comment above. */
5280 memcpy (chars, SDATA (p->decoding_buf), carryover);
5282 #ifdef DATAGRAM_SOCKETS
5283 /* We have a working select, so proc_buffered_char is always -1. */
5284 if (DATAGRAM_CHAN_P (channel))
5286 socklen_t len = datagram_address[channel].len;
5287 nbytes = recvfrom (channel, chars + carryover, readmax,
5288 0, datagram_address[channel].sa, &len);
5290 else
5291 #endif
5293 bool buffered = proc_buffered_char[channel] >= 0;
5294 if (buffered)
5296 chars[carryover] = proc_buffered_char[channel];
5297 proc_buffered_char[channel] = -1;
5299 #ifdef HAVE_GNUTLS
5300 if (p->gnutls_p && p->gnutls_state)
5301 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5302 readmax - buffered);
5303 else
5304 #endif
5305 nbytes = emacs_read (channel, chars + carryover + buffered,
5306 readmax - buffered);
5307 if (nbytes > 0 && p->adaptive_read_buffering)
5309 int delay = p->read_output_delay;
5310 if (nbytes < 256)
5312 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5314 if (delay == 0)
5315 process_output_delay_count++;
5316 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5319 else if (delay > 0 && nbytes == readmax - buffered)
5321 delay -= READ_OUTPUT_DELAY_INCREMENT;
5322 if (delay == 0)
5323 process_output_delay_count--;
5325 p->read_output_delay = delay;
5326 if (delay)
5328 p->read_output_skip = 1;
5329 process_output_skip = 1;
5332 nbytes += buffered;
5333 nbytes += buffered && nbytes <= 0;
5336 p->decoding_carryover = 0;
5338 /* At this point, NBYTES holds number of bytes just received
5339 (including the one in proc_buffered_char[channel]). */
5340 if (nbytes <= 0)
5342 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5343 return nbytes;
5344 coding->mode |= CODING_MODE_LAST_BLOCK;
5347 /* Now set NBYTES how many bytes we must decode. */
5348 nbytes += carryover;
5350 odeactivate = Vdeactivate_mark;
5351 /* There's no good reason to let process filters change the current
5352 buffer, and many callers of accept-process-output, sit-for, and
5353 friends don't expect current-buffer to be changed from under them. */
5354 record_unwind_current_buffer ();
5356 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5358 /* Handling the process output should not deactivate the mark. */
5359 Vdeactivate_mark = odeactivate;
5361 unbind_to (count, Qnil);
5362 return nbytes;
5365 static void
5366 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5367 ssize_t nbytes,
5368 struct coding_system *coding)
5370 Lisp_Object outstream = p->filter;
5371 Lisp_Object text;
5372 bool outer_running_asynch_code = running_asynch_code;
5373 int waiting = waiting_for_user_input_p;
5375 #if 0
5376 Lisp_Object obuffer, okeymap;
5377 XSETBUFFER (obuffer, current_buffer);
5378 okeymap = BVAR (current_buffer, keymap);
5379 #endif
5381 /* We inhibit quit here instead of just catching it so that
5382 hitting ^G when a filter happens to be running won't screw
5383 it up. */
5384 specbind (Qinhibit_quit, Qt);
5385 specbind (Qlast_nonmenu_event, Qt);
5387 /* In case we get recursively called,
5388 and we already saved the match data nonrecursively,
5389 save the same match data in safely recursive fashion. */
5390 if (outer_running_asynch_code)
5392 Lisp_Object tem;
5393 /* Don't clobber the CURRENT match data, either! */
5394 tem = Fmatch_data (Qnil, Qnil, Qnil);
5395 restore_search_regs ();
5396 record_unwind_save_match_data ();
5397 Fset_match_data (tem, Qt);
5400 /* For speed, if a search happens within this code,
5401 save the match data in a special nonrecursive fashion. */
5402 running_asynch_code = 1;
5404 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5405 text = coding->dst_object;
5406 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5407 /* A new coding system might be found. */
5408 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5410 pset_decode_coding_system (p, Vlast_coding_system_used);
5412 /* Don't call setup_coding_system for
5413 proc_decode_coding_system[channel] here. It is done in
5414 detect_coding called via decode_coding above. */
5416 /* If a coding system for encoding is not yet decided, we set
5417 it as the same as coding-system for decoding.
5419 But, before doing that we must check if
5420 proc_encode_coding_system[p->outfd] surely points to a
5421 valid memory because p->outfd will be changed once EOF is
5422 sent to the process. */
5423 if (NILP (p->encode_coding_system) && p->outfd >= 0
5424 && proc_encode_coding_system[p->outfd])
5426 pset_encode_coding_system
5427 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5428 setup_coding_system (p->encode_coding_system,
5429 proc_encode_coding_system[p->outfd]);
5433 if (coding->carryover_bytes > 0)
5435 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5436 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5437 memcpy (SDATA (p->decoding_buf), coding->carryover,
5438 coding->carryover_bytes);
5439 p->decoding_carryover = coding->carryover_bytes;
5441 if (SBYTES (text) > 0)
5442 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5443 sometimes it's simply wrong to wrap (e.g. when called from
5444 accept-process-output). */
5445 internal_condition_case_1 (read_process_output_call,
5446 list3 (outstream, make_lisp_proc (p), text),
5447 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5448 read_process_output_error_handler);
5450 /* If we saved the match data nonrecursively, restore it now. */
5451 restore_search_regs ();
5452 running_asynch_code = outer_running_asynch_code;
5454 /* Restore waiting_for_user_input_p as it was
5455 when we were called, in case the filter clobbered it. */
5456 waiting_for_user_input_p = waiting;
5458 #if 0 /* Call record_asynch_buffer_change unconditionally,
5459 because we might have changed minor modes or other things
5460 that affect key bindings. */
5461 if (! EQ (Fcurrent_buffer (), obuffer)
5462 || ! EQ (current_buffer->keymap, okeymap))
5463 #endif
5464 /* But do it only if the caller is actually going to read events.
5465 Otherwise there's no need to make him wake up, and it could
5466 cause trouble (for example it would make sit_for return). */
5467 if (waiting_for_user_input_p == -1)
5468 record_asynch_buffer_change ();
5471 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5472 Sinternal_default_process_filter, 2, 2, 0,
5473 doc: /* Function used as default process filter.
5474 This inserts the process's output into its buffer, if there is one.
5475 Otherwise it discards the output. */)
5476 (Lisp_Object proc, Lisp_Object text)
5478 struct Lisp_Process *p;
5479 ptrdiff_t opoint;
5481 CHECK_PROCESS (proc);
5482 p = XPROCESS (proc);
5483 CHECK_STRING (text);
5485 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5487 Lisp_Object old_read_only;
5488 ptrdiff_t old_begv, old_zv;
5489 ptrdiff_t old_begv_byte, old_zv_byte;
5490 ptrdiff_t before, before_byte;
5491 ptrdiff_t opoint_byte;
5492 struct buffer *b;
5494 Fset_buffer (p->buffer);
5495 opoint = PT;
5496 opoint_byte = PT_BYTE;
5497 old_read_only = BVAR (current_buffer, read_only);
5498 old_begv = BEGV;
5499 old_zv = ZV;
5500 old_begv_byte = BEGV_BYTE;
5501 old_zv_byte = ZV_BYTE;
5503 bset_read_only (current_buffer, Qnil);
5505 /* Insert new output into buffer at the current end-of-output
5506 marker, thus preserving logical ordering of input and output. */
5507 if (XMARKER (p->mark)->buffer)
5508 set_point_from_marker (p->mark);
5509 else
5510 SET_PT_BOTH (ZV, ZV_BYTE);
5511 before = PT;
5512 before_byte = PT_BYTE;
5514 /* If the output marker is outside of the visible region, save
5515 the restriction and widen. */
5516 if (! (BEGV <= PT && PT <= ZV))
5517 Fwiden ();
5519 /* Adjust the multibyteness of TEXT to that of the buffer. */
5520 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5521 != ! STRING_MULTIBYTE (text))
5522 text = (STRING_MULTIBYTE (text)
5523 ? Fstring_as_unibyte (text)
5524 : Fstring_to_multibyte (text));
5525 /* Insert before markers in case we are inserting where
5526 the buffer's mark is, and the user's next command is Meta-y. */
5527 insert_from_string_before_markers (text, 0, 0,
5528 SCHARS (text), SBYTES (text), 0);
5530 /* Make sure the process marker's position is valid when the
5531 process buffer is changed in the signal_after_change above.
5532 W3 is known to do that. */
5533 if (BUFFERP (p->buffer)
5534 && (b = XBUFFER (p->buffer), b != current_buffer))
5535 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5536 else
5537 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5539 update_mode_lines = 23;
5541 /* Make sure opoint and the old restrictions
5542 float ahead of any new text just as point would. */
5543 if (opoint >= before)
5545 opoint += PT - before;
5546 opoint_byte += PT_BYTE - before_byte;
5548 if (old_begv > before)
5550 old_begv += PT - before;
5551 old_begv_byte += PT_BYTE - before_byte;
5553 if (old_zv >= before)
5555 old_zv += PT - before;
5556 old_zv_byte += PT_BYTE - before_byte;
5559 /* If the restriction isn't what it should be, set it. */
5560 if (old_begv != BEGV || old_zv != ZV)
5561 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5563 bset_read_only (current_buffer, old_read_only);
5564 SET_PT_BOTH (opoint, opoint_byte);
5566 return Qnil;
5569 /* Sending data to subprocess. */
5571 /* In send_process, when a write fails temporarily,
5572 wait_reading_process_output is called. It may execute user code,
5573 e.g. timers, that attempts to write new data to the same process.
5574 We must ensure that data is sent in the right order, and not
5575 interspersed half-completed with other writes (Bug#10815). This is
5576 handled by the write_queue element of struct process. It is a list
5577 with each entry having the form
5579 (string . (offset . length))
5581 where STRING is a lisp string, OFFSET is the offset into the
5582 string's byte sequence from which we should begin to send, and
5583 LENGTH is the number of bytes left to send. */
5585 /* Create a new entry in write_queue.
5586 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5587 BUF is a pointer to the string sequence of the input_obj or a C
5588 string in case of Qt or Qnil. */
5590 static void
5591 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5592 const char *buf, ptrdiff_t len, bool front)
5594 ptrdiff_t offset;
5595 Lisp_Object entry, obj;
5597 if (STRINGP (input_obj))
5599 offset = buf - SSDATA (input_obj);
5600 obj = input_obj;
5602 else
5604 offset = 0;
5605 obj = make_unibyte_string (buf, len);
5608 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5610 if (front)
5611 pset_write_queue (p, Fcons (entry, p->write_queue));
5612 else
5613 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5616 /* Remove the first element in the write_queue of process P, put its
5617 contents in OBJ, BUF and LEN, and return true. If the
5618 write_queue is empty, return false. */
5620 static bool
5621 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5622 const char **buf, ptrdiff_t *len)
5624 Lisp_Object entry, offset_length;
5625 ptrdiff_t offset;
5627 if (NILP (p->write_queue))
5628 return 0;
5630 entry = XCAR (p->write_queue);
5631 pset_write_queue (p, XCDR (p->write_queue));
5633 *obj = XCAR (entry);
5634 offset_length = XCDR (entry);
5636 *len = XINT (XCDR (offset_length));
5637 offset = XINT (XCAR (offset_length));
5638 *buf = SSDATA (*obj) + offset;
5640 return 1;
5643 /* Send some data to process PROC.
5644 BUF is the beginning of the data; LEN is the number of characters.
5645 OBJECT is the Lisp object that the data comes from. If OBJECT is
5646 nil or t, it means that the data comes from C string.
5648 If OBJECT is not nil, the data is encoded by PROC's coding-system
5649 for encoding before it is sent.
5651 This function can evaluate Lisp code and can garbage collect. */
5653 static void
5654 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5655 Lisp_Object object)
5657 struct Lisp_Process *p = XPROCESS (proc);
5658 ssize_t rv;
5659 struct coding_system *coding;
5661 if (p->raw_status_new)
5662 update_status (p);
5663 if (! EQ (p->status, Qrun))
5664 error ("Process %s not running", SDATA (p->name));
5665 if (p->outfd < 0)
5666 error ("Output file descriptor of %s is closed", SDATA (p->name));
5668 coding = proc_encode_coding_system[p->outfd];
5669 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5671 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5672 || (BUFFERP (object)
5673 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5674 || EQ (object, Qt))
5676 pset_encode_coding_system
5677 (p, complement_process_encoding_system (p->encode_coding_system));
5678 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5680 /* The coding system for encoding was changed to raw-text
5681 because we sent a unibyte text previously. Now we are
5682 sending a multibyte text, thus we must encode it by the
5683 original coding system specified for the current process.
5685 Another reason we come here is that the coding system
5686 was just complemented and a new one was returned by
5687 complement_process_encoding_system. */
5688 setup_coding_system (p->encode_coding_system, coding);
5689 Vlast_coding_system_used = p->encode_coding_system;
5691 coding->src_multibyte = 1;
5693 else
5695 coding->src_multibyte = 0;
5696 /* For sending a unibyte text, character code conversion should
5697 not take place but EOL conversion should. So, setup raw-text
5698 or one of the subsidiary if we have not yet done it. */
5699 if (CODING_REQUIRE_ENCODING (coding))
5701 if (CODING_REQUIRE_FLUSHING (coding))
5703 /* But, before changing the coding, we must flush out data. */
5704 coding->mode |= CODING_MODE_LAST_BLOCK;
5705 send_process (proc, "", 0, Qt);
5706 coding->mode &= CODING_MODE_LAST_BLOCK;
5708 setup_coding_system (raw_text_coding_system
5709 (Vlast_coding_system_used),
5710 coding);
5711 coding->src_multibyte = 0;
5714 coding->dst_multibyte = 0;
5716 if (CODING_REQUIRE_ENCODING (coding))
5718 coding->dst_object = Qt;
5719 if (BUFFERP (object))
5721 ptrdiff_t from_byte, from, to;
5722 ptrdiff_t save_pt, save_pt_byte;
5723 struct buffer *cur = current_buffer;
5725 set_buffer_internal (XBUFFER (object));
5726 save_pt = PT, save_pt_byte = PT_BYTE;
5728 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5729 from = BYTE_TO_CHAR (from_byte);
5730 to = BYTE_TO_CHAR (from_byte + len);
5731 TEMP_SET_PT_BOTH (from, from_byte);
5732 encode_coding_object (coding, object, from, from_byte,
5733 to, from_byte + len, Qt);
5734 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5735 set_buffer_internal (cur);
5737 else if (STRINGP (object))
5739 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5740 SBYTES (object), Qt);
5742 else
5744 coding->dst_object = make_unibyte_string (buf, len);
5745 coding->produced = len;
5748 len = coding->produced;
5749 object = coding->dst_object;
5750 buf = SSDATA (object);
5753 /* If there is already data in the write_queue, put the new data
5754 in the back of queue. Otherwise, ignore it. */
5755 if (!NILP (p->write_queue))
5756 write_queue_push (p, object, buf, len, 0);
5758 do /* while !NILP (p->write_queue) */
5760 ptrdiff_t cur_len = -1;
5761 const char *cur_buf;
5762 Lisp_Object cur_object;
5764 /* If write_queue is empty, ignore it. */
5765 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5767 cur_len = len;
5768 cur_buf = buf;
5769 cur_object = object;
5772 while (cur_len > 0)
5774 /* Send this batch, using one or more write calls. */
5775 ptrdiff_t written = 0;
5776 int outfd = p->outfd;
5777 #ifdef DATAGRAM_SOCKETS
5778 if (DATAGRAM_CHAN_P (outfd))
5780 rv = sendto (outfd, cur_buf, cur_len,
5781 0, datagram_address[outfd].sa,
5782 datagram_address[outfd].len);
5783 if (rv >= 0)
5784 written = rv;
5785 else if (errno == EMSGSIZE)
5786 report_file_error ("Sending datagram", proc);
5788 else
5789 #endif
5791 #ifdef HAVE_GNUTLS
5792 if (p->gnutls_p && p->gnutls_state)
5793 written = emacs_gnutls_write (p, cur_buf, cur_len);
5794 else
5795 #endif
5796 written = emacs_write_sig (outfd, cur_buf, cur_len);
5797 rv = (written ? 0 : -1);
5798 if (p->read_output_delay > 0
5799 && p->adaptive_read_buffering == 1)
5801 p->read_output_delay = 0;
5802 process_output_delay_count--;
5803 p->read_output_skip = 0;
5807 if (rv < 0)
5809 if (errno == EAGAIN
5810 #ifdef EWOULDBLOCK
5811 || errno == EWOULDBLOCK
5812 #endif
5814 /* Buffer is full. Wait, accepting input;
5815 that may allow the program
5816 to finish doing output and read more. */
5818 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5819 /* A gross hack to work around a bug in FreeBSD.
5820 In the following sequence, read(2) returns
5821 bogus data:
5823 write(2) 1022 bytes
5824 write(2) 954 bytes, get EAGAIN
5825 read(2) 1024 bytes in process_read_output
5826 read(2) 11 bytes in process_read_output
5828 That is, read(2) returns more bytes than have
5829 ever been written successfully. The 1033 bytes
5830 read are the 1022 bytes written successfully
5831 after processing (for example with CRs added if
5832 the terminal is set up that way which it is
5833 here). The same bytes will be seen again in a
5834 later read(2), without the CRs. */
5836 if (errno == EAGAIN)
5838 int flags = FWRITE;
5839 ioctl (p->outfd, TIOCFLUSH, &flags);
5841 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5843 /* Put what we should have written in wait_queue. */
5844 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5845 wait_reading_process_output (0, 20 * 1000 * 1000,
5846 0, 0, Qnil, NULL, 0);
5847 /* Reread queue, to see what is left. */
5848 break;
5850 else if (errno == EPIPE)
5852 p->raw_status_new = 0;
5853 pset_status (p, list2 (Qexit, make_number (256)));
5854 p->tick = ++process_tick;
5855 deactivate_process (proc);
5856 error ("process %s no longer connected to pipe; closed it",
5857 SDATA (p->name));
5859 else
5860 /* This is a real error. */
5861 report_file_error ("Writing to process", proc);
5863 cur_buf += written;
5864 cur_len -= written;
5867 while (!NILP (p->write_queue));
5870 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5871 3, 3, 0,
5872 doc: /* Send current contents of region as input to PROCESS.
5873 PROCESS may be a process, a buffer, the name of a process or buffer, or
5874 nil, indicating the current buffer's process.
5875 Called from program, takes three arguments, PROCESS, START and END.
5876 If the region is more than 500 characters long,
5877 it is sent in several bunches. This may happen even for shorter regions.
5878 Output from processes can arrive in between bunches. */)
5879 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5881 Lisp_Object proc = get_process (process);
5882 ptrdiff_t start_byte, end_byte;
5884 validate_region (&start, &end);
5886 start_byte = CHAR_TO_BYTE (XINT (start));
5887 end_byte = CHAR_TO_BYTE (XINT (end));
5889 if (XINT (start) < GPT && XINT (end) > GPT)
5890 move_gap_both (XINT (start), start_byte);
5892 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5893 end_byte - start_byte, Fcurrent_buffer ());
5895 return Qnil;
5898 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5899 2, 2, 0,
5900 doc: /* Send PROCESS the contents of STRING as input.
5901 PROCESS may be a process, a buffer, the name of a process or buffer, or
5902 nil, indicating the current buffer's process.
5903 If STRING is more than 500 characters long,
5904 it is sent in several bunches. This may happen even for shorter strings.
5905 Output from processes can arrive in between bunches. */)
5906 (Lisp_Object process, Lisp_Object string)
5908 Lisp_Object proc;
5909 CHECK_STRING (string);
5910 proc = get_process (process);
5911 send_process (proc, SSDATA (string),
5912 SBYTES (string), string);
5913 return Qnil;
5916 /* Return the foreground process group for the tty/pty that
5917 the process P uses. */
5918 static pid_t
5919 emacs_get_tty_pgrp (struct Lisp_Process *p)
5921 pid_t gid = -1;
5923 #ifdef TIOCGPGRP
5924 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5926 int fd;
5927 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5928 master side. Try the slave side. */
5929 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5931 if (fd != -1)
5933 ioctl (fd, TIOCGPGRP, &gid);
5934 emacs_close (fd);
5937 #endif /* defined (TIOCGPGRP ) */
5939 return gid;
5942 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5943 Sprocess_running_child_p, 0, 1, 0,
5944 doc: /* Return non-nil if PROCESS has given the terminal to a
5945 child. If the operating system does not make it possible to find out,
5946 return t. If we can find out, return the numeric ID of the foreground
5947 process group. */)
5948 (Lisp_Object process)
5950 /* Initialize in case ioctl doesn't exist or gives an error,
5951 in a way that will cause returning t. */
5952 pid_t gid;
5953 Lisp_Object proc;
5954 struct Lisp_Process *p;
5956 proc = get_process (process);
5957 p = XPROCESS (proc);
5959 if (!EQ (p->type, Qreal))
5960 error ("Process %s is not a subprocess",
5961 SDATA (p->name));
5962 if (p->infd < 0)
5963 error ("Process %s is not active",
5964 SDATA (p->name));
5966 gid = emacs_get_tty_pgrp (p);
5968 if (gid == p->pid)
5969 return Qnil;
5970 if (gid != -1)
5971 return make_number (gid);
5972 return Qt;
5975 /* Send a signal number SIGNO to PROCESS.
5976 If CURRENT_GROUP is t, that means send to the process group
5977 that currently owns the terminal being used to communicate with PROCESS.
5978 This is used for various commands in shell mode.
5979 If CURRENT_GROUP is lambda, that means send to the process group
5980 that currently owns the terminal, but only if it is NOT the shell itself.
5982 If NOMSG is false, insert signal-announcements into process's buffers
5983 right away.
5985 If we can, we try to signal PROCESS by sending control characters
5986 down the pty. This allows us to signal inferiors who have changed
5987 their uid, for which kill would return an EPERM error. */
5989 static void
5990 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5991 bool nomsg)
5993 Lisp_Object proc;
5994 struct Lisp_Process *p;
5995 pid_t gid;
5996 bool no_pgrp = 0;
5998 proc = get_process (process);
5999 p = XPROCESS (proc);
6001 if (!EQ (p->type, Qreal))
6002 error ("Process %s is not a subprocess",
6003 SDATA (p->name));
6004 if (p->infd < 0)
6005 error ("Process %s is not active",
6006 SDATA (p->name));
6008 if (!p->pty_flag)
6009 current_group = Qnil;
6011 /* If we are using pgrps, get a pgrp number and make it negative. */
6012 if (NILP (current_group))
6013 /* Send the signal to the shell's process group. */
6014 gid = p->pid;
6015 else
6017 #ifdef SIGNALS_VIA_CHARACTERS
6018 /* If possible, send signals to the entire pgrp
6019 by sending an input character to it. */
6021 struct termios t;
6022 cc_t *sig_char = NULL;
6024 tcgetattr (p->infd, &t);
6026 switch (signo)
6028 case SIGINT:
6029 sig_char = &t.c_cc[VINTR];
6030 break;
6032 case SIGQUIT:
6033 sig_char = &t.c_cc[VQUIT];
6034 break;
6036 case SIGTSTP:
6037 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6038 sig_char = &t.c_cc[VSWTCH];
6039 #else
6040 sig_char = &t.c_cc[VSUSP];
6041 #endif
6042 break;
6045 if (sig_char && *sig_char != CDISABLE)
6047 send_process (proc, (char *) sig_char, 1, Qnil);
6048 return;
6050 /* If we can't send the signal with a character,
6051 fall through and send it another way. */
6053 /* The code above may fall through if it can't
6054 handle the signal. */
6055 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6057 #ifdef TIOCGPGRP
6058 /* Get the current pgrp using the tty itself, if we have that.
6059 Otherwise, use the pty to get the pgrp.
6060 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6061 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6062 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6063 His patch indicates that if TIOCGPGRP returns an error, then
6064 we should just assume that p->pid is also the process group id. */
6066 gid = emacs_get_tty_pgrp (p);
6068 if (gid == -1)
6069 /* If we can't get the information, assume
6070 the shell owns the tty. */
6071 gid = p->pid;
6073 /* It is not clear whether anything really can set GID to -1.
6074 Perhaps on some system one of those ioctls can or could do so.
6075 Or perhaps this is vestigial. */
6076 if (gid == -1)
6077 no_pgrp = 1;
6078 #else /* ! defined (TIOCGPGRP) */
6079 /* Can't select pgrps on this system, so we know that
6080 the child itself heads the pgrp. */
6081 gid = p->pid;
6082 #endif /* ! defined (TIOCGPGRP) */
6084 /* If current_group is lambda, and the shell owns the terminal,
6085 don't send any signal. */
6086 if (EQ (current_group, Qlambda) && gid == p->pid)
6087 return;
6090 #ifdef SIGCONT
6091 if (signo == SIGCONT)
6093 p->raw_status_new = 0;
6094 pset_status (p, Qrun);
6095 p->tick = ++process_tick;
6096 if (!nomsg)
6098 status_notify (NULL, NULL);
6099 redisplay_preserve_echo_area (13);
6102 #endif
6104 #ifdef TIOCSIGSEND
6105 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6106 We don't know whether the bug is fixed in later HP-UX versions. */
6107 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6108 return;
6109 #endif
6111 /* If we don't have process groups, send the signal to the immediate
6112 subprocess. That isn't really right, but it's better than any
6113 obvious alternative. */
6114 pid_t pid = no_pgrp ? gid : - gid;
6116 /* Do not kill an already-reaped process, as that could kill an
6117 innocent bystander that happens to have the same process ID. */
6118 sigset_t oldset;
6119 block_child_signal (&oldset);
6120 if (p->alive)
6121 kill (pid, signo);
6122 unblock_child_signal (&oldset);
6125 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6126 doc: /* Interrupt process PROCESS.
6127 PROCESS may be a process, a buffer, or the name of a process or buffer.
6128 No arg or nil means current buffer's process.
6129 Second arg CURRENT-GROUP non-nil means send signal to
6130 the current process-group of the process's controlling terminal
6131 rather than to the process's own process group.
6132 If the process is a shell, this means interrupt current subjob
6133 rather than the shell.
6135 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6136 don't send the signal. */)
6137 (Lisp_Object process, Lisp_Object current_group)
6139 process_send_signal (process, SIGINT, current_group, 0);
6140 return process;
6143 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6144 doc: /* Kill process PROCESS. May be process or name of one.
6145 See function `interrupt-process' for more details on usage. */)
6146 (Lisp_Object process, Lisp_Object current_group)
6148 process_send_signal (process, SIGKILL, current_group, 0);
6149 return process;
6152 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6153 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6154 See function `interrupt-process' for more details on usage. */)
6155 (Lisp_Object process, Lisp_Object current_group)
6157 process_send_signal (process, SIGQUIT, current_group, 0);
6158 return process;
6161 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6162 doc: /* Stop process PROCESS. May be process or name of one.
6163 See function `interrupt-process' for more details on usage.
6164 If PROCESS is a network or serial process, inhibit handling of incoming
6165 traffic. */)
6166 (Lisp_Object process, Lisp_Object current_group)
6168 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6169 || PIPECONN_P (process)))
6171 struct Lisp_Process *p;
6173 p = XPROCESS (process);
6174 if (NILP (p->command)
6175 && p->infd >= 0)
6177 FD_CLR (p->infd, &input_wait_mask);
6178 FD_CLR (p->infd, &non_keyboard_wait_mask);
6180 pset_command (p, Qt);
6181 return process;
6183 #ifndef SIGTSTP
6184 error ("No SIGTSTP support");
6185 #else
6186 process_send_signal (process, SIGTSTP, current_group, 0);
6187 #endif
6188 return process;
6191 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6192 doc: /* Continue process PROCESS. May be process or name of one.
6193 See function `interrupt-process' for more details on usage.
6194 If PROCESS is a network or serial process, resume handling of incoming
6195 traffic. */)
6196 (Lisp_Object process, Lisp_Object current_group)
6198 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6199 || PIPECONN_P (process)))
6201 struct Lisp_Process *p;
6203 p = XPROCESS (process);
6204 if (EQ (p->command, Qt)
6205 && p->infd >= 0
6206 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6208 FD_SET (p->infd, &input_wait_mask);
6209 FD_SET (p->infd, &non_keyboard_wait_mask);
6210 #ifdef WINDOWSNT
6211 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6212 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6213 #else /* not WINDOWSNT */
6214 tcflush (p->infd, TCIFLUSH);
6215 #endif /* not WINDOWSNT */
6217 pset_command (p, Qnil);
6218 return process;
6220 #ifdef SIGCONT
6221 process_send_signal (process, SIGCONT, current_group, 0);
6222 #else
6223 error ("No SIGCONT support");
6224 #endif
6225 return process;
6228 /* Return the integer value of the signal whose abbreviation is ABBR,
6229 or a negative number if there is no such signal. */
6230 static int
6231 abbr_to_signal (char const *name)
6233 int i, signo;
6234 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6236 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6237 name += 3;
6239 for (i = 0; i < sizeof sigbuf; i++)
6241 sigbuf[i] = c_toupper (name[i]);
6242 if (! sigbuf[i])
6243 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6246 return -1;
6249 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6250 2, 2, "sProcess (name or number): \nnSignal code: ",
6251 doc: /* Send PROCESS the signal with code SIGCODE.
6252 PROCESS may also be a number specifying the process id of the
6253 process to signal; in this case, the process need not be a child of
6254 this Emacs.
6255 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6256 (Lisp_Object process, Lisp_Object sigcode)
6258 pid_t pid;
6259 int signo;
6261 if (STRINGP (process))
6263 Lisp_Object tem = Fget_process (process);
6264 if (NILP (tem))
6266 Lisp_Object process_number
6267 = string_to_number (SSDATA (process), 10, 1);
6268 if (NUMBERP (process_number))
6269 tem = process_number;
6271 process = tem;
6273 else if (!NUMBERP (process))
6274 process = get_process (process);
6276 if (NILP (process))
6277 return process;
6279 if (NUMBERP (process))
6280 CONS_TO_INTEGER (process, pid_t, pid);
6281 else
6283 CHECK_PROCESS (process);
6284 pid = XPROCESS (process)->pid;
6285 if (pid <= 0)
6286 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6289 if (INTEGERP (sigcode))
6291 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6292 signo = XINT (sigcode);
6294 else
6296 char *name;
6298 CHECK_SYMBOL (sigcode);
6299 name = SSDATA (SYMBOL_NAME (sigcode));
6301 signo = abbr_to_signal (name);
6302 if (signo < 0)
6303 error ("Undefined signal name %s", name);
6306 return make_number (kill (pid, signo));
6309 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6310 doc: /* Make PROCESS see end-of-file in its input.
6311 EOF comes after any text already sent to it.
6312 PROCESS may be a process, a buffer, the name of a process or buffer, or
6313 nil, indicating the current buffer's process.
6314 If PROCESS is a network connection, or is a process communicating
6315 through a pipe (as opposed to a pty), then you cannot send any more
6316 text to PROCESS after you call this function.
6317 If PROCESS is a serial process, wait until all output written to the
6318 process has been transmitted to the serial port. */)
6319 (Lisp_Object process)
6321 Lisp_Object proc;
6322 struct coding_system *coding = NULL;
6323 int outfd;
6325 if (DATAGRAM_CONN_P (process))
6326 return process;
6328 proc = get_process (process);
6329 outfd = XPROCESS (proc)->outfd;
6330 if (outfd >= 0)
6331 coding = proc_encode_coding_system[outfd];
6333 /* Make sure the process is really alive. */
6334 if (XPROCESS (proc)->raw_status_new)
6335 update_status (XPROCESS (proc));
6336 if (! EQ (XPROCESS (proc)->status, Qrun))
6337 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6339 if (coding && CODING_REQUIRE_FLUSHING (coding))
6341 coding->mode |= CODING_MODE_LAST_BLOCK;
6342 send_process (proc, "", 0, Qnil);
6345 if (XPROCESS (proc)->pty_flag)
6346 send_process (proc, "\004", 1, Qnil);
6347 else if (EQ (XPROCESS (proc)->type, Qserial))
6349 #ifndef WINDOWSNT
6350 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6351 report_file_error ("Failed tcdrain", Qnil);
6352 #endif /* not WINDOWSNT */
6353 /* Do nothing on Windows because writes are blocking. */
6355 else
6357 struct Lisp_Process *p = XPROCESS (proc);
6358 int old_outfd = p->outfd;
6359 int new_outfd;
6361 #ifdef HAVE_SHUTDOWN
6362 /* If this is a network connection, or socketpair is used
6363 for communication with the subprocess, call shutdown to cause EOF.
6364 (In some old system, shutdown to socketpair doesn't work.
6365 Then we just can't win.) */
6366 if (0 <= old_outfd
6367 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6368 shutdown (old_outfd, 1);
6369 #endif
6370 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6371 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6372 if (new_outfd < 0)
6373 report_file_error ("Opening null device", Qnil);
6374 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6375 p->outfd = new_outfd;
6377 if (!proc_encode_coding_system[new_outfd])
6378 proc_encode_coding_system[new_outfd]
6379 = xmalloc (sizeof (struct coding_system));
6380 if (old_outfd >= 0)
6382 *proc_encode_coding_system[new_outfd]
6383 = *proc_encode_coding_system[old_outfd];
6384 memset (proc_encode_coding_system[old_outfd], 0,
6385 sizeof (struct coding_system));
6387 else
6388 setup_coding_system (p->encode_coding_system,
6389 proc_encode_coding_system[new_outfd]);
6391 return process;
6394 /* The main Emacs thread records child processes in three places:
6396 - Vprocess_alist, for asynchronous subprocesses, which are child
6397 processes visible to Lisp.
6399 - deleted_pid_list, for child processes invisible to Lisp,
6400 typically because of delete-process. These are recorded so that
6401 the processes can be reaped when they exit, so that the operating
6402 system's process table is not cluttered by zombies.
6404 - the local variable PID in Fcall_process, call_process_cleanup and
6405 call_process_kill, for synchronous subprocesses.
6406 record_unwind_protect is used to make sure this process is not
6407 forgotten: if the user interrupts call-process and the child
6408 process refuses to exit immediately even with two C-g's,
6409 call_process_kill adds PID's contents to deleted_pid_list before
6410 returning.
6412 The main Emacs thread invokes waitpid only on child processes that
6413 it creates and that have not been reaped. This avoid races on
6414 platforms such as GTK, where other threads create their own
6415 subprocesses which the main thread should not reap. For example,
6416 if the main thread attempted to reap an already-reaped child, it
6417 might inadvertently reap a GTK-created process that happened to
6418 have the same process ID. */
6420 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6421 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6422 keep track of its own children. GNUstep is similar. */
6424 static void dummy_handler (int sig) {}
6425 static signal_handler_t volatile lib_child_handler;
6427 /* Handle a SIGCHLD signal by looking for known child processes of
6428 Emacs whose status have changed. For each one found, record its
6429 new status.
6431 All we do is change the status; we do not run sentinels or print
6432 notifications. That is saved for the next time keyboard input is
6433 done, in order to avoid timing errors.
6435 ** WARNING: this can be called during garbage collection.
6436 Therefore, it must not be fooled by the presence of mark bits in
6437 Lisp objects.
6439 ** USG WARNING: Although it is not obvious from the documentation
6440 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6441 signal() before executing at least one wait(), otherwise the
6442 handler will be called again, resulting in an infinite loop. The
6443 relevant portion of the documentation reads "SIGCLD signals will be
6444 queued and the signal-catching function will be continually
6445 reentered until the queue is empty". Invoking signal() causes the
6446 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6447 Inc.
6449 ** Malloc WARNING: This should never call malloc either directly or
6450 indirectly; if it does, that is a bug. */
6452 static void
6453 handle_child_signal (int sig)
6455 Lisp_Object tail, proc;
6457 /* Find the process that signaled us, and record its status. */
6459 /* The process can have been deleted by Fdelete_process, or have
6460 been started asynchronously by Fcall_process. */
6461 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6463 bool all_pids_are_fixnums
6464 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6465 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6466 Lisp_Object head = XCAR (tail);
6467 Lisp_Object xpid;
6468 if (! CONSP (head))
6469 continue;
6470 xpid = XCAR (head);
6471 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6473 pid_t deleted_pid;
6474 if (INTEGERP (xpid))
6475 deleted_pid = XINT (xpid);
6476 else
6477 deleted_pid = XFLOAT_DATA (xpid);
6478 if (child_status_changed (deleted_pid, 0, 0))
6480 if (STRINGP (XCDR (head)))
6481 unlink (SSDATA (XCDR (head)));
6482 XSETCAR (tail, Qnil);
6487 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6488 FOR_EACH_PROCESS (tail, proc)
6490 struct Lisp_Process *p = XPROCESS (proc);
6491 int status;
6493 if (p->alive
6494 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6496 /* Change the status of the process that was found. */
6497 p->tick = ++process_tick;
6498 p->raw_status = status;
6499 p->raw_status_new = 1;
6501 /* If process has terminated, stop waiting for its output. */
6502 if (WIFSIGNALED (status) || WIFEXITED (status))
6504 bool clear_desc_flag = 0;
6505 p->alive = 0;
6506 if (p->infd >= 0)
6507 clear_desc_flag = 1;
6509 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6510 if (clear_desc_flag)
6512 FD_CLR (p->infd, &input_wait_mask);
6513 FD_CLR (p->infd, &non_keyboard_wait_mask);
6519 lib_child_handler (sig);
6520 #ifdef NS_IMPL_GNUSTEP
6521 /* NSTask in GNUstep sets its child handler each time it is called.
6522 So we must re-set ours. */
6523 catch_child_signal ();
6524 #endif
6527 static void
6528 deliver_child_signal (int sig)
6530 deliver_process_signal (sig, handle_child_signal);
6534 static Lisp_Object
6535 exec_sentinel_error_handler (Lisp_Object error_val)
6537 cmd_error_internal (error_val, "error in process sentinel: ");
6538 Vinhibit_quit = Qt;
6539 update_echo_area ();
6540 Fsleep_for (make_number (2), Qnil);
6541 return Qt;
6544 static void
6545 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6547 Lisp_Object sentinel, odeactivate;
6548 struct Lisp_Process *p = XPROCESS (proc);
6549 ptrdiff_t count = SPECPDL_INDEX ();
6550 bool outer_running_asynch_code = running_asynch_code;
6551 int waiting = waiting_for_user_input_p;
6553 if (inhibit_sentinels)
6554 return;
6556 odeactivate = Vdeactivate_mark;
6557 #if 0
6558 Lisp_Object obuffer, okeymap;
6559 XSETBUFFER (obuffer, current_buffer);
6560 okeymap = BVAR (current_buffer, keymap);
6561 #endif
6563 /* There's no good reason to let sentinels change the current
6564 buffer, and many callers of accept-process-output, sit-for, and
6565 friends don't expect current-buffer to be changed from under them. */
6566 record_unwind_current_buffer ();
6568 sentinel = p->sentinel;
6570 /* Inhibit quit so that random quits don't screw up a running filter. */
6571 specbind (Qinhibit_quit, Qt);
6572 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6574 /* In case we get recursively called,
6575 and we already saved the match data nonrecursively,
6576 save the same match data in safely recursive fashion. */
6577 if (outer_running_asynch_code)
6579 Lisp_Object tem;
6580 tem = Fmatch_data (Qnil, Qnil, Qnil);
6581 restore_search_regs ();
6582 record_unwind_save_match_data ();
6583 Fset_match_data (tem, Qt);
6586 /* For speed, if a search happens within this code,
6587 save the match data in a special nonrecursive fashion. */
6588 running_asynch_code = 1;
6590 internal_condition_case_1 (read_process_output_call,
6591 list3 (sentinel, proc, reason),
6592 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6593 exec_sentinel_error_handler);
6595 /* If we saved the match data nonrecursively, restore it now. */
6596 restore_search_regs ();
6597 running_asynch_code = outer_running_asynch_code;
6599 Vdeactivate_mark = odeactivate;
6601 /* Restore waiting_for_user_input_p as it was
6602 when we were called, in case the filter clobbered it. */
6603 waiting_for_user_input_p = waiting;
6605 #if 0
6606 if (! EQ (Fcurrent_buffer (), obuffer)
6607 || ! EQ (current_buffer->keymap, okeymap))
6608 #endif
6609 /* But do it only if the caller is actually going to read events.
6610 Otherwise there's no need to make him wake up, and it could
6611 cause trouble (for example it would make sit_for return). */
6612 if (waiting_for_user_input_p == -1)
6613 record_asynch_buffer_change ();
6615 unbind_to (count, Qnil);
6618 /* Report all recent events of a change in process status
6619 (either run the sentinel or output a message).
6620 This is usually done while Emacs is waiting for keyboard input
6621 but can be done at other times.
6623 Return positive if any input was received from WAIT_PROC (or from
6624 any process if WAIT_PROC is null), zero if input was attempted but
6625 none received, and negative if we didn't even try. */
6627 static int
6628 status_notify (struct Lisp_Process *deleting_process,
6629 struct Lisp_Process *wait_proc)
6631 Lisp_Object proc;
6632 Lisp_Object tail, msg;
6633 int got_some_output = -1;
6635 tail = Qnil;
6636 msg = Qnil;
6638 /* Set this now, so that if new processes are created by sentinels
6639 that we run, we get called again to handle their status changes. */
6640 update_tick = process_tick;
6642 FOR_EACH_PROCESS (tail, proc)
6644 Lisp_Object symbol;
6645 register struct Lisp_Process *p = XPROCESS (proc);
6647 if (p->tick != p->update_tick)
6649 p->update_tick = p->tick;
6651 /* If process is still active, read any output that remains. */
6652 while (! EQ (p->filter, Qt)
6653 && ! EQ (p->status, Qconnect)
6654 && ! EQ (p->status, Qlisten)
6655 /* Network or serial process not stopped: */
6656 && ! EQ (p->command, Qt)
6657 && p->infd >= 0
6658 && p != deleting_process)
6660 int nread = read_process_output (proc, p->infd);
6661 if ((!wait_proc || wait_proc == XPROCESS (proc))
6662 && got_some_output < nread)
6663 got_some_output = nread;
6664 if (nread <= 0)
6665 break;
6668 /* Get the text to use for the message. */
6669 if (p->raw_status_new)
6670 update_status (p);
6671 msg = status_message (p);
6673 /* If process is terminated, deactivate it or delete it. */
6674 symbol = p->status;
6675 if (CONSP (p->status))
6676 symbol = XCAR (p->status);
6678 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6679 || EQ (symbol, Qclosed))
6681 if (delete_exited_processes)
6682 remove_process (proc);
6683 else
6684 deactivate_process (proc);
6687 /* The actions above may have further incremented p->tick.
6688 So set p->update_tick again so that an error in the sentinel will
6689 not cause this code to be run again. */
6690 p->update_tick = p->tick;
6691 /* Now output the message suitably. */
6692 exec_sentinel (proc, msg);
6693 if (BUFFERP (p->buffer))
6694 /* In case it uses %s in mode-line-format. */
6695 bset_update_mode_line (XBUFFER (p->buffer));
6697 } /* end for */
6699 return got_some_output;
6702 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6703 Sinternal_default_process_sentinel, 2, 2, 0,
6704 doc: /* Function used as default sentinel for processes.
6705 This inserts a status message into the process's buffer, if there is one. */)
6706 (Lisp_Object proc, Lisp_Object msg)
6708 Lisp_Object buffer, symbol;
6709 struct Lisp_Process *p;
6710 CHECK_PROCESS (proc);
6711 p = XPROCESS (proc);
6712 buffer = p->buffer;
6713 symbol = p->status;
6714 if (CONSP (symbol))
6715 symbol = XCAR (symbol);
6717 if (!EQ (symbol, Qrun) && !NILP (buffer))
6719 Lisp_Object tem;
6720 struct buffer *old = current_buffer;
6721 ptrdiff_t opoint, opoint_byte;
6722 ptrdiff_t before, before_byte;
6724 /* Avoid error if buffer is deleted
6725 (probably that's why the process is dead, too). */
6726 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6727 return Qnil;
6728 Fset_buffer (buffer);
6730 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6731 msg = (code_convert_string_norecord
6732 (msg, Vlocale_coding_system, 1));
6734 opoint = PT;
6735 opoint_byte = PT_BYTE;
6736 /* Insert new output into buffer
6737 at the current end-of-output marker,
6738 thus preserving logical ordering of input and output. */
6739 if (XMARKER (p->mark)->buffer)
6740 Fgoto_char (p->mark);
6741 else
6742 SET_PT_BOTH (ZV, ZV_BYTE);
6744 before = PT;
6745 before_byte = PT_BYTE;
6747 tem = BVAR (current_buffer, read_only);
6748 bset_read_only (current_buffer, Qnil);
6749 insert_string ("\nProcess ");
6750 { /* FIXME: temporary kludge. */
6751 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6752 insert_string (" ");
6753 Finsert (1, &msg);
6754 bset_read_only (current_buffer, tem);
6755 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6757 if (opoint >= before)
6758 SET_PT_BOTH (opoint + (PT - before),
6759 opoint_byte + (PT_BYTE - before_byte));
6760 else
6761 SET_PT_BOTH (opoint, opoint_byte);
6763 set_buffer_internal (old);
6765 return Qnil;
6769 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6770 Sset_process_coding_system, 1, 3, 0,
6771 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6772 DECODING will be used to decode subprocess output and ENCODING to
6773 encode subprocess input. */)
6774 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6776 register struct Lisp_Process *p;
6778 CHECK_PROCESS (process);
6779 p = XPROCESS (process);
6780 if (p->infd < 0)
6781 error ("Input file descriptor of %s closed", SDATA (p->name));
6782 if (p->outfd < 0)
6783 error ("Output file descriptor of %s closed", SDATA (p->name));
6784 Fcheck_coding_system (decoding);
6785 Fcheck_coding_system (encoding);
6786 encoding = coding_inherit_eol_type (encoding, Qnil);
6787 pset_decode_coding_system (p, decoding);
6788 pset_encode_coding_system (p, encoding);
6789 setup_process_coding_systems (process);
6791 return Qnil;
6794 DEFUN ("process-coding-system",
6795 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6796 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6797 (register Lisp_Object process)
6799 CHECK_PROCESS (process);
6800 return Fcons (XPROCESS (process)->decode_coding_system,
6801 XPROCESS (process)->encode_coding_system);
6804 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6805 Sset_process_filter_multibyte, 2, 2, 0,
6806 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6807 If FLAG is non-nil, the filter is given multibyte strings.
6808 If FLAG is nil, the filter is given unibyte strings. In this case,
6809 all character code conversion except for end-of-line conversion is
6810 suppressed. */)
6811 (Lisp_Object process, Lisp_Object flag)
6813 register struct Lisp_Process *p;
6815 CHECK_PROCESS (process);
6816 p = XPROCESS (process);
6817 if (NILP (flag))
6818 pset_decode_coding_system
6819 (p, raw_text_coding_system (p->decode_coding_system));
6820 setup_process_coding_systems (process);
6822 return Qnil;
6825 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6826 Sprocess_filter_multibyte_p, 1, 1, 0,
6827 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6828 (Lisp_Object process)
6830 register struct Lisp_Process *p;
6831 struct coding_system *coding;
6833 CHECK_PROCESS (process);
6834 p = XPROCESS (process);
6835 if (p->infd < 0)
6836 return Qnil;
6837 coding = proc_decode_coding_system[p->infd];
6838 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6844 # ifdef HAVE_GPM
6846 void
6847 add_gpm_wait_descriptor (int desc)
6849 add_keyboard_wait_descriptor (desc);
6852 void
6853 delete_gpm_wait_descriptor (int desc)
6855 delete_keyboard_wait_descriptor (desc);
6858 # endif
6860 # ifdef USABLE_SIGIO
6862 /* Return true if *MASK has a bit set
6863 that corresponds to one of the keyboard input descriptors. */
6865 static bool
6866 keyboard_bit_set (fd_set *mask)
6868 int fd;
6870 for (fd = 0; fd <= max_input_desc; fd++)
6871 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6872 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6873 return 1;
6875 return 0;
6877 # endif
6879 #else /* not subprocesses */
6881 /* Defined in msdos.c. */
6882 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6883 struct timespec *, void *);
6885 /* Implementation of wait_reading_process_output, assuming that there
6886 are no subprocesses. Used only by the MS-DOS build.
6888 Wait for timeout to elapse and/or keyboard input to be available.
6890 TIME_LIMIT is:
6891 timeout in seconds
6892 If negative, gobble data immediately available but don't wait for any.
6894 NSECS is:
6895 an additional duration to wait, measured in nanoseconds
6896 If TIME_LIMIT is zero, then:
6897 If NSECS == 0, there is no limit.
6898 If NSECS > 0, the timeout consists of NSECS only.
6899 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6901 READ_KBD is:
6902 0 to ignore keyboard input, or
6903 1 to return when input is available, or
6904 -1 means caller will actually read the input, so don't throw to
6905 the quit handler.
6907 see full version for other parameters. We know that wait_proc will
6908 always be NULL, since `subprocesses' isn't defined.
6910 DO_DISPLAY means redisplay should be done to show subprocess
6911 output that arrives.
6913 Return -1 signifying we got no output and did not try. */
6916 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6917 bool do_display,
6918 Lisp_Object wait_for_cell,
6919 struct Lisp_Process *wait_proc, int just_wait_proc)
6921 register int nfds;
6922 struct timespec end_time, timeout;
6923 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
6925 if (TYPE_MAXIMUM (time_t) < time_limit)
6926 time_limit = TYPE_MAXIMUM (time_t);
6928 if (time_limit < 0 || nsecs < 0)
6929 wait = MINIMUM;
6930 else if (time_limit > 0 || nsecs > 0)
6932 wait = TIMEOUT;
6933 end_time = timespec_add (current_timespec (),
6934 make_timespec (time_limit, nsecs));
6936 else
6937 wait = INFINITY;
6939 /* Turn off periodic alarms (in case they are in use)
6940 and then turn off any other atimers,
6941 because the select emulator uses alarms. */
6942 stop_polling ();
6943 turn_on_atimers (0);
6945 while (1)
6947 bool timeout_reduced_for_timers = false;
6948 fd_set waitchannels;
6949 int xerrno;
6951 /* If calling from keyboard input, do not quit
6952 since we want to return C-g as an input character.
6953 Otherwise, do pending quit if requested. */
6954 if (read_kbd >= 0)
6955 QUIT;
6957 /* Exit now if the cell we're waiting for became non-nil. */
6958 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6959 break;
6961 /* Compute time from now till when time limit is up. */
6962 /* Exit if already run out. */
6963 if (wait == TIMEOUT)
6965 struct timespec now = current_timespec ();
6966 if (timespec_cmp (end_time, now) <= 0)
6967 break;
6968 timeout = timespec_sub (end_time, now);
6970 else
6971 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
6973 /* If our caller will not immediately handle keyboard events,
6974 run timer events directly.
6975 (Callers that will immediately read keyboard events
6976 call timer_delay on their own.) */
6977 if (NILP (wait_for_cell))
6979 struct timespec timer_delay;
6983 unsigned old_timers_run = timers_run;
6984 timer_delay = timer_check ();
6985 if (timers_run != old_timers_run && do_display)
6986 /* We must retry, since a timer may have requeued itself
6987 and that could alter the time delay. */
6988 redisplay_preserve_echo_area (14);
6989 else
6990 break;
6992 while (!detect_input_pending ());
6994 /* If there is unread keyboard input, also return. */
6995 if (read_kbd != 0
6996 && requeued_events_pending_p ())
6997 break;
6999 if (timespec_valid_p (timer_delay))
7001 if (timespec_cmp (timer_delay, timeout) < 0)
7003 timeout = timer_delay;
7004 timeout_reduced_for_timers = true;
7009 /* Cause C-g and alarm signals to take immediate action,
7010 and cause input available signals to zero out timeout. */
7011 if (read_kbd < 0)
7012 set_waiting_for_input (&timeout);
7014 /* If a frame has been newly mapped and needs updating,
7015 reprocess its display stuff. */
7016 if (frame_garbaged && do_display)
7018 clear_waiting_for_input ();
7019 redisplay_preserve_echo_area (15);
7020 if (read_kbd < 0)
7021 set_waiting_for_input (&timeout);
7024 /* Wait till there is something to do. */
7025 FD_ZERO (&waitchannels);
7026 if (read_kbd && detect_input_pending ())
7027 nfds = 0;
7028 else
7030 if (read_kbd || !NILP (wait_for_cell))
7031 FD_SET (0, &waitchannels);
7032 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7035 xerrno = errno;
7037 /* Make C-g and alarm signals set flags again. */
7038 clear_waiting_for_input ();
7040 /* If we woke up due to SIGWINCH, actually change size now. */
7041 do_pending_window_change (0);
7043 if (wait < INFINITY && nfds == 0 && ! timeout_reduced_for_timers)
7044 /* We waited the full specified time, so return now. */
7045 break;
7047 if (nfds == -1)
7049 /* If the system call was interrupted, then go around the
7050 loop again. */
7051 if (xerrno == EINTR)
7052 FD_ZERO (&waitchannels);
7053 else
7054 report_file_errno ("Failed select", Qnil, xerrno);
7057 /* Check for keyboard input. */
7059 if (read_kbd
7060 && detect_input_pending_run_timers (do_display))
7062 swallow_events (do_display);
7063 if (detect_input_pending_run_timers (do_display))
7064 break;
7067 /* If there is unread keyboard input, also return. */
7068 if (read_kbd
7069 && requeued_events_pending_p ())
7070 break;
7072 /* If wait_for_cell. check for keyboard input
7073 but don't run any timers.
7074 ??? (It seems wrong to me to check for keyboard
7075 input at all when wait_for_cell, but the code
7076 has been this way since July 1994.
7077 Try changing this after version 19.31.) */
7078 if (! NILP (wait_for_cell)
7079 && detect_input_pending ())
7081 swallow_events (do_display);
7082 if (detect_input_pending ())
7083 break;
7086 /* Exit now if the cell we're waiting for became non-nil. */
7087 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7088 break;
7091 start_polling ();
7093 return -1;
7096 #endif /* not subprocesses */
7098 /* The following functions are needed even if async subprocesses are
7099 not supported. Some of them are no-op stubs in that case. */
7101 #ifdef HAVE_TIMERFD
7103 /* Add FD, which is a descriptor returned by timerfd_create,
7104 to the set of non-keyboard input descriptors. */
7106 void
7107 add_timer_wait_descriptor (int fd)
7109 FD_SET (fd, &input_wait_mask);
7110 FD_SET (fd, &non_keyboard_wait_mask);
7111 FD_SET (fd, &non_process_wait_mask);
7112 fd_callback_info[fd].func = timerfd_callback;
7113 fd_callback_info[fd].data = NULL;
7114 fd_callback_info[fd].condition |= FOR_READ;
7115 if (fd > max_input_desc)
7116 max_input_desc = fd;
7119 #endif /* HAVE_TIMERFD */
7121 /* Add DESC to the set of keyboard input descriptors. */
7123 void
7124 add_keyboard_wait_descriptor (int desc)
7126 #ifdef subprocesses /* Actually means "not MSDOS". */
7127 FD_SET (desc, &input_wait_mask);
7128 FD_SET (desc, &non_process_wait_mask);
7129 if (desc > max_input_desc)
7130 max_input_desc = desc;
7131 #endif
7134 /* From now on, do not expect DESC to give keyboard input. */
7136 void
7137 delete_keyboard_wait_descriptor (int desc)
7139 #ifdef subprocesses
7140 FD_CLR (desc, &input_wait_mask);
7141 FD_CLR (desc, &non_process_wait_mask);
7142 delete_input_desc (desc);
7143 #endif
7146 /* Setup coding systems of PROCESS. */
7148 void
7149 setup_process_coding_systems (Lisp_Object process)
7151 #ifdef subprocesses
7152 struct Lisp_Process *p = XPROCESS (process);
7153 int inch = p->infd;
7154 int outch = p->outfd;
7155 Lisp_Object coding_system;
7157 if (inch < 0 || outch < 0)
7158 return;
7160 if (!proc_decode_coding_system[inch])
7161 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7162 coding_system = p->decode_coding_system;
7163 if (EQ (p->filter, Qinternal_default_process_filter)
7164 && BUFFERP (p->buffer))
7166 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7167 coding_system = raw_text_coding_system (coding_system);
7169 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7171 if (!proc_encode_coding_system[outch])
7172 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7173 setup_coding_system (p->encode_coding_system,
7174 proc_encode_coding_system[outch]);
7175 #endif
7178 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7179 doc: /* Return the (or a) live process associated with BUFFER.
7180 BUFFER may be a buffer or the name of one.
7181 Return nil if all processes associated with BUFFER have been
7182 deleted or killed. */)
7183 (register Lisp_Object buffer)
7185 #ifdef subprocesses
7186 register Lisp_Object buf, tail, proc;
7188 if (NILP (buffer)) return Qnil;
7189 buf = Fget_buffer (buffer);
7190 if (NILP (buf)) return Qnil;
7192 FOR_EACH_PROCESS (tail, proc)
7193 if (EQ (XPROCESS (proc)->buffer, buf))
7194 return proc;
7195 #endif /* subprocesses */
7196 return Qnil;
7199 DEFUN ("process-inherit-coding-system-flag",
7200 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7201 1, 1, 0,
7202 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7203 If this flag is t, `buffer-file-coding-system' of the buffer
7204 associated with PROCESS will inherit the coding system used to decode
7205 the process output. */)
7206 (register Lisp_Object process)
7208 #ifdef subprocesses
7209 CHECK_PROCESS (process);
7210 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7211 #else
7212 /* Ignore the argument and return the value of
7213 inherit-process-coding-system. */
7214 return inherit_process_coding_system ? Qt : Qnil;
7215 #endif
7218 /* Kill all processes associated with `buffer'.
7219 If `buffer' is nil, kill all processes. */
7221 void
7222 kill_buffer_processes (Lisp_Object buffer)
7224 #ifdef subprocesses
7225 Lisp_Object tail, proc;
7227 FOR_EACH_PROCESS (tail, proc)
7228 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7230 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7231 Fdelete_process (proc);
7232 else if (XPROCESS (proc)->infd >= 0)
7233 process_send_signal (proc, SIGHUP, Qnil, 1);
7235 #else /* subprocesses */
7236 /* Since we have no subprocesses, this does nothing. */
7237 #endif /* subprocesses */
7240 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7241 Swaiting_for_user_input_p, 0, 0, 0,
7242 doc: /* Return non-nil if Emacs is waiting for input from the user.
7243 This is intended for use by asynchronous process output filters and sentinels. */)
7244 (void)
7246 #ifdef subprocesses
7247 return (waiting_for_user_input_p ? Qt : Qnil);
7248 #else
7249 return Qnil;
7250 #endif
7253 /* Stop reading input from keyboard sources. */
7255 void
7256 hold_keyboard_input (void)
7258 kbd_is_on_hold = 1;
7261 /* Resume reading input from keyboard sources. */
7263 void
7264 unhold_keyboard_input (void)
7266 kbd_is_on_hold = 0;
7269 /* Return true if keyboard input is on hold, zero otherwise. */
7271 bool
7272 kbd_on_hold_p (void)
7274 return kbd_is_on_hold;
7278 /* Enumeration of and access to system processes a-la ps(1). */
7280 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7281 0, 0, 0,
7282 doc: /* Return a list of numerical process IDs of all running processes.
7283 If this functionality is unsupported, return nil.
7285 See `process-attributes' for getting attributes of a process given its ID. */)
7286 (void)
7288 return list_system_processes ();
7291 DEFUN ("process-attributes", Fprocess_attributes,
7292 Sprocess_attributes, 1, 1, 0,
7293 doc: /* Return attributes of the process given by its PID, a number.
7295 Value is an alist where each element is a cons cell of the form
7297 (KEY . VALUE)
7299 If this functionality is unsupported, the value is nil.
7301 See `list-system-processes' for getting a list of all process IDs.
7303 The KEYs of the attributes that this function may return are listed
7304 below, together with the type of the associated VALUE (in parentheses).
7305 Not all platforms support all of these attributes; unsupported
7306 attributes will not appear in the returned alist.
7307 Unless explicitly indicated otherwise, numbers can have either
7308 integer or floating point values.
7310 euid -- Effective user User ID of the process (number)
7311 user -- User name corresponding to euid (string)
7312 egid -- Effective user Group ID of the process (number)
7313 group -- Group name corresponding to egid (string)
7314 comm -- Command name (executable name only) (string)
7315 state -- Process state code, such as "S", "R", or "T" (string)
7316 ppid -- Parent process ID (number)
7317 pgrp -- Process group ID (number)
7318 sess -- Session ID, i.e. process ID of session leader (number)
7319 ttname -- Controlling tty name (string)
7320 tpgid -- ID of foreground process group on the process's tty (number)
7321 minflt -- number of minor page faults (number)
7322 majflt -- number of major page faults (number)
7323 cminflt -- cumulative number of minor page faults (number)
7324 cmajflt -- cumulative number of major page faults (number)
7325 utime -- user time used by the process, in (current-time) format,
7326 which is a list of integers (HIGH LOW USEC PSEC)
7327 stime -- system time used by the process (current-time)
7328 time -- sum of utime and stime (current-time)
7329 cutime -- user time used by the process and its children (current-time)
7330 cstime -- system time used by the process and its children (current-time)
7331 ctime -- sum of cutime and cstime (current-time)
7332 pri -- priority of the process (number)
7333 nice -- nice value of the process (number)
7334 thcount -- process thread count (number)
7335 start -- time the process started (current-time)
7336 vsize -- virtual memory size of the process in KB's (number)
7337 rss -- resident set size of the process in KB's (number)
7338 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7339 pcpu -- percents of CPU time used by the process (floating-point number)
7340 pmem -- percents of total physical memory used by process's resident set
7341 (floating-point number)
7342 args -- command line which invoked the process (string). */)
7343 ( Lisp_Object pid)
7345 return system_process_attributes (pid);
7348 #ifdef subprocesses
7349 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7350 Invoke this after init_process_emacs, and after glib and/or GNUstep
7351 futz with the SIGCHLD handler, but before Emacs forks any children.
7352 This function's caller should block SIGCHLD. */
7354 void
7355 catch_child_signal (void)
7357 struct sigaction action, old_action;
7358 sigset_t oldset;
7359 emacs_sigaction_init (&action, deliver_child_signal);
7360 block_child_signal (&oldset);
7361 sigaction (SIGCHLD, &action, &old_action);
7362 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7363 || ! (old_action.sa_flags & SA_SIGINFO));
7365 if (old_action.sa_handler != deliver_child_signal)
7366 lib_child_handler
7367 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7368 ? dummy_handler
7369 : old_action.sa_handler);
7370 unblock_child_signal (&oldset);
7372 #endif /* subprocesses */
7375 /* This is not called "init_process" because that is the name of a
7376 Mach system call, so it would cause problems on Darwin systems. */
7377 void
7378 init_process_emacs (void)
7380 #ifdef subprocesses
7381 register int i;
7383 inhibit_sentinels = 0;
7385 #ifndef CANNOT_DUMP
7386 if (! noninteractive || initialized)
7387 #endif
7389 #if defined HAVE_GLIB && !defined WINDOWSNT
7390 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7391 this should always fail, but is enough to initialize glib's
7392 private SIGCHLD handler, allowing catch_child_signal to copy
7393 it into lib_child_handler. */
7394 g_source_unref (g_child_watch_source_new (getpid ()));
7395 #endif
7396 catch_child_signal ();
7399 FD_ZERO (&input_wait_mask);
7400 FD_ZERO (&non_keyboard_wait_mask);
7401 FD_ZERO (&non_process_wait_mask);
7402 FD_ZERO (&write_mask);
7403 max_process_desc = max_input_desc = -1;
7404 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7406 #ifdef NON_BLOCKING_CONNECT
7407 FD_ZERO (&connect_wait_mask);
7408 num_pending_connects = 0;
7409 #endif
7411 process_output_delay_count = 0;
7412 process_output_skip = 0;
7414 /* Don't do this, it caused infinite select loops. The display
7415 method should call add_keyboard_wait_descriptor on stdin if it
7416 needs that. */
7417 #if 0
7418 FD_SET (0, &input_wait_mask);
7419 #endif
7421 Vprocess_alist = Qnil;
7422 deleted_pid_list = Qnil;
7423 for (i = 0; i < FD_SETSIZE; i++)
7425 chan_process[i] = Qnil;
7426 proc_buffered_char[i] = -1;
7428 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7429 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7430 #ifdef DATAGRAM_SOCKETS
7431 memset (datagram_address, 0, sizeof datagram_address);
7432 #endif
7434 #if defined (DARWIN_OS)
7435 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7436 processes. As such, we only change the default value. */
7437 if (initialized)
7439 char const *release = (STRINGP (Voperating_system_release)
7440 ? SSDATA (Voperating_system_release)
7441 : 0);
7442 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7443 Vprocess_connection_type = Qnil;
7446 #endif
7447 #endif /* subprocesses */
7448 kbd_is_on_hold = 0;
7451 void
7452 syms_of_process (void)
7454 #ifdef subprocesses
7456 DEFSYM (Qprocessp, "processp");
7457 DEFSYM (Qrun, "run");
7458 DEFSYM (Qstop, "stop");
7459 DEFSYM (Qsignal, "signal");
7461 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7462 here again. */
7464 DEFSYM (Qopen, "open");
7465 DEFSYM (Qclosed, "closed");
7466 DEFSYM (Qconnect, "connect");
7467 DEFSYM (Qfailed, "failed");
7468 DEFSYM (Qlisten, "listen");
7469 DEFSYM (Qlocal, "local");
7470 DEFSYM (Qipv4, "ipv4");
7471 #ifdef AF_INET6
7472 DEFSYM (Qipv6, "ipv6");
7473 #endif
7474 DEFSYM (Qdatagram, "datagram");
7475 DEFSYM (Qseqpacket, "seqpacket");
7477 DEFSYM (QCport, ":port");
7478 DEFSYM (QCspeed, ":speed");
7479 DEFSYM (QCprocess, ":process");
7481 DEFSYM (QCbytesize, ":bytesize");
7482 DEFSYM (QCstopbits, ":stopbits");
7483 DEFSYM (QCparity, ":parity");
7484 DEFSYM (Qodd, "odd");
7485 DEFSYM (Qeven, "even");
7486 DEFSYM (QCflowcontrol, ":flowcontrol");
7487 DEFSYM (Qhw, "hw");
7488 DEFSYM (Qsw, "sw");
7489 DEFSYM (QCsummary, ":summary");
7491 DEFSYM (Qreal, "real");
7492 DEFSYM (Qnetwork, "network");
7493 DEFSYM (Qserial, "serial");
7494 DEFSYM (Qpipe, "pipe");
7495 DEFSYM (QCbuffer, ":buffer");
7496 DEFSYM (QChost, ":host");
7497 DEFSYM (QCservice, ":service");
7498 DEFSYM (QClocal, ":local");
7499 DEFSYM (QCremote, ":remote");
7500 DEFSYM (QCcoding, ":coding");
7501 DEFSYM (QCserver, ":server");
7502 DEFSYM (QCnowait, ":nowait");
7503 DEFSYM (QCsentinel, ":sentinel");
7504 DEFSYM (QClog, ":log");
7505 DEFSYM (QCnoquery, ":noquery");
7506 DEFSYM (QCstop, ":stop");
7507 DEFSYM (QCplist, ":plist");
7508 DEFSYM (QCcommand, ":command");
7509 DEFSYM (QCconnection_type, ":connection-type");
7510 DEFSYM (QCstderr, ":stderr");
7511 DEFSYM (Qpty, "pty");
7512 DEFSYM (Qpipe, "pipe");
7514 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7516 staticpro (&Vprocess_alist);
7517 staticpro (&deleted_pid_list);
7519 #endif /* subprocesses */
7521 DEFSYM (QCname, ":name");
7522 DEFSYM (QCtype, ":type");
7524 DEFSYM (Qeuid, "euid");
7525 DEFSYM (Qegid, "egid");
7526 DEFSYM (Quser, "user");
7527 DEFSYM (Qgroup, "group");
7528 DEFSYM (Qcomm, "comm");
7529 DEFSYM (Qstate, "state");
7530 DEFSYM (Qppid, "ppid");
7531 DEFSYM (Qpgrp, "pgrp");
7532 DEFSYM (Qsess, "sess");
7533 DEFSYM (Qttname, "ttname");
7534 DEFSYM (Qtpgid, "tpgid");
7535 DEFSYM (Qminflt, "minflt");
7536 DEFSYM (Qmajflt, "majflt");
7537 DEFSYM (Qcminflt, "cminflt");
7538 DEFSYM (Qcmajflt, "cmajflt");
7539 DEFSYM (Qutime, "utime");
7540 DEFSYM (Qstime, "stime");
7541 DEFSYM (Qtime, "time");
7542 DEFSYM (Qcutime, "cutime");
7543 DEFSYM (Qcstime, "cstime");
7544 DEFSYM (Qctime, "ctime");
7545 #ifdef subprocesses
7546 DEFSYM (Qinternal_default_process_sentinel,
7547 "internal-default-process-sentinel");
7548 DEFSYM (Qinternal_default_process_filter,
7549 "internal-default-process-filter");
7550 #endif
7551 DEFSYM (Qpri, "pri");
7552 DEFSYM (Qnice, "nice");
7553 DEFSYM (Qthcount, "thcount");
7554 DEFSYM (Qstart, "start");
7555 DEFSYM (Qvsize, "vsize");
7556 DEFSYM (Qrss, "rss");
7557 DEFSYM (Qetime, "etime");
7558 DEFSYM (Qpcpu, "pcpu");
7559 DEFSYM (Qpmem, "pmem");
7560 DEFSYM (Qargs, "args");
7562 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7563 doc: /* Non-nil means delete processes immediately when they exit.
7564 A value of nil means don't delete them until `list-processes' is run. */);
7566 delete_exited_processes = 1;
7568 #ifdef subprocesses
7569 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7570 doc: /* Control type of device used to communicate with subprocesses.
7571 Values are nil to use a pipe, or t or `pty' to use a pty.
7572 The value has no effect if the system has no ptys or if all ptys are busy:
7573 then a pipe is used in any case.
7574 The value takes effect when `start-process' is called. */);
7575 Vprocess_connection_type = Qt;
7577 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7578 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7579 On some systems, when Emacs reads the output from a subprocess, the output data
7580 is read in very small blocks, potentially resulting in very poor performance.
7581 This behavior can be remedied to some extent by setting this variable to a
7582 non-nil value, as it will automatically delay reading from such processes, to
7583 allow them to produce more output before Emacs tries to read it.
7584 If the value is t, the delay is reset after each write to the process; any other
7585 non-nil value means that the delay is not reset on write.
7586 The variable takes effect when `start-process' is called. */);
7587 Vprocess_adaptive_read_buffering = Qt;
7589 defsubr (&Sprocessp);
7590 defsubr (&Sget_process);
7591 defsubr (&Sdelete_process);
7592 defsubr (&Sprocess_status);
7593 defsubr (&Sprocess_exit_status);
7594 defsubr (&Sprocess_id);
7595 defsubr (&Sprocess_name);
7596 defsubr (&Sprocess_tty_name);
7597 defsubr (&Sprocess_command);
7598 defsubr (&Sset_process_buffer);
7599 defsubr (&Sprocess_buffer);
7600 defsubr (&Sprocess_mark);
7601 defsubr (&Sset_process_filter);
7602 defsubr (&Sprocess_filter);
7603 defsubr (&Sset_process_sentinel);
7604 defsubr (&Sprocess_sentinel);
7605 defsubr (&Sset_process_window_size);
7606 defsubr (&Sset_process_inherit_coding_system_flag);
7607 defsubr (&Sset_process_query_on_exit_flag);
7608 defsubr (&Sprocess_query_on_exit_flag);
7609 defsubr (&Sprocess_contact);
7610 defsubr (&Sprocess_plist);
7611 defsubr (&Sset_process_plist);
7612 defsubr (&Sprocess_list);
7613 defsubr (&Smake_process);
7614 defsubr (&Smake_pipe_process);
7615 defsubr (&Sserial_process_configure);
7616 defsubr (&Smake_serial_process);
7617 defsubr (&Sset_network_process_option);
7618 defsubr (&Smake_network_process);
7619 defsubr (&Sformat_network_address);
7620 defsubr (&Snetwork_interface_list);
7621 defsubr (&Snetwork_interface_info);
7622 #ifdef DATAGRAM_SOCKETS
7623 defsubr (&Sprocess_datagram_address);
7624 defsubr (&Sset_process_datagram_address);
7625 #endif
7626 defsubr (&Saccept_process_output);
7627 defsubr (&Sprocess_send_region);
7628 defsubr (&Sprocess_send_string);
7629 defsubr (&Sinterrupt_process);
7630 defsubr (&Skill_process);
7631 defsubr (&Squit_process);
7632 defsubr (&Sstop_process);
7633 defsubr (&Scontinue_process);
7634 defsubr (&Sprocess_running_child_p);
7635 defsubr (&Sprocess_send_eof);
7636 defsubr (&Ssignal_process);
7637 defsubr (&Swaiting_for_user_input_p);
7638 defsubr (&Sprocess_type);
7639 defsubr (&Sinternal_default_process_sentinel);
7640 defsubr (&Sinternal_default_process_filter);
7641 defsubr (&Sset_process_coding_system);
7642 defsubr (&Sprocess_coding_system);
7643 defsubr (&Sset_process_filter_multibyte);
7644 defsubr (&Sprocess_filter_multibyte_p);
7646 #endif /* subprocesses */
7648 defsubr (&Sget_buffer_process);
7649 defsubr (&Sprocess_inherit_coding_system_flag);
7650 defsubr (&Slist_system_processes);
7651 defsubr (&Sprocess_attributes);
7654 Lisp_Object subfeatures = Qnil;
7655 const struct socket_options *sopt;
7657 #define ADD_SUBFEATURE(key, val) \
7658 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7660 #ifdef NON_BLOCKING_CONNECT
7661 ADD_SUBFEATURE (QCnowait, Qt);
7662 #endif
7663 #ifdef DATAGRAM_SOCKETS
7664 ADD_SUBFEATURE (QCtype, Qdatagram);
7665 #endif
7666 #ifdef HAVE_SEQPACKET
7667 ADD_SUBFEATURE (QCtype, Qseqpacket);
7668 #endif
7669 #ifdef HAVE_LOCAL_SOCKETS
7670 ADD_SUBFEATURE (QCfamily, Qlocal);
7671 #endif
7672 ADD_SUBFEATURE (QCfamily, Qipv4);
7673 #ifdef AF_INET6
7674 ADD_SUBFEATURE (QCfamily, Qipv6);
7675 #endif
7676 #ifdef HAVE_GETSOCKNAME
7677 ADD_SUBFEATURE (QCservice, Qt);
7678 #endif
7679 ADD_SUBFEATURE (QCserver, Qt);
7681 for (sopt = socket_options; sopt->name; sopt++)
7682 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7684 Fprovide (intern_c_string ("make-network-process"), subfeatures);