Improve doc string of 'completion-at-point-functions'
[emacs.git] / src / process.c
blobe6ea2fbe8f7228b5dbc4a23ea433715b8ff97c72
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 (at
11 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 /* True if ERRNUM represents an error where the system call would
155 block if a blocking variant were used. */
156 static bool
157 would_block (int errnum)
159 #ifdef EWOULDBLOCK
160 if (EWOULDBLOCK != EAGAIN && errnum == EWOULDBLOCK)
161 return true;
162 #endif
163 return errnum == EAGAIN;
166 #ifndef HAVE_ACCEPT4
168 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
170 static int
171 close_on_exec (int fd)
173 if (0 <= fd)
174 fcntl (fd, F_SETFD, FD_CLOEXEC);
175 return fd;
178 # undef accept4
179 # define accept4(sockfd, addr, addrlen, flags) \
180 process_accept4 (sockfd, addr, addrlen, flags)
181 static int
182 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
184 return close_on_exec (accept (sockfd, addr, addrlen));
187 static int
188 process_socket (int domain, int type, int protocol)
190 return close_on_exec (socket (domain, type, protocol));
192 # undef socket
193 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
194 #endif
196 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
197 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
198 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
199 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
200 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
201 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
203 /* Number of events of change of status of a process. */
204 static EMACS_INT process_tick;
205 /* Number of events for which the user or sentinel has been notified. */
206 static EMACS_INT update_tick;
208 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects.
209 The code can be simplified by assuming NON_BLOCKING_CONNECT once
210 Emacs starts assuming POSIX 1003.1-2001 or later. */
212 #if (defined HAVE_SELECT \
213 && (defined GNU_LINUX || defined HAVE_GETPEERNAME) \
214 && (defined EWOULDBLOCK || defined EINPROGRESS))
215 # define NON_BLOCKING_CONNECT
216 #endif
218 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
219 this system. We need to read full packets, so we need a
220 "non-destructive" select. So we require either native select,
221 or emulation of select using FIONREAD. */
223 #ifndef BROKEN_DATAGRAM_SOCKETS
224 # if defined HAVE_SELECT || defined USABLE_FIONREAD
225 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
226 # define DATAGRAM_SOCKETS
227 # endif
228 # endif
229 #endif
231 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
232 # define HAVE_SEQPACKET
233 #endif
235 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
236 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
237 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
239 /* Number of processes which have a non-zero read_output_delay,
240 and therefore might be delayed for adaptive read buffering. */
242 static int process_output_delay_count;
244 /* True if any process has non-nil read_output_skip. */
246 static bool process_output_skip;
248 static void create_process (Lisp_Object, char **, Lisp_Object);
249 #ifdef USABLE_SIGIO
250 static bool keyboard_bit_set (fd_set *);
251 #endif
252 static void deactivate_process (Lisp_Object);
253 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
254 static int read_process_output (Lisp_Object, int);
255 static void handle_child_signal (int);
256 static void create_pty (Lisp_Object);
258 static Lisp_Object get_process (register Lisp_Object name);
259 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
261 /* Mask of bits indicating the descriptors that we wait for input on. */
263 static fd_set input_wait_mask;
265 /* Mask that excludes keyboard input descriptor(s). */
267 static fd_set non_keyboard_wait_mask;
269 /* Mask that excludes process input descriptor(s). */
271 static fd_set non_process_wait_mask;
273 /* Mask for selecting for write. */
275 static fd_set write_mask;
277 #ifdef NON_BLOCKING_CONNECT
278 /* Mask of bits indicating the descriptors that we wait for connect to
279 complete on. Once they complete, they are removed from this mask
280 and added to the input_wait_mask and non_keyboard_wait_mask. */
282 static fd_set connect_wait_mask;
284 /* Number of bits set in connect_wait_mask. */
285 static int num_pending_connects;
286 #endif /* NON_BLOCKING_CONNECT */
288 /* The largest descriptor currently in use for a process object; -1 if none. */
289 static int max_process_desc;
291 /* The largest descriptor currently in use for input; -1 if none. */
292 static int max_input_desc;
294 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
295 static Lisp_Object chan_process[FD_SETSIZE];
297 /* Alist of elements (NAME . PROCESS). */
298 static Lisp_Object Vprocess_alist;
300 /* Buffered-ahead input char from process, indexed by channel.
301 -1 means empty (no char is buffered).
302 Used on sys V where the only way to tell if there is any
303 output from the process is to read at least one char.
304 Always -1 on systems that support FIONREAD. */
306 static int proc_buffered_char[FD_SETSIZE];
308 /* Table of `struct coding-system' for each process. */
309 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
310 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
312 #ifdef DATAGRAM_SOCKETS
313 /* Table of `partner address' for datagram sockets. */
314 static struct sockaddr_and_len {
315 struct sockaddr *sa;
316 int len;
317 } datagram_address[FD_SETSIZE];
318 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
319 #define DATAGRAM_CONN_P(proc) \
320 (PROCESSP (proc) && \
321 XPROCESS (proc)->infd >= 0 && \
322 datagram_address[XPROCESS (proc)->infd].sa != 0)
323 #else
324 #define DATAGRAM_CHAN_P(chan) (0)
325 #define DATAGRAM_CONN_P(proc) (0)
326 #endif
328 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
329 a `for' loop which iterates over processes from Vprocess_alist. */
331 #define FOR_EACH_PROCESS(list_var, proc_var) \
332 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
334 /* These setters are used only in this file, so they can be private. */
335 static void
336 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
338 p->buffer = val;
340 static void
341 pset_command (struct Lisp_Process *p, Lisp_Object val)
343 p->command = val;
345 static void
346 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
348 p->decode_coding_system = val;
350 static void
351 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
353 p->decoding_buf = val;
355 static void
356 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
358 p->encode_coding_system = val;
360 static void
361 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
363 p->encoding_buf = val;
365 static void
366 pset_filter (struct Lisp_Process *p, Lisp_Object val)
368 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
370 static void
371 pset_log (struct Lisp_Process *p, Lisp_Object val)
373 p->log = val;
375 static void
376 pset_mark (struct Lisp_Process *p, Lisp_Object val)
378 p->mark = val;
380 static void
381 pset_name (struct Lisp_Process *p, Lisp_Object val)
383 p->name = val;
385 static void
386 pset_plist (struct Lisp_Process *p, Lisp_Object val)
388 p->plist = val;
390 static void
391 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
393 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
395 static void
396 pset_status (struct Lisp_Process *p, Lisp_Object val)
398 p->status = val;
400 static void
401 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
403 p->tty_name = val;
405 static void
406 pset_type (struct Lisp_Process *p, Lisp_Object val)
408 p->type = val;
410 static void
411 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
413 p->write_queue = val;
415 static void
416 pset_stderrproc (struct Lisp_Process *p, Lisp_Object val)
418 p->stderrproc = val;
422 static Lisp_Object
423 make_lisp_proc (struct Lisp_Process *p)
425 return make_lisp_ptr (p, Lisp_Vectorlike);
428 static struct fd_callback_data
430 fd_callback func;
431 void *data;
432 #define FOR_READ 1
433 #define FOR_WRITE 2
434 int condition; /* Mask of the defines above. */
435 } fd_callback_info[FD_SETSIZE];
438 /* Add a file descriptor FD to be monitored for when read is possible.
439 When read is possible, call FUNC with argument DATA. */
441 void
442 add_read_fd (int fd, fd_callback func, void *data)
444 add_keyboard_wait_descriptor (fd);
446 fd_callback_info[fd].func = func;
447 fd_callback_info[fd].data = data;
448 fd_callback_info[fd].condition |= FOR_READ;
451 /* Stop monitoring file descriptor FD for when read is possible. */
453 void
454 delete_read_fd (int fd)
456 delete_keyboard_wait_descriptor (fd);
458 fd_callback_info[fd].condition &= ~FOR_READ;
459 if (fd_callback_info[fd].condition == 0)
461 fd_callback_info[fd].func = 0;
462 fd_callback_info[fd].data = 0;
466 /* Add a file descriptor FD to be monitored for when write is possible.
467 When write is possible, call FUNC with argument DATA. */
469 void
470 add_write_fd (int fd, fd_callback func, void *data)
472 FD_SET (fd, &write_mask);
473 if (fd > max_input_desc)
474 max_input_desc = fd;
476 fd_callback_info[fd].func = func;
477 fd_callback_info[fd].data = data;
478 fd_callback_info[fd].condition |= FOR_WRITE;
481 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
483 static void
484 delete_input_desc (int fd)
486 if (fd == max_input_desc)
489 fd--;
490 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
491 || FD_ISSET (fd, &write_mask)));
493 max_input_desc = fd;
497 /* Stop monitoring file descriptor FD for when write is possible. */
499 void
500 delete_write_fd (int fd)
502 FD_CLR (fd, &write_mask);
503 fd_callback_info[fd].condition &= ~FOR_WRITE;
504 if (fd_callback_info[fd].condition == 0)
506 fd_callback_info[fd].func = 0;
507 fd_callback_info[fd].data = 0;
508 delete_input_desc (fd);
513 /* Compute the Lisp form of the process status, p->status, from
514 the numeric status that was returned by `wait'. */
516 static Lisp_Object status_convert (int);
518 static void
519 update_status (struct Lisp_Process *p)
521 eassert (p->raw_status_new);
522 pset_status (p, status_convert (p->raw_status));
523 p->raw_status_new = 0;
526 /* Convert a process status word in Unix format to
527 the list that we use internally. */
529 static Lisp_Object
530 status_convert (int w)
532 if (WIFSTOPPED (w))
533 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
534 else if (WIFEXITED (w))
535 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
536 WCOREDUMP (w) ? Qt : Qnil));
537 else if (WIFSIGNALED (w))
538 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
539 WCOREDUMP (w) ? Qt : Qnil));
540 else
541 return Qrun;
544 /* Given a status-list, extract the three pieces of information
545 and store them individually through the three pointers. */
547 static void
548 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
550 Lisp_Object tem;
552 if (SYMBOLP (l))
554 *symbol = l;
555 *code = 0;
556 *coredump = 0;
558 else
560 *symbol = XCAR (l);
561 tem = XCDR (l);
562 *code = XFASTINT (XCAR (tem));
563 tem = XCDR (tem);
564 *coredump = !NILP (tem);
568 /* Return a string describing a process status list. */
570 static Lisp_Object
571 status_message (struct Lisp_Process *p)
573 Lisp_Object status = p->status;
574 Lisp_Object symbol;
575 int code;
576 bool coredump;
577 Lisp_Object string;
579 decode_status (status, &symbol, &code, &coredump);
581 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
583 char const *signame;
584 synchronize_system_messages_locale ();
585 signame = strsignal (code);
586 if (signame == 0)
587 string = build_string ("unknown");
588 else
590 int c1, c2;
592 string = build_unibyte_string (signame);
593 if (! NILP (Vlocale_coding_system))
594 string = (code_convert_string_norecord
595 (string, Vlocale_coding_system, 0));
596 c1 = STRING_CHAR (SDATA (string));
597 c2 = downcase (c1);
598 if (c1 != c2)
599 Faset (string, make_number (0), make_number (c2));
601 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
602 return concat2 (string, suffix);
604 else if (EQ (symbol, Qexit))
606 if (NETCONN1_P (p))
607 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
608 if (code == 0)
609 return build_string ("finished\n");
610 AUTO_STRING (prefix, "exited abnormally with code ");
611 string = Fnumber_to_string (make_number (code));
612 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
613 return concat3 (prefix, string, suffix);
615 else if (EQ (symbol, Qfailed))
617 AUTO_STRING (prefix, "failed with code ");
618 string = Fnumber_to_string (make_number (code));
619 AUTO_STRING (suffix, "\n");
620 return concat3 (prefix, string, suffix);
622 else
623 return Fcopy_sequence (Fsymbol_name (symbol));
626 enum { PTY_NAME_SIZE = 24 };
628 /* Open an available pty, returning a file descriptor.
629 Store into PTY_NAME the file name of the terminal corresponding to the pty.
630 Return -1 on failure. */
632 static int
633 allocate_pty (char pty_name[PTY_NAME_SIZE])
635 #ifdef HAVE_PTYS
636 int fd;
638 #ifdef PTY_ITERATION
639 PTY_ITERATION
640 #else
641 register int c, i;
642 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
643 for (i = 0; i < 16; i++)
644 #endif
646 #ifdef PTY_NAME_SPRINTF
647 PTY_NAME_SPRINTF
648 #else
649 sprintf (pty_name, "/dev/pty%c%x", c, i);
650 #endif /* no PTY_NAME_SPRINTF */
652 #ifdef PTY_OPEN
653 PTY_OPEN;
654 #else /* no PTY_OPEN */
655 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
656 #endif /* no PTY_OPEN */
658 if (fd >= 0)
660 #ifdef PTY_TTY_NAME_SPRINTF
661 PTY_TTY_NAME_SPRINTF
662 #else
663 sprintf (pty_name, "/dev/tty%c%x", c, i);
664 #endif /* no PTY_TTY_NAME_SPRINTF */
666 /* Set FD's close-on-exec flag. This is needed even if
667 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
668 doesn't require support for that combination.
669 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
670 doesn't work if the close-on-exec flag is set (Bug#20555).
671 Multithreaded platforms where posix_openpt ignores
672 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
673 have a race condition between the PTY_OPEN and here. */
674 fcntl (fd, F_SETFD, FD_CLOEXEC);
676 /* Check to make certain that both sides are available.
677 This avoids a nasty yet stupid bug in rlogins. */
678 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
680 emacs_close (fd);
681 # ifndef __sgi
682 continue;
683 # else
684 return -1;
685 # endif /* __sgi */
687 setup_pty (fd);
688 return fd;
691 #endif /* HAVE_PTYS */
692 return -1;
695 /* Allocate basically initialized process. */
697 static struct Lisp_Process *
698 allocate_process (void)
700 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
703 static Lisp_Object
704 make_process (Lisp_Object name)
706 register Lisp_Object val, tem, name1;
707 register struct Lisp_Process *p;
708 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
709 printmax_t i;
711 p = allocate_process ();
712 /* Initialize Lisp data. Note that allocate_process initializes all
713 Lisp data to nil, so do it only for slots which should not be nil. */
714 pset_status (p, Qrun);
715 pset_mark (p, Fmake_marker ());
717 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
718 non-Lisp data, so do it only for slots which should not be zero. */
719 p->infd = -1;
720 p->outfd = -1;
721 for (i = 0; i < PROCESS_OPEN_FDS; i++)
722 p->open_fd[i] = -1;
724 #ifdef HAVE_GNUTLS
725 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
726 #endif
728 /* If name is already in use, modify it until it is unused. */
730 name1 = name;
731 for (i = 1; ; i++)
733 tem = Fget_process (name1);
734 if (NILP (tem)) break;
735 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
737 name = name1;
738 pset_name (p, name);
739 pset_sentinel (p, Qinternal_default_process_sentinel);
740 pset_filter (p, Qinternal_default_process_filter);
741 XSETPROCESS (val, p);
742 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
743 return val;
746 static void
747 remove_process (register Lisp_Object proc)
749 register Lisp_Object pair;
751 pair = Frassq (proc, Vprocess_alist);
752 Vprocess_alist = Fdelq (pair, Vprocess_alist);
754 deactivate_process (proc);
758 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
759 doc: /* Return t if OBJECT is a process. */)
760 (Lisp_Object object)
762 return PROCESSP (object) ? Qt : Qnil;
765 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
766 doc: /* Return the process named NAME, or nil if there is none. */)
767 (register Lisp_Object name)
769 if (PROCESSP (name))
770 return name;
771 CHECK_STRING (name);
772 return Fcdr (Fassoc (name, Vprocess_alist));
775 /* This is how commands for the user decode process arguments. It
776 accepts a process, a process name, a buffer, a buffer name, or nil.
777 Buffers denote the first process in the buffer, and nil denotes the
778 current buffer. */
780 static Lisp_Object
781 get_process (register Lisp_Object name)
783 register Lisp_Object proc, obj;
784 if (STRINGP (name))
786 obj = Fget_process (name);
787 if (NILP (obj))
788 obj = Fget_buffer (name);
789 if (NILP (obj))
790 error ("Process %s does not exist", SDATA (name));
792 else if (NILP (name))
793 obj = Fcurrent_buffer ();
794 else
795 obj = name;
797 /* Now obj should be either a buffer object or a process object. */
798 if (BUFFERP (obj))
800 if (NILP (BVAR (XBUFFER (obj), name)))
801 error ("Attempt to get process for a dead buffer");
802 proc = Fget_buffer_process (obj);
803 if (NILP (proc))
804 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
806 else
808 CHECK_PROCESS (obj);
809 proc = obj;
811 return proc;
815 /* Fdelete_process promises to immediately forget about the process, but in
816 reality, Emacs needs to remember those processes until they have been
817 treated by the SIGCHLD handler and waitpid has been invoked on them;
818 otherwise they might fill up the kernel's process table.
820 Some processes created by call-process are also put onto this list.
822 Members of this list are (process-ID . filename) pairs. The
823 process-ID is a number; the filename, if a string, is a file that
824 needs to be removed after the process exits. */
825 static Lisp_Object deleted_pid_list;
827 void
828 record_deleted_pid (pid_t pid, Lisp_Object filename)
830 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
831 /* GC treated elements set to nil. */
832 Fdelq (Qnil, deleted_pid_list));
836 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
837 doc: /* Delete PROCESS: kill it and forget about it immediately.
838 PROCESS may be a process, a buffer, the name of a process or buffer, or
839 nil, indicating the current buffer's process. */)
840 (register Lisp_Object process)
842 register struct Lisp_Process *p;
844 process = get_process (process);
845 p = XPROCESS (process);
847 p->raw_status_new = 0;
848 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
850 pset_status (p, list2 (Qexit, make_number (0)));
851 p->tick = ++process_tick;
852 status_notify (p, NULL);
853 redisplay_preserve_echo_area (13);
855 else
857 if (p->alive)
858 record_kill_process (p, Qnil);
860 if (p->infd >= 0)
862 /* Update P's status, since record_kill_process will make the
863 SIGCHLD handler update deleted_pid_list, not *P. */
864 Lisp_Object symbol;
865 if (p->raw_status_new)
866 update_status (p);
867 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
868 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
869 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
871 p->tick = ++process_tick;
872 status_notify (p, NULL);
873 redisplay_preserve_echo_area (13);
876 remove_process (process);
877 return Qnil;
880 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
881 doc: /* Return the status of PROCESS.
882 The returned value is one of the following symbols:
883 run -- for a process that is running.
884 stop -- for a process stopped but continuable.
885 exit -- for a process that has exited.
886 signal -- for a process that has got a fatal signal.
887 open -- for a network stream connection that is open.
888 listen -- for a network stream server that is listening.
889 closed -- for a network stream connection that is closed.
890 connect -- when waiting for a non-blocking connection to complete.
891 failed -- when a non-blocking connection has failed.
892 nil -- if arg is a process name and no such process exists.
893 PROCESS may be a process, a buffer, the name of a process, or
894 nil, indicating the current buffer's process. */)
895 (register Lisp_Object process)
897 register struct Lisp_Process *p;
898 register Lisp_Object status;
900 if (STRINGP (process))
901 process = Fget_process (process);
902 else
903 process = get_process (process);
905 if (NILP (process))
906 return process;
908 p = XPROCESS (process);
909 if (p->raw_status_new)
910 update_status (p);
911 status = p->status;
912 if (CONSP (status))
913 status = XCAR (status);
914 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
916 if (EQ (status, Qexit))
917 status = Qclosed;
918 else if (EQ (p->command, Qt))
919 status = Qstop;
920 else if (EQ (status, Qrun))
921 status = Qopen;
923 return status;
926 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
927 1, 1, 0,
928 doc: /* Return the exit status of PROCESS or the signal number that killed it.
929 If PROCESS has not yet exited or died, return 0. */)
930 (register Lisp_Object process)
932 CHECK_PROCESS (process);
933 if (XPROCESS (process)->raw_status_new)
934 update_status (XPROCESS (process));
935 if (CONSP (XPROCESS (process)->status))
936 return XCAR (XCDR (XPROCESS (process)->status));
937 return make_number (0);
940 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
941 doc: /* Return the process id of PROCESS.
942 This is the pid of the external process which PROCESS uses or talks to.
943 For a network, serial, and pipe connections, this value is nil. */)
944 (register Lisp_Object process)
946 pid_t pid;
948 CHECK_PROCESS (process);
949 pid = XPROCESS (process)->pid;
950 return (pid ? make_fixnum_or_float (pid) : Qnil);
953 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
954 doc: /* Return the name of PROCESS, as a string.
955 This is the name of the program invoked in PROCESS,
956 possibly modified to make it unique among process names. */)
957 (register Lisp_Object process)
959 CHECK_PROCESS (process);
960 return XPROCESS (process)->name;
963 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
964 doc: /* Return the command that was executed to start PROCESS.
965 This is a list of strings, the first string being the program executed
966 and the rest of the strings being the arguments given to it.
967 For a network or serial or pipe connection, this is nil (process is running)
968 or t (process is stopped). */)
969 (register Lisp_Object process)
971 CHECK_PROCESS (process);
972 return XPROCESS (process)->command;
975 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
976 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
977 This is the terminal that the process itself reads and writes on,
978 not the name of the pty that Emacs uses to talk with that terminal. */)
979 (register Lisp_Object process)
981 CHECK_PROCESS (process);
982 return XPROCESS (process)->tty_name;
985 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
986 2, 2, 0,
987 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
988 Return BUFFER. */)
989 (register Lisp_Object process, Lisp_Object buffer)
991 struct Lisp_Process *p;
993 CHECK_PROCESS (process);
994 if (!NILP (buffer))
995 CHECK_BUFFER (buffer);
996 p = XPROCESS (process);
997 pset_buffer (p, buffer);
998 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
999 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1000 setup_process_coding_systems (process);
1001 return buffer;
1004 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1005 1, 1, 0,
1006 doc: /* Return the buffer PROCESS is associated with.
1007 The default process filter inserts output from PROCESS into this buffer. */)
1008 (register Lisp_Object process)
1010 CHECK_PROCESS (process);
1011 return XPROCESS (process)->buffer;
1014 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1015 1, 1, 0,
1016 doc: /* Return the marker for the end of the last output from PROCESS. */)
1017 (register Lisp_Object process)
1019 CHECK_PROCESS (process);
1020 return XPROCESS (process)->mark;
1023 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1024 2, 2, 0,
1025 doc: /* Give PROCESS the filter function FILTER; nil means default.
1026 A value of t means stop accepting output from the process.
1028 When a process has a non-default filter, its buffer is not used for output.
1029 Instead, each time it does output, the entire string of output is
1030 passed to the filter.
1032 The filter gets two arguments: the process and the string of output.
1033 The string argument is normally a multibyte string, except:
1034 - if the process's input coding system is no-conversion or raw-text,
1035 it is a unibyte string (the non-converted input), or else
1036 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1037 string (the result of converting the decoded input multibyte
1038 string to unibyte with `string-make-unibyte'). */)
1039 (register Lisp_Object process, Lisp_Object filter)
1041 struct Lisp_Process *p;
1043 CHECK_PROCESS (process);
1044 p = XPROCESS (process);
1046 /* Don't signal an error if the process's input file descriptor
1047 is closed. This could make debugging Lisp more difficult,
1048 for example when doing something like
1050 (setq process (start-process ...))
1051 (debug)
1052 (set-process-filter process ...) */
1054 if (NILP (filter))
1055 filter = Qinternal_default_process_filter;
1057 if (p->infd >= 0)
1059 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1061 FD_CLR (p->infd, &input_wait_mask);
1062 FD_CLR (p->infd, &non_keyboard_wait_mask);
1064 else if (EQ (p->filter, Qt)
1065 /* Network or serial process not stopped: */
1066 && !EQ (p->command, Qt))
1068 FD_SET (p->infd, &input_wait_mask);
1069 FD_SET (p->infd, &non_keyboard_wait_mask);
1073 pset_filter (p, filter);
1074 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1075 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1076 setup_process_coding_systems (process);
1077 return filter;
1080 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1081 1, 1, 0,
1082 doc: /* Return the filter function of PROCESS.
1083 See `set-process-filter' for more info on filter functions. */)
1084 (register Lisp_Object process)
1086 CHECK_PROCESS (process);
1087 return XPROCESS (process)->filter;
1090 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1091 2, 2, 0,
1092 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1093 The sentinel is called as a function when the process changes state.
1094 It gets two arguments: the process, and a string describing the change. */)
1095 (register Lisp_Object process, Lisp_Object sentinel)
1097 struct Lisp_Process *p;
1099 CHECK_PROCESS (process);
1100 p = XPROCESS (process);
1102 if (NILP (sentinel))
1103 sentinel = Qinternal_default_process_sentinel;
1105 pset_sentinel (p, sentinel);
1106 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1107 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1108 return sentinel;
1111 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1112 1, 1, 0,
1113 doc: /* Return the sentinel of PROCESS.
1114 See `set-process-sentinel' for more info on sentinels. */)
1115 (register Lisp_Object process)
1117 CHECK_PROCESS (process);
1118 return XPROCESS (process)->sentinel;
1121 DEFUN ("set-process-window-size", Fset_process_window_size,
1122 Sset_process_window_size, 3, 3, 0,
1123 doc: /* Tell PROCESS that it has logical window size WIDTH by HEIGHT.
1124 Value is t if PROCESS was successfully told about the window size,
1125 nil otherwise. */)
1126 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1128 CHECK_PROCESS (process);
1130 /* All known platforms store window sizes as 'unsigned short'. */
1131 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1132 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1134 if (XPROCESS (process)->infd < 0
1135 || (set_window_size (XPROCESS (process)->infd,
1136 XINT (height), XINT (width))
1137 < 0))
1138 return Qnil;
1139 else
1140 return Qt;
1143 DEFUN ("set-process-inherit-coding-system-flag",
1144 Fset_process_inherit_coding_system_flag,
1145 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1146 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1147 If the second argument FLAG is non-nil, then the variable
1148 `buffer-file-coding-system' of the buffer associated with PROCESS
1149 will be bound to the value of the coding system used to decode
1150 the process output.
1152 This is useful when the coding system specified for the process buffer
1153 leaves either the character code conversion or the end-of-line conversion
1154 unspecified, or if the coding system used to decode the process output
1155 is more appropriate for saving the process buffer.
1157 Binding the variable `inherit-process-coding-system' to non-nil before
1158 starting the process is an alternative way of setting the inherit flag
1159 for the process which will run.
1161 This function returns FLAG. */)
1162 (register Lisp_Object process, Lisp_Object flag)
1164 CHECK_PROCESS (process);
1165 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1166 return flag;
1169 DEFUN ("set-process-query-on-exit-flag",
1170 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1171 2, 2, 0,
1172 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1173 If the second argument FLAG is non-nil, Emacs will query the user before
1174 exiting or killing a buffer if PROCESS is running. This function
1175 returns FLAG. */)
1176 (register Lisp_Object process, Lisp_Object flag)
1178 CHECK_PROCESS (process);
1179 XPROCESS (process)->kill_without_query = NILP (flag);
1180 return flag;
1183 DEFUN ("process-query-on-exit-flag",
1184 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1185 1, 1, 0,
1186 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1187 (register Lisp_Object process)
1189 CHECK_PROCESS (process);
1190 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1193 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1194 1, 2, 0,
1195 doc: /* Return the contact info of PROCESS; t for a real child.
1196 For a network or serial or pipe connection, the value depends on the
1197 optional KEY arg. If KEY is nil, value is a cons cell of the form
1198 \(HOST SERVICE) for a network connection or (PORT SPEED) for a serial
1199 connection; it is t for a pipe connection. If KEY is t, the complete
1200 contact information for the connection is returned, else the specific
1201 value for the keyword KEY is returned. See `make-network-process',
1202 \`make-serial-process', or `make-pipe-process' for the list of keywords. */)
1203 (register Lisp_Object process, Lisp_Object key)
1205 Lisp_Object contact;
1207 CHECK_PROCESS (process);
1208 contact = XPROCESS (process)->childp;
1210 #ifdef DATAGRAM_SOCKETS
1211 if (DATAGRAM_CONN_P (process)
1212 && (EQ (key, Qt) || EQ (key, QCremote)))
1213 contact = Fplist_put (contact, QCremote,
1214 Fprocess_datagram_address (process));
1215 #endif
1217 if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1218 || EQ (key, Qt))
1219 return contact;
1220 if (NILP (key) && NETCONN_P (process))
1221 return list2 (Fplist_get (contact, QChost),
1222 Fplist_get (contact, QCservice));
1223 if (NILP (key) && SERIALCONN_P (process))
1224 return list2 (Fplist_get (contact, QCport),
1225 Fplist_get (contact, QCspeed));
1226 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1227 if the pipe process is useful for purposes other than receiving
1228 stderr. */
1229 if (NILP (key) && PIPECONN_P (process))
1230 return Qt;
1231 return Fplist_get (contact, key);
1234 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1235 1, 1, 0,
1236 doc: /* Return the plist of PROCESS. */)
1237 (register Lisp_Object process)
1239 CHECK_PROCESS (process);
1240 return XPROCESS (process)->plist;
1243 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1244 2, 2, 0,
1245 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1246 (register Lisp_Object process, Lisp_Object plist)
1248 CHECK_PROCESS (process);
1249 CHECK_LIST (plist);
1251 pset_plist (XPROCESS (process), plist);
1252 return plist;
1255 #if 0 /* Turned off because we don't currently record this info
1256 in the process. Perhaps add it. */
1257 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1258 doc: /* Return the connection type of PROCESS.
1259 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1260 a socket connection. */)
1261 (Lisp_Object process)
1263 return XPROCESS (process)->type;
1265 #endif
1267 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1268 doc: /* Return the connection type of PROCESS.
1269 The value is either the symbol `real', `network', `serial', or `pipe'.
1270 PROCESS may be a process, a buffer, the name of a process or buffer, or
1271 nil, indicating the current buffer's process. */)
1272 (Lisp_Object process)
1274 Lisp_Object proc;
1275 proc = get_process (process);
1276 return XPROCESS (proc)->type;
1279 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1280 1, 2, 0,
1281 doc: /* Convert network ADDRESS from internal format to a string.
1282 A 4 or 5 element vector represents an IPv4 address (with port number).
1283 An 8 or 9 element vector represents an IPv6 address (with port number).
1284 If optional second argument OMIT-PORT is non-nil, don't include a port
1285 number in the string, even when present in ADDRESS.
1286 Returns nil if format of ADDRESS is invalid. */)
1287 (Lisp_Object address, Lisp_Object omit_port)
1289 if (NILP (address))
1290 return Qnil;
1292 if (STRINGP (address)) /* AF_LOCAL */
1293 return address;
1295 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1297 register struct Lisp_Vector *p = XVECTOR (address);
1298 ptrdiff_t size = p->header.size;
1299 Lisp_Object args[10];
1300 int nargs, i;
1301 char const *format;
1303 if (size == 4 || (size == 5 && !NILP (omit_port)))
1305 format = "%d.%d.%d.%d";
1306 nargs = 4;
1308 else if (size == 5)
1310 format = "%d.%d.%d.%d:%d";
1311 nargs = 5;
1313 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1315 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1316 nargs = 8;
1318 else if (size == 9)
1320 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1321 nargs = 9;
1323 else
1324 return Qnil;
1326 AUTO_STRING (format_obj, format);
1327 args[0] = format_obj;
1329 for (i = 0; i < nargs; i++)
1331 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1332 return Qnil;
1334 if (nargs <= 5 /* IPv4 */
1335 && i < 4 /* host, not port */
1336 && XINT (p->contents[i]) > 255)
1337 return Qnil;
1339 args[i + 1] = p->contents[i];
1342 return Fformat (nargs + 1, args);
1345 if (CONSP (address))
1347 AUTO_STRING (format, "<Family %d>");
1348 return CALLN (Fformat, format, Fcar (address));
1351 return Qnil;
1354 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1355 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1356 (void)
1358 return Fmapcar (Qcdr, Vprocess_alist);
1361 /* Starting asynchronous inferior processes. */
1363 static void start_process_unwind (Lisp_Object proc);
1365 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1366 doc: /* Start a program in a subprocess. Return the process object for it.
1368 This is similar to `start-process', but arguments are specified as
1369 keyword/argument pairs. The following arguments are defined:
1371 :name NAME -- NAME is name for process. It is modified if necessary
1372 to make it unique.
1374 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1375 with the process. Process output goes at end of that buffer, unless
1376 you specify an output stream or filter function to handle the output.
1377 BUFFER may be also nil, meaning that this process is not associated
1378 with any buffer.
1380 :command COMMAND -- COMMAND is a list starting with the program file
1381 name, followed by strings to give to the program as arguments.
1383 :coding CODING -- If CODING is a symbol, it specifies the coding
1384 system used for both reading and writing for this process. If CODING
1385 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1386 ENCODING is used for writing.
1388 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1389 the process is running. If BOOL is not given, query before exiting.
1391 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1392 In the stopped state, a process does not accept incoming data, but you
1393 can send outgoing data. The stopped state is cleared by
1394 `continue-process' and set by `stop-process'.
1396 :connection-type TYPE -- TYPE is control type of device used to
1397 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1398 to use a pty, or nil to use the default specified through
1399 `process-connection-type'.
1401 :filter FILTER -- Install FILTER as the process filter.
1403 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1405 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1406 to the standard error of subprocess. Specifying this implies
1407 `:connection-type' is set to `pipe'.
1409 usage: (make-process &rest ARGS) */)
1410 (ptrdiff_t nargs, Lisp_Object *args)
1412 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1413 Lisp_Object xstderr, stderrproc;
1414 ptrdiff_t count = SPECPDL_INDEX ();
1415 USE_SAFE_ALLOCA;
1417 if (nargs == 0)
1418 return Qnil;
1420 /* Save arguments for process-contact and clone-process. */
1421 contact = Flist (nargs, args);
1423 buffer = Fplist_get (contact, QCbuffer);
1424 if (!NILP (buffer))
1425 buffer = Fget_buffer_create (buffer);
1427 /* Make sure that the child will be able to chdir to the current
1428 buffer's current directory, or its unhandled equivalent. We
1429 can't just have the child check for an error when it does the
1430 chdir, since it's in a vfork. */
1431 current_dir = encode_current_directory ();
1433 name = Fplist_get (contact, QCname);
1434 CHECK_STRING (name);
1436 command = Fplist_get (contact, QCcommand);
1437 if (CONSP (command))
1438 program = XCAR (command);
1439 else
1440 program = Qnil;
1442 if (!NILP (program))
1443 CHECK_STRING (program);
1445 stderrproc = Qnil;
1446 xstderr = Fplist_get (contact, QCstderr);
1447 if (PROCESSP (xstderr))
1449 if (!PIPECONN_P (xstderr))
1450 error ("Process is not a pipe process");
1451 stderrproc = xstderr;
1453 else if (!NILP (xstderr))
1455 CHECK_STRING (program);
1456 stderrproc = CALLN (Fmake_pipe_process,
1457 QCname,
1458 concat2 (name, build_string (" stderr")),
1459 QCbuffer,
1460 Fget_buffer_create (xstderr));
1463 proc = make_process (name);
1464 /* If an error occurs and we can't start the process, we want to
1465 remove it from the process list. This means that each error
1466 check in create_process doesn't need to call remove_process
1467 itself; it's all taken care of here. */
1468 record_unwind_protect (start_process_unwind, proc);
1470 pset_childp (XPROCESS (proc), Qt);
1471 pset_plist (XPROCESS (proc), Qnil);
1472 pset_type (XPROCESS (proc), Qreal);
1473 pset_buffer (XPROCESS (proc), buffer);
1474 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1475 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1476 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1478 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
1479 XPROCESS (proc)->kill_without_query = 1;
1480 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1481 pset_command (XPROCESS (proc), Qt);
1483 tem = Fplist_get (contact, QCconnection_type);
1484 if (EQ (tem, Qpty))
1485 XPROCESS (proc)->pty_flag = true;
1486 else if (EQ (tem, Qpipe))
1487 XPROCESS (proc)->pty_flag = false;
1488 else if (NILP (tem))
1489 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1490 else
1491 report_file_error ("Unknown connection type", tem);
1493 if (!NILP (stderrproc))
1495 pset_stderrproc (XPROCESS (proc), stderrproc);
1497 XPROCESS (proc)->pty_flag = false;
1500 #ifdef HAVE_GNUTLS
1501 /* AKA GNUTLS_INITSTAGE(proc). */
1502 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1503 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1504 #endif
1506 XPROCESS (proc)->adaptive_read_buffering
1507 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1508 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1510 /* Make the process marker point into the process buffer (if any). */
1511 if (BUFFERP (buffer))
1512 set_marker_both (XPROCESS (proc)->mark, buffer,
1513 BUF_ZV (XBUFFER (buffer)),
1514 BUF_ZV_BYTE (XBUFFER (buffer)));
1517 /* Decide coding systems for communicating with the process. Here
1518 we don't setup the structure coding_system nor pay attention to
1519 unibyte mode. They are done in create_process. */
1521 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1522 Lisp_Object coding_systems = Qt;
1523 Lisp_Object val, *args2;
1525 tem = Fplist_get (contact, QCcoding);
1526 if (!NILP (tem))
1528 val = tem;
1529 if (CONSP (val))
1530 val = XCAR (val);
1532 else
1533 val = Vcoding_system_for_read;
1534 if (NILP (val))
1536 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1537 Lisp_Object tem2;
1538 SAFE_ALLOCA_LISP (args2, nargs2);
1539 ptrdiff_t i = 0;
1540 args2[i++] = Qstart_process;
1541 args2[i++] = name;
1542 args2[i++] = buffer;
1543 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1544 args2[i++] = XCAR (tem2);
1545 if (!NILP (program))
1546 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1547 if (CONSP (coding_systems))
1548 val = XCAR (coding_systems);
1549 else if (CONSP (Vdefault_process_coding_system))
1550 val = XCAR (Vdefault_process_coding_system);
1552 pset_decode_coding_system (XPROCESS (proc), val);
1554 if (!NILP (tem))
1556 val = tem;
1557 if (CONSP (val))
1558 val = XCDR (val);
1560 else
1561 val = Vcoding_system_for_write;
1562 if (NILP (val))
1564 if (EQ (coding_systems, Qt))
1566 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1567 Lisp_Object tem2;
1568 SAFE_ALLOCA_LISP (args2, nargs2);
1569 ptrdiff_t i = 0;
1570 args2[i++] = Qstart_process;
1571 args2[i++] = name;
1572 args2[i++] = buffer;
1573 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1574 args2[i++] = XCAR (tem2);
1575 if (!NILP (program))
1576 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1578 if (CONSP (coding_systems))
1579 val = XCDR (coding_systems);
1580 else if (CONSP (Vdefault_process_coding_system))
1581 val = XCDR (Vdefault_process_coding_system);
1583 pset_encode_coding_system (XPROCESS (proc), val);
1584 /* Note: At this moment, the above coding system may leave
1585 text-conversion or eol-conversion unspecified. They will be
1586 decided after we read output from the process and decode it by
1587 some coding system, or just before we actually send a text to
1588 the process. */
1592 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1593 XPROCESS (proc)->decoding_carryover = 0;
1594 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1596 XPROCESS (proc)->inherit_coding_system_flag
1597 = !(NILP (buffer) || !inherit_process_coding_system);
1599 if (!NILP (program))
1601 Lisp_Object program_args = XCDR (command);
1603 /* If program file name is not absolute, search our path for it.
1604 Put the name we will really use in TEM. */
1605 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1606 && !(SCHARS (program) > 1
1607 && IS_DEVICE_SEP (SREF (program, 1))))
1609 tem = Qnil;
1610 openp (Vexec_path, program, Vexec_suffixes, &tem,
1611 make_number (X_OK), false);
1612 if (NILP (tem))
1613 report_file_error ("Searching for program", program);
1614 tem = Fexpand_file_name (tem, Qnil);
1616 else
1618 if (!NILP (Ffile_directory_p (program)))
1619 error ("Specified program for new process is a directory");
1620 tem = program;
1623 /* Remove "/:" from TEM. */
1624 tem = remove_slash_colon (tem);
1626 Lisp_Object arg_encoding = Qnil;
1628 /* Encode the file name and put it in NEW_ARGV.
1629 That's where the child will use it to execute the program. */
1630 tem = list1 (ENCODE_FILE (tem));
1631 ptrdiff_t new_argc = 1;
1633 /* Here we encode arguments by the coding system used for sending
1634 data to the process. We don't support using different coding
1635 systems for encoding arguments and for encoding data sent to the
1636 process. */
1638 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1640 Lisp_Object arg = XCAR (tem2);
1641 CHECK_STRING (arg);
1642 if (STRING_MULTIBYTE (arg))
1644 if (NILP (arg_encoding))
1645 arg_encoding = (complement_process_encoding_system
1646 (XPROCESS (proc)->encode_coding_system));
1647 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1649 tem = Fcons (arg, tem);
1650 new_argc++;
1653 /* Now that everything is encoded we can collect the strings into
1654 NEW_ARGV. */
1655 char **new_argv;
1656 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1657 new_argv[new_argc] = 0;
1659 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1661 new_argv[i] = SSDATA (XCAR (tem));
1662 tem = XCDR (tem);
1665 create_process (proc, new_argv, current_dir);
1667 else
1668 create_pty (proc);
1670 SAFE_FREE ();
1671 return unbind_to (count, proc);
1674 /* This function is the unwind_protect form for Fstart_process. If
1675 PROC doesn't have its pid set, then we know someone has signaled
1676 an error and the process wasn't started successfully, so we should
1677 remove it from the process list. */
1678 static void
1679 start_process_unwind (Lisp_Object proc)
1681 if (!PROCESSP (proc))
1682 emacs_abort ();
1684 /* Was PROC started successfully?
1685 -2 is used for a pty with no process, eg for gdb. */
1686 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1687 remove_process (proc);
1690 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1692 static void
1693 close_process_fd (int *fd_addr)
1695 int fd = *fd_addr;
1696 if (0 <= fd)
1698 *fd_addr = -1;
1699 emacs_close (fd);
1703 /* Indexes of file descriptors in open_fds. */
1704 enum
1706 /* The pipe from Emacs to its subprocess. */
1707 SUBPROCESS_STDIN,
1708 WRITE_TO_SUBPROCESS,
1710 /* The main pipe from the subprocess to Emacs. */
1711 READ_FROM_SUBPROCESS,
1712 SUBPROCESS_STDOUT,
1714 /* The pipe from the subprocess to Emacs that is closed when the
1715 subprocess execs. */
1716 READ_FROM_EXEC_MONITOR,
1717 EXEC_MONITOR_OUTPUT
1720 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1722 static void
1723 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1725 struct Lisp_Process *p = XPROCESS (process);
1726 int inchannel, outchannel;
1727 pid_t pid;
1728 int vfork_errno;
1729 int forkin, forkout, forkerr = -1;
1730 bool pty_flag = 0;
1731 char pty_name[PTY_NAME_SIZE];
1732 Lisp_Object lisp_pty_name = Qnil;
1733 sigset_t oldset;
1735 inchannel = outchannel = -1;
1737 if (p->pty_flag)
1738 outchannel = inchannel = allocate_pty (pty_name);
1740 if (inchannel >= 0)
1742 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1743 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1744 /* On most USG systems it does not work to open the pty's tty here,
1745 then close it and reopen it in the child. */
1746 /* Don't let this terminal become our controlling terminal
1747 (in case we don't have one). */
1748 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1749 if (forkin < 0)
1750 report_file_error ("Opening pty", Qnil);
1751 p->open_fd[SUBPROCESS_STDIN] = forkin;
1752 #else
1753 forkin = forkout = -1;
1754 #endif /* not USG, or USG_SUBTTY_WORKS */
1755 pty_flag = 1;
1756 lisp_pty_name = build_string (pty_name);
1758 else
1760 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1761 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1762 report_file_error ("Creating pipe", Qnil);
1763 forkin = p->open_fd[SUBPROCESS_STDIN];
1764 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1765 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1766 forkout = p->open_fd[SUBPROCESS_STDOUT];
1768 if (!NILP (p->stderrproc))
1770 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
1772 forkerr = pp->open_fd[SUBPROCESS_STDOUT];
1774 /* Close unnecessary file descriptors. */
1775 close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
1776 close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
1780 #ifndef WINDOWSNT
1781 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1782 report_file_error ("Creating pipe", Qnil);
1783 #endif
1785 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1786 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1788 /* Record this as an active process, with its channels. */
1789 chan_process[inchannel] = process;
1790 p->infd = inchannel;
1791 p->outfd = outchannel;
1793 /* Previously we recorded the tty descriptor used in the subprocess.
1794 It was only used for getting the foreground tty process, so now
1795 we just reopen the device (see emacs_get_tty_pgrp) as this is
1796 more portable (see USG_SUBTTY_WORKS above). */
1798 p->pty_flag = pty_flag;
1799 pset_status (p, Qrun);
1801 if (!EQ (p->command, Qt))
1803 FD_SET (inchannel, &input_wait_mask);
1804 FD_SET (inchannel, &non_keyboard_wait_mask);
1807 if (inchannel > max_process_desc)
1808 max_process_desc = inchannel;
1810 /* This may signal an error. */
1811 setup_process_coding_systems (process);
1813 block_input ();
1814 block_child_signal (&oldset);
1816 #ifndef WINDOWSNT
1817 /* vfork, and prevent local vars from being clobbered by the vfork. */
1818 Lisp_Object volatile current_dir_volatile = current_dir;
1819 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1820 char **volatile new_argv_volatile = new_argv;
1821 int volatile forkin_volatile = forkin;
1822 int volatile forkout_volatile = forkout;
1823 int volatile forkerr_volatile = forkerr;
1824 struct Lisp_Process *p_volatile = p;
1826 pid = vfork ();
1828 current_dir = current_dir_volatile;
1829 lisp_pty_name = lisp_pty_name_volatile;
1830 new_argv = new_argv_volatile;
1831 forkin = forkin_volatile;
1832 forkout = forkout_volatile;
1833 forkerr = forkerr_volatile;
1834 p = p_volatile;
1836 pty_flag = p->pty_flag;
1838 if (pid == 0)
1839 #endif /* not WINDOWSNT */
1841 /* Make the pty be the controlling terminal of the process. */
1842 #ifdef HAVE_PTYS
1843 /* First, disconnect its current controlling terminal. */
1844 /* We tried doing setsid only if pty_flag, but it caused
1845 process_set_signal to fail on SGI when using a pipe. */
1846 setsid ();
1847 /* Make the pty's terminal the controlling terminal. */
1848 if (pty_flag && forkin >= 0)
1850 #ifdef TIOCSCTTY
1851 /* We ignore the return value
1852 because faith@cs.unc.edu says that is necessary on Linux. */
1853 ioctl (forkin, TIOCSCTTY, 0);
1854 #endif
1856 #if defined (LDISC1)
1857 if (pty_flag && forkin >= 0)
1859 struct termios t;
1860 tcgetattr (forkin, &t);
1861 t.c_lflag = LDISC1;
1862 if (tcsetattr (forkin, TCSANOW, &t) < 0)
1863 emacs_perror ("create_process/tcsetattr LDISC1");
1865 #else
1866 #if defined (NTTYDISC) && defined (TIOCSETD)
1867 if (pty_flag && forkin >= 0)
1869 /* Use new line discipline. */
1870 int ldisc = NTTYDISC;
1871 ioctl (forkin, TIOCSETD, &ldisc);
1873 #endif
1874 #endif
1875 #ifdef TIOCNOTTY
1876 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1877 can do TIOCSPGRP only to the process's controlling tty. */
1878 if (pty_flag)
1880 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1881 I can't test it since I don't have 4.3. */
1882 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1883 if (j >= 0)
1885 ioctl (j, TIOCNOTTY, 0);
1886 emacs_close (j);
1889 #endif /* TIOCNOTTY */
1891 #if !defined (DONT_REOPEN_PTY)
1892 /*** There is a suggestion that this ought to be a
1893 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1894 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1895 that system does seem to need this code, even though
1896 both TIOCSCTTY is defined. */
1897 /* Now close the pty (if we had it open) and reopen it.
1898 This makes the pty the controlling terminal of the subprocess. */
1899 if (pty_flag)
1902 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1903 would work? */
1904 if (forkin >= 0)
1905 emacs_close (forkin);
1906 forkout = forkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1908 if (forkin < 0)
1910 emacs_perror (SSDATA (lisp_pty_name));
1911 _exit (EXIT_CANCELED);
1915 #endif /* not DONT_REOPEN_PTY */
1917 #ifdef SETUP_SLAVE_PTY
1918 if (pty_flag)
1920 SETUP_SLAVE_PTY;
1922 #endif /* SETUP_SLAVE_PTY */
1923 #endif /* HAVE_PTYS */
1925 signal (SIGINT, SIG_DFL);
1926 signal (SIGQUIT, SIG_DFL);
1927 #ifdef SIGPROF
1928 signal (SIGPROF, SIG_DFL);
1929 #endif
1931 /* Emacs ignores SIGPIPE, but the child should not. */
1932 signal (SIGPIPE, SIG_DFL);
1934 /* Stop blocking SIGCHLD in the child. */
1935 unblock_child_signal (&oldset);
1937 if (pty_flag)
1938 child_setup_tty (forkout);
1940 if (forkerr < 0)
1941 forkerr = forkout;
1942 #ifdef WINDOWSNT
1943 pid = child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1944 #else /* not WINDOWSNT */
1945 child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1946 #endif /* not WINDOWSNT */
1949 /* Back in the parent process. */
1951 vfork_errno = errno;
1952 p->pid = pid;
1953 if (pid >= 0)
1954 p->alive = 1;
1956 /* Stop blocking in the parent. */
1957 unblock_child_signal (&oldset);
1958 unblock_input ();
1960 if (pid < 0)
1961 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1962 else
1964 /* vfork succeeded. */
1966 /* Close the pipe ends that the child uses, or the child's pty. */
1967 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
1968 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
1970 #ifdef WINDOWSNT
1971 register_child (pid, inchannel);
1972 #endif /* WINDOWSNT */
1974 pset_tty_name (p, lisp_pty_name);
1976 #ifndef WINDOWSNT
1977 /* Wait for child_setup to complete in case that vfork is
1978 actually defined as fork. The descriptor
1979 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1980 of a pipe is closed at the child side either by close-on-exec
1981 on successful execve or the _exit call in child_setup. */
1983 char dummy;
1985 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
1986 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
1987 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
1989 #endif
1990 if (!NILP (p->stderrproc))
1992 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
1993 close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
1998 static void
1999 create_pty (Lisp_Object process)
2001 struct Lisp_Process *p = XPROCESS (process);
2002 char pty_name[PTY_NAME_SIZE];
2003 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
2005 if (pty_fd >= 0)
2007 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
2008 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2009 /* On most USG systems it does not work to open the pty's tty here,
2010 then close it and reopen it in the child. */
2011 /* Don't let this terminal become our controlling terminal
2012 (in case we don't have one). */
2013 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2014 if (forkout < 0)
2015 report_file_error ("Opening pty", Qnil);
2016 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2017 #if defined (DONT_REOPEN_PTY)
2018 /* In the case that vfork is defined as fork, the parent process
2019 (Emacs) may send some data before the child process completes
2020 tty options setup. So we setup tty before forking. */
2021 child_setup_tty (forkout);
2022 #endif /* DONT_REOPEN_PTY */
2023 #endif /* not USG, or USG_SUBTTY_WORKS */
2025 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2027 /* Record this as an active process, with its channels.
2028 As a result, child_setup will close Emacs's side of the pipes. */
2029 chan_process[pty_fd] = process;
2030 p->infd = pty_fd;
2031 p->outfd = pty_fd;
2033 /* Previously we recorded the tty descriptor used in the subprocess.
2034 It was only used for getting the foreground tty process, so now
2035 we just reopen the device (see emacs_get_tty_pgrp) as this is
2036 more portable (see USG_SUBTTY_WORKS above). */
2038 p->pty_flag = 1;
2039 pset_status (p, Qrun);
2040 setup_process_coding_systems (process);
2042 FD_SET (pty_fd, &input_wait_mask);
2043 FD_SET (pty_fd, &non_keyboard_wait_mask);
2044 if (pty_fd > max_process_desc)
2045 max_process_desc = pty_fd;
2047 pset_tty_name (p, build_string (pty_name));
2050 p->pid = -2;
2053 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2054 0, MANY, 0,
2055 doc: /* Create and return a bidirectional pipe process.
2057 In Emacs, pipes are represented by process objects, so input and
2058 output work as for subprocesses, and `delete-process' closes a pipe.
2059 However, a pipe process has no process id, it cannot be signaled,
2060 and the status codes are different from normal processes.
2062 Arguments are specified as keyword/argument pairs. The following
2063 arguments are defined:
2065 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2067 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2068 with the process. Process output goes at the end of that buffer,
2069 unless you specify an output stream or filter function to handle the
2070 output. If BUFFER is not given, the value of NAME is used.
2072 :coding CODING -- If CODING is a symbol, it specifies the coding
2073 system used for both reading and writing for this process. If CODING
2074 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2075 ENCODING is used for writing.
2077 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2078 the process is running. If BOOL is not given, query before exiting.
2080 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2081 In the stopped state, a pipe process does not accept incoming data,
2082 but you can send outgoing data. The stopped state is cleared by
2083 `continue-process' and set by `stop-process'.
2085 :filter FILTER -- Install FILTER as the process filter.
2087 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2089 usage: (make-pipe-process &rest ARGS) */)
2090 (ptrdiff_t nargs, Lisp_Object *args)
2092 Lisp_Object proc, contact;
2093 struct Lisp_Process *p;
2094 Lisp_Object name, buffer;
2095 Lisp_Object tem;
2096 ptrdiff_t specpdl_count;
2097 int inchannel, outchannel;
2099 if (nargs == 0)
2100 return Qnil;
2102 contact = Flist (nargs, args);
2104 name = Fplist_get (contact, QCname);
2105 CHECK_STRING (name);
2106 proc = make_process (name);
2107 specpdl_count = SPECPDL_INDEX ();
2108 record_unwind_protect (remove_process, proc);
2109 p = XPROCESS (proc);
2111 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2112 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2113 report_file_error ("Creating pipe", Qnil);
2114 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2115 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2117 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2118 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2120 #ifdef WINDOWSNT
2121 register_aux_fd (inchannel);
2122 #endif
2124 /* Record this as an active process, with its channels. */
2125 chan_process[inchannel] = proc;
2126 p->infd = inchannel;
2127 p->outfd = outchannel;
2129 if (inchannel > max_process_desc)
2130 max_process_desc = inchannel;
2132 buffer = Fplist_get (contact, QCbuffer);
2133 if (NILP (buffer))
2134 buffer = name;
2135 buffer = Fget_buffer_create (buffer);
2136 pset_buffer (p, buffer);
2138 pset_childp (p, contact);
2139 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2140 pset_type (p, Qpipe);
2141 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2142 pset_filter (p, Fplist_get (contact, QCfilter));
2143 pset_log (p, Qnil);
2144 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2145 p->kill_without_query = 1;
2146 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2147 pset_command (p, Qt);
2148 eassert (! p->pty_flag);
2150 if (!EQ (p->command, Qt))
2152 FD_SET (inchannel, &input_wait_mask);
2153 FD_SET (inchannel, &non_keyboard_wait_mask);
2155 p->adaptive_read_buffering
2156 = (NILP (Vprocess_adaptive_read_buffering) ? 0
2157 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2159 /* Make the process marker point into the process buffer (if any). */
2160 if (BUFFERP (buffer))
2161 set_marker_both (p->mark, buffer,
2162 BUF_ZV (XBUFFER (buffer)),
2163 BUF_ZV_BYTE (XBUFFER (buffer)));
2166 /* Setup coding systems for communicating with the network stream. */
2168 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2169 Lisp_Object coding_systems = Qt;
2170 Lisp_Object val;
2172 tem = Fplist_get (contact, QCcoding);
2173 val = Qnil;
2174 if (!NILP (tem))
2176 val = tem;
2177 if (CONSP (val))
2178 val = XCAR (val);
2180 else if (!NILP (Vcoding_system_for_read))
2181 val = Vcoding_system_for_read;
2182 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2183 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2184 /* We dare not decode end-of-line format by setting VAL to
2185 Qraw_text, because the existing Emacs Lisp libraries
2186 assume that they receive bare code including a sequence of
2187 CR LF. */
2188 val = Qnil;
2189 else
2191 if (CONSP (coding_systems))
2192 val = XCAR (coding_systems);
2193 else if (CONSP (Vdefault_process_coding_system))
2194 val = XCAR (Vdefault_process_coding_system);
2195 else
2196 val = Qnil;
2198 pset_decode_coding_system (p, val);
2200 if (!NILP (tem))
2202 val = tem;
2203 if (CONSP (val))
2204 val = XCDR (val);
2206 else if (!NILP (Vcoding_system_for_write))
2207 val = Vcoding_system_for_write;
2208 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2209 val = Qnil;
2210 else
2212 if (CONSP (coding_systems))
2213 val = XCDR (coding_systems);
2214 else if (CONSP (Vdefault_process_coding_system))
2215 val = XCDR (Vdefault_process_coding_system);
2216 else
2217 val = Qnil;
2219 pset_encode_coding_system (p, val);
2221 /* This may signal an error. */
2222 setup_process_coding_systems (proc);
2224 specpdl_ptr = specpdl + specpdl_count;
2226 return proc;
2230 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2231 The address family of sa is not included in the result. */
2233 Lisp_Object
2234 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2236 Lisp_Object address;
2237 int i;
2238 unsigned char *cp;
2239 register struct Lisp_Vector *p;
2241 /* Workaround for a bug in getsockname on BSD: Names bound to
2242 sockets in the UNIX domain are inaccessible; getsockname returns
2243 a zero length name. */
2244 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2245 return empty_unibyte_string;
2247 switch (sa->sa_family)
2249 case AF_INET:
2251 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2252 len = sizeof (sin->sin_addr) + 1;
2253 address = Fmake_vector (make_number (len), Qnil);
2254 p = XVECTOR (address);
2255 p->contents[--len] = make_number (ntohs (sin->sin_port));
2256 cp = (unsigned char *) &sin->sin_addr;
2257 break;
2259 #ifdef AF_INET6
2260 case AF_INET6:
2262 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2263 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2264 len = sizeof (sin6->sin6_addr) / 2 + 1;
2265 address = Fmake_vector (make_number (len), Qnil);
2266 p = XVECTOR (address);
2267 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2268 for (i = 0; i < len; i++)
2269 p->contents[i] = make_number (ntohs (ip6[i]));
2270 return address;
2272 #endif
2273 #ifdef HAVE_LOCAL_SOCKETS
2274 case AF_LOCAL:
2276 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2277 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2278 /* If the first byte is NUL, the name is a Linux abstract
2279 socket name, and the name can contain embedded NULs. If
2280 it's not, we have a NUL-terminated string. Be careful not
2281 to walk past the end of the object looking for the name
2282 terminator, however. */
2283 if (name_length > 0 && sockun->sun_path[0] != '\0')
2285 const char *terminator
2286 = memchr (sockun->sun_path, '\0', name_length);
2288 if (terminator)
2289 name_length = terminator - (const char *) sockun->sun_path;
2292 return make_unibyte_string (sockun->sun_path, name_length);
2294 #endif
2295 default:
2296 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2297 address = Fcons (make_number (sa->sa_family),
2298 Fmake_vector (make_number (len), Qnil));
2299 p = XVECTOR (XCDR (address));
2300 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2301 break;
2304 i = 0;
2305 while (i < len)
2306 p->contents[i++] = make_number (*cp++);
2308 return address;
2312 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2314 static int
2315 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2317 register struct Lisp_Vector *p;
2319 if (VECTORP (address))
2321 p = XVECTOR (address);
2322 if (p->header.size == 5)
2324 *familyp = AF_INET;
2325 return sizeof (struct sockaddr_in);
2327 #ifdef AF_INET6
2328 else if (p->header.size == 9)
2330 *familyp = AF_INET6;
2331 return sizeof (struct sockaddr_in6);
2333 #endif
2335 #ifdef HAVE_LOCAL_SOCKETS
2336 else if (STRINGP (address))
2338 *familyp = AF_LOCAL;
2339 return sizeof (struct sockaddr_un);
2341 #endif
2342 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2343 && VECTORP (XCDR (address)))
2345 struct sockaddr *sa;
2346 p = XVECTOR (XCDR (address));
2347 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2348 return 0;
2349 *familyp = XINT (XCAR (address));
2350 return p->header.size + sizeof (sa->sa_family);
2352 return 0;
2355 /* Convert an address object (vector or string) to an internal sockaddr.
2357 The address format has been basically validated by
2358 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2359 it could have come from user data. So if FAMILY is not valid,
2360 we return after zeroing *SA. */
2362 static void
2363 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2365 register struct Lisp_Vector *p;
2366 register unsigned char *cp = NULL;
2367 register int i;
2368 EMACS_INT hostport;
2370 memset (sa, 0, len);
2372 if (VECTORP (address))
2374 p = XVECTOR (address);
2375 if (family == AF_INET)
2377 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2378 len = sizeof (sin->sin_addr) + 1;
2379 hostport = XINT (p->contents[--len]);
2380 sin->sin_port = htons (hostport);
2381 cp = (unsigned char *)&sin->sin_addr;
2382 sa->sa_family = family;
2384 #ifdef AF_INET6
2385 else if (family == AF_INET6)
2387 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2388 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2389 len = sizeof (sin6->sin6_addr) / 2 + 1;
2390 hostport = XINT (p->contents[--len]);
2391 sin6->sin6_port = htons (hostport);
2392 for (i = 0; i < len; i++)
2393 if (INTEGERP (p->contents[i]))
2395 int j = XFASTINT (p->contents[i]) & 0xffff;
2396 ip6[i] = ntohs (j);
2398 sa->sa_family = family;
2399 return;
2401 #endif
2402 else
2403 return;
2405 else if (STRINGP (address))
2407 #ifdef HAVE_LOCAL_SOCKETS
2408 if (family == AF_LOCAL)
2410 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2411 cp = SDATA (address);
2412 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2413 sockun->sun_path[i] = *cp++;
2414 sa->sa_family = family;
2416 #endif
2417 return;
2419 else
2421 p = XVECTOR (XCDR (address));
2422 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2425 for (i = 0; i < len; i++)
2426 if (INTEGERP (p->contents[i]))
2427 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2430 #ifdef DATAGRAM_SOCKETS
2431 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2432 1, 1, 0,
2433 doc: /* Get the current datagram address associated with PROCESS. */)
2434 (Lisp_Object process)
2436 int channel;
2438 CHECK_PROCESS (process);
2440 if (!DATAGRAM_CONN_P (process))
2441 return Qnil;
2443 channel = XPROCESS (process)->infd;
2444 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2445 datagram_address[channel].len);
2448 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2449 2, 2, 0,
2450 doc: /* Set the datagram address for PROCESS to ADDRESS.
2451 Returns nil upon error setting address, ADDRESS otherwise. */)
2452 (Lisp_Object process, Lisp_Object address)
2454 int channel;
2455 int family, len;
2457 CHECK_PROCESS (process);
2459 if (!DATAGRAM_CONN_P (process))
2460 return Qnil;
2462 channel = XPROCESS (process)->infd;
2464 len = get_lisp_to_sockaddr_size (address, &family);
2465 if (len == 0 || datagram_address[channel].len != len)
2466 return Qnil;
2467 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2468 return address;
2470 #endif
2473 static const struct socket_options {
2474 /* The name of this option. Should be lowercase version of option
2475 name without SO_ prefix. */
2476 const char *name;
2477 /* Option level SOL_... */
2478 int optlevel;
2479 /* Option number SO_... */
2480 int optnum;
2481 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2482 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2483 } socket_options[] =
2485 #ifdef SO_BINDTODEVICE
2486 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2487 #endif
2488 #ifdef SO_BROADCAST
2489 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2490 #endif
2491 #ifdef SO_DONTROUTE
2492 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2493 #endif
2494 #ifdef SO_KEEPALIVE
2495 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2496 #endif
2497 #ifdef SO_LINGER
2498 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2499 #endif
2500 #ifdef SO_OOBINLINE
2501 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2502 #endif
2503 #ifdef SO_PRIORITY
2504 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2505 #endif
2506 #ifdef SO_REUSEADDR
2507 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2508 #endif
2509 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2512 /* Set option OPT to value VAL on socket S.
2514 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2515 Signals an error if setting a known option fails.
2518 static int
2519 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2521 char *name;
2522 const struct socket_options *sopt;
2523 int ret = 0;
2525 CHECK_SYMBOL (opt);
2527 name = SSDATA (SYMBOL_NAME (opt));
2528 for (sopt = socket_options; sopt->name; sopt++)
2529 if (strcmp (name, sopt->name) == 0)
2530 break;
2532 switch (sopt->opttype)
2534 case SOPT_BOOL:
2536 int optval;
2537 optval = NILP (val) ? 0 : 1;
2538 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2539 &optval, sizeof (optval));
2540 break;
2543 case SOPT_INT:
2545 int optval;
2546 if (TYPE_RANGED_INTEGERP (int, val))
2547 optval = XINT (val);
2548 else
2549 error ("Bad option value for %s", name);
2550 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2551 &optval, sizeof (optval));
2552 break;
2555 #ifdef SO_BINDTODEVICE
2556 case SOPT_IFNAME:
2558 char devname[IFNAMSIZ + 1];
2560 /* This is broken, at least in the Linux 2.4 kernel.
2561 To unbind, the arg must be a zero integer, not the empty string.
2562 This should work on all systems. KFS. 2003-09-23. */
2563 memset (devname, 0, sizeof devname);
2564 if (STRINGP (val))
2566 char *arg = SSDATA (val);
2567 int len = min (strlen (arg), IFNAMSIZ);
2568 memcpy (devname, arg, len);
2570 else if (!NILP (val))
2571 error ("Bad option value for %s", name);
2572 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2573 devname, IFNAMSIZ);
2574 break;
2576 #endif
2578 #ifdef SO_LINGER
2579 case SOPT_LINGER:
2581 struct linger linger;
2583 linger.l_onoff = 1;
2584 linger.l_linger = 0;
2585 if (TYPE_RANGED_INTEGERP (int, val))
2586 linger.l_linger = XINT (val);
2587 else
2588 linger.l_onoff = NILP (val) ? 0 : 1;
2589 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2590 &linger, sizeof (linger));
2591 break;
2593 #endif
2595 default:
2596 return 0;
2599 if (ret < 0)
2601 int setsockopt_errno = errno;
2602 report_file_errno ("Cannot set network option", list2 (opt, val),
2603 setsockopt_errno);
2606 return (1 << sopt->optbit);
2610 DEFUN ("set-network-process-option",
2611 Fset_network_process_option, Sset_network_process_option,
2612 3, 4, 0,
2613 doc: /* For network process PROCESS set option OPTION to value VALUE.
2614 See `make-network-process' for a list of options and values.
2615 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2616 OPTION is not a supported option, return nil instead; otherwise return t. */)
2617 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2619 int s;
2620 struct Lisp_Process *p;
2622 CHECK_PROCESS (process);
2623 p = XPROCESS (process);
2624 if (!NETCONN1_P (p))
2625 error ("Process is not a network process");
2627 s = p->infd;
2628 if (s < 0)
2629 error ("Process is not running");
2631 if (set_socket_option (s, option, value))
2633 pset_childp (p, Fplist_put (p->childp, option, value));
2634 return Qt;
2637 if (NILP (no_error))
2638 error ("Unknown or unsupported option");
2640 return Qnil;
2644 DEFUN ("serial-process-configure",
2645 Fserial_process_configure,
2646 Sserial_process_configure,
2647 0, MANY, 0,
2648 doc: /* Configure speed, bytesize, etc. of a serial process.
2650 Arguments are specified as keyword/argument pairs. Attributes that
2651 are not given are re-initialized from the process's current
2652 configuration (available via the function `process-contact') or set to
2653 reasonable default values. The following arguments are defined:
2655 :process PROCESS
2656 :name NAME
2657 :buffer BUFFER
2658 :port PORT
2659 -- Any of these arguments can be given to identify the process that is
2660 to be configured. If none of these arguments is given, the current
2661 buffer's process is used.
2663 :speed SPEED -- SPEED is the speed of the serial port in bits per
2664 second, also called baud rate. Any value can be given for SPEED, but
2665 most serial ports work only at a few defined values between 1200 and
2666 115200, with 9600 being the most common value. If SPEED is nil, the
2667 serial port is not configured any further, i.e., all other arguments
2668 are ignored. This may be useful for special serial ports such as
2669 Bluetooth-to-serial converters which can only be configured through AT
2670 commands. A value of nil for SPEED can be used only when passed
2671 through `make-serial-process' or `serial-term'.
2673 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2674 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2676 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2677 `odd' (use odd parity), or the symbol `even' (use even parity). If
2678 PARITY is not given, no parity is used.
2680 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2681 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2682 is not given or nil, 1 stopbit is used.
2684 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2685 flowcontrol to be used, which is either nil (don't use flowcontrol),
2686 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2687 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2688 flowcontrol is used.
2690 `serial-process-configure' is called by `make-serial-process' for the
2691 initial configuration of the serial port.
2693 Examples:
2695 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2697 \(serial-process-configure
2698 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2700 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2702 usage: (serial-process-configure &rest ARGS) */)
2703 (ptrdiff_t nargs, Lisp_Object *args)
2705 struct Lisp_Process *p;
2706 Lisp_Object contact = Qnil;
2707 Lisp_Object proc = Qnil;
2709 contact = Flist (nargs, args);
2711 proc = Fplist_get (contact, QCprocess);
2712 if (NILP (proc))
2713 proc = Fplist_get (contact, QCname);
2714 if (NILP (proc))
2715 proc = Fplist_get (contact, QCbuffer);
2716 if (NILP (proc))
2717 proc = Fplist_get (contact, QCport);
2718 proc = get_process (proc);
2719 p = XPROCESS (proc);
2720 if (!EQ (p->type, Qserial))
2721 error ("Not a serial process");
2723 if (NILP (Fplist_get (p->childp, QCspeed)))
2724 return Qnil;
2726 serial_configure (p, contact);
2727 return Qnil;
2730 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2731 0, MANY, 0,
2732 doc: /* Create and return a serial port process.
2734 In Emacs, serial port connections are represented by process objects,
2735 so input and output work as for subprocesses, and `delete-process'
2736 closes a serial port connection. However, a serial process has no
2737 process id, it cannot be signaled, and the status codes are different
2738 from normal processes.
2740 `make-serial-process' creates a process and a buffer, on which you
2741 probably want to use `process-send-string'. Try \\[serial-term] for
2742 an interactive terminal. See below for examples.
2744 Arguments are specified as keyword/argument pairs. The following
2745 arguments are defined:
2747 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2748 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2749 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2750 the backslashes in strings).
2752 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2753 which this function calls.
2755 :name NAME -- NAME is the name of the process. If NAME is not given,
2756 the value of PORT is used.
2758 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2759 with the process. Process output goes at the end of that buffer,
2760 unless you specify an output stream or filter function to handle the
2761 output. If BUFFER is not given, the value of NAME is used.
2763 :coding CODING -- If CODING is a symbol, it specifies the coding
2764 system used for both reading and writing for this process. If CODING
2765 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2766 ENCODING is used for writing.
2768 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2769 the process is running. If BOOL is not given, query before exiting.
2771 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2772 In the stopped state, a serial process does not accept incoming data,
2773 but you can send outgoing data. The stopped state is cleared by
2774 `continue-process' and set by `stop-process'.
2776 :filter FILTER -- Install FILTER as the process filter.
2778 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2780 :plist PLIST -- Install PLIST as the initial plist of the process.
2782 :bytesize
2783 :parity
2784 :stopbits
2785 :flowcontrol
2786 -- This function calls `serial-process-configure' to handle these
2787 arguments.
2789 The original argument list, possibly modified by later configuration,
2790 is available via the function `process-contact'.
2792 Examples:
2794 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2796 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2798 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2800 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2802 usage: (make-serial-process &rest ARGS) */)
2803 (ptrdiff_t nargs, Lisp_Object *args)
2805 int fd = -1;
2806 Lisp_Object proc, contact, port;
2807 struct Lisp_Process *p;
2808 Lisp_Object name, buffer;
2809 Lisp_Object tem, val;
2810 ptrdiff_t specpdl_count;
2812 if (nargs == 0)
2813 return Qnil;
2815 contact = Flist (nargs, args);
2817 port = Fplist_get (contact, QCport);
2818 if (NILP (port))
2819 error ("No port specified");
2820 CHECK_STRING (port);
2822 if (NILP (Fplist_member (contact, QCspeed)))
2823 error (":speed not specified");
2824 if (!NILP (Fplist_get (contact, QCspeed)))
2825 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2827 name = Fplist_get (contact, QCname);
2828 if (NILP (name))
2829 name = port;
2830 CHECK_STRING (name);
2831 proc = make_process (name);
2832 specpdl_count = SPECPDL_INDEX ();
2833 record_unwind_protect (remove_process, proc);
2834 p = XPROCESS (proc);
2836 fd = serial_open (port);
2837 p->open_fd[SUBPROCESS_STDIN] = fd;
2838 p->infd = fd;
2839 p->outfd = fd;
2840 if (fd > max_process_desc)
2841 max_process_desc = fd;
2842 chan_process[fd] = proc;
2844 buffer = Fplist_get (contact, QCbuffer);
2845 if (NILP (buffer))
2846 buffer = name;
2847 buffer = Fget_buffer_create (buffer);
2848 pset_buffer (p, buffer);
2850 pset_childp (p, contact);
2851 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2852 pset_type (p, Qserial);
2853 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2854 pset_filter (p, Fplist_get (contact, QCfilter));
2855 pset_log (p, Qnil);
2856 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2857 p->kill_without_query = 1;
2858 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2859 pset_command (p, Qt);
2860 eassert (! p->pty_flag);
2862 if (!EQ (p->command, Qt))
2864 FD_SET (fd, &input_wait_mask);
2865 FD_SET (fd, &non_keyboard_wait_mask);
2868 if (BUFFERP (buffer))
2870 set_marker_both (p->mark, buffer,
2871 BUF_ZV (XBUFFER (buffer)),
2872 BUF_ZV_BYTE (XBUFFER (buffer)));
2875 tem = Fplist_member (contact, QCcoding);
2876 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2877 tem = Qnil;
2879 val = Qnil;
2880 if (!NILP (tem))
2882 val = XCAR (XCDR (tem));
2883 if (CONSP (val))
2884 val = XCAR (val);
2886 else if (!NILP (Vcoding_system_for_read))
2887 val = Vcoding_system_for_read;
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_decode_coding_system (p, val);
2893 val = Qnil;
2894 if (!NILP (tem))
2896 val = XCAR (XCDR (tem));
2897 if (CONSP (val))
2898 val = XCDR (val);
2900 else if (!NILP (Vcoding_system_for_write))
2901 val = Vcoding_system_for_write;
2902 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2903 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2904 val = Qnil;
2905 pset_encode_coding_system (p, val);
2907 setup_process_coding_systems (proc);
2908 pset_decoding_buf (p, empty_unibyte_string);
2909 p->decoding_carryover = 0;
2910 pset_encoding_buf (p, empty_unibyte_string);
2911 p->inherit_coding_system_flag
2912 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2914 Fserial_process_configure (nargs, args);
2916 specpdl_ptr = specpdl + specpdl_count;
2918 return proc;
2921 /* Create a network stream/datagram client/server process. Treated
2922 exactly like a normal process when reading and writing. Primary
2923 differences are in status display and process deletion. A network
2924 connection has no PID; you cannot signal it. All you can do is
2925 stop/continue it and deactivate/close it via delete-process. */
2927 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2928 0, MANY, 0,
2929 doc: /* Create and return a network server or client process.
2931 In Emacs, network connections are represented by process objects, so
2932 input and output work as for subprocesses and `delete-process' closes
2933 a network connection. However, a network process has no process id,
2934 it cannot be signaled, and the status codes are different from normal
2935 processes.
2937 Arguments are specified as keyword/argument pairs. The following
2938 arguments are defined:
2940 :name NAME -- NAME is name for process. It is modified if necessary
2941 to make it unique.
2943 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2944 with the process. Process output goes at end of that buffer, unless
2945 you specify an output stream or filter function to handle the output.
2946 BUFFER may be also nil, meaning that this process is not associated
2947 with any buffer.
2949 :host HOST -- HOST is name of the host to connect to, or its IP
2950 address. The symbol `local' specifies the local host. If specified
2951 for a server process, it must be a valid name or address for the local
2952 host, and only clients connecting to that address will be accepted.
2954 :service SERVICE -- SERVICE is name of the service desired, or an
2955 integer specifying a port number to connect to. If SERVICE is t,
2956 a random port number is selected for the server. (If Emacs was
2957 compiled with getaddrinfo, a port number can also be specified as a
2958 string, e.g. "80", as well as an integer. This is not portable.)
2960 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2961 stream type connection, `datagram' creates a datagram type connection,
2962 `seqpacket' creates a reliable datagram connection.
2964 :family FAMILY -- FAMILY is the address (and protocol) family for the
2965 service specified by HOST and SERVICE. The default (nil) is to use
2966 whatever address family (IPv4 or IPv6) that is defined for the host
2967 and port number specified by HOST and SERVICE. Other address families
2968 supported are:
2969 local -- for a local (i.e. UNIX) address specified by SERVICE.
2970 ipv4 -- use IPv4 address family only.
2971 ipv6 -- use IPv6 address family only.
2973 :local ADDRESS -- ADDRESS is the local address used for the connection.
2974 This parameter is ignored when opening a client process. When specified
2975 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2977 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2978 connection. This parameter is ignored when opening a stream server
2979 process. For a datagram server process, it specifies the initial
2980 setting of the remote datagram address. When specified for a client
2981 process, the FAMILY, HOST, and SERVICE args are ignored.
2983 The format of ADDRESS depends on the address family:
2984 - An IPv4 address is represented as an vector of integers [A B C D P]
2985 corresponding to numeric IP address A.B.C.D and port number P.
2986 - A local address is represented as a string with the address in the
2987 local address space.
2988 - An "unsupported family" address is represented by a cons (F . AV)
2989 where F is the family number and AV is a vector containing the socket
2990 address data with one element per address data byte. Do not rely on
2991 this format in portable code, as it may depend on implementation
2992 defined constants, data sizes, and data structure alignment.
2994 :coding CODING -- If CODING is a symbol, it specifies the coding
2995 system used for both reading and writing for this process. If CODING
2996 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2997 ENCODING is used for writing.
2999 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3000 return without waiting for the connection to complete; instead, the
3001 sentinel function will be called with second arg matching "open" (if
3002 successful) or "failed" when the connect completes. Default is to use
3003 a blocking connect (i.e. wait) for stream type connections.
3005 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3006 running when Emacs is exited.
3008 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3009 In the stopped state, a server process does not accept new
3010 connections, and a client process does not handle incoming traffic.
3011 The stopped state is cleared by `continue-process' and set by
3012 `stop-process'.
3014 :filter FILTER -- Install FILTER as the process filter.
3016 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3017 process filter are multibyte, otherwise they are unibyte.
3018 If this keyword is not specified, the strings are multibyte if
3019 the default value of `enable-multibyte-characters' is non-nil.
3021 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3023 :log LOG -- Install LOG as the server process log function. This
3024 function is called when the server accepts a network connection from a
3025 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3026 is the server process, CLIENT is the new process for the connection,
3027 and MESSAGE is a string.
3029 :plist PLIST -- Install PLIST as the new process's initial plist.
3031 :server QLEN -- if QLEN is non-nil, create a server process for the
3032 specified FAMILY, SERVICE, and connection type (stream or datagram).
3033 If QLEN is an integer, it is used as the max. length of the server's
3034 pending connection queue (also known as the backlog); the default
3035 queue length is 5. Default is to create a client process.
3037 The following network options can be specified for this connection:
3039 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3040 :dontroute BOOL -- Only send to directly connected hosts.
3041 :keepalive BOOL -- Send keep-alive messages on network stream.
3042 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3043 :oobinline BOOL -- Place out-of-band data in receive data stream.
3044 :priority INT -- Set protocol defined priority for sent packets.
3045 :reuseaddr BOOL -- Allow reusing a recently used local address
3046 (this is allowed by default for a server process).
3047 :bindtodevice NAME -- bind to interface NAME. Using this may require
3048 special privileges on some systems.
3050 Consult the relevant system programmer's manual pages for more
3051 information on using these options.
3054 A server process will listen for and accept connections from clients.
3055 When a client connection is accepted, a new network process is created
3056 for the connection with the following parameters:
3058 - The client's process name is constructed by concatenating the server
3059 process's NAME and a client identification string.
3060 - If the FILTER argument is non-nil, the client process will not get a
3061 separate process buffer; otherwise, the client's process buffer is a newly
3062 created buffer named after the server process's BUFFER name or process
3063 NAME concatenated with the client identification string.
3064 - The connection type and the process filter and sentinel parameters are
3065 inherited from the server process's TYPE, FILTER and SENTINEL.
3066 - The client process's contact info is set according to the client's
3067 addressing information (typically an IP address and a port number).
3068 - The client process's plist is initialized from the server's plist.
3070 Notice that the FILTER and SENTINEL args are never used directly by
3071 the server process. Also, the BUFFER argument is not used directly by
3072 the server process, but via the optional :log function, accepted (and
3073 failed) connections may be logged in the server process's buffer.
3075 The original argument list, modified with the actual connection
3076 information, is available via the `process-contact' function.
3078 usage: (make-network-process &rest ARGS) */)
3079 (ptrdiff_t nargs, Lisp_Object *args)
3081 Lisp_Object proc;
3082 Lisp_Object contact;
3083 struct Lisp_Process *p;
3084 #ifdef HAVE_GETADDRINFO
3085 struct addrinfo ai, *res, *lres;
3086 struct addrinfo hints;
3087 const char *portstring;
3088 char portbuf[128];
3089 #else /* HAVE_GETADDRINFO */
3090 struct _emacs_addrinfo
3092 int ai_family;
3093 int ai_socktype;
3094 int ai_protocol;
3095 int ai_addrlen;
3096 struct sockaddr *ai_addr;
3097 struct _emacs_addrinfo *ai_next;
3098 } ai, *res, *lres;
3099 #endif /* HAVE_GETADDRINFO */
3100 struct sockaddr_in address_in;
3101 #ifdef HAVE_LOCAL_SOCKETS
3102 struct sockaddr_un address_un;
3103 #endif
3104 int port;
3105 int ret = 0;
3106 int xerrno = 0;
3107 int s = -1, outch, inch;
3108 ptrdiff_t count = SPECPDL_INDEX ();
3109 ptrdiff_t count1;
3110 Lisp_Object colon_address; /* Either QClocal or QCremote. */
3111 Lisp_Object tem;
3112 Lisp_Object name, buffer, host, service, address;
3113 Lisp_Object filter, sentinel;
3114 bool is_non_blocking_client = 0;
3115 bool is_server = 0;
3116 int backlog = 5;
3117 int socktype;
3118 int family = -1;
3120 if (nargs == 0)
3121 return Qnil;
3123 /* Save arguments for process-contact and clone-process. */
3124 contact = Flist (nargs, args);
3126 #ifdef WINDOWSNT
3127 /* Ensure socket support is loaded if available. */
3128 init_winsock (TRUE);
3129 #endif
3131 /* :type TYPE (nil: stream, datagram */
3132 tem = Fplist_get (contact, QCtype);
3133 if (NILP (tem))
3134 socktype = SOCK_STREAM;
3135 #ifdef DATAGRAM_SOCKETS
3136 else if (EQ (tem, Qdatagram))
3137 socktype = SOCK_DGRAM;
3138 #endif
3139 #ifdef HAVE_SEQPACKET
3140 else if (EQ (tem, Qseqpacket))
3141 socktype = SOCK_SEQPACKET;
3142 #endif
3143 else
3144 error ("Unsupported connection type");
3146 /* :server BOOL */
3147 tem = Fplist_get (contact, QCserver);
3148 if (!NILP (tem))
3150 /* Don't support network sockets when non-blocking mode is
3151 not available, since a blocked Emacs is not useful. */
3152 is_server = 1;
3153 if (TYPE_RANGED_INTEGERP (int, tem))
3154 backlog = XINT (tem);
3157 /* Make colon_address an alias for :local (server) or :remote (client). */
3158 colon_address = is_server ? QClocal : QCremote;
3160 /* :nowait BOOL */
3161 if (!is_server && socktype != SOCK_DGRAM
3162 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3164 #ifndef NON_BLOCKING_CONNECT
3165 error ("Non-blocking connect not supported");
3166 #else
3167 is_non_blocking_client = 1;
3168 #endif
3171 name = Fplist_get (contact, QCname);
3172 buffer = Fplist_get (contact, QCbuffer);
3173 filter = Fplist_get (contact, QCfilter);
3174 sentinel = Fplist_get (contact, QCsentinel);
3176 CHECK_STRING (name);
3178 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3179 ai.ai_socktype = socktype;
3180 ai.ai_protocol = 0;
3181 ai.ai_next = NULL;
3182 res = &ai;
3184 /* :local ADDRESS or :remote ADDRESS */
3185 address = Fplist_get (contact, colon_address);
3186 if (!NILP (address))
3188 host = service = Qnil;
3190 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3191 error ("Malformed :address");
3192 ai.ai_family = family;
3193 ai.ai_addr = alloca (ai.ai_addrlen);
3194 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3195 goto open_socket;
3198 /* :family FAMILY -- nil (for Inet), local, or integer. */
3199 tem = Fplist_get (contact, QCfamily);
3200 if (NILP (tem))
3202 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3203 family = AF_UNSPEC;
3204 #else
3205 family = AF_INET;
3206 #endif
3208 #ifdef HAVE_LOCAL_SOCKETS
3209 else if (EQ (tem, Qlocal))
3210 family = AF_LOCAL;
3211 #endif
3212 #ifdef AF_INET6
3213 else if (EQ (tem, Qipv6))
3214 family = AF_INET6;
3215 #endif
3216 else if (EQ (tem, Qipv4))
3217 family = AF_INET;
3218 else if (TYPE_RANGED_INTEGERP (int, tem))
3219 family = XINT (tem);
3220 else
3221 error ("Unknown address family");
3223 ai.ai_family = family;
3225 /* :service SERVICE -- string, integer (port number), or t (random port). */
3226 service = Fplist_get (contact, QCservice);
3228 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3229 host = Fplist_get (contact, QChost);
3230 if (!NILP (host))
3232 if (EQ (host, Qlocal))
3233 /* Depending on setup, "localhost" may map to different IPv4 and/or
3234 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3235 host = build_string ("127.0.0.1");
3236 CHECK_STRING (host);
3239 #ifdef HAVE_LOCAL_SOCKETS
3240 if (family == AF_LOCAL)
3242 if (!NILP (host))
3244 message (":family local ignores the :host property");
3245 contact = Fplist_put (contact, QChost, Qnil);
3246 host = Qnil;
3248 CHECK_STRING (service);
3249 memset (&address_un, 0, sizeof address_un);
3250 address_un.sun_family = AF_LOCAL;
3251 if (sizeof address_un.sun_path <= SBYTES (service))
3252 error ("Service name too long");
3253 lispstpcpy (address_un.sun_path, service);
3254 ai.ai_addr = (struct sockaddr *) &address_un;
3255 ai.ai_addrlen = sizeof address_un;
3256 goto open_socket;
3258 #endif
3260 /* Slow down polling to every ten seconds.
3261 Some kernels have a bug which causes retrying connect to fail
3262 after a connect. Polling can interfere with gethostbyname too. */
3263 #ifdef POLL_FOR_INPUT
3264 if (socktype != SOCK_DGRAM)
3266 record_unwind_protect_void (run_all_atimers);
3267 bind_polling_period (10);
3269 #endif
3271 #ifdef HAVE_GETADDRINFO
3272 /* If we have a host, use getaddrinfo to resolve both host and service.
3273 Otherwise, use getservbyname to lookup the service. */
3274 if (!NILP (host))
3277 /* SERVICE can either be a string or int.
3278 Convert to a C string for later use by getaddrinfo. */
3279 if (EQ (service, Qt))
3280 portstring = "0";
3281 else if (INTEGERP (service))
3283 sprintf (portbuf, "%"pI"d", XINT (service));
3284 portstring = portbuf;
3286 else
3288 CHECK_STRING (service);
3289 portstring = SSDATA (service);
3292 immediate_quit = 1;
3293 QUIT;
3294 memset (&hints, 0, sizeof (hints));
3295 hints.ai_flags = 0;
3296 hints.ai_family = family;
3297 hints.ai_socktype = socktype;
3298 hints.ai_protocol = 0;
3300 #ifdef HAVE_RES_INIT
3301 res_init ();
3302 #endif
3304 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3305 if (ret)
3306 #ifdef HAVE_GAI_STRERROR
3307 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3308 #else
3309 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3310 #endif
3311 immediate_quit = 0;
3313 goto open_socket;
3315 #endif /* HAVE_GETADDRINFO */
3317 /* We end up here if getaddrinfo is not defined, or in case no hostname
3318 has been specified (e.g. for a local server process). */
3320 if (EQ (service, Qt))
3321 port = 0;
3322 else if (INTEGERP (service))
3323 port = htons ((unsigned short) XINT (service));
3324 else
3326 struct servent *svc_info;
3327 CHECK_STRING (service);
3328 svc_info = getservbyname (SSDATA (service),
3329 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3330 if (svc_info == 0)
3331 error ("Unknown service: %s", SDATA (service));
3332 port = svc_info->s_port;
3335 memset (&address_in, 0, sizeof address_in);
3336 address_in.sin_family = family;
3337 address_in.sin_addr.s_addr = INADDR_ANY;
3338 address_in.sin_port = port;
3340 #ifndef HAVE_GETADDRINFO
3341 if (!NILP (host))
3343 struct hostent *host_info_ptr;
3345 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3346 as it may `hang' Emacs for a very long time. */
3347 immediate_quit = 1;
3348 QUIT;
3350 #ifdef HAVE_RES_INIT
3351 res_init ();
3352 #endif
3354 host_info_ptr = gethostbyname (SDATA (host));
3355 immediate_quit = 0;
3357 if (host_info_ptr)
3359 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3360 host_info_ptr->h_length);
3361 family = host_info_ptr->h_addrtype;
3362 address_in.sin_family = family;
3364 else
3365 /* Attempt to interpret host as numeric inet address. */
3367 unsigned long numeric_addr;
3368 numeric_addr = inet_addr (SSDATA (host));
3369 if (numeric_addr == -1)
3370 error ("Unknown host \"%s\"", SDATA (host));
3372 memcpy (&address_in.sin_addr, &numeric_addr,
3373 sizeof (address_in.sin_addr));
3377 #endif /* not HAVE_GETADDRINFO */
3379 ai.ai_family = family;
3380 ai.ai_addr = (struct sockaddr *) &address_in;
3381 ai.ai_addrlen = sizeof address_in;
3383 open_socket:
3385 /* Do this in case we never enter the for-loop below. */
3386 count1 = SPECPDL_INDEX ();
3387 s = -1;
3389 for (lres = res; lres; lres = lres->ai_next)
3391 ptrdiff_t optn;
3392 int optbits;
3394 #ifdef WINDOWSNT
3395 retry_connect:
3396 #endif
3398 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3399 lres->ai_protocol);
3400 if (s < 0)
3402 xerrno = errno;
3403 continue;
3406 #ifdef DATAGRAM_SOCKETS
3407 if (!is_server && socktype == SOCK_DGRAM)
3408 break;
3409 #endif /* DATAGRAM_SOCKETS */
3411 #ifdef NON_BLOCKING_CONNECT
3412 if (is_non_blocking_client)
3414 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3415 if (ret < 0)
3417 xerrno = errno;
3418 emacs_close (s);
3419 s = -1;
3420 continue;
3423 #endif
3425 /* Make us close S if quit. */
3426 record_unwind_protect_int (close_file_unwind, s);
3428 /* Parse network options in the arg list.
3429 We simply ignore anything which isn't a known option (including other keywords).
3430 An error is signaled if setting a known option fails. */
3431 for (optn = optbits = 0; optn < nargs - 1; optn += 2)
3432 optbits |= set_socket_option (s, args[optn], args[optn + 1]);
3434 if (is_server)
3436 /* Configure as a server socket. */
3438 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3439 explicit :reuseaddr key to override this. */
3440 #ifdef HAVE_LOCAL_SOCKETS
3441 if (family != AF_LOCAL)
3442 #endif
3443 if (!(optbits & (1 << OPIX_REUSEADDR)))
3445 int optval = 1;
3446 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3447 report_file_error ("Cannot set reuse option on server socket", Qnil);
3450 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3451 report_file_error ("Cannot bind server socket", Qnil);
3453 #ifdef HAVE_GETSOCKNAME
3454 if (EQ (service, Qt))
3456 struct sockaddr_in sa1;
3457 socklen_t len1 = sizeof (sa1);
3458 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3460 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3461 service = make_number (ntohs (sa1.sin_port));
3462 contact = Fplist_put (contact, QCservice, service);
3465 #endif
3467 if (socktype != SOCK_DGRAM && listen (s, backlog))
3468 report_file_error ("Cannot listen on server socket", Qnil);
3470 break;
3473 immediate_quit = 1;
3474 QUIT;
3476 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3477 xerrno = errno;
3479 if (ret == 0 || xerrno == EISCONN)
3481 /* The unwind-protect will be discarded afterwards.
3482 Likewise for immediate_quit. */
3483 break;
3486 #ifdef NON_BLOCKING_CONNECT
3487 #ifdef EINPROGRESS
3488 if (is_non_blocking_client && xerrno == EINPROGRESS)
3489 break;
3490 #else
3491 #ifdef EWOULDBLOCK
3492 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3493 break;
3494 #endif
3495 #endif
3496 #endif
3498 #ifndef WINDOWSNT
3499 if (xerrno == EINTR)
3501 /* Unlike most other syscalls connect() cannot be called
3502 again. (That would return EALREADY.) The proper way to
3503 wait for completion is pselect(). */
3504 int sc;
3505 socklen_t len;
3506 fd_set fdset;
3507 retry_select:
3508 FD_ZERO (&fdset);
3509 FD_SET (s, &fdset);
3510 QUIT;
3511 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3512 if (sc == -1)
3514 if (errno == EINTR)
3515 goto retry_select;
3516 else
3517 report_file_error ("Failed select", Qnil);
3519 eassert (sc > 0);
3521 len = sizeof xerrno;
3522 eassert (FD_ISSET (s, &fdset));
3523 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3524 report_file_error ("Failed getsockopt", Qnil);
3525 if (xerrno)
3526 report_file_errno ("Failed connect", Qnil, xerrno);
3527 break;
3529 #endif /* !WINDOWSNT */
3531 immediate_quit = 0;
3533 /* Discard the unwind protect closing S. */
3534 specpdl_ptr = specpdl + count1;
3535 emacs_close (s);
3536 s = -1;
3538 #ifdef WINDOWSNT
3539 if (xerrno == EINTR)
3540 goto retry_connect;
3541 #endif
3544 if (s >= 0)
3546 #ifdef DATAGRAM_SOCKETS
3547 if (socktype == SOCK_DGRAM)
3549 if (datagram_address[s].sa)
3550 emacs_abort ();
3551 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3552 datagram_address[s].len = lres->ai_addrlen;
3553 if (is_server)
3555 Lisp_Object remote;
3556 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3557 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3559 int rfamily, rlen;
3560 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3561 if (rlen != 0 && rfamily == lres->ai_family
3562 && rlen == lres->ai_addrlen)
3563 conv_lisp_to_sockaddr (rfamily, remote,
3564 datagram_address[s].sa, rlen);
3567 else
3568 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3570 #endif
3571 contact = Fplist_put (contact, colon_address,
3572 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3573 #ifdef HAVE_GETSOCKNAME
3574 if (!is_server)
3576 struct sockaddr_in sa1;
3577 socklen_t len1 = sizeof (sa1);
3578 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3579 contact = Fplist_put (contact, QClocal,
3580 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3582 #endif
3585 immediate_quit = 0;
3587 #ifdef HAVE_GETADDRINFO
3588 if (res != &ai)
3590 block_input ();
3591 freeaddrinfo (res);
3592 unblock_input ();
3594 #endif
3596 if (s < 0)
3598 /* If non-blocking got this far - and failed - assume non-blocking is
3599 not supported after all. This is probably a wrong assumption, but
3600 the normal blocking calls to open-network-stream handles this error
3601 better. */
3602 if (is_non_blocking_client)
3603 return Qnil;
3605 report_file_errno ((is_server
3606 ? "make server process failed"
3607 : "make client process failed"),
3608 contact, xerrno);
3611 inch = s;
3612 outch = s;
3614 if (!NILP (buffer))
3615 buffer = Fget_buffer_create (buffer);
3616 proc = make_process (name);
3618 chan_process[inch] = proc;
3620 fcntl (inch, F_SETFL, O_NONBLOCK);
3622 p = XPROCESS (proc);
3624 pset_childp (p, contact);
3625 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3626 pset_type (p, Qnetwork);
3628 pset_buffer (p, buffer);
3629 pset_sentinel (p, sentinel);
3630 pset_filter (p, filter);
3631 pset_log (p, Fplist_get (contact, QClog));
3632 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3633 p->kill_without_query = 1;
3634 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3635 pset_command (p, Qt);
3636 p->pid = 0;
3638 p->open_fd[SUBPROCESS_STDIN] = inch;
3639 p->infd = inch;
3640 p->outfd = outch;
3642 /* Discard the unwind protect for closing S, if any. */
3643 specpdl_ptr = specpdl + count1;
3645 /* Unwind bind_polling_period and request_sigio. */
3646 unbind_to (count, Qnil);
3648 if (is_server && socktype != SOCK_DGRAM)
3649 pset_status (p, Qlisten);
3651 /* Make the process marker point into the process buffer (if any). */
3652 if (BUFFERP (buffer))
3653 set_marker_both (p->mark, buffer,
3654 BUF_ZV (XBUFFER (buffer)),
3655 BUF_ZV_BYTE (XBUFFER (buffer)));
3657 #ifdef NON_BLOCKING_CONNECT
3658 if (is_non_blocking_client)
3660 /* We may get here if connect did succeed immediately. However,
3661 in that case, we still need to signal this like a non-blocking
3662 connection. */
3663 pset_status (p, Qconnect);
3664 if (!FD_ISSET (inch, &connect_wait_mask))
3666 FD_SET (inch, &connect_wait_mask);
3667 FD_SET (inch, &write_mask);
3668 num_pending_connects++;
3671 else
3672 #endif
3673 /* A server may have a client filter setting of Qt, but it must
3674 still listen for incoming connects unless it is stopped. */
3675 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3676 || (EQ (p->status, Qlisten) && NILP (p->command)))
3678 FD_SET (inch, &input_wait_mask);
3679 FD_SET (inch, &non_keyboard_wait_mask);
3682 if (inch > max_process_desc)
3683 max_process_desc = inch;
3685 tem = Fplist_member (contact, QCcoding);
3686 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3687 tem = Qnil; /* No error message (too late!). */
3690 /* Setup coding systems for communicating with the network stream. */
3691 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3692 Lisp_Object coding_systems = Qt;
3693 Lisp_Object val;
3695 if (!NILP (tem))
3697 val = XCAR (XCDR (tem));
3698 if (CONSP (val))
3699 val = XCAR (val);
3701 else if (!NILP (Vcoding_system_for_read))
3702 val = Vcoding_system_for_read;
3703 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3704 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3705 /* We dare not decode end-of-line format by setting VAL to
3706 Qraw_text, because the existing Emacs Lisp libraries
3707 assume that they receive bare code including a sequence of
3708 CR LF. */
3709 val = Qnil;
3710 else
3712 if (NILP (host) || NILP (service))
3713 coding_systems = Qnil;
3714 else
3715 coding_systems = CALLN (Ffind_operation_coding_system,
3716 Qopen_network_stream, name, buffer,
3717 host, service);
3718 if (CONSP (coding_systems))
3719 val = XCAR (coding_systems);
3720 else if (CONSP (Vdefault_process_coding_system))
3721 val = XCAR (Vdefault_process_coding_system);
3722 else
3723 val = Qnil;
3725 pset_decode_coding_system (p, val);
3727 if (!NILP (tem))
3729 val = XCAR (XCDR (tem));
3730 if (CONSP (val))
3731 val = XCDR (val);
3733 else if (!NILP (Vcoding_system_for_write))
3734 val = Vcoding_system_for_write;
3735 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3736 val = Qnil;
3737 else
3739 if (EQ (coding_systems, Qt))
3741 if (NILP (host) || NILP (service))
3742 coding_systems = Qnil;
3743 else
3744 coding_systems = CALLN (Ffind_operation_coding_system,
3745 Qopen_network_stream, name, buffer,
3746 host, service);
3748 if (CONSP (coding_systems))
3749 val = XCDR (coding_systems);
3750 else if (CONSP (Vdefault_process_coding_system))
3751 val = XCDR (Vdefault_process_coding_system);
3752 else
3753 val = Qnil;
3755 pset_encode_coding_system (p, val);
3757 setup_process_coding_systems (proc);
3759 pset_decoding_buf (p, empty_unibyte_string);
3760 p->decoding_carryover = 0;
3761 pset_encoding_buf (p, empty_unibyte_string);
3763 p->inherit_coding_system_flag
3764 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3766 return proc;
3770 #ifdef HAVE_NET_IF_H
3772 #ifdef SIOCGIFCONF
3773 static Lisp_Object
3774 network_interface_list (void)
3776 struct ifconf ifconf;
3777 struct ifreq *ifreq;
3778 void *buf = NULL;
3779 ptrdiff_t buf_size = 512;
3780 int s;
3781 Lisp_Object res;
3782 ptrdiff_t count;
3784 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3785 if (s < 0)
3786 return Qnil;
3787 count = SPECPDL_INDEX ();
3788 record_unwind_protect_int (close_file_unwind, s);
3792 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3793 ifconf.ifc_buf = buf;
3794 ifconf.ifc_len = buf_size;
3795 if (ioctl (s, SIOCGIFCONF, &ifconf))
3797 emacs_close (s);
3798 xfree (buf);
3799 return Qnil;
3802 while (ifconf.ifc_len == buf_size);
3804 res = unbind_to (count, Qnil);
3805 ifreq = ifconf.ifc_req;
3806 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3808 struct ifreq *ifq = ifreq;
3809 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3810 #define SIZEOF_IFREQ(sif) \
3811 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3812 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3814 int len = SIZEOF_IFREQ (ifq);
3815 #else
3816 int len = sizeof (*ifreq);
3817 #endif
3818 char namebuf[sizeof (ifq->ifr_name) + 1];
3819 ifreq = (struct ifreq *) ((char *) ifreq + len);
3821 if (ifq->ifr_addr.sa_family != AF_INET)
3822 continue;
3824 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3825 namebuf[sizeof (ifq->ifr_name)] = 0;
3826 res = Fcons (Fcons (build_string (namebuf),
3827 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3828 sizeof (struct sockaddr))),
3829 res);
3832 xfree (buf);
3833 return res;
3835 #endif /* SIOCGIFCONF */
3837 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3839 struct ifflag_def {
3840 int flag_bit;
3841 const char *flag_sym;
3844 static const struct ifflag_def ifflag_table[] = {
3845 #ifdef IFF_UP
3846 { IFF_UP, "up" },
3847 #endif
3848 #ifdef IFF_BROADCAST
3849 { IFF_BROADCAST, "broadcast" },
3850 #endif
3851 #ifdef IFF_DEBUG
3852 { IFF_DEBUG, "debug" },
3853 #endif
3854 #ifdef IFF_LOOPBACK
3855 { IFF_LOOPBACK, "loopback" },
3856 #endif
3857 #ifdef IFF_POINTOPOINT
3858 { IFF_POINTOPOINT, "pointopoint" },
3859 #endif
3860 #ifdef IFF_RUNNING
3861 { IFF_RUNNING, "running" },
3862 #endif
3863 #ifdef IFF_NOARP
3864 { IFF_NOARP, "noarp" },
3865 #endif
3866 #ifdef IFF_PROMISC
3867 { IFF_PROMISC, "promisc" },
3868 #endif
3869 #ifdef IFF_NOTRAILERS
3870 #ifdef NS_IMPL_COCOA
3871 /* Really means smart, notrailers is obsolete. */
3872 { IFF_NOTRAILERS, "smart" },
3873 #else
3874 { IFF_NOTRAILERS, "notrailers" },
3875 #endif
3876 #endif
3877 #ifdef IFF_ALLMULTI
3878 { IFF_ALLMULTI, "allmulti" },
3879 #endif
3880 #ifdef IFF_MASTER
3881 { IFF_MASTER, "master" },
3882 #endif
3883 #ifdef IFF_SLAVE
3884 { IFF_SLAVE, "slave" },
3885 #endif
3886 #ifdef IFF_MULTICAST
3887 { IFF_MULTICAST, "multicast" },
3888 #endif
3889 #ifdef IFF_PORTSEL
3890 { IFF_PORTSEL, "portsel" },
3891 #endif
3892 #ifdef IFF_AUTOMEDIA
3893 { IFF_AUTOMEDIA, "automedia" },
3894 #endif
3895 #ifdef IFF_DYNAMIC
3896 { IFF_DYNAMIC, "dynamic" },
3897 #endif
3898 #ifdef IFF_OACTIVE
3899 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
3900 #endif
3901 #ifdef IFF_SIMPLEX
3902 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
3903 #endif
3904 #ifdef IFF_LINK0
3905 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
3906 #endif
3907 #ifdef IFF_LINK1
3908 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
3909 #endif
3910 #ifdef IFF_LINK2
3911 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
3912 #endif
3913 { 0, 0 }
3916 static Lisp_Object
3917 network_interface_info (Lisp_Object ifname)
3919 struct ifreq rq;
3920 Lisp_Object res = Qnil;
3921 Lisp_Object elt;
3922 int s;
3923 bool any = 0;
3924 ptrdiff_t count;
3925 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3926 && defined HAVE_GETIFADDRS && defined LLADDR)
3927 struct ifaddrs *ifap;
3928 #endif
3930 CHECK_STRING (ifname);
3932 if (sizeof rq.ifr_name <= SBYTES (ifname))
3933 error ("interface name too long");
3934 lispstpcpy (rq.ifr_name, ifname);
3936 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3937 if (s < 0)
3938 return Qnil;
3939 count = SPECPDL_INDEX ();
3940 record_unwind_protect_int (close_file_unwind, s);
3942 elt = Qnil;
3943 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3944 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3946 int flags = rq.ifr_flags;
3947 const struct ifflag_def *fp;
3948 int fnum;
3950 /* If flags is smaller than int (i.e. short) it may have the high bit set
3951 due to IFF_MULTICAST. In that case, sign extending it into
3952 an int is wrong. */
3953 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3954 flags = (unsigned short) rq.ifr_flags;
3956 any = 1;
3957 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3959 if (flags & fp->flag_bit)
3961 elt = Fcons (intern (fp->flag_sym), elt);
3962 flags -= fp->flag_bit;
3965 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3967 if (flags & 1)
3969 elt = Fcons (make_number (fnum), elt);
3973 #endif
3974 res = Fcons (elt, res);
3976 elt = Qnil;
3977 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3978 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3980 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3981 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3982 int n;
3984 any = 1;
3985 for (n = 0; n < 6; n++)
3986 p->contents[n] = make_number (((unsigned char *)
3987 &rq.ifr_hwaddr.sa_data[0])
3988 [n]);
3989 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3991 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3992 if (getifaddrs (&ifap) != -1)
3994 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3995 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3996 struct ifaddrs *it;
3998 for (it = ifap; it != NULL; it = it->ifa_next)
4000 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
4001 unsigned char linkaddr[6];
4002 int n;
4004 if (it->ifa_addr->sa_family != AF_LINK
4005 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4006 || sdl->sdl_alen != 6)
4007 continue;
4009 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4010 for (n = 0; n < 6; n++)
4011 p->contents[n] = make_number (linkaddr[n]);
4013 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4014 break;
4017 #ifdef HAVE_FREEIFADDRS
4018 freeifaddrs (ifap);
4019 #endif
4021 #endif /* HAVE_GETIFADDRS && LLADDR */
4023 res = Fcons (elt, res);
4025 elt = Qnil;
4026 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4027 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4029 any = 1;
4030 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4031 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4032 #else
4033 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4034 #endif
4036 #endif
4037 res = Fcons (elt, res);
4039 elt = Qnil;
4040 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4041 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4043 any = 1;
4044 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4046 #endif
4047 res = Fcons (elt, res);
4049 elt = Qnil;
4050 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4051 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4053 any = 1;
4054 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4056 #endif
4057 res = Fcons (elt, res);
4059 return unbind_to (count, any ? res : Qnil);
4061 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4062 #endif /* defined (HAVE_NET_IF_H) */
4064 DEFUN ("network-interface-list", Fnetwork_interface_list,
4065 Snetwork_interface_list, 0, 0, 0,
4066 doc: /* Return an alist of all network interfaces and their network address.
4067 Each element is a cons, the car of which is a string containing the
4068 interface name, and the cdr is the network address in internal
4069 format; see the description of ADDRESS in `make-network-process'.
4071 If the information is not available, return nil. */)
4072 (void)
4074 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4075 return network_interface_list ();
4076 #else
4077 return Qnil;
4078 #endif
4081 DEFUN ("network-interface-info", Fnetwork_interface_info,
4082 Snetwork_interface_info, 1, 1, 0,
4083 doc: /* Return information about network interface named IFNAME.
4084 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4085 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4086 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4087 FLAGS is the current flags of the interface.
4089 Data that is unavailable is returned as nil. */)
4090 (Lisp_Object ifname)
4092 #if ((defined HAVE_NET_IF_H \
4093 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4094 || defined SIOCGIFFLAGS)) \
4095 || defined WINDOWSNT)
4096 return network_interface_info (ifname);
4097 #else
4098 return Qnil;
4099 #endif
4102 /* Turn off input and output for process PROC. */
4104 static void
4105 deactivate_process (Lisp_Object proc)
4107 int inchannel;
4108 struct Lisp_Process *p = XPROCESS (proc);
4109 int i;
4111 #ifdef HAVE_GNUTLS
4112 /* Delete GnuTLS structures in PROC, if any. */
4113 emacs_gnutls_deinit (proc);
4114 #endif /* HAVE_GNUTLS */
4116 if (p->read_output_delay > 0)
4118 if (--process_output_delay_count < 0)
4119 process_output_delay_count = 0;
4120 p->read_output_delay = 0;
4121 p->read_output_skip = 0;
4124 /* Beware SIGCHLD hereabouts. */
4126 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4127 close_process_fd (&p->open_fd[i]);
4129 inchannel = p->infd;
4130 if (inchannel >= 0)
4132 p->infd = -1;
4133 p->outfd = -1;
4134 #ifdef DATAGRAM_SOCKETS
4135 if (DATAGRAM_CHAN_P (inchannel))
4137 xfree (datagram_address[inchannel].sa);
4138 datagram_address[inchannel].sa = 0;
4139 datagram_address[inchannel].len = 0;
4141 #endif
4142 chan_process[inchannel] = Qnil;
4143 FD_CLR (inchannel, &input_wait_mask);
4144 FD_CLR (inchannel, &non_keyboard_wait_mask);
4145 #ifdef NON_BLOCKING_CONNECT
4146 if (FD_ISSET (inchannel, &connect_wait_mask))
4148 FD_CLR (inchannel, &connect_wait_mask);
4149 FD_CLR (inchannel, &write_mask);
4150 if (--num_pending_connects < 0)
4151 emacs_abort ();
4153 #endif
4154 if (inchannel == max_process_desc)
4156 /* We just closed the highest-numbered process input descriptor,
4157 so recompute the highest-numbered one now. */
4158 int i = inchannel;
4160 i--;
4161 while (0 <= i && NILP (chan_process[i]));
4163 max_process_desc = i;
4169 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4170 0, 4, 0,
4171 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4172 It is given to their filter functions.
4173 Optional argument PROCESS means do not return until output has been
4174 received from PROCESS.
4176 Optional second argument SECONDS and third argument MILLISEC
4177 specify a timeout; return after that much time even if there is
4178 no subprocess output. If SECONDS is a floating point number,
4179 it specifies a fractional number of seconds to wait.
4180 The MILLISEC argument is obsolete and should be avoided.
4182 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4183 from PROCESS only, suspending reading output from other processes.
4184 If JUST-THIS-ONE is an integer, don't run any timers either.
4185 Return non-nil if we received any output from PROCESS (or, if PROCESS
4186 is nil, from any process) before the timeout expired. */)
4187 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4189 intmax_t secs;
4190 int nsecs;
4192 if (! NILP (process))
4193 CHECK_PROCESS (process);
4194 else
4195 just_this_one = Qnil;
4197 if (!NILP (millisec))
4198 { /* Obsolete calling convention using integers rather than floats. */
4199 CHECK_NUMBER (millisec);
4200 if (NILP (seconds))
4201 seconds = make_float (XINT (millisec) / 1000.0);
4202 else
4204 CHECK_NUMBER (seconds);
4205 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4209 secs = 0;
4210 nsecs = -1;
4212 if (!NILP (seconds))
4214 if (INTEGERP (seconds))
4216 if (XINT (seconds) > 0)
4218 secs = XINT (seconds);
4219 nsecs = 0;
4222 else if (FLOATP (seconds))
4224 if (XFLOAT_DATA (seconds) > 0)
4226 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4227 secs = min (t.tv_sec, WAIT_READING_MAX);
4228 nsecs = t.tv_nsec;
4231 else
4232 wrong_type_argument (Qnumberp, seconds);
4234 else if (! NILP (process))
4235 nsecs = 0;
4237 return
4238 ((wait_reading_process_output (secs, nsecs, 0, 0,
4239 Qnil,
4240 !NILP (process) ? XPROCESS (process) : NULL,
4241 (NILP (just_this_one) ? 0
4242 : !INTEGERP (just_this_one) ? 1 : -1))
4243 <= 0)
4244 ? Qnil : Qt);
4247 /* Accept a connection for server process SERVER on CHANNEL. */
4249 static EMACS_INT connect_counter = 0;
4251 static void
4252 server_accept_connection (Lisp_Object server, int channel)
4254 Lisp_Object proc, caller, name, buffer;
4255 Lisp_Object contact, host, service;
4256 struct Lisp_Process *ps = XPROCESS (server);
4257 struct Lisp_Process *p;
4258 int s;
4259 union u_sockaddr {
4260 struct sockaddr sa;
4261 struct sockaddr_in in;
4262 #ifdef AF_INET6
4263 struct sockaddr_in6 in6;
4264 #endif
4265 #ifdef HAVE_LOCAL_SOCKETS
4266 struct sockaddr_un un;
4267 #endif
4268 } saddr;
4269 socklen_t len = sizeof saddr;
4270 ptrdiff_t count;
4272 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4274 if (s < 0)
4276 int code = errno;
4277 if (!would_block (code) && !NILP (ps->log))
4278 call3 (ps->log, server, Qnil,
4279 concat3 (build_string ("accept failed with code"),
4280 Fnumber_to_string (make_number (code)),
4281 build_string ("\n")));
4282 return;
4285 count = SPECPDL_INDEX ();
4286 record_unwind_protect_int (close_file_unwind, s);
4288 connect_counter++;
4290 /* Setup a new process to handle the connection. */
4292 /* Generate a unique identification of the caller, and build contact
4293 information for this process. */
4294 host = Qt;
4295 service = Qnil;
4296 switch (saddr.sa.sa_family)
4298 case AF_INET:
4300 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4302 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4303 host = CALLN (Fformat, ipv4_format,
4304 make_number (ip[0]), make_number (ip[1]),
4305 make_number (ip[2]), make_number (ip[3]));
4306 service = make_number (ntohs (saddr.in.sin_port));
4307 AUTO_STRING (caller_format, " <%s:%d>");
4308 caller = CALLN (Fformat, caller_format, host, service);
4310 break;
4312 #ifdef AF_INET6
4313 case AF_INET6:
4315 Lisp_Object args[9];
4316 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4317 int i;
4319 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4320 args[0] = ipv6_format;
4321 for (i = 0; i < 8; i++)
4322 args[i + 1] = make_number (ntohs (ip6[i]));
4323 host = CALLMANY (Fformat, args);
4324 service = make_number (ntohs (saddr.in.sin_port));
4325 AUTO_STRING (caller_format, " <[%s]:%d>");
4326 caller = CALLN (Fformat, caller_format, host, service);
4328 break;
4329 #endif
4331 #ifdef HAVE_LOCAL_SOCKETS
4332 case AF_LOCAL:
4333 #endif
4334 default:
4335 caller = Fnumber_to_string (make_number (connect_counter));
4336 AUTO_STRING (space_less_than, " <");
4337 AUTO_STRING (greater_than, ">");
4338 caller = concat3 (space_less_than, caller, greater_than);
4339 break;
4342 /* Create a new buffer name for this process if it doesn't have a
4343 filter. The new buffer name is based on the buffer name or
4344 process name of the server process concatenated with the caller
4345 identification. */
4347 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4348 || EQ (ps->filter, Qt)))
4349 buffer = Qnil;
4350 else
4352 buffer = ps->buffer;
4353 if (!NILP (buffer))
4354 buffer = Fbuffer_name (buffer);
4355 else
4356 buffer = ps->name;
4357 if (!NILP (buffer))
4359 buffer = concat2 (buffer, caller);
4360 buffer = Fget_buffer_create (buffer);
4364 /* Generate a unique name for the new server process. Combine the
4365 server process name with the caller identification. */
4367 name = concat2 (ps->name, caller);
4368 proc = make_process (name);
4370 chan_process[s] = proc;
4372 fcntl (s, F_SETFL, O_NONBLOCK);
4374 p = XPROCESS (proc);
4376 /* Build new contact information for this setup. */
4377 contact = Fcopy_sequence (ps->childp);
4378 contact = Fplist_put (contact, QCserver, Qnil);
4379 contact = Fplist_put (contact, QChost, host);
4380 if (!NILP (service))
4381 contact = Fplist_put (contact, QCservice, service);
4382 contact = Fplist_put (contact, QCremote,
4383 conv_sockaddr_to_lisp (&saddr.sa, len));
4384 #ifdef HAVE_GETSOCKNAME
4385 len = sizeof saddr;
4386 if (getsockname (s, &saddr.sa, &len) == 0)
4387 contact = Fplist_put (contact, QClocal,
4388 conv_sockaddr_to_lisp (&saddr.sa, len));
4389 #endif
4391 pset_childp (p, contact);
4392 pset_plist (p, Fcopy_sequence (ps->plist));
4393 pset_type (p, Qnetwork);
4395 pset_buffer (p, buffer);
4396 pset_sentinel (p, ps->sentinel);
4397 pset_filter (p, ps->filter);
4398 pset_command (p, Qnil);
4399 p->pid = 0;
4401 /* Discard the unwind protect for closing S. */
4402 specpdl_ptr = specpdl + count;
4404 p->open_fd[SUBPROCESS_STDIN] = s;
4405 p->infd = s;
4406 p->outfd = s;
4407 pset_status (p, Qrun);
4409 /* Client processes for accepted connections are not stopped initially. */
4410 if (!EQ (p->filter, Qt))
4412 FD_SET (s, &input_wait_mask);
4413 FD_SET (s, &non_keyboard_wait_mask);
4416 if (s > max_process_desc)
4417 max_process_desc = s;
4419 /* Setup coding system for new process based on server process.
4420 This seems to be the proper thing to do, as the coding system
4421 of the new process should reflect the settings at the time the
4422 server socket was opened; not the current settings. */
4424 pset_decode_coding_system (p, ps->decode_coding_system);
4425 pset_encode_coding_system (p, ps->encode_coding_system);
4426 setup_process_coding_systems (proc);
4428 pset_decoding_buf (p, empty_unibyte_string);
4429 p->decoding_carryover = 0;
4430 pset_encoding_buf (p, empty_unibyte_string);
4432 p->inherit_coding_system_flag
4433 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4435 AUTO_STRING (dash, "-");
4436 AUTO_STRING (nl, "\n");
4437 Lisp_Object host_string = STRINGP (host) ? host : dash;
4439 if (!NILP (ps->log))
4441 AUTO_STRING (accept_from, "accept from ");
4442 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4445 AUTO_STRING (open_from, "open from ");
4446 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4449 /* This variable is different from waiting_for_input in keyboard.c.
4450 It is used to communicate to a lisp process-filter/sentinel (via the
4451 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4452 for user-input when that process-filter was called.
4453 waiting_for_input cannot be used as that is by definition 0 when
4454 lisp code is being evalled.
4455 This is also used in record_asynch_buffer_change.
4456 For that purpose, this must be 0
4457 when not inside wait_reading_process_output. */
4458 static int waiting_for_user_input_p;
4460 static void
4461 wait_reading_process_output_unwind (int data)
4463 waiting_for_user_input_p = data;
4466 /* This is here so breakpoints can be put on it. */
4467 static void
4468 wait_reading_process_output_1 (void)
4472 /* Read and dispose of subprocess output while waiting for timeout to
4473 elapse and/or keyboard input to be available.
4475 TIME_LIMIT is:
4476 timeout in seconds
4477 If negative, gobble data immediately available but don't wait for any.
4479 NSECS is:
4480 an additional duration to wait, measured in nanoseconds
4481 If TIME_LIMIT is zero, then:
4482 If NSECS == 0, there is no limit.
4483 If NSECS > 0, the timeout consists of NSECS only.
4484 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4486 READ_KBD is:
4487 0 to ignore keyboard input, or
4488 1 to return when input is available, or
4489 -1 meaning caller will actually read the input, so don't throw to
4490 the quit handler, or
4492 DO_DISPLAY means redisplay should be done to show subprocess
4493 output that arrives.
4495 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4496 (and gobble terminal input into the buffer if any arrives).
4498 If WAIT_PROC is specified, wait until something arrives from that
4499 process.
4501 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4502 (suspending output from other processes). A negative value
4503 means don't run any timers either.
4505 Return positive if we received input from WAIT_PROC (or from any
4506 process if WAIT_PROC is null), zero if we attempted to receive
4507 input but got none, and negative if we didn't even try. */
4510 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4511 bool do_display,
4512 Lisp_Object wait_for_cell,
4513 struct Lisp_Process *wait_proc, int just_wait_proc)
4515 int channel, nfds;
4516 fd_set Available;
4517 fd_set Writeok;
4518 bool check_write;
4519 int check_delay;
4520 bool no_avail;
4521 int xerrno;
4522 Lisp_Object proc;
4523 struct timespec timeout, end_time, timer_delay;
4524 struct timespec got_output_end_time = invalid_timespec ();
4525 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
4526 int got_some_output = -1;
4527 ptrdiff_t count = SPECPDL_INDEX ();
4529 /* Close to the current time if known, an invalid timespec otherwise. */
4530 struct timespec now = invalid_timespec ();
4532 FD_ZERO (&Available);
4533 FD_ZERO (&Writeok);
4535 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4536 && !(CONSP (wait_proc->status)
4537 && EQ (XCAR (wait_proc->status), Qexit)))
4538 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4540 record_unwind_protect_int (wait_reading_process_output_unwind,
4541 waiting_for_user_input_p);
4542 waiting_for_user_input_p = read_kbd;
4544 if (TYPE_MAXIMUM (time_t) < time_limit)
4545 time_limit = TYPE_MAXIMUM (time_t);
4547 if (time_limit < 0 || nsecs < 0)
4548 wait = MINIMUM;
4549 else if (time_limit > 0 || nsecs > 0)
4551 wait = TIMEOUT;
4552 now = current_timespec ();
4553 end_time = timespec_add (now, make_timespec (time_limit, nsecs));
4555 else
4556 wait = INFINITY;
4558 while (1)
4560 bool process_skipped = false;
4562 /* If calling from keyboard input, do not quit
4563 since we want to return C-g as an input character.
4564 Otherwise, do pending quit if requested. */
4565 if (read_kbd >= 0)
4566 QUIT;
4567 else if (pending_signals)
4568 process_pending_signals ();
4570 /* Exit now if the cell we're waiting for became non-nil. */
4571 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4572 break;
4574 /* Compute time from now till when time limit is up. */
4575 /* Exit if already run out. */
4576 if (wait == TIMEOUT)
4578 if (!timespec_valid_p (now))
4579 now = current_timespec ();
4580 if (timespec_cmp (end_time, now) <= 0)
4581 break;
4582 timeout = timespec_sub (end_time, now);
4584 else
4585 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
4587 /* Normally we run timers here.
4588 But not if wait_for_cell; in those cases,
4589 the wait is supposed to be short,
4590 and those callers cannot handle running arbitrary Lisp code here. */
4591 if (NILP (wait_for_cell)
4592 && just_wait_proc >= 0)
4596 unsigned old_timers_run = timers_run;
4597 struct buffer *old_buffer = current_buffer;
4598 Lisp_Object old_window = selected_window;
4600 timer_delay = timer_check ();
4602 /* If a timer has run, this might have changed buffers
4603 an alike. Make read_key_sequence aware of that. */
4604 if (timers_run != old_timers_run
4605 && (old_buffer != current_buffer
4606 || !EQ (old_window, selected_window))
4607 && waiting_for_user_input_p == -1)
4608 record_asynch_buffer_change ();
4610 if (timers_run != old_timers_run && do_display)
4611 /* We must retry, since a timer may have requeued itself
4612 and that could alter the time_delay. */
4613 redisplay_preserve_echo_area (9);
4614 else
4615 break;
4617 while (!detect_input_pending ());
4619 /* If there is unread keyboard input, also return. */
4620 if (read_kbd != 0
4621 && requeued_events_pending_p ())
4622 break;
4624 /* This is so a breakpoint can be put here. */
4625 if (!timespec_valid_p (timer_delay))
4626 wait_reading_process_output_1 ();
4629 /* Cause C-g and alarm signals to take immediate action,
4630 and cause input available signals to zero out timeout.
4632 It is important that we do this before checking for process
4633 activity. If we get a SIGCHLD after the explicit checks for
4634 process activity, timeout is the only way we will know. */
4635 if (read_kbd < 0)
4636 set_waiting_for_input (&timeout);
4638 /* If status of something has changed, and no input is
4639 available, notify the user of the change right away. After
4640 this explicit check, we'll let the SIGCHLD handler zap
4641 timeout to get our attention. */
4642 if (update_tick != process_tick)
4644 fd_set Atemp;
4645 fd_set Ctemp;
4647 if (kbd_on_hold_p ())
4648 FD_ZERO (&Atemp);
4649 else
4650 Atemp = input_wait_mask;
4651 Ctemp = write_mask;
4653 timeout = make_timespec (0, 0);
4654 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4655 &Atemp,
4656 #ifdef NON_BLOCKING_CONNECT
4657 (num_pending_connects > 0 ? &Ctemp : NULL),
4658 #else
4659 NULL,
4660 #endif
4661 NULL, &timeout, NULL)
4662 <= 0))
4664 /* It's okay for us to do this and then continue with
4665 the loop, since timeout has already been zeroed out. */
4666 clear_waiting_for_input ();
4667 got_some_output = status_notify (NULL, wait_proc);
4668 if (do_display) redisplay_preserve_echo_area (13);
4672 /* Don't wait for output from a non-running process. Just
4673 read whatever data has already been received. */
4674 if (wait_proc && wait_proc->raw_status_new)
4675 update_status (wait_proc);
4676 if (wait_proc
4677 && ! EQ (wait_proc->status, Qrun)
4678 && ! EQ (wait_proc->status, Qconnect))
4680 bool read_some_bytes = false;
4682 clear_waiting_for_input ();
4684 /* If data can be read from the process, do so until exhausted. */
4685 if (wait_proc->infd >= 0)
4687 XSETPROCESS (proc, wait_proc);
4689 while (true)
4691 int nread = read_process_output (proc, wait_proc->infd);
4692 if (nread < 0)
4694 if (errno == EIO || would_block (errno))
4695 break;
4697 else
4699 if (got_some_output < nread)
4700 got_some_output = nread;
4701 if (nread == 0)
4702 break;
4703 read_some_bytes = true;
4708 if (read_some_bytes && do_display)
4709 redisplay_preserve_echo_area (10);
4711 break;
4714 /* Wait till there is something to do. */
4716 if (wait_proc && just_wait_proc)
4718 if (wait_proc->infd < 0) /* Terminated. */
4719 break;
4720 FD_SET (wait_proc->infd, &Available);
4721 check_delay = 0;
4722 check_write = 0;
4724 else if (!NILP (wait_for_cell))
4726 Available = non_process_wait_mask;
4727 check_delay = 0;
4728 check_write = 0;
4730 else
4732 if (! read_kbd)
4733 Available = non_keyboard_wait_mask;
4734 else
4735 Available = input_wait_mask;
4736 Writeok = write_mask;
4737 check_delay = wait_proc ? 0 : process_output_delay_count;
4738 check_write = true;
4741 /* If frame size has changed or the window is newly mapped,
4742 redisplay now, before we start to wait. There is a race
4743 condition here; if a SIGIO arrives between now and the select
4744 and indicates that a frame is trashed, the select may block
4745 displaying a trashed screen. */
4746 if (frame_garbaged && do_display)
4748 clear_waiting_for_input ();
4749 redisplay_preserve_echo_area (11);
4750 if (read_kbd < 0)
4751 set_waiting_for_input (&timeout);
4754 /* Skip the `select' call if input is available and we're
4755 waiting for keyboard input or a cell change (which can be
4756 triggered by processing X events). In the latter case, set
4757 nfds to 1 to avoid breaking the loop. */
4758 no_avail = 0;
4759 if ((read_kbd || !NILP (wait_for_cell))
4760 && detect_input_pending ())
4762 nfds = read_kbd ? 0 : 1;
4763 no_avail = 1;
4764 FD_ZERO (&Available);
4766 else
4768 /* Set the timeout for adaptive read buffering if any
4769 process has non-zero read_output_skip and non-zero
4770 read_output_delay, and we are not reading output for a
4771 specific process. It is not executed if
4772 Vprocess_adaptive_read_buffering is nil. */
4773 if (process_output_skip && check_delay > 0)
4775 int adaptive_nsecs = timeout.tv_nsec;
4776 if (timeout.tv_sec > 0 || adaptive_nsecs > READ_OUTPUT_DELAY_MAX)
4777 adaptive_nsecs = READ_OUTPUT_DELAY_MAX;
4778 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4780 proc = chan_process[channel];
4781 if (NILP (proc))
4782 continue;
4783 /* Find minimum non-zero read_output_delay among the
4784 processes with non-zero read_output_skip. */
4785 if (XPROCESS (proc)->read_output_delay > 0)
4787 check_delay--;
4788 if (!XPROCESS (proc)->read_output_skip)
4789 continue;
4790 FD_CLR (channel, &Available);
4791 process_skipped = true;
4792 XPROCESS (proc)->read_output_skip = 0;
4793 if (XPROCESS (proc)->read_output_delay < adaptive_nsecs)
4794 adaptive_nsecs = XPROCESS (proc)->read_output_delay;
4797 timeout = make_timespec (0, adaptive_nsecs);
4798 process_output_skip = 0;
4801 /* If we've got some output and haven't limited our timeout
4802 with adaptive read buffering, limit it. */
4803 if (got_some_output > 0 && !process_skipped
4804 && (timeout.tv_sec
4805 || timeout.tv_nsec > READ_OUTPUT_DELAY_INCREMENT))
4806 timeout = make_timespec (0, READ_OUTPUT_DELAY_INCREMENT);
4809 if (NILP (wait_for_cell) && just_wait_proc >= 0
4810 && timespec_valid_p (timer_delay)
4811 && timespec_cmp (timer_delay, timeout) < 0)
4813 if (!timespec_valid_p (now))
4814 now = current_timespec ();
4815 struct timespec timeout_abs = timespec_add (now, timeout);
4816 if (!timespec_valid_p (got_output_end_time)
4817 || timespec_cmp (timeout_abs, got_output_end_time) < 0)
4818 got_output_end_time = timeout_abs;
4819 timeout = timer_delay;
4821 else
4822 got_output_end_time = invalid_timespec ();
4824 /* NOW can become inaccurate if time can pass during pselect. */
4825 if (timeout.tv_sec > 0 || timeout.tv_nsec > 0)
4826 now = invalid_timespec ();
4828 #if defined (HAVE_NS)
4829 nfds = ns_select
4830 #elif defined (HAVE_GLIB)
4831 nfds = xg_select
4832 #else
4833 nfds = pselect
4834 #endif
4835 (max (max_process_desc, max_input_desc) + 1,
4836 &Available,
4837 (check_write ? &Writeok : 0),
4838 NULL, &timeout, NULL);
4840 #ifdef HAVE_GNUTLS
4841 /* GnuTLS buffers data internally. In lowat mode it leaves
4842 some data in the TCP buffers so that select works, but
4843 with custom pull/push functions we need to check if some
4844 data is available in the buffers manually. */
4845 if (nfds == 0)
4847 fd_set tls_available;
4848 int set = 0;
4850 FD_ZERO (&tls_available);
4851 if (! wait_proc)
4853 /* We're not waiting on a specific process, so loop
4854 through all the channels and check for data.
4855 This is a workaround needed for some versions of
4856 the gnutls library -- 2.12.14 has been confirmed
4857 to need it. See
4858 http://comments.gmane.org/gmane.emacs.devel/145074 */
4859 for (channel = 0; channel < FD_SETSIZE; ++channel)
4860 if (! NILP (chan_process[channel]))
4862 struct Lisp_Process *p =
4863 XPROCESS (chan_process[channel]);
4864 if (p && p->gnutls_p && p->gnutls_state
4865 && ((emacs_gnutls_record_check_pending
4866 (p->gnutls_state))
4867 > 0))
4869 nfds++;
4870 eassert (p->infd == channel);
4871 FD_SET (p->infd, &tls_available);
4872 set++;
4876 else
4878 /* Check this specific channel. */
4879 if (wait_proc->gnutls_p /* Check for valid process. */
4880 && wait_proc->gnutls_state
4881 /* Do we have pending data? */
4882 && ((emacs_gnutls_record_check_pending
4883 (wait_proc->gnutls_state))
4884 > 0))
4886 nfds = 1;
4887 eassert (0 <= wait_proc->infd);
4888 /* Set to Available. */
4889 FD_SET (wait_proc->infd, &tls_available);
4890 set++;
4893 if (set)
4894 Available = tls_available;
4896 #endif
4899 xerrno = errno;
4901 /* Make C-g and alarm signals set flags again. */
4902 clear_waiting_for_input ();
4904 /* If we woke up due to SIGWINCH, actually change size now. */
4905 do_pending_window_change (0);
4907 if (nfds == 0)
4909 /* Exit the main loop if we've passed the requested timeout,
4910 or aren't skipping processes and got some output and
4911 haven't lowered our timeout due to timers or SIGIO and
4912 have waited a long amount of time due to repeated
4913 timers. */
4914 struct timespec huge_timespec
4915 = make_timespec (TYPE_MAXIMUM (time_t), 2 * TIMESPEC_RESOLUTION);
4916 struct timespec cmp_time = huge_timespec;
4917 if (wait < TIMEOUT)
4918 break;
4919 if (wait == TIMEOUT)
4920 cmp_time = end_time;
4921 if (!process_skipped && got_some_output > 0
4922 && (timeout.tv_sec > 0 || timeout.tv_nsec > 0))
4924 if (!timespec_valid_p (got_output_end_time))
4925 break;
4926 if (timespec_cmp (got_output_end_time, cmp_time) < 0)
4927 cmp_time = got_output_end_time;
4929 if (timespec_cmp (cmp_time, huge_timespec) < 0)
4931 now = current_timespec ();
4932 if (timespec_cmp (cmp_time, now) <= 0)
4933 break;
4937 if (nfds < 0)
4939 if (xerrno == EINTR)
4940 no_avail = 1;
4941 else if (xerrno == EBADF)
4942 emacs_abort ();
4943 else
4944 report_file_errno ("Failed select", Qnil, xerrno);
4947 /* Check for keyboard input. */
4948 /* If there is any, return immediately
4949 to give it higher priority than subprocesses. */
4951 if (read_kbd != 0)
4953 unsigned old_timers_run = timers_run;
4954 struct buffer *old_buffer = current_buffer;
4955 Lisp_Object old_window = selected_window;
4956 bool leave = false;
4958 if (detect_input_pending_run_timers (do_display))
4960 swallow_events (do_display);
4961 if (detect_input_pending_run_timers (do_display))
4962 leave = true;
4965 /* If a timer has run, this might have changed buffers
4966 an alike. Make read_key_sequence aware of that. */
4967 if (timers_run != old_timers_run
4968 && waiting_for_user_input_p == -1
4969 && (old_buffer != current_buffer
4970 || !EQ (old_window, selected_window)))
4971 record_asynch_buffer_change ();
4973 if (leave)
4974 break;
4977 /* If there is unread keyboard input, also return. */
4978 if (read_kbd != 0
4979 && requeued_events_pending_p ())
4980 break;
4982 /* If we are not checking for keyboard input now,
4983 do process events (but don't run any timers).
4984 This is so that X events will be processed.
4985 Otherwise they may have to wait until polling takes place.
4986 That would causes delays in pasting selections, for example.
4988 (We used to do this only if wait_for_cell.) */
4989 if (read_kbd == 0 && detect_input_pending ())
4991 swallow_events (do_display);
4992 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4993 if (detect_input_pending ())
4994 break;
4995 #endif
4998 /* Exit now if the cell we're waiting for became non-nil. */
4999 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5000 break;
5002 #ifdef USABLE_SIGIO
5003 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5004 go read it. This can happen with X on BSD after logging out.
5005 In that case, there really is no input and no SIGIO,
5006 but select says there is input. */
5008 if (read_kbd && interrupt_input
5009 && keyboard_bit_set (&Available) && ! noninteractive)
5010 handle_input_available_signal (SIGIO);
5011 #endif
5013 /* If checking input just got us a size-change event from X,
5014 obey it now if we should. */
5015 if (read_kbd || ! NILP (wait_for_cell))
5016 do_pending_window_change (0);
5018 /* Check for data from a process. */
5019 if (no_avail || nfds == 0)
5020 continue;
5022 for (channel = 0; channel <= max_input_desc; ++channel)
5024 struct fd_callback_data *d = &fd_callback_info[channel];
5025 if (d->func
5026 && ((d->condition & FOR_READ
5027 && FD_ISSET (channel, &Available))
5028 || (d->condition & FOR_WRITE
5029 && FD_ISSET (channel, &write_mask))))
5030 d->func (channel, d->data);
5033 for (channel = 0; channel <= max_process_desc; channel++)
5035 if (FD_ISSET (channel, &Available)
5036 && FD_ISSET (channel, &non_keyboard_wait_mask)
5037 && !FD_ISSET (channel, &non_process_wait_mask))
5039 int nread;
5041 /* If waiting for this channel, arrange to return as
5042 soon as no more input to be processed. No more
5043 waiting. */
5044 proc = chan_process[channel];
5045 if (NILP (proc))
5046 continue;
5048 /* If this is a server stream socket, accept connection. */
5049 if (EQ (XPROCESS (proc)->status, Qlisten))
5051 server_accept_connection (proc, channel);
5052 continue;
5055 /* Read data from the process, starting with our
5056 buffered-ahead character if we have one. */
5058 nread = read_process_output (proc, channel);
5059 if ((!wait_proc || wait_proc == XPROCESS (proc))
5060 && got_some_output < nread)
5061 got_some_output = nread;
5062 if (nread > 0)
5064 /* Vacuum up any leftovers without waiting. */
5065 if (wait_proc == XPROCESS (proc))
5066 wait = MINIMUM;
5067 /* Since read_process_output can run a filter,
5068 which can call accept-process-output,
5069 don't try to read from any other processes
5070 before doing the select again. */
5071 FD_ZERO (&Available);
5073 if (do_display)
5074 redisplay_preserve_echo_area (12);
5076 else if (nread == -1 && would_block (errno))
5078 #ifdef WINDOWSNT
5079 /* FIXME: Is this special case still needed? */
5080 /* Note that we cannot distinguish between no input
5081 available now and a closed pipe.
5082 With luck, a closed pipe will be accompanied by
5083 subprocess termination and SIGCHLD. */
5084 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5085 && !PIPECONN_P (proc))
5087 #endif
5088 #ifdef HAVE_PTYS
5089 /* On some OSs with ptys, when the process on one end of
5090 a pty exits, the other end gets an error reading with
5091 errno = EIO instead of getting an EOF (0 bytes read).
5092 Therefore, if we get an error reading and errno =
5093 EIO, just continue, because the child process has
5094 exited and should clean itself up soon (e.g. when we
5095 get a SIGCHLD). */
5096 else if (nread == -1 && errno == EIO)
5098 struct Lisp_Process *p = XPROCESS (proc);
5100 /* Clear the descriptor now, so we only raise the
5101 signal once. */
5102 FD_CLR (channel, &input_wait_mask);
5103 FD_CLR (channel, &non_keyboard_wait_mask);
5105 if (p->pid == -2)
5107 /* If the EIO occurs on a pty, the SIGCHLD handler's
5108 waitpid call will not find the process object to
5109 delete. Do it here. */
5110 p->tick = ++process_tick;
5111 pset_status (p, Qfailed);
5114 #endif /* HAVE_PTYS */
5115 /* If we can detect process termination, don't consider the
5116 process gone just because its pipe is closed. */
5117 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5118 && !PIPECONN_P (proc))
5120 else if (nread == 0 && PIPECONN_P (proc))
5122 /* Preserve status of processes already terminated. */
5123 XPROCESS (proc)->tick = ++process_tick;
5124 deactivate_process (proc);
5125 if (EQ (XPROCESS (proc)->status, Qrun))
5126 pset_status (XPROCESS (proc),
5127 list2 (Qexit, make_number (0)));
5129 else
5131 /* Preserve status of processes already terminated. */
5132 XPROCESS (proc)->tick = ++process_tick;
5133 deactivate_process (proc);
5134 if (XPROCESS (proc)->raw_status_new)
5135 update_status (XPROCESS (proc));
5136 if (EQ (XPROCESS (proc)->status, Qrun))
5137 pset_status (XPROCESS (proc),
5138 list2 (Qexit, make_number (256)));
5141 #ifdef NON_BLOCKING_CONNECT
5142 if (FD_ISSET (channel, &Writeok)
5143 && FD_ISSET (channel, &connect_wait_mask))
5145 struct Lisp_Process *p;
5147 FD_CLR (channel, &connect_wait_mask);
5148 FD_CLR (channel, &write_mask);
5149 if (--num_pending_connects < 0)
5150 emacs_abort ();
5152 proc = chan_process[channel];
5153 if (NILP (proc))
5154 continue;
5156 p = XPROCESS (proc);
5158 #ifdef GNU_LINUX
5159 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5160 So only use it on systems where it is known to work. */
5162 socklen_t xlen = sizeof (xerrno);
5163 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5164 xerrno = errno;
5166 #else
5168 struct sockaddr pname;
5169 socklen_t pnamelen = sizeof (pname);
5171 /* If connection failed, getpeername will fail. */
5172 xerrno = 0;
5173 if (getpeername (channel, &pname, &pnamelen) < 0)
5175 /* Obtain connect failure code through error slippage. */
5176 char dummy;
5177 xerrno = errno;
5178 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5179 xerrno = errno;
5182 #endif
5183 if (xerrno)
5185 p->tick = ++process_tick;
5186 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5187 deactivate_process (proc);
5189 else
5191 pset_status (p, Qrun);
5192 /* Execute the sentinel here. If we had relied on
5193 status_notify to do it later, it will read input
5194 from the process before calling the sentinel. */
5195 exec_sentinel (proc, build_string ("open\n"));
5196 if (0 <= p->infd && !EQ (p->filter, Qt)
5197 && !EQ (p->command, Qt))
5199 FD_SET (p->infd, &input_wait_mask);
5200 FD_SET (p->infd, &non_keyboard_wait_mask);
5204 #endif /* NON_BLOCKING_CONNECT */
5205 } /* End for each file descriptor. */
5206 } /* End while exit conditions not met. */
5208 unbind_to (count, Qnil);
5210 /* If calling from keyboard input, do not quit
5211 since we want to return C-g as an input character.
5212 Otherwise, do pending quit if requested. */
5213 if (read_kbd >= 0)
5215 /* Prevent input_pending from remaining set if we quit. */
5216 clear_input_pending ();
5217 QUIT;
5220 return got_some_output;
5223 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5225 static Lisp_Object
5226 read_process_output_call (Lisp_Object fun_and_args)
5228 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5231 static Lisp_Object
5232 read_process_output_error_handler (Lisp_Object error_val)
5234 cmd_error_internal (error_val, "error in process filter: ");
5235 Vinhibit_quit = Qt;
5236 update_echo_area ();
5237 Fsleep_for (make_number (2), Qnil);
5238 return Qt;
5241 static void
5242 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5243 ssize_t nbytes,
5244 struct coding_system *coding);
5246 /* Read pending output from the process channel,
5247 starting with our buffered-ahead character if we have one.
5248 Yield number of decoded characters read.
5250 This function reads at most 4096 characters.
5251 If you want to read all available subprocess output,
5252 you must call it repeatedly until it returns zero.
5254 The characters read are decoded according to PROC's coding-system
5255 for decoding. */
5257 static int
5258 read_process_output (Lisp_Object proc, int channel)
5260 ssize_t nbytes;
5261 struct Lisp_Process *p = XPROCESS (proc);
5262 struct coding_system *coding = proc_decode_coding_system[channel];
5263 int carryover = p->decoding_carryover;
5264 enum { readmax = 4096 };
5265 ptrdiff_t count = SPECPDL_INDEX ();
5266 Lisp_Object odeactivate;
5267 char chars[sizeof coding->carryover + readmax];
5269 if (carryover)
5270 /* See the comment above. */
5271 memcpy (chars, SDATA (p->decoding_buf), carryover);
5273 #ifdef DATAGRAM_SOCKETS
5274 /* We have a working select, so proc_buffered_char is always -1. */
5275 if (DATAGRAM_CHAN_P (channel))
5277 socklen_t len = datagram_address[channel].len;
5278 nbytes = recvfrom (channel, chars + carryover, readmax,
5279 0, datagram_address[channel].sa, &len);
5281 else
5282 #endif
5284 bool buffered = proc_buffered_char[channel] >= 0;
5285 if (buffered)
5287 chars[carryover] = proc_buffered_char[channel];
5288 proc_buffered_char[channel] = -1;
5290 #ifdef HAVE_GNUTLS
5291 if (p->gnutls_p && p->gnutls_state)
5292 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5293 readmax - buffered);
5294 else
5295 #endif
5296 nbytes = emacs_read (channel, chars + carryover + buffered,
5297 readmax - buffered);
5298 if (nbytes > 0 && p->adaptive_read_buffering)
5300 int delay = p->read_output_delay;
5301 if (nbytes < 256)
5303 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5305 if (delay == 0)
5306 process_output_delay_count++;
5307 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5310 else if (delay > 0 && nbytes == readmax - buffered)
5312 delay -= READ_OUTPUT_DELAY_INCREMENT;
5313 if (delay == 0)
5314 process_output_delay_count--;
5316 p->read_output_delay = delay;
5317 if (delay)
5319 p->read_output_skip = 1;
5320 process_output_skip = 1;
5323 nbytes += buffered;
5324 nbytes += buffered && nbytes <= 0;
5327 p->decoding_carryover = 0;
5329 /* At this point, NBYTES holds number of bytes just received
5330 (including the one in proc_buffered_char[channel]). */
5331 if (nbytes <= 0)
5333 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5334 return nbytes;
5335 coding->mode |= CODING_MODE_LAST_BLOCK;
5338 /* Now set NBYTES how many bytes we must decode. */
5339 nbytes += carryover;
5341 odeactivate = Vdeactivate_mark;
5342 /* There's no good reason to let process filters change the current
5343 buffer, and many callers of accept-process-output, sit-for, and
5344 friends don't expect current-buffer to be changed from under them. */
5345 record_unwind_current_buffer ();
5347 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5349 /* Handling the process output should not deactivate the mark. */
5350 Vdeactivate_mark = odeactivate;
5352 unbind_to (count, Qnil);
5353 return nbytes;
5356 static void
5357 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5358 ssize_t nbytes,
5359 struct coding_system *coding)
5361 Lisp_Object outstream = p->filter;
5362 Lisp_Object text;
5363 bool outer_running_asynch_code = running_asynch_code;
5364 int waiting = waiting_for_user_input_p;
5366 #if 0
5367 Lisp_Object obuffer, okeymap;
5368 XSETBUFFER (obuffer, current_buffer);
5369 okeymap = BVAR (current_buffer, keymap);
5370 #endif
5372 /* We inhibit quit here instead of just catching it so that
5373 hitting ^G when a filter happens to be running won't screw
5374 it up. */
5375 specbind (Qinhibit_quit, Qt);
5376 specbind (Qlast_nonmenu_event, Qt);
5378 /* In case we get recursively called,
5379 and we already saved the match data nonrecursively,
5380 save the same match data in safely recursive fashion. */
5381 if (outer_running_asynch_code)
5383 Lisp_Object tem;
5384 /* Don't clobber the CURRENT match data, either! */
5385 tem = Fmatch_data (Qnil, Qnil, Qnil);
5386 restore_search_regs ();
5387 record_unwind_save_match_data ();
5388 Fset_match_data (tem, Qt);
5391 /* For speed, if a search happens within this code,
5392 save the match data in a special nonrecursive fashion. */
5393 running_asynch_code = 1;
5395 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5396 text = coding->dst_object;
5397 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5398 /* A new coding system might be found. */
5399 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5401 pset_decode_coding_system (p, Vlast_coding_system_used);
5403 /* Don't call setup_coding_system for
5404 proc_decode_coding_system[channel] here. It is done in
5405 detect_coding called via decode_coding above. */
5407 /* If a coding system for encoding is not yet decided, we set
5408 it as the same as coding-system for decoding.
5410 But, before doing that we must check if
5411 proc_encode_coding_system[p->outfd] surely points to a
5412 valid memory because p->outfd will be changed once EOF is
5413 sent to the process. */
5414 if (NILP (p->encode_coding_system) && p->outfd >= 0
5415 && proc_encode_coding_system[p->outfd])
5417 pset_encode_coding_system
5418 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5419 setup_coding_system (p->encode_coding_system,
5420 proc_encode_coding_system[p->outfd]);
5424 if (coding->carryover_bytes > 0)
5426 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5427 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5428 memcpy (SDATA (p->decoding_buf), coding->carryover,
5429 coding->carryover_bytes);
5430 p->decoding_carryover = coding->carryover_bytes;
5432 if (SBYTES (text) > 0)
5433 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5434 sometimes it's simply wrong to wrap (e.g. when called from
5435 accept-process-output). */
5436 internal_condition_case_1 (read_process_output_call,
5437 list3 (outstream, make_lisp_proc (p), text),
5438 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5439 read_process_output_error_handler);
5441 /* If we saved the match data nonrecursively, restore it now. */
5442 restore_search_regs ();
5443 running_asynch_code = outer_running_asynch_code;
5445 /* Restore waiting_for_user_input_p as it was
5446 when we were called, in case the filter clobbered it. */
5447 waiting_for_user_input_p = waiting;
5449 #if 0 /* Call record_asynch_buffer_change unconditionally,
5450 because we might have changed minor modes or other things
5451 that affect key bindings. */
5452 if (! EQ (Fcurrent_buffer (), obuffer)
5453 || ! EQ (current_buffer->keymap, okeymap))
5454 #endif
5455 /* But do it only if the caller is actually going to read events.
5456 Otherwise there's no need to make him wake up, and it could
5457 cause trouble (for example it would make sit_for return). */
5458 if (waiting_for_user_input_p == -1)
5459 record_asynch_buffer_change ();
5462 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5463 Sinternal_default_process_filter, 2, 2, 0,
5464 doc: /* Function used as default process filter.
5465 This inserts the process's output into its buffer, if there is one.
5466 Otherwise it discards the output. */)
5467 (Lisp_Object proc, Lisp_Object text)
5469 struct Lisp_Process *p;
5470 ptrdiff_t opoint;
5472 CHECK_PROCESS (proc);
5473 p = XPROCESS (proc);
5474 CHECK_STRING (text);
5476 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5478 Lisp_Object old_read_only;
5479 ptrdiff_t old_begv, old_zv;
5480 ptrdiff_t old_begv_byte, old_zv_byte;
5481 ptrdiff_t before, before_byte;
5482 ptrdiff_t opoint_byte;
5483 struct buffer *b;
5485 Fset_buffer (p->buffer);
5486 opoint = PT;
5487 opoint_byte = PT_BYTE;
5488 old_read_only = BVAR (current_buffer, read_only);
5489 old_begv = BEGV;
5490 old_zv = ZV;
5491 old_begv_byte = BEGV_BYTE;
5492 old_zv_byte = ZV_BYTE;
5494 bset_read_only (current_buffer, Qnil);
5496 /* Insert new output into buffer at the current end-of-output
5497 marker, thus preserving logical ordering of input and output. */
5498 if (XMARKER (p->mark)->buffer)
5499 set_point_from_marker (p->mark);
5500 else
5501 SET_PT_BOTH (ZV, ZV_BYTE);
5502 before = PT;
5503 before_byte = PT_BYTE;
5505 /* If the output marker is outside of the visible region, save
5506 the restriction and widen. */
5507 if (! (BEGV <= PT && PT <= ZV))
5508 Fwiden ();
5510 /* Adjust the multibyteness of TEXT to that of the buffer. */
5511 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5512 != ! STRING_MULTIBYTE (text))
5513 text = (STRING_MULTIBYTE (text)
5514 ? Fstring_as_unibyte (text)
5515 : Fstring_to_multibyte (text));
5516 /* Insert before markers in case we are inserting where
5517 the buffer's mark is, and the user's next command is Meta-y. */
5518 insert_from_string_before_markers (text, 0, 0,
5519 SCHARS (text), SBYTES (text), 0);
5521 /* Make sure the process marker's position is valid when the
5522 process buffer is changed in the signal_after_change above.
5523 W3 is known to do that. */
5524 if (BUFFERP (p->buffer)
5525 && (b = XBUFFER (p->buffer), b != current_buffer))
5526 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5527 else
5528 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5530 update_mode_lines = 23;
5532 /* Make sure opoint and the old restrictions
5533 float ahead of any new text just as point would. */
5534 if (opoint >= before)
5536 opoint += PT - before;
5537 opoint_byte += PT_BYTE - before_byte;
5539 if (old_begv > before)
5541 old_begv += PT - before;
5542 old_begv_byte += PT_BYTE - before_byte;
5544 if (old_zv >= before)
5546 old_zv += PT - before;
5547 old_zv_byte += PT_BYTE - before_byte;
5550 /* If the restriction isn't what it should be, set it. */
5551 if (old_begv != BEGV || old_zv != ZV)
5552 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5554 bset_read_only (current_buffer, old_read_only);
5555 SET_PT_BOTH (opoint, opoint_byte);
5557 return Qnil;
5560 /* Sending data to subprocess. */
5562 /* In send_process, when a write fails temporarily,
5563 wait_reading_process_output is called. It may execute user code,
5564 e.g. timers, that attempts to write new data to the same process.
5565 We must ensure that data is sent in the right order, and not
5566 interspersed half-completed with other writes (Bug#10815). This is
5567 handled by the write_queue element of struct process. It is a list
5568 with each entry having the form
5570 (string . (offset . length))
5572 where STRING is a lisp string, OFFSET is the offset into the
5573 string's byte sequence from which we should begin to send, and
5574 LENGTH is the number of bytes left to send. */
5576 /* Create a new entry in write_queue.
5577 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5578 BUF is a pointer to the string sequence of the input_obj or a C
5579 string in case of Qt or Qnil. */
5581 static void
5582 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5583 const char *buf, ptrdiff_t len, bool front)
5585 ptrdiff_t offset;
5586 Lisp_Object entry, obj;
5588 if (STRINGP (input_obj))
5590 offset = buf - SSDATA (input_obj);
5591 obj = input_obj;
5593 else
5595 offset = 0;
5596 obj = make_unibyte_string (buf, len);
5599 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5601 if (front)
5602 pset_write_queue (p, Fcons (entry, p->write_queue));
5603 else
5604 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5607 /* Remove the first element in the write_queue of process P, put its
5608 contents in OBJ, BUF and LEN, and return true. If the
5609 write_queue is empty, return false. */
5611 static bool
5612 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5613 const char **buf, ptrdiff_t *len)
5615 Lisp_Object entry, offset_length;
5616 ptrdiff_t offset;
5618 if (NILP (p->write_queue))
5619 return 0;
5621 entry = XCAR (p->write_queue);
5622 pset_write_queue (p, XCDR (p->write_queue));
5624 *obj = XCAR (entry);
5625 offset_length = XCDR (entry);
5627 *len = XINT (XCDR (offset_length));
5628 offset = XINT (XCAR (offset_length));
5629 *buf = SSDATA (*obj) + offset;
5631 return 1;
5634 /* Send some data to process PROC.
5635 BUF is the beginning of the data; LEN is the number of characters.
5636 OBJECT is the Lisp object that the data comes from. If OBJECT is
5637 nil or t, it means that the data comes from C string.
5639 If OBJECT is not nil, the data is encoded by PROC's coding-system
5640 for encoding before it is sent.
5642 This function can evaluate Lisp code and can garbage collect. */
5644 static void
5645 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5646 Lisp_Object object)
5648 struct Lisp_Process *p = XPROCESS (proc);
5649 ssize_t rv;
5650 struct coding_system *coding;
5652 if (p->raw_status_new)
5653 update_status (p);
5654 if (! EQ (p->status, Qrun))
5655 error ("Process %s not running", SDATA (p->name));
5656 if (p->outfd < 0)
5657 error ("Output file descriptor of %s is closed", SDATA (p->name));
5659 coding = proc_encode_coding_system[p->outfd];
5660 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5662 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5663 || (BUFFERP (object)
5664 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5665 || EQ (object, Qt))
5667 pset_encode_coding_system
5668 (p, complement_process_encoding_system (p->encode_coding_system));
5669 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5671 /* The coding system for encoding was changed to raw-text
5672 because we sent a unibyte text previously. Now we are
5673 sending a multibyte text, thus we must encode it by the
5674 original coding system specified for the current process.
5676 Another reason we come here is that the coding system
5677 was just complemented and a new one was returned by
5678 complement_process_encoding_system. */
5679 setup_coding_system (p->encode_coding_system, coding);
5680 Vlast_coding_system_used = p->encode_coding_system;
5682 coding->src_multibyte = 1;
5684 else
5686 coding->src_multibyte = 0;
5687 /* For sending a unibyte text, character code conversion should
5688 not take place but EOL conversion should. So, setup raw-text
5689 or one of the subsidiary if we have not yet done it. */
5690 if (CODING_REQUIRE_ENCODING (coding))
5692 if (CODING_REQUIRE_FLUSHING (coding))
5694 /* But, before changing the coding, we must flush out data. */
5695 coding->mode |= CODING_MODE_LAST_BLOCK;
5696 send_process (proc, "", 0, Qt);
5697 coding->mode &= CODING_MODE_LAST_BLOCK;
5699 setup_coding_system (raw_text_coding_system
5700 (Vlast_coding_system_used),
5701 coding);
5702 coding->src_multibyte = 0;
5705 coding->dst_multibyte = 0;
5707 if (CODING_REQUIRE_ENCODING (coding))
5709 coding->dst_object = Qt;
5710 if (BUFFERP (object))
5712 ptrdiff_t from_byte, from, to;
5713 ptrdiff_t save_pt, save_pt_byte;
5714 struct buffer *cur = current_buffer;
5716 set_buffer_internal (XBUFFER (object));
5717 save_pt = PT, save_pt_byte = PT_BYTE;
5719 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5720 from = BYTE_TO_CHAR (from_byte);
5721 to = BYTE_TO_CHAR (from_byte + len);
5722 TEMP_SET_PT_BOTH (from, from_byte);
5723 encode_coding_object (coding, object, from, from_byte,
5724 to, from_byte + len, Qt);
5725 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5726 set_buffer_internal (cur);
5728 else if (STRINGP (object))
5730 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5731 SBYTES (object), Qt);
5733 else
5735 coding->dst_object = make_unibyte_string (buf, len);
5736 coding->produced = len;
5739 len = coding->produced;
5740 object = coding->dst_object;
5741 buf = SSDATA (object);
5744 /* If there is already data in the write_queue, put the new data
5745 in the back of queue. Otherwise, ignore it. */
5746 if (!NILP (p->write_queue))
5747 write_queue_push (p, object, buf, len, 0);
5749 do /* while !NILP (p->write_queue) */
5751 ptrdiff_t cur_len = -1;
5752 const char *cur_buf;
5753 Lisp_Object cur_object;
5755 /* If write_queue is empty, ignore it. */
5756 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5758 cur_len = len;
5759 cur_buf = buf;
5760 cur_object = object;
5763 while (cur_len > 0)
5765 /* Send this batch, using one or more write calls. */
5766 ptrdiff_t written = 0;
5767 int outfd = p->outfd;
5768 #ifdef DATAGRAM_SOCKETS
5769 if (DATAGRAM_CHAN_P (outfd))
5771 rv = sendto (outfd, cur_buf, cur_len,
5772 0, datagram_address[outfd].sa,
5773 datagram_address[outfd].len);
5774 if (rv >= 0)
5775 written = rv;
5776 else if (errno == EMSGSIZE)
5777 report_file_error ("Sending datagram", proc);
5779 else
5780 #endif
5782 #ifdef HAVE_GNUTLS
5783 if (p->gnutls_p && p->gnutls_state)
5784 written = emacs_gnutls_write (p, cur_buf, cur_len);
5785 else
5786 #endif
5787 written = emacs_write_sig (outfd, cur_buf, cur_len);
5788 rv = (written ? 0 : -1);
5789 if (p->read_output_delay > 0
5790 && p->adaptive_read_buffering == 1)
5792 p->read_output_delay = 0;
5793 process_output_delay_count--;
5794 p->read_output_skip = 0;
5798 if (rv < 0)
5800 if (would_block (errno))
5801 /* Buffer is full. Wait, accepting input;
5802 that may allow the program
5803 to finish doing output and read more. */
5805 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5806 /* A gross hack to work around a bug in FreeBSD.
5807 In the following sequence, read(2) returns
5808 bogus data:
5810 write(2) 1022 bytes
5811 write(2) 954 bytes, get EAGAIN
5812 read(2) 1024 bytes in process_read_output
5813 read(2) 11 bytes in process_read_output
5815 That is, read(2) returns more bytes than have
5816 ever been written successfully. The 1033 bytes
5817 read are the 1022 bytes written successfully
5818 after processing (for example with CRs added if
5819 the terminal is set up that way which it is
5820 here). The same bytes will be seen again in a
5821 later read(2), without the CRs. */
5823 if (errno == EAGAIN)
5825 int flags = FWRITE;
5826 ioctl (p->outfd, TIOCFLUSH, &flags);
5828 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5830 /* Put what we should have written in wait_queue. */
5831 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5832 wait_reading_process_output (0, 20 * 1000 * 1000,
5833 0, 0, Qnil, NULL, 0);
5834 /* Reread queue, to see what is left. */
5835 break;
5837 else if (errno == EPIPE)
5839 p->raw_status_new = 0;
5840 pset_status (p, list2 (Qexit, make_number (256)));
5841 p->tick = ++process_tick;
5842 deactivate_process (proc);
5843 error ("process %s no longer connected to pipe; closed it",
5844 SDATA (p->name));
5846 else
5847 /* This is a real error. */
5848 report_file_error ("Writing to process", proc);
5850 cur_buf += written;
5851 cur_len -= written;
5854 while (!NILP (p->write_queue));
5857 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5858 3, 3, 0,
5859 doc: /* Send current contents of region as input to PROCESS.
5860 PROCESS may be a process, a buffer, the name of a process or buffer, or
5861 nil, indicating the current buffer's process.
5862 Called from program, takes three arguments, PROCESS, START and END.
5863 If the region is more than 500 characters long,
5864 it is sent in several bunches. This may happen even for shorter regions.
5865 Output from processes can arrive in between bunches. */)
5866 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5868 Lisp_Object proc = get_process (process);
5869 ptrdiff_t start_byte, end_byte;
5871 validate_region (&start, &end);
5873 start_byte = CHAR_TO_BYTE (XINT (start));
5874 end_byte = CHAR_TO_BYTE (XINT (end));
5876 if (XINT (start) < GPT && XINT (end) > GPT)
5877 move_gap_both (XINT (start), start_byte);
5879 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5880 end_byte - start_byte, Fcurrent_buffer ());
5882 return Qnil;
5885 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5886 2, 2, 0,
5887 doc: /* Send PROCESS the contents of STRING as input.
5888 PROCESS may be a process, a buffer, the name of a process or buffer, or
5889 nil, indicating the current buffer's process.
5890 If STRING is more than 500 characters long,
5891 it is sent in several bunches. This may happen even for shorter strings.
5892 Output from processes can arrive in between bunches. */)
5893 (Lisp_Object process, Lisp_Object string)
5895 Lisp_Object proc;
5896 CHECK_STRING (string);
5897 proc = get_process (process);
5898 send_process (proc, SSDATA (string),
5899 SBYTES (string), string);
5900 return Qnil;
5903 /* Return the foreground process group for the tty/pty that
5904 the process P uses. */
5905 static pid_t
5906 emacs_get_tty_pgrp (struct Lisp_Process *p)
5908 pid_t gid = -1;
5910 #ifdef TIOCGPGRP
5911 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5913 int fd;
5914 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5915 master side. Try the slave side. */
5916 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5918 if (fd != -1)
5920 ioctl (fd, TIOCGPGRP, &gid);
5921 emacs_close (fd);
5924 #endif /* defined (TIOCGPGRP ) */
5926 return gid;
5929 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5930 Sprocess_running_child_p, 0, 1, 0,
5931 doc: /* Return non-nil if PROCESS has given the terminal to a
5932 child. If the operating system does not make it possible to find out,
5933 return t. If we can find out, return the numeric ID of the foreground
5934 process group. */)
5935 (Lisp_Object process)
5937 /* Initialize in case ioctl doesn't exist or gives an error,
5938 in a way that will cause returning t. */
5939 pid_t gid;
5940 Lisp_Object proc;
5941 struct Lisp_Process *p;
5943 proc = get_process (process);
5944 p = XPROCESS (proc);
5946 if (!EQ (p->type, Qreal))
5947 error ("Process %s is not a subprocess",
5948 SDATA (p->name));
5949 if (p->infd < 0)
5950 error ("Process %s is not active",
5951 SDATA (p->name));
5953 gid = emacs_get_tty_pgrp (p);
5955 if (gid == p->pid)
5956 return Qnil;
5957 if (gid != -1)
5958 return make_number (gid);
5959 return Qt;
5962 /* Send a signal number SIGNO to PROCESS.
5963 If CURRENT_GROUP is t, that means send to the process group
5964 that currently owns the terminal being used to communicate with PROCESS.
5965 This is used for various commands in shell mode.
5966 If CURRENT_GROUP is lambda, that means send to the process group
5967 that currently owns the terminal, but only if it is NOT the shell itself.
5969 If NOMSG is false, insert signal-announcements into process's buffers
5970 right away.
5972 If we can, we try to signal PROCESS by sending control characters
5973 down the pty. This allows us to signal inferiors who have changed
5974 their uid, for which kill would return an EPERM error. */
5976 static void
5977 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5978 bool nomsg)
5980 Lisp_Object proc;
5981 struct Lisp_Process *p;
5982 pid_t gid;
5983 bool no_pgrp = 0;
5985 proc = get_process (process);
5986 p = XPROCESS (proc);
5988 if (!EQ (p->type, Qreal))
5989 error ("Process %s is not a subprocess",
5990 SDATA (p->name));
5991 if (p->infd < 0)
5992 error ("Process %s is not active",
5993 SDATA (p->name));
5995 if (!p->pty_flag)
5996 current_group = Qnil;
5998 /* If we are using pgrps, get a pgrp number and make it negative. */
5999 if (NILP (current_group))
6000 /* Send the signal to the shell's process group. */
6001 gid = p->pid;
6002 else
6004 #ifdef SIGNALS_VIA_CHARACTERS
6005 /* If possible, send signals to the entire pgrp
6006 by sending an input character to it. */
6008 struct termios t;
6009 cc_t *sig_char = NULL;
6011 tcgetattr (p->infd, &t);
6013 switch (signo)
6015 case SIGINT:
6016 sig_char = &t.c_cc[VINTR];
6017 break;
6019 case SIGQUIT:
6020 sig_char = &t.c_cc[VQUIT];
6021 break;
6023 case SIGTSTP:
6024 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6025 sig_char = &t.c_cc[VSWTCH];
6026 #else
6027 sig_char = &t.c_cc[VSUSP];
6028 #endif
6029 break;
6032 if (sig_char && *sig_char != CDISABLE)
6034 send_process (proc, (char *) sig_char, 1, Qnil);
6035 return;
6037 /* If we can't send the signal with a character,
6038 fall through and send it another way. */
6040 /* The code above may fall through if it can't
6041 handle the signal. */
6042 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6044 #ifdef TIOCGPGRP
6045 /* Get the current pgrp using the tty itself, if we have that.
6046 Otherwise, use the pty to get the pgrp.
6047 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6048 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6049 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6050 His patch indicates that if TIOCGPGRP returns an error, then
6051 we should just assume that p->pid is also the process group id. */
6053 gid = emacs_get_tty_pgrp (p);
6055 if (gid == -1)
6056 /* If we can't get the information, assume
6057 the shell owns the tty. */
6058 gid = p->pid;
6060 /* It is not clear whether anything really can set GID to -1.
6061 Perhaps on some system one of those ioctls can or could do so.
6062 Or perhaps this is vestigial. */
6063 if (gid == -1)
6064 no_pgrp = 1;
6065 #else /* ! defined (TIOCGPGRP) */
6066 /* Can't select pgrps on this system, so we know that
6067 the child itself heads the pgrp. */
6068 gid = p->pid;
6069 #endif /* ! defined (TIOCGPGRP) */
6071 /* If current_group is lambda, and the shell owns the terminal,
6072 don't send any signal. */
6073 if (EQ (current_group, Qlambda) && gid == p->pid)
6074 return;
6077 #ifdef SIGCONT
6078 if (signo == SIGCONT)
6080 p->raw_status_new = 0;
6081 pset_status (p, Qrun);
6082 p->tick = ++process_tick;
6083 if (!nomsg)
6085 status_notify (NULL, NULL);
6086 redisplay_preserve_echo_area (13);
6089 #endif
6091 #ifdef TIOCSIGSEND
6092 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6093 We don't know whether the bug is fixed in later HP-UX versions. */
6094 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6095 return;
6096 #endif
6098 /* If we don't have process groups, send the signal to the immediate
6099 subprocess. That isn't really right, but it's better than any
6100 obvious alternative. */
6101 pid_t pid = no_pgrp ? gid : - gid;
6103 /* Do not kill an already-reaped process, as that could kill an
6104 innocent bystander that happens to have the same process ID. */
6105 sigset_t oldset;
6106 block_child_signal (&oldset);
6107 if (p->alive)
6108 kill (pid, signo);
6109 unblock_child_signal (&oldset);
6112 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6113 doc: /* Interrupt process PROCESS.
6114 PROCESS may be a process, a buffer, or the name of a process or buffer.
6115 No arg or nil means current buffer's process.
6116 Second arg CURRENT-GROUP non-nil means send signal to
6117 the current process-group of the process's controlling terminal
6118 rather than to the process's own process group.
6119 If the process is a shell, this means interrupt current subjob
6120 rather than the shell.
6122 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6123 don't send the signal. */)
6124 (Lisp_Object process, Lisp_Object current_group)
6126 process_send_signal (process, SIGINT, current_group, 0);
6127 return process;
6130 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6131 doc: /* Kill process PROCESS. May be process or name of one.
6132 See function `interrupt-process' for more details on usage. */)
6133 (Lisp_Object process, Lisp_Object current_group)
6135 process_send_signal (process, SIGKILL, current_group, 0);
6136 return process;
6139 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6140 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6141 See function `interrupt-process' for more details on usage. */)
6142 (Lisp_Object process, Lisp_Object current_group)
6144 process_send_signal (process, SIGQUIT, current_group, 0);
6145 return process;
6148 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6149 doc: /* Stop process PROCESS. May be process or name of one.
6150 See function `interrupt-process' for more details on usage.
6151 If PROCESS is a network or serial or pipe connection, inhibit handling
6152 of incoming traffic. */)
6153 (Lisp_Object process, Lisp_Object current_group)
6155 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6156 || PIPECONN_P (process)))
6158 struct Lisp_Process *p;
6160 p = XPROCESS (process);
6161 if (NILP (p->command)
6162 && p->infd >= 0)
6164 FD_CLR (p->infd, &input_wait_mask);
6165 FD_CLR (p->infd, &non_keyboard_wait_mask);
6167 pset_command (p, Qt);
6168 return process;
6170 #ifndef SIGTSTP
6171 error ("No SIGTSTP support");
6172 #else
6173 process_send_signal (process, SIGTSTP, current_group, 0);
6174 #endif
6175 return process;
6178 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6179 doc: /* Continue process PROCESS. May be process or name of one.
6180 See function `interrupt-process' for more details on usage.
6181 If PROCESS is a network or serial process, resume handling of incoming
6182 traffic. */)
6183 (Lisp_Object process, Lisp_Object current_group)
6185 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6186 || PIPECONN_P (process)))
6188 struct Lisp_Process *p;
6190 p = XPROCESS (process);
6191 if (EQ (p->command, Qt)
6192 && p->infd >= 0
6193 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6195 FD_SET (p->infd, &input_wait_mask);
6196 FD_SET (p->infd, &non_keyboard_wait_mask);
6197 #ifdef WINDOWSNT
6198 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6199 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6200 #else /* not WINDOWSNT */
6201 tcflush (p->infd, TCIFLUSH);
6202 #endif /* not WINDOWSNT */
6204 pset_command (p, Qnil);
6205 return process;
6207 #ifdef SIGCONT
6208 process_send_signal (process, SIGCONT, current_group, 0);
6209 #else
6210 error ("No SIGCONT support");
6211 #endif
6212 return process;
6215 /* Return the integer value of the signal whose abbreviation is ABBR,
6216 or a negative number if there is no such signal. */
6217 static int
6218 abbr_to_signal (char const *name)
6220 int i, signo;
6221 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6223 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6224 name += 3;
6226 for (i = 0; i < sizeof sigbuf; i++)
6228 sigbuf[i] = c_toupper (name[i]);
6229 if (! sigbuf[i])
6230 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6233 return -1;
6236 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6237 2, 2, "sProcess (name or number): \nnSignal code: ",
6238 doc: /* Send PROCESS the signal with code SIGCODE.
6239 PROCESS may also be a number specifying the process id of the
6240 process to signal; in this case, the process need not be a child of
6241 this Emacs.
6242 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6243 (Lisp_Object process, Lisp_Object sigcode)
6245 pid_t pid;
6246 int signo;
6248 if (STRINGP (process))
6250 Lisp_Object tem = Fget_process (process);
6251 if (NILP (tem))
6253 Lisp_Object process_number
6254 = string_to_number (SSDATA (process), 10, 1);
6255 if (NUMBERP (process_number))
6256 tem = process_number;
6258 process = tem;
6260 else if (!NUMBERP (process))
6261 process = get_process (process);
6263 if (NILP (process))
6264 return process;
6266 if (NUMBERP (process))
6267 CONS_TO_INTEGER (process, pid_t, pid);
6268 else
6270 CHECK_PROCESS (process);
6271 pid = XPROCESS (process)->pid;
6272 if (pid <= 0)
6273 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6276 if (INTEGERP (sigcode))
6278 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6279 signo = XINT (sigcode);
6281 else
6283 char *name;
6285 CHECK_SYMBOL (sigcode);
6286 name = SSDATA (SYMBOL_NAME (sigcode));
6288 signo = abbr_to_signal (name);
6289 if (signo < 0)
6290 error ("Undefined signal name %s", name);
6293 return make_number (kill (pid, signo));
6296 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6297 doc: /* Make PROCESS see end-of-file in its input.
6298 EOF comes after any text already sent to it.
6299 PROCESS may be a process, a buffer, the name of a process or buffer, or
6300 nil, indicating the current buffer's process.
6301 If PROCESS is a network connection, or is a process communicating
6302 through a pipe (as opposed to a pty), then you cannot send any more
6303 text to PROCESS after you call this function.
6304 If PROCESS is a serial process, wait until all output written to the
6305 process has been transmitted to the serial port. */)
6306 (Lisp_Object process)
6308 Lisp_Object proc;
6309 struct coding_system *coding = NULL;
6310 int outfd;
6312 if (DATAGRAM_CONN_P (process))
6313 return process;
6315 proc = get_process (process);
6316 outfd = XPROCESS (proc)->outfd;
6317 if (outfd >= 0)
6318 coding = proc_encode_coding_system[outfd];
6320 /* Make sure the process is really alive. */
6321 if (XPROCESS (proc)->raw_status_new)
6322 update_status (XPROCESS (proc));
6323 if (! EQ (XPROCESS (proc)->status, Qrun))
6324 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6326 if (coding && CODING_REQUIRE_FLUSHING (coding))
6328 coding->mode |= CODING_MODE_LAST_BLOCK;
6329 send_process (proc, "", 0, Qnil);
6332 if (XPROCESS (proc)->pty_flag)
6333 send_process (proc, "\004", 1, Qnil);
6334 else if (EQ (XPROCESS (proc)->type, Qserial))
6336 #ifndef WINDOWSNT
6337 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6338 report_file_error ("Failed tcdrain", Qnil);
6339 #endif /* not WINDOWSNT */
6340 /* Do nothing on Windows because writes are blocking. */
6342 else
6344 struct Lisp_Process *p = XPROCESS (proc);
6345 int old_outfd = p->outfd;
6346 int new_outfd;
6348 #ifdef HAVE_SHUTDOWN
6349 /* If this is a network connection, or socketpair is used
6350 for communication with the subprocess, call shutdown to cause EOF.
6351 (In some old system, shutdown to socketpair doesn't work.
6352 Then we just can't win.) */
6353 if (0 <= old_outfd
6354 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6355 shutdown (old_outfd, 1);
6356 #endif
6357 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6358 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6359 if (new_outfd < 0)
6360 report_file_error ("Opening null device", Qnil);
6361 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6362 p->outfd = new_outfd;
6364 if (!proc_encode_coding_system[new_outfd])
6365 proc_encode_coding_system[new_outfd]
6366 = xmalloc (sizeof (struct coding_system));
6367 if (old_outfd >= 0)
6369 *proc_encode_coding_system[new_outfd]
6370 = *proc_encode_coding_system[old_outfd];
6371 memset (proc_encode_coding_system[old_outfd], 0,
6372 sizeof (struct coding_system));
6374 else
6375 setup_coding_system (p->encode_coding_system,
6376 proc_encode_coding_system[new_outfd]);
6378 return process;
6381 /* The main Emacs thread records child processes in three places:
6383 - Vprocess_alist, for asynchronous subprocesses, which are child
6384 processes visible to Lisp.
6386 - deleted_pid_list, for child processes invisible to Lisp,
6387 typically because of delete-process. These are recorded so that
6388 the processes can be reaped when they exit, so that the operating
6389 system's process table is not cluttered by zombies.
6391 - the local variable PID in Fcall_process, call_process_cleanup and
6392 call_process_kill, for synchronous subprocesses.
6393 record_unwind_protect is used to make sure this process is not
6394 forgotten: if the user interrupts call-process and the child
6395 process refuses to exit immediately even with two C-g's,
6396 call_process_kill adds PID's contents to deleted_pid_list before
6397 returning.
6399 The main Emacs thread invokes waitpid only on child processes that
6400 it creates and that have not been reaped. This avoid races on
6401 platforms such as GTK, where other threads create their own
6402 subprocesses which the main thread should not reap. For example,
6403 if the main thread attempted to reap an already-reaped child, it
6404 might inadvertently reap a GTK-created process that happened to
6405 have the same process ID. */
6407 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6408 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6409 keep track of its own children. GNUstep is similar. */
6411 static void dummy_handler (int sig) {}
6412 static signal_handler_t volatile lib_child_handler;
6414 /* Handle a SIGCHLD signal by looking for known child processes of
6415 Emacs whose status have changed. For each one found, record its
6416 new status.
6418 All we do is change the status; we do not run sentinels or print
6419 notifications. That is saved for the next time keyboard input is
6420 done, in order to avoid timing errors.
6422 ** WARNING: this can be called during garbage collection.
6423 Therefore, it must not be fooled by the presence of mark bits in
6424 Lisp objects.
6426 ** USG WARNING: Although it is not obvious from the documentation
6427 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6428 signal() before executing at least one wait(), otherwise the
6429 handler will be called again, resulting in an infinite loop. The
6430 relevant portion of the documentation reads "SIGCLD signals will be
6431 queued and the signal-catching function will be continually
6432 reentered until the queue is empty". Invoking signal() causes the
6433 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6434 Inc.
6436 ** Malloc WARNING: This should never call malloc either directly or
6437 indirectly; if it does, that is a bug. */
6439 static void
6440 handle_child_signal (int sig)
6442 Lisp_Object tail, proc;
6444 /* Find the process that signaled us, and record its status. */
6446 /* The process can have been deleted by Fdelete_process, or have
6447 been started asynchronously by Fcall_process. */
6448 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6450 bool all_pids_are_fixnums
6451 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6452 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6453 Lisp_Object head = XCAR (tail);
6454 Lisp_Object xpid;
6455 if (! CONSP (head))
6456 continue;
6457 xpid = XCAR (head);
6458 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6460 pid_t deleted_pid;
6461 if (INTEGERP (xpid))
6462 deleted_pid = XINT (xpid);
6463 else
6464 deleted_pid = XFLOAT_DATA (xpid);
6465 if (child_status_changed (deleted_pid, 0, 0))
6467 if (STRINGP (XCDR (head)))
6468 unlink (SSDATA (XCDR (head)));
6469 XSETCAR (tail, Qnil);
6474 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6475 FOR_EACH_PROCESS (tail, proc)
6477 struct Lisp_Process *p = XPROCESS (proc);
6478 int status;
6480 if (p->alive
6481 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6483 /* Change the status of the process that was found. */
6484 p->tick = ++process_tick;
6485 p->raw_status = status;
6486 p->raw_status_new = 1;
6488 /* If process has terminated, stop waiting for its output. */
6489 if (WIFSIGNALED (status) || WIFEXITED (status))
6491 bool clear_desc_flag = 0;
6492 p->alive = 0;
6493 if (p->infd >= 0)
6494 clear_desc_flag = 1;
6496 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6497 if (clear_desc_flag)
6499 FD_CLR (p->infd, &input_wait_mask);
6500 FD_CLR (p->infd, &non_keyboard_wait_mask);
6506 lib_child_handler (sig);
6507 #ifdef NS_IMPL_GNUSTEP
6508 /* NSTask in GNUstep sets its child handler each time it is called.
6509 So we must re-set ours. */
6510 catch_child_signal ();
6511 #endif
6514 static void
6515 deliver_child_signal (int sig)
6517 deliver_process_signal (sig, handle_child_signal);
6521 static Lisp_Object
6522 exec_sentinel_error_handler (Lisp_Object error_val)
6524 cmd_error_internal (error_val, "error in process sentinel: ");
6525 Vinhibit_quit = Qt;
6526 update_echo_area ();
6527 Fsleep_for (make_number (2), Qnil);
6528 return Qt;
6531 static void
6532 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6534 Lisp_Object sentinel, odeactivate;
6535 struct Lisp_Process *p = XPROCESS (proc);
6536 ptrdiff_t count = SPECPDL_INDEX ();
6537 bool outer_running_asynch_code = running_asynch_code;
6538 int waiting = waiting_for_user_input_p;
6540 if (inhibit_sentinels)
6541 return;
6543 odeactivate = Vdeactivate_mark;
6544 #if 0
6545 Lisp_Object obuffer, okeymap;
6546 XSETBUFFER (obuffer, current_buffer);
6547 okeymap = BVAR (current_buffer, keymap);
6548 #endif
6550 /* There's no good reason to let sentinels change the current
6551 buffer, and many callers of accept-process-output, sit-for, and
6552 friends don't expect current-buffer to be changed from under them. */
6553 record_unwind_current_buffer ();
6555 sentinel = p->sentinel;
6557 /* Inhibit quit so that random quits don't screw up a running filter. */
6558 specbind (Qinhibit_quit, Qt);
6559 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6561 /* In case we get recursively called,
6562 and we already saved the match data nonrecursively,
6563 save the same match data in safely recursive fashion. */
6564 if (outer_running_asynch_code)
6566 Lisp_Object tem;
6567 tem = Fmatch_data (Qnil, Qnil, Qnil);
6568 restore_search_regs ();
6569 record_unwind_save_match_data ();
6570 Fset_match_data (tem, Qt);
6573 /* For speed, if a search happens within this code,
6574 save the match data in a special nonrecursive fashion. */
6575 running_asynch_code = 1;
6577 internal_condition_case_1 (read_process_output_call,
6578 list3 (sentinel, proc, reason),
6579 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6580 exec_sentinel_error_handler);
6582 /* If we saved the match data nonrecursively, restore it now. */
6583 restore_search_regs ();
6584 running_asynch_code = outer_running_asynch_code;
6586 Vdeactivate_mark = odeactivate;
6588 /* Restore waiting_for_user_input_p as it was
6589 when we were called, in case the filter clobbered it. */
6590 waiting_for_user_input_p = waiting;
6592 #if 0
6593 if (! EQ (Fcurrent_buffer (), obuffer)
6594 || ! EQ (current_buffer->keymap, okeymap))
6595 #endif
6596 /* But do it only if the caller is actually going to read events.
6597 Otherwise there's no need to make him wake up, and it could
6598 cause trouble (for example it would make sit_for return). */
6599 if (waiting_for_user_input_p == -1)
6600 record_asynch_buffer_change ();
6602 unbind_to (count, Qnil);
6605 /* Report all recent events of a change in process status
6606 (either run the sentinel or output a message).
6607 This is usually done while Emacs is waiting for keyboard input
6608 but can be done at other times.
6610 Return positive if any input was received from WAIT_PROC (or from
6611 any process if WAIT_PROC is null), zero if input was attempted but
6612 none received, and negative if we didn't even try. */
6614 static int
6615 status_notify (struct Lisp_Process *deleting_process,
6616 struct Lisp_Process *wait_proc)
6618 Lisp_Object proc;
6619 Lisp_Object tail, msg;
6620 int got_some_output = -1;
6622 tail = Qnil;
6623 msg = Qnil;
6625 /* Set this now, so that if new processes are created by sentinels
6626 that we run, we get called again to handle their status changes. */
6627 update_tick = process_tick;
6629 FOR_EACH_PROCESS (tail, proc)
6631 Lisp_Object symbol;
6632 register struct Lisp_Process *p = XPROCESS (proc);
6634 if (p->tick != p->update_tick)
6636 p->update_tick = p->tick;
6638 /* If process is still active, read any output that remains. */
6639 while (! EQ (p->filter, Qt)
6640 && ! EQ (p->status, Qconnect)
6641 && ! EQ (p->status, Qlisten)
6642 /* Network or serial process not stopped: */
6643 && ! EQ (p->command, Qt)
6644 && p->infd >= 0
6645 && p != deleting_process)
6647 int nread = read_process_output (proc, p->infd);
6648 if ((!wait_proc || wait_proc == XPROCESS (proc))
6649 && got_some_output < nread)
6650 got_some_output = nread;
6651 if (nread <= 0)
6652 break;
6655 /* Get the text to use for the message. */
6656 if (p->raw_status_new)
6657 update_status (p);
6658 msg = status_message (p);
6660 /* If process is terminated, deactivate it or delete it. */
6661 symbol = p->status;
6662 if (CONSP (p->status))
6663 symbol = XCAR (p->status);
6665 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6666 || EQ (symbol, Qclosed))
6668 if (delete_exited_processes)
6669 remove_process (proc);
6670 else
6671 deactivate_process (proc);
6674 /* The actions above may have further incremented p->tick.
6675 So set p->update_tick again so that an error in the sentinel will
6676 not cause this code to be run again. */
6677 p->update_tick = p->tick;
6678 /* Now output the message suitably. */
6679 exec_sentinel (proc, msg);
6680 if (BUFFERP (p->buffer))
6681 /* In case it uses %s in mode-line-format. */
6682 bset_update_mode_line (XBUFFER (p->buffer));
6684 } /* end for */
6686 return got_some_output;
6689 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6690 Sinternal_default_process_sentinel, 2, 2, 0,
6691 doc: /* Function used as default sentinel for processes.
6692 This inserts a status message into the process's buffer, if there is one. */)
6693 (Lisp_Object proc, Lisp_Object msg)
6695 Lisp_Object buffer, symbol;
6696 struct Lisp_Process *p;
6697 CHECK_PROCESS (proc);
6698 p = XPROCESS (proc);
6699 buffer = p->buffer;
6700 symbol = p->status;
6701 if (CONSP (symbol))
6702 symbol = XCAR (symbol);
6704 if (!EQ (symbol, Qrun) && !NILP (buffer))
6706 Lisp_Object tem;
6707 struct buffer *old = current_buffer;
6708 ptrdiff_t opoint, opoint_byte;
6709 ptrdiff_t before, before_byte;
6711 /* Avoid error if buffer is deleted
6712 (probably that's why the process is dead, too). */
6713 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6714 return Qnil;
6715 Fset_buffer (buffer);
6717 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6718 msg = (code_convert_string_norecord
6719 (msg, Vlocale_coding_system, 1));
6721 opoint = PT;
6722 opoint_byte = PT_BYTE;
6723 /* Insert new output into buffer
6724 at the current end-of-output marker,
6725 thus preserving logical ordering of input and output. */
6726 if (XMARKER (p->mark)->buffer)
6727 Fgoto_char (p->mark);
6728 else
6729 SET_PT_BOTH (ZV, ZV_BYTE);
6731 before = PT;
6732 before_byte = PT_BYTE;
6734 tem = BVAR (current_buffer, read_only);
6735 bset_read_only (current_buffer, Qnil);
6736 insert_string ("\nProcess ");
6737 { /* FIXME: temporary kludge. */
6738 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6739 insert_string (" ");
6740 Finsert (1, &msg);
6741 bset_read_only (current_buffer, tem);
6742 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6744 if (opoint >= before)
6745 SET_PT_BOTH (opoint + (PT - before),
6746 opoint_byte + (PT_BYTE - before_byte));
6747 else
6748 SET_PT_BOTH (opoint, opoint_byte);
6750 set_buffer_internal (old);
6752 return Qnil;
6756 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6757 Sset_process_coding_system, 1, 3, 0,
6758 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6759 DECODING will be used to decode subprocess output and ENCODING to
6760 encode subprocess input. */)
6761 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6763 register struct Lisp_Process *p;
6765 CHECK_PROCESS (process);
6766 p = XPROCESS (process);
6767 if (p->infd < 0)
6768 error ("Input file descriptor of %s closed", SDATA (p->name));
6769 if (p->outfd < 0)
6770 error ("Output file descriptor of %s closed", SDATA (p->name));
6771 Fcheck_coding_system (decoding);
6772 Fcheck_coding_system (encoding);
6773 encoding = coding_inherit_eol_type (encoding, Qnil);
6774 pset_decode_coding_system (p, decoding);
6775 pset_encode_coding_system (p, encoding);
6776 setup_process_coding_systems (process);
6778 return Qnil;
6781 DEFUN ("process-coding-system",
6782 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6783 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6784 (register Lisp_Object process)
6786 CHECK_PROCESS (process);
6787 return Fcons (XPROCESS (process)->decode_coding_system,
6788 XPROCESS (process)->encode_coding_system);
6791 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6792 Sset_process_filter_multibyte, 2, 2, 0,
6793 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6794 If FLAG is non-nil, the filter is given multibyte strings.
6795 If FLAG is nil, the filter is given unibyte strings. In this case,
6796 all character code conversion except for end-of-line conversion is
6797 suppressed. */)
6798 (Lisp_Object process, Lisp_Object flag)
6800 register struct Lisp_Process *p;
6802 CHECK_PROCESS (process);
6803 p = XPROCESS (process);
6804 if (NILP (flag))
6805 pset_decode_coding_system
6806 (p, raw_text_coding_system (p->decode_coding_system));
6807 setup_process_coding_systems (process);
6809 return Qnil;
6812 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6813 Sprocess_filter_multibyte_p, 1, 1, 0,
6814 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6815 (Lisp_Object process)
6817 register struct Lisp_Process *p;
6818 struct coding_system *coding;
6820 CHECK_PROCESS (process);
6821 p = XPROCESS (process);
6822 if (p->infd < 0)
6823 return Qnil;
6824 coding = proc_decode_coding_system[p->infd];
6825 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6831 # ifdef HAVE_GPM
6833 void
6834 add_gpm_wait_descriptor (int desc)
6836 add_keyboard_wait_descriptor (desc);
6839 void
6840 delete_gpm_wait_descriptor (int desc)
6842 delete_keyboard_wait_descriptor (desc);
6845 # endif
6847 # ifdef USABLE_SIGIO
6849 /* Return true if *MASK has a bit set
6850 that corresponds to one of the keyboard input descriptors. */
6852 static bool
6853 keyboard_bit_set (fd_set *mask)
6855 int fd;
6857 for (fd = 0; fd <= max_input_desc; fd++)
6858 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6859 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6860 return 1;
6862 return 0;
6864 # endif
6866 #else /* not subprocesses */
6868 /* Defined in msdos.c. */
6869 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6870 struct timespec *, void *);
6872 /* Implementation of wait_reading_process_output, assuming that there
6873 are no subprocesses. Used only by the MS-DOS build.
6875 Wait for timeout to elapse and/or keyboard input to be available.
6877 TIME_LIMIT is:
6878 timeout in seconds
6879 If negative, gobble data immediately available but don't wait for any.
6881 NSECS is:
6882 an additional duration to wait, measured in nanoseconds
6883 If TIME_LIMIT is zero, then:
6884 If NSECS == 0, there is no limit.
6885 If NSECS > 0, the timeout consists of NSECS only.
6886 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6888 READ_KBD is:
6889 0 to ignore keyboard input, or
6890 1 to return when input is available, or
6891 -1 means caller will actually read the input, so don't throw to
6892 the quit handler.
6894 see full version for other parameters. We know that wait_proc will
6895 always be NULL, since `subprocesses' isn't defined.
6897 DO_DISPLAY means redisplay should be done to show subprocess
6898 output that arrives.
6900 Return -1 signifying we got no output and did not try. */
6903 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6904 bool do_display,
6905 Lisp_Object wait_for_cell,
6906 struct Lisp_Process *wait_proc, int just_wait_proc)
6908 register int nfds;
6909 struct timespec end_time, timeout;
6910 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
6912 if (TYPE_MAXIMUM (time_t) < time_limit)
6913 time_limit = TYPE_MAXIMUM (time_t);
6915 if (time_limit < 0 || nsecs < 0)
6916 wait = MINIMUM;
6917 else if (time_limit > 0 || nsecs > 0)
6919 wait = TIMEOUT;
6920 end_time = timespec_add (current_timespec (),
6921 make_timespec (time_limit, nsecs));
6923 else
6924 wait = INFINITY;
6926 /* Turn off periodic alarms (in case they are in use)
6927 and then turn off any other atimers,
6928 because the select emulator uses alarms. */
6929 stop_polling ();
6930 turn_on_atimers (0);
6932 while (1)
6934 bool timeout_reduced_for_timers = false;
6935 fd_set waitchannels;
6936 int xerrno;
6938 /* If calling from keyboard input, do not quit
6939 since we want to return C-g as an input character.
6940 Otherwise, do pending quit if requested. */
6941 if (read_kbd >= 0)
6942 QUIT;
6944 /* Exit now if the cell we're waiting for became non-nil. */
6945 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6946 break;
6948 /* Compute time from now till when time limit is up. */
6949 /* Exit if already run out. */
6950 if (wait == TIMEOUT)
6952 struct timespec now = current_timespec ();
6953 if (timespec_cmp (end_time, now) <= 0)
6954 break;
6955 timeout = timespec_sub (end_time, now);
6957 else
6958 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
6960 /* If our caller will not immediately handle keyboard events,
6961 run timer events directly.
6962 (Callers that will immediately read keyboard events
6963 call timer_delay on their own.) */
6964 if (NILP (wait_for_cell))
6966 struct timespec timer_delay;
6970 unsigned old_timers_run = timers_run;
6971 timer_delay = timer_check ();
6972 if (timers_run != old_timers_run && do_display)
6973 /* We must retry, since a timer may have requeued itself
6974 and that could alter the time delay. */
6975 redisplay_preserve_echo_area (14);
6976 else
6977 break;
6979 while (!detect_input_pending ());
6981 /* If there is unread keyboard input, also return. */
6982 if (read_kbd != 0
6983 && requeued_events_pending_p ())
6984 break;
6986 if (timespec_valid_p (timer_delay))
6988 if (timespec_cmp (timer_delay, timeout) < 0)
6990 timeout = timer_delay;
6991 timeout_reduced_for_timers = true;
6996 /* Cause C-g and alarm signals to take immediate action,
6997 and cause input available signals to zero out timeout. */
6998 if (read_kbd < 0)
6999 set_waiting_for_input (&timeout);
7001 /* If a frame has been newly mapped and needs updating,
7002 reprocess its display stuff. */
7003 if (frame_garbaged && do_display)
7005 clear_waiting_for_input ();
7006 redisplay_preserve_echo_area (15);
7007 if (read_kbd < 0)
7008 set_waiting_for_input (&timeout);
7011 /* Wait till there is something to do. */
7012 FD_ZERO (&waitchannels);
7013 if (read_kbd && detect_input_pending ())
7014 nfds = 0;
7015 else
7017 if (read_kbd || !NILP (wait_for_cell))
7018 FD_SET (0, &waitchannels);
7019 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7022 xerrno = errno;
7024 /* Make C-g and alarm signals set flags again. */
7025 clear_waiting_for_input ();
7027 /* If we woke up due to SIGWINCH, actually change size now. */
7028 do_pending_window_change (0);
7030 if (wait < INFINITY && nfds == 0 && ! timeout_reduced_for_timers)
7031 /* We waited the full specified time, so return now. */
7032 break;
7034 if (nfds == -1)
7036 /* If the system call was interrupted, then go around the
7037 loop again. */
7038 if (xerrno == EINTR)
7039 FD_ZERO (&waitchannels);
7040 else
7041 report_file_errno ("Failed select", Qnil, xerrno);
7044 /* Check for keyboard input. */
7046 if (read_kbd
7047 && detect_input_pending_run_timers (do_display))
7049 swallow_events (do_display);
7050 if (detect_input_pending_run_timers (do_display))
7051 break;
7054 /* If there is unread keyboard input, also return. */
7055 if (read_kbd
7056 && requeued_events_pending_p ())
7057 break;
7059 /* If wait_for_cell. check for keyboard input
7060 but don't run any timers.
7061 ??? (It seems wrong to me to check for keyboard
7062 input at all when wait_for_cell, but the code
7063 has been this way since July 1994.
7064 Try changing this after version 19.31.) */
7065 if (! NILP (wait_for_cell)
7066 && detect_input_pending ())
7068 swallow_events (do_display);
7069 if (detect_input_pending ())
7070 break;
7073 /* Exit now if the cell we're waiting for became non-nil. */
7074 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7075 break;
7078 start_polling ();
7080 return -1;
7083 #endif /* not subprocesses */
7085 /* The following functions are needed even if async subprocesses are
7086 not supported. Some of them are no-op stubs in that case. */
7088 #ifdef HAVE_TIMERFD
7090 /* Add FD, which is a descriptor returned by timerfd_create,
7091 to the set of non-keyboard input descriptors. */
7093 void
7094 add_timer_wait_descriptor (int fd)
7096 FD_SET (fd, &input_wait_mask);
7097 FD_SET (fd, &non_keyboard_wait_mask);
7098 FD_SET (fd, &non_process_wait_mask);
7099 fd_callback_info[fd].func = timerfd_callback;
7100 fd_callback_info[fd].data = NULL;
7101 fd_callback_info[fd].condition |= FOR_READ;
7102 if (fd > max_input_desc)
7103 max_input_desc = fd;
7106 #endif /* HAVE_TIMERFD */
7108 /* If program file NAME starts with /: for quoting a magic
7109 name, remove that, preserving the multibyteness of NAME. */
7111 Lisp_Object
7112 remove_slash_colon (Lisp_Object name)
7114 return
7115 ((SBYTES (name) > 2 && SREF (name, 0) == '/' && SREF (name, 1) == ':')
7116 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
7117 SBYTES (name) - 2, STRING_MULTIBYTE (name))
7118 : name);
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);
7647 Lisp_Object subfeatures = Qnil;
7648 const struct socket_options *sopt;
7650 #define ADD_SUBFEATURE(key, val) \
7651 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7653 #ifdef NON_BLOCKING_CONNECT
7654 ADD_SUBFEATURE (QCnowait, Qt);
7655 #endif
7656 #ifdef DATAGRAM_SOCKETS
7657 ADD_SUBFEATURE (QCtype, Qdatagram);
7658 #endif
7659 #ifdef HAVE_SEQPACKET
7660 ADD_SUBFEATURE (QCtype, Qseqpacket);
7661 #endif
7662 #ifdef HAVE_LOCAL_SOCKETS
7663 ADD_SUBFEATURE (QCfamily, Qlocal);
7664 #endif
7665 ADD_SUBFEATURE (QCfamily, Qipv4);
7666 #ifdef AF_INET6
7667 ADD_SUBFEATURE (QCfamily, Qipv6);
7668 #endif
7669 #ifdef HAVE_GETSOCKNAME
7670 ADD_SUBFEATURE (QCservice, Qt);
7671 #endif
7672 ADD_SUBFEATURE (QCserver, Qt);
7674 for (sopt = socket_options; sopt->name; sopt++)
7675 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7677 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7680 #endif /* subprocesses */
7682 defsubr (&Sget_buffer_process);
7683 defsubr (&Sprocess_inherit_coding_system_flag);
7684 defsubr (&Slist_system_processes);
7685 defsubr (&Sprocess_attributes);