`nreverse' Grep hits before passing them to xref--convert-hits
[emacs.git] / src / process.c
blob2c758a4c9a7801f4bc0f51865efb47fe95b06dfd
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 #ifndef HAVE_ACCEPT4
156 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
158 static int
159 close_on_exec (int fd)
161 if (0 <= fd)
162 fcntl (fd, F_SETFD, FD_CLOEXEC);
163 return fd;
166 # undef accept4
167 # define accept4(sockfd, addr, addrlen, flags) \
168 process_accept4 (sockfd, addr, addrlen, flags)
169 static int
170 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
172 return close_on_exec (accept (sockfd, addr, addrlen));
175 static int
176 process_socket (int domain, int type, int protocol)
178 return close_on_exec (socket (domain, type, protocol));
180 # undef socket
181 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
182 #endif
184 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
185 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
186 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
187 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
188 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
189 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
191 /* Number of events of change of status of a process. */
192 static EMACS_INT process_tick;
193 /* Number of events for which the user or sentinel has been notified. */
194 static EMACS_INT update_tick;
196 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects.
197 The code can be simplified by assuming NON_BLOCKING_CONNECT once
198 Emacs starts assuming POSIX 1003.1-2001 or later. */
200 #if (defined HAVE_SELECT \
201 && (defined GNU_LINUX || defined HAVE_GETPEERNAME) \
202 && (defined EWOULDBLOCK || defined EINPROGRESS))
203 # define NON_BLOCKING_CONNECT
204 #endif
206 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
207 this system. We need to read full packets, so we need a
208 "non-destructive" select. So we require either native select,
209 or emulation of select using FIONREAD. */
211 #ifndef BROKEN_DATAGRAM_SOCKETS
212 # if defined HAVE_SELECT || defined USABLE_FIONREAD
213 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
214 # define DATAGRAM_SOCKETS
215 # endif
216 # endif
217 #endif
219 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
220 # define HAVE_SEQPACKET
221 #endif
223 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
224 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
225 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
227 /* Number of processes which have a non-zero read_output_delay,
228 and therefore might be delayed for adaptive read buffering. */
230 static int process_output_delay_count;
232 /* True if any process has non-nil read_output_skip. */
234 static bool process_output_skip;
236 static void create_process (Lisp_Object, char **, Lisp_Object);
237 #ifdef USABLE_SIGIO
238 static bool keyboard_bit_set (fd_set *);
239 #endif
240 static void deactivate_process (Lisp_Object);
241 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
242 static int read_process_output (Lisp_Object, int);
243 static void handle_child_signal (int);
244 static void create_pty (Lisp_Object);
246 static Lisp_Object get_process (register Lisp_Object name);
247 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
249 /* Mask of bits indicating the descriptors that we wait for input on. */
251 static fd_set input_wait_mask;
253 /* Mask that excludes keyboard input descriptor(s). */
255 static fd_set non_keyboard_wait_mask;
257 /* Mask that excludes process input descriptor(s). */
259 static fd_set non_process_wait_mask;
261 /* Mask for selecting for write. */
263 static fd_set write_mask;
265 #ifdef NON_BLOCKING_CONNECT
266 /* Mask of bits indicating the descriptors that we wait for connect to
267 complete on. Once they complete, they are removed from this mask
268 and added to the input_wait_mask and non_keyboard_wait_mask. */
270 static fd_set connect_wait_mask;
272 /* Number of bits set in connect_wait_mask. */
273 static int num_pending_connects;
274 #endif /* NON_BLOCKING_CONNECT */
276 /* The largest descriptor currently in use for a process object; -1 if none. */
277 static int max_process_desc;
279 /* The largest descriptor currently in use for input; -1 if none. */
280 static int max_input_desc;
282 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
283 static Lisp_Object chan_process[FD_SETSIZE];
285 /* Alist of elements (NAME . PROCESS). */
286 static Lisp_Object Vprocess_alist;
288 /* Buffered-ahead input char from process, indexed by channel.
289 -1 means empty (no char is buffered).
290 Used on sys V where the only way to tell if there is any
291 output from the process is to read at least one char.
292 Always -1 on systems that support FIONREAD. */
294 static int proc_buffered_char[FD_SETSIZE];
296 /* Table of `struct coding-system' for each process. */
297 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
298 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
300 #ifdef DATAGRAM_SOCKETS
301 /* Table of `partner address' for datagram sockets. */
302 static struct sockaddr_and_len {
303 struct sockaddr *sa;
304 int len;
305 } datagram_address[FD_SETSIZE];
306 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
307 #define DATAGRAM_CONN_P(proc) \
308 (PROCESSP (proc) && \
309 XPROCESS (proc)->infd >= 0 && \
310 datagram_address[XPROCESS (proc)->infd].sa != 0)
311 #else
312 #define DATAGRAM_CHAN_P(chan) (0)
313 #define DATAGRAM_CONN_P(proc) (0)
314 #endif
316 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
317 a `for' loop which iterates over processes from Vprocess_alist. */
319 #define FOR_EACH_PROCESS(list_var, proc_var) \
320 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
322 /* These setters are used only in this file, so they can be private. */
323 static void
324 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
326 p->buffer = val;
328 static void
329 pset_command (struct Lisp_Process *p, Lisp_Object val)
331 p->command = val;
333 static void
334 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
336 p->decode_coding_system = val;
338 static void
339 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
341 p->decoding_buf = val;
343 static void
344 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
346 p->encode_coding_system = val;
348 static void
349 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
351 p->encoding_buf = val;
353 static void
354 pset_filter (struct Lisp_Process *p, Lisp_Object val)
356 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
358 static void
359 pset_log (struct Lisp_Process *p, Lisp_Object val)
361 p->log = val;
363 static void
364 pset_mark (struct Lisp_Process *p, Lisp_Object val)
366 p->mark = val;
368 static void
369 pset_name (struct Lisp_Process *p, Lisp_Object val)
371 p->name = val;
373 static void
374 pset_plist (struct Lisp_Process *p, Lisp_Object val)
376 p->plist = val;
378 static void
379 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
381 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
383 static void
384 pset_status (struct Lisp_Process *p, Lisp_Object val)
386 p->status = val;
388 static void
389 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
391 p->tty_name = val;
393 static void
394 pset_type (struct Lisp_Process *p, Lisp_Object val)
396 p->type = val;
398 static void
399 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
401 p->write_queue = val;
403 static void
404 pset_stderrproc (struct Lisp_Process *p, Lisp_Object val)
406 p->stderrproc = val;
410 static Lisp_Object
411 make_lisp_proc (struct Lisp_Process *p)
413 return make_lisp_ptr (p, Lisp_Vectorlike);
416 static struct fd_callback_data
418 fd_callback func;
419 void *data;
420 #define FOR_READ 1
421 #define FOR_WRITE 2
422 int condition; /* Mask of the defines above. */
423 } fd_callback_info[FD_SETSIZE];
426 /* Add a file descriptor FD to be monitored for when read is possible.
427 When read is possible, call FUNC with argument DATA. */
429 void
430 add_read_fd (int fd, fd_callback func, void *data)
432 add_keyboard_wait_descriptor (fd);
434 fd_callback_info[fd].func = func;
435 fd_callback_info[fd].data = data;
436 fd_callback_info[fd].condition |= FOR_READ;
439 /* Stop monitoring file descriptor FD for when read is possible. */
441 void
442 delete_read_fd (int fd)
444 delete_keyboard_wait_descriptor (fd);
446 fd_callback_info[fd].condition &= ~FOR_READ;
447 if (fd_callback_info[fd].condition == 0)
449 fd_callback_info[fd].func = 0;
450 fd_callback_info[fd].data = 0;
454 /* Add a file descriptor FD to be monitored for when write is possible.
455 When write is possible, call FUNC with argument DATA. */
457 void
458 add_write_fd (int fd, fd_callback func, void *data)
460 FD_SET (fd, &write_mask);
461 if (fd > max_input_desc)
462 max_input_desc = fd;
464 fd_callback_info[fd].func = func;
465 fd_callback_info[fd].data = data;
466 fd_callback_info[fd].condition |= FOR_WRITE;
469 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
471 static void
472 delete_input_desc (int fd)
474 if (fd == max_input_desc)
477 fd--;
478 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
479 || FD_ISSET (fd, &write_mask)));
481 max_input_desc = fd;
485 /* Stop monitoring file descriptor FD for when write is possible. */
487 void
488 delete_write_fd (int fd)
490 FD_CLR (fd, &write_mask);
491 fd_callback_info[fd].condition &= ~FOR_WRITE;
492 if (fd_callback_info[fd].condition == 0)
494 fd_callback_info[fd].func = 0;
495 fd_callback_info[fd].data = 0;
496 delete_input_desc (fd);
501 /* Compute the Lisp form of the process status, p->status, from
502 the numeric status that was returned by `wait'. */
504 static Lisp_Object status_convert (int);
506 static void
507 update_status (struct Lisp_Process *p)
509 eassert (p->raw_status_new);
510 pset_status (p, status_convert (p->raw_status));
511 p->raw_status_new = 0;
514 /* Convert a process status word in Unix format to
515 the list that we use internally. */
517 static Lisp_Object
518 status_convert (int w)
520 if (WIFSTOPPED (w))
521 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
522 else if (WIFEXITED (w))
523 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
524 WCOREDUMP (w) ? Qt : Qnil));
525 else if (WIFSIGNALED (w))
526 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
527 WCOREDUMP (w) ? Qt : Qnil));
528 else
529 return Qrun;
532 /* Given a status-list, extract the three pieces of information
533 and store them individually through the three pointers. */
535 static void
536 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
538 Lisp_Object tem;
540 if (SYMBOLP (l))
542 *symbol = l;
543 *code = 0;
544 *coredump = 0;
546 else
548 *symbol = XCAR (l);
549 tem = XCDR (l);
550 *code = XFASTINT (XCAR (tem));
551 tem = XCDR (tem);
552 *coredump = !NILP (tem);
556 /* Return a string describing a process status list. */
558 static Lisp_Object
559 status_message (struct Lisp_Process *p)
561 Lisp_Object status = p->status;
562 Lisp_Object symbol;
563 int code;
564 bool coredump;
565 Lisp_Object string;
567 decode_status (status, &symbol, &code, &coredump);
569 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
571 char const *signame;
572 synchronize_system_messages_locale ();
573 signame = strsignal (code);
574 if (signame == 0)
575 string = build_string ("unknown");
576 else
578 int c1, c2;
580 string = build_unibyte_string (signame);
581 if (! NILP (Vlocale_coding_system))
582 string = (code_convert_string_norecord
583 (string, Vlocale_coding_system, 0));
584 c1 = STRING_CHAR (SDATA (string));
585 c2 = downcase (c1);
586 if (c1 != c2)
587 Faset (string, make_number (0), make_number (c2));
589 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
590 return concat2 (string, suffix);
592 else if (EQ (symbol, Qexit))
594 if (NETCONN1_P (p))
595 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
596 if (code == 0)
597 return build_string ("finished\n");
598 AUTO_STRING (prefix, "exited abnormally with code ");
599 string = Fnumber_to_string (make_number (code));
600 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
601 return concat3 (prefix, string, suffix);
603 else if (EQ (symbol, Qfailed))
605 AUTO_STRING (prefix, "failed with code ");
606 string = Fnumber_to_string (make_number (code));
607 AUTO_STRING (suffix, "\n");
608 return concat3 (prefix, string, suffix);
610 else
611 return Fcopy_sequence (Fsymbol_name (symbol));
614 enum { PTY_NAME_SIZE = 24 };
616 /* Open an available pty, returning a file descriptor.
617 Store into PTY_NAME the file name of the terminal corresponding to the pty.
618 Return -1 on failure. */
620 static int
621 allocate_pty (char pty_name[PTY_NAME_SIZE])
623 #ifdef HAVE_PTYS
624 int fd;
626 #ifdef PTY_ITERATION
627 PTY_ITERATION
628 #else
629 register int c, i;
630 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
631 for (i = 0; i < 16; i++)
632 #endif
634 #ifdef PTY_NAME_SPRINTF
635 PTY_NAME_SPRINTF
636 #else
637 sprintf (pty_name, "/dev/pty%c%x", c, i);
638 #endif /* no PTY_NAME_SPRINTF */
640 #ifdef PTY_OPEN
641 PTY_OPEN;
642 #else /* no PTY_OPEN */
643 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
644 #endif /* no PTY_OPEN */
646 if (fd >= 0)
648 #ifdef PTY_TTY_NAME_SPRINTF
649 PTY_TTY_NAME_SPRINTF
650 #else
651 sprintf (pty_name, "/dev/tty%c%x", c, i);
652 #endif /* no PTY_TTY_NAME_SPRINTF */
654 /* Set FD's close-on-exec flag. This is needed even if
655 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
656 doesn't require support for that combination.
657 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
658 doesn't work if the close-on-exec flag is set (Bug#20555).
659 Multithreaded platforms where posix_openpt ignores
660 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
661 have a race condition between the PTY_OPEN and here. */
662 fcntl (fd, F_SETFD, FD_CLOEXEC);
664 /* Check to make certain that both sides are available.
665 This avoids a nasty yet stupid bug in rlogins. */
666 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
668 emacs_close (fd);
669 # ifndef __sgi
670 continue;
671 # else
672 return -1;
673 # endif /* __sgi */
675 setup_pty (fd);
676 return fd;
679 #endif /* HAVE_PTYS */
680 return -1;
683 /* Allocate basically initialized process. */
685 static struct Lisp_Process *
686 allocate_process (void)
688 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
691 static Lisp_Object
692 make_process (Lisp_Object name)
694 register Lisp_Object val, tem, name1;
695 register struct Lisp_Process *p;
696 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
697 printmax_t i;
699 p = allocate_process ();
700 /* Initialize Lisp data. Note that allocate_process initializes all
701 Lisp data to nil, so do it only for slots which should not be nil. */
702 pset_status (p, Qrun);
703 pset_mark (p, Fmake_marker ());
705 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
706 non-Lisp data, so do it only for slots which should not be zero. */
707 p->infd = -1;
708 p->outfd = -1;
709 for (i = 0; i < PROCESS_OPEN_FDS; i++)
710 p->open_fd[i] = -1;
712 #ifdef HAVE_GNUTLS
713 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
714 #endif
716 /* If name is already in use, modify it until it is unused. */
718 name1 = name;
719 for (i = 1; ; i++)
721 tem = Fget_process (name1);
722 if (NILP (tem)) break;
723 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
725 name = name1;
726 pset_name (p, name);
727 pset_sentinel (p, Qinternal_default_process_sentinel);
728 pset_filter (p, Qinternal_default_process_filter);
729 XSETPROCESS (val, p);
730 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
731 return val;
734 static void
735 remove_process (register Lisp_Object proc)
737 register Lisp_Object pair;
739 pair = Frassq (proc, Vprocess_alist);
740 Vprocess_alist = Fdelq (pair, Vprocess_alist);
742 deactivate_process (proc);
746 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
747 doc: /* Return t if OBJECT is a process. */)
748 (Lisp_Object object)
750 return PROCESSP (object) ? Qt : Qnil;
753 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
754 doc: /* Return the process named NAME, or nil if there is none. */)
755 (register Lisp_Object name)
757 if (PROCESSP (name))
758 return name;
759 CHECK_STRING (name);
760 return Fcdr (Fassoc (name, Vprocess_alist));
763 /* This is how commands for the user decode process arguments. It
764 accepts a process, a process name, a buffer, a buffer name, or nil.
765 Buffers denote the first process in the buffer, and nil denotes the
766 current buffer. */
768 static Lisp_Object
769 get_process (register Lisp_Object name)
771 register Lisp_Object proc, obj;
772 if (STRINGP (name))
774 obj = Fget_process (name);
775 if (NILP (obj))
776 obj = Fget_buffer (name);
777 if (NILP (obj))
778 error ("Process %s does not exist", SDATA (name));
780 else if (NILP (name))
781 obj = Fcurrent_buffer ();
782 else
783 obj = name;
785 /* Now obj should be either a buffer object or a process object. */
786 if (BUFFERP (obj))
788 if (NILP (BVAR (XBUFFER (obj), name)))
789 error ("Attempt to get process for a dead buffer");
790 proc = Fget_buffer_process (obj);
791 if (NILP (proc))
792 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
794 else
796 CHECK_PROCESS (obj);
797 proc = obj;
799 return proc;
803 /* Fdelete_process promises to immediately forget about the process, but in
804 reality, Emacs needs to remember those processes until they have been
805 treated by the SIGCHLD handler and waitpid has been invoked on them;
806 otherwise they might fill up the kernel's process table.
808 Some processes created by call-process are also put onto this list.
810 Members of this list are (process-ID . filename) pairs. The
811 process-ID is a number; the filename, if a string, is a file that
812 needs to be removed after the process exits. */
813 static Lisp_Object deleted_pid_list;
815 void
816 record_deleted_pid (pid_t pid, Lisp_Object filename)
818 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
819 /* GC treated elements set to nil. */
820 Fdelq (Qnil, deleted_pid_list));
824 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
825 doc: /* Delete PROCESS: kill it and forget about it immediately.
826 PROCESS may be a process, a buffer, the name of a process or buffer, or
827 nil, indicating the current buffer's process. */)
828 (register Lisp_Object process)
830 register struct Lisp_Process *p;
832 process = get_process (process);
833 p = XPROCESS (process);
835 p->raw_status_new = 0;
836 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
838 pset_status (p, list2 (Qexit, make_number (0)));
839 p->tick = ++process_tick;
840 status_notify (p, NULL);
841 redisplay_preserve_echo_area (13);
843 else
845 if (p->alive)
846 record_kill_process (p, Qnil);
848 if (p->infd >= 0)
850 /* Update P's status, since record_kill_process will make the
851 SIGCHLD handler update deleted_pid_list, not *P. */
852 Lisp_Object symbol;
853 if (p->raw_status_new)
854 update_status (p);
855 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
856 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
857 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
859 p->tick = ++process_tick;
860 status_notify (p, NULL);
861 redisplay_preserve_echo_area (13);
864 remove_process (process);
865 return Qnil;
868 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
869 doc: /* Return the status of PROCESS.
870 The returned value is one of the following symbols:
871 run -- for a process that is running.
872 stop -- for a process stopped but continuable.
873 exit -- for a process that has exited.
874 signal -- for a process that has got a fatal signal.
875 open -- for a network stream connection that is open.
876 listen -- for a network stream server that is listening.
877 closed -- for a network stream connection that is closed.
878 connect -- when waiting for a non-blocking connection to complete.
879 failed -- when a non-blocking connection has failed.
880 nil -- if arg is a process name and no such process exists.
881 PROCESS may be a process, a buffer, the name of a process, or
882 nil, indicating the current buffer's process. */)
883 (register Lisp_Object process)
885 register struct Lisp_Process *p;
886 register Lisp_Object status;
888 if (STRINGP (process))
889 process = Fget_process (process);
890 else
891 process = get_process (process);
893 if (NILP (process))
894 return process;
896 p = XPROCESS (process);
897 if (p->raw_status_new)
898 update_status (p);
899 status = p->status;
900 if (CONSP (status))
901 status = XCAR (status);
902 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
904 if (EQ (status, Qexit))
905 status = Qclosed;
906 else if (EQ (p->command, Qt))
907 status = Qstop;
908 else if (EQ (status, Qrun))
909 status = Qopen;
911 return status;
914 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
915 1, 1, 0,
916 doc: /* Return the exit status of PROCESS or the signal number that killed it.
917 If PROCESS has not yet exited or died, return 0. */)
918 (register Lisp_Object process)
920 CHECK_PROCESS (process);
921 if (XPROCESS (process)->raw_status_new)
922 update_status (XPROCESS (process));
923 if (CONSP (XPROCESS (process)->status))
924 return XCAR (XCDR (XPROCESS (process)->status));
925 return make_number (0);
928 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
929 doc: /* Return the process id of PROCESS.
930 This is the pid of the external process which PROCESS uses or talks to.
931 For a network connection, this value is nil. */)
932 (register Lisp_Object process)
934 pid_t pid;
936 CHECK_PROCESS (process);
937 pid = XPROCESS (process)->pid;
938 return (pid ? make_fixnum_or_float (pid) : Qnil);
941 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
942 doc: /* Return the name of PROCESS, as a string.
943 This is the name of the program invoked in PROCESS,
944 possibly modified to make it unique among process names. */)
945 (register Lisp_Object process)
947 CHECK_PROCESS (process);
948 return XPROCESS (process)->name;
951 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
952 doc: /* Return the command that was executed to start PROCESS.
953 This is a list of strings, the first string being the program executed
954 and the rest of the strings being the arguments given to it.
955 For a network or serial process, this is nil (process is running) or t
956 \(process is stopped). */)
957 (register Lisp_Object process)
959 CHECK_PROCESS (process);
960 return XPROCESS (process)->command;
963 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
964 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
965 This is the terminal that the process itself reads and writes on,
966 not the name of the pty that Emacs uses to talk with that terminal. */)
967 (register Lisp_Object process)
969 CHECK_PROCESS (process);
970 return XPROCESS (process)->tty_name;
973 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
974 2, 2, 0,
975 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
976 Return BUFFER. */)
977 (register Lisp_Object process, Lisp_Object buffer)
979 struct Lisp_Process *p;
981 CHECK_PROCESS (process);
982 if (!NILP (buffer))
983 CHECK_BUFFER (buffer);
984 p = XPROCESS (process);
985 pset_buffer (p, buffer);
986 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
987 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
988 setup_process_coding_systems (process);
989 return buffer;
992 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
993 1, 1, 0,
994 doc: /* Return the buffer PROCESS is associated with.
995 The default process filter inserts output from PROCESS into this buffer. */)
996 (register Lisp_Object process)
998 CHECK_PROCESS (process);
999 return XPROCESS (process)->buffer;
1002 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1003 1, 1, 0,
1004 doc: /* Return the marker for the end of the last output from PROCESS. */)
1005 (register Lisp_Object process)
1007 CHECK_PROCESS (process);
1008 return XPROCESS (process)->mark;
1011 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1012 2, 2, 0,
1013 doc: /* Give PROCESS the filter function FILTER; nil means default.
1014 A value of t means stop accepting output from the process.
1016 When a process has a non-default filter, its buffer is not used for output.
1017 Instead, each time it does output, the entire string of output is
1018 passed to the filter.
1020 The filter gets two arguments: the process and the string of output.
1021 The string argument is normally a multibyte string, except:
1022 - if the process's input coding system is no-conversion or raw-text,
1023 it is a unibyte string (the non-converted input), or else
1024 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1025 string (the result of converting the decoded input multibyte
1026 string to unibyte with `string-make-unibyte'). */)
1027 (register Lisp_Object process, Lisp_Object filter)
1029 struct Lisp_Process *p;
1031 CHECK_PROCESS (process);
1032 p = XPROCESS (process);
1034 /* Don't signal an error if the process's input file descriptor
1035 is closed. This could make debugging Lisp more difficult,
1036 for example when doing something like
1038 (setq process (start-process ...))
1039 (debug)
1040 (set-process-filter process ...) */
1042 if (NILP (filter))
1043 filter = Qinternal_default_process_filter;
1045 if (p->infd >= 0)
1047 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1049 FD_CLR (p->infd, &input_wait_mask);
1050 FD_CLR (p->infd, &non_keyboard_wait_mask);
1052 else if (EQ (p->filter, Qt)
1053 /* Network or serial process not stopped: */
1054 && !EQ (p->command, Qt))
1056 FD_SET (p->infd, &input_wait_mask);
1057 FD_SET (p->infd, &non_keyboard_wait_mask);
1061 pset_filter (p, filter);
1062 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1063 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1064 setup_process_coding_systems (process);
1065 return filter;
1068 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1069 1, 1, 0,
1070 doc: /* Return the filter function of PROCESS.
1071 See `set-process-filter' for more info on filter functions. */)
1072 (register Lisp_Object process)
1074 CHECK_PROCESS (process);
1075 return XPROCESS (process)->filter;
1078 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1079 2, 2, 0,
1080 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1081 The sentinel is called as a function when the process changes state.
1082 It gets two arguments: the process, and a string describing the change. */)
1083 (register Lisp_Object process, Lisp_Object sentinel)
1085 struct Lisp_Process *p;
1087 CHECK_PROCESS (process);
1088 p = XPROCESS (process);
1090 if (NILP (sentinel))
1091 sentinel = Qinternal_default_process_sentinel;
1093 pset_sentinel (p, sentinel);
1094 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1095 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1096 return sentinel;
1099 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1100 1, 1, 0,
1101 doc: /* Return the sentinel of PROCESS.
1102 See `set-process-sentinel' for more info on sentinels. */)
1103 (register Lisp_Object process)
1105 CHECK_PROCESS (process);
1106 return XPROCESS (process)->sentinel;
1109 DEFUN ("set-process-window-size", Fset_process_window_size,
1110 Sset_process_window_size, 3, 3, 0,
1111 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1112 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1114 CHECK_PROCESS (process);
1116 /* All known platforms store window sizes as 'unsigned short'. */
1117 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1118 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1120 if (XPROCESS (process)->infd < 0
1121 || (set_window_size (XPROCESS (process)->infd,
1122 XINT (height), XINT (width))
1123 < 0))
1124 return Qnil;
1125 else
1126 return Qt;
1129 DEFUN ("set-process-inherit-coding-system-flag",
1130 Fset_process_inherit_coding_system_flag,
1131 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1132 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1133 If the second argument FLAG is non-nil, then the variable
1134 `buffer-file-coding-system' of the buffer associated with PROCESS
1135 will be bound to the value of the coding system used to decode
1136 the process output.
1138 This is useful when the coding system specified for the process buffer
1139 leaves either the character code conversion or the end-of-line conversion
1140 unspecified, or if the coding system used to decode the process output
1141 is more appropriate for saving the process buffer.
1143 Binding the variable `inherit-process-coding-system' to non-nil before
1144 starting the process is an alternative way of setting the inherit flag
1145 for the process which will run.
1147 This function returns FLAG. */)
1148 (register Lisp_Object process, Lisp_Object flag)
1150 CHECK_PROCESS (process);
1151 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1152 return flag;
1155 DEFUN ("set-process-query-on-exit-flag",
1156 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1157 2, 2, 0,
1158 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1159 If the second argument FLAG is non-nil, Emacs will query the user before
1160 exiting or killing a buffer if PROCESS is running. This function
1161 returns FLAG. */)
1162 (register Lisp_Object process, Lisp_Object flag)
1164 CHECK_PROCESS (process);
1165 XPROCESS (process)->kill_without_query = NILP (flag);
1166 return flag;
1169 DEFUN ("process-query-on-exit-flag",
1170 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1171 1, 1, 0,
1172 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1173 (register Lisp_Object process)
1175 CHECK_PROCESS (process);
1176 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1179 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1180 1, 2, 0,
1181 doc: /* Return the contact info of PROCESS; t for a real child.
1182 For a network or serial connection, the value depends on the optional
1183 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1184 SERVICE) for a network connection or (PORT SPEED) for a serial
1185 connection. If KEY is t, the complete contact information for the
1186 connection is returned, else the specific value for the keyword KEY is
1187 returned. See `make-network-process' or `make-serial-process' for a
1188 list of keywords. */)
1189 (register Lisp_Object process, Lisp_Object key)
1191 Lisp_Object contact;
1193 CHECK_PROCESS (process);
1194 contact = XPROCESS (process)->childp;
1196 #ifdef DATAGRAM_SOCKETS
1197 if (DATAGRAM_CONN_P (process)
1198 && (EQ (key, Qt) || EQ (key, QCremote)))
1199 contact = Fplist_put (contact, QCremote,
1200 Fprocess_datagram_address (process));
1201 #endif
1203 if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1204 || EQ (key, Qt))
1205 return contact;
1206 if (NILP (key) && NETCONN_P (process))
1207 return list2 (Fplist_get (contact, QChost),
1208 Fplist_get (contact, QCservice));
1209 if (NILP (key) && SERIALCONN_P (process))
1210 return list2 (Fplist_get (contact, QCport),
1211 Fplist_get (contact, QCspeed));
1212 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1213 if the pipe process is useful for purposes other than receiving
1214 stderr. */
1215 if (NILP (key) && PIPECONN_P (process))
1216 return Qt;
1217 return Fplist_get (contact, key);
1220 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1221 1, 1, 0,
1222 doc: /* Return the plist of PROCESS. */)
1223 (register Lisp_Object process)
1225 CHECK_PROCESS (process);
1226 return XPROCESS (process)->plist;
1229 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1230 2, 2, 0,
1231 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1232 (register Lisp_Object process, Lisp_Object plist)
1234 CHECK_PROCESS (process);
1235 CHECK_LIST (plist);
1237 pset_plist (XPROCESS (process), plist);
1238 return plist;
1241 #if 0 /* Turned off because we don't currently record this info
1242 in the process. Perhaps add it. */
1243 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1244 doc: /* Return the connection type of PROCESS.
1245 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1246 a socket connection. */)
1247 (Lisp_Object process)
1249 return XPROCESS (process)->type;
1251 #endif
1253 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1254 doc: /* Return the connection type of PROCESS.
1255 The value is either the symbol `real', `network', or `serial'.
1256 PROCESS may be a process, a buffer, the name of a process or buffer, or
1257 nil, indicating the current buffer's process. */)
1258 (Lisp_Object process)
1260 Lisp_Object proc;
1261 proc = get_process (process);
1262 return XPROCESS (proc)->type;
1265 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1266 1, 2, 0,
1267 doc: /* Convert network ADDRESS from internal format to a string.
1268 A 4 or 5 element vector represents an IPv4 address (with port number).
1269 An 8 or 9 element vector represents an IPv6 address (with port number).
1270 If optional second argument OMIT-PORT is non-nil, don't include a port
1271 number in the string, even when present in ADDRESS.
1272 Returns nil if format of ADDRESS is invalid. */)
1273 (Lisp_Object address, Lisp_Object omit_port)
1275 if (NILP (address))
1276 return Qnil;
1278 if (STRINGP (address)) /* AF_LOCAL */
1279 return address;
1281 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1283 register struct Lisp_Vector *p = XVECTOR (address);
1284 ptrdiff_t size = p->header.size;
1285 Lisp_Object args[10];
1286 int nargs, i;
1287 char const *format;
1289 if (size == 4 || (size == 5 && !NILP (omit_port)))
1291 format = "%d.%d.%d.%d";
1292 nargs = 4;
1294 else if (size == 5)
1296 format = "%d.%d.%d.%d:%d";
1297 nargs = 5;
1299 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1301 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1302 nargs = 8;
1304 else if (size == 9)
1306 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1307 nargs = 9;
1309 else
1310 return Qnil;
1312 AUTO_STRING (format_obj, format);
1313 args[0] = format_obj;
1315 for (i = 0; i < nargs; i++)
1317 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1318 return Qnil;
1320 if (nargs <= 5 /* IPv4 */
1321 && i < 4 /* host, not port */
1322 && XINT (p->contents[i]) > 255)
1323 return Qnil;
1325 args[i + 1] = p->contents[i];
1328 return Fformat (nargs + 1, args);
1331 if (CONSP (address))
1333 AUTO_STRING (format, "<Family %d>");
1334 return CALLN (Fformat, format, Fcar (address));
1337 return Qnil;
1340 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1341 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1342 (void)
1344 return Fmapcar (Qcdr, Vprocess_alist);
1347 /* Starting asynchronous inferior processes. */
1349 static void start_process_unwind (Lisp_Object proc);
1351 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1352 doc: /* Start a program in a subprocess. Return the process object for it.
1354 This is similar to `start-process', but arguments are specified as
1355 keyword/argument pairs. The following arguments are defined:
1357 :name NAME -- NAME is name for process. It is modified if necessary
1358 to make it unique.
1360 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1361 with the process. Process output goes at end of that buffer, unless
1362 you specify an output stream or filter function to handle the output.
1363 BUFFER may be also nil, meaning that this process is not associated
1364 with any buffer.
1366 :command COMMAND -- COMMAND is a list starting with the program file
1367 name, followed by strings to give to the program as arguments.
1369 :coding CODING -- If CODING is a symbol, it specifies the coding
1370 system used for both reading and writing for this process. If CODING
1371 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1372 ENCODING is used for writing.
1374 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1375 the process is running. If BOOL is not given, query before exiting.
1377 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1378 In the stopped state, a process does not accept incoming data, but you
1379 can send outgoing data. The stopped state is cleared by
1380 `continue-process' and set by `stop-process'.
1382 :connection-type TYPE -- TYPE is control type of device used to
1383 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1384 to use a pty, or nil to use the default specified through
1385 `process-connection-type'.
1387 :filter FILTER -- Install FILTER as the process filter.
1389 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1391 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1392 to the standard error of subprocess. Specifying this implies
1393 `:connection-type' is set to `pipe'.
1395 usage: (make-process &rest ARGS) */)
1396 (ptrdiff_t nargs, Lisp_Object *args)
1398 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1399 Lisp_Object xstderr, stderrproc;
1400 ptrdiff_t count = SPECPDL_INDEX ();
1401 USE_SAFE_ALLOCA;
1403 if (nargs == 0)
1404 return Qnil;
1406 /* Save arguments for process-contact and clone-process. */
1407 contact = Flist (nargs, args);
1409 buffer = Fplist_get (contact, QCbuffer);
1410 if (!NILP (buffer))
1411 buffer = Fget_buffer_create (buffer);
1413 /* Make sure that the child will be able to chdir to the current
1414 buffer's current directory, or its unhandled equivalent. We
1415 can't just have the child check for an error when it does the
1416 chdir, since it's in a vfork. */
1417 current_dir = encode_current_directory ();
1419 name = Fplist_get (contact, QCname);
1420 CHECK_STRING (name);
1422 command = Fplist_get (contact, QCcommand);
1423 if (CONSP (command))
1424 program = XCAR (command);
1425 else
1426 program = Qnil;
1428 if (!NILP (program))
1429 CHECK_STRING (program);
1431 stderrproc = Qnil;
1432 xstderr = Fplist_get (contact, QCstderr);
1433 if (PROCESSP (xstderr))
1435 if (!PIPECONN_P (xstderr))
1436 error ("Process is not a pipe process");
1437 stderrproc = xstderr;
1439 else if (!NILP (xstderr))
1441 CHECK_STRING (program);
1442 stderrproc = CALLN (Fmake_pipe_process,
1443 QCname,
1444 concat2 (name, build_string (" stderr")),
1445 QCbuffer,
1446 Fget_buffer_create (xstderr));
1449 proc = make_process (name);
1450 /* If an error occurs and we can't start the process, we want to
1451 remove it from the process list. This means that each error
1452 check in create_process doesn't need to call remove_process
1453 itself; it's all taken care of here. */
1454 record_unwind_protect (start_process_unwind, proc);
1456 pset_childp (XPROCESS (proc), Qt);
1457 pset_plist (XPROCESS (proc), Qnil);
1458 pset_type (XPROCESS (proc), Qreal);
1459 pset_buffer (XPROCESS (proc), buffer);
1460 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1461 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1462 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1464 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
1465 XPROCESS (proc)->kill_without_query = 1;
1466 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1467 pset_command (XPROCESS (proc), Qt);
1469 tem = Fplist_get (contact, QCconnection_type);
1470 if (EQ (tem, Qpty))
1471 XPROCESS (proc)->pty_flag = true;
1472 else if (EQ (tem, Qpipe))
1473 XPROCESS (proc)->pty_flag = false;
1474 else if (NILP (tem))
1475 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1476 else
1477 report_file_error ("Unknown connection type", tem);
1479 if (!NILP (stderrproc))
1481 pset_stderrproc (XPROCESS (proc), stderrproc);
1483 XPROCESS (proc)->pty_flag = false;
1486 #ifdef HAVE_GNUTLS
1487 /* AKA GNUTLS_INITSTAGE(proc). */
1488 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1489 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1490 #endif
1492 XPROCESS (proc)->adaptive_read_buffering
1493 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1494 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1496 /* Make the process marker point into the process buffer (if any). */
1497 if (BUFFERP (buffer))
1498 set_marker_both (XPROCESS (proc)->mark, buffer,
1499 BUF_ZV (XBUFFER (buffer)),
1500 BUF_ZV_BYTE (XBUFFER (buffer)));
1503 /* Decide coding systems for communicating with the process. Here
1504 we don't setup the structure coding_system nor pay attention to
1505 unibyte mode. They are done in create_process. */
1507 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1508 Lisp_Object coding_systems = Qt;
1509 Lisp_Object val, *args2;
1511 tem = Fplist_get (contact, QCcoding);
1512 if (!NILP (tem))
1514 val = tem;
1515 if (CONSP (val))
1516 val = XCAR (val);
1518 else
1519 val = Vcoding_system_for_read;
1520 if (NILP (val))
1522 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1523 Lisp_Object tem2;
1524 SAFE_ALLOCA_LISP (args2, nargs2);
1525 ptrdiff_t i = 0;
1526 args2[i++] = Qstart_process;
1527 args2[i++] = name;
1528 args2[i++] = buffer;
1529 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1530 args2[i++] = XCAR (tem2);
1531 if (!NILP (program))
1532 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1533 if (CONSP (coding_systems))
1534 val = XCAR (coding_systems);
1535 else if (CONSP (Vdefault_process_coding_system))
1536 val = XCAR (Vdefault_process_coding_system);
1538 pset_decode_coding_system (XPROCESS (proc), val);
1540 if (!NILP (tem))
1542 val = tem;
1543 if (CONSP (val))
1544 val = XCDR (val);
1546 else
1547 val = Vcoding_system_for_write;
1548 if (NILP (val))
1550 if (EQ (coding_systems, Qt))
1552 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1553 Lisp_Object tem2;
1554 SAFE_ALLOCA_LISP (args2, nargs2);
1555 ptrdiff_t i = 0;
1556 args2[i++] = Qstart_process;
1557 args2[i++] = name;
1558 args2[i++] = buffer;
1559 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1560 args2[i++] = XCAR (tem2);
1561 if (!NILP (program))
1562 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1564 if (CONSP (coding_systems))
1565 val = XCDR (coding_systems);
1566 else if (CONSP (Vdefault_process_coding_system))
1567 val = XCDR (Vdefault_process_coding_system);
1569 pset_encode_coding_system (XPROCESS (proc), val);
1570 /* Note: At this moment, the above coding system may leave
1571 text-conversion or eol-conversion unspecified. They will be
1572 decided after we read output from the process and decode it by
1573 some coding system, or just before we actually send a text to
1574 the process. */
1578 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1579 XPROCESS (proc)->decoding_carryover = 0;
1580 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1582 XPROCESS (proc)->inherit_coding_system_flag
1583 = !(NILP (buffer) || !inherit_process_coding_system);
1585 if (!NILP (program))
1587 Lisp_Object program_args = XCDR (command);
1589 /* If program file name is not absolute, search our path for it.
1590 Put the name we will really use in TEM. */
1591 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1592 && !(SCHARS (program) > 1
1593 && IS_DEVICE_SEP (SREF (program, 1))))
1595 tem = Qnil;
1596 openp (Vexec_path, program, Vexec_suffixes, &tem,
1597 make_number (X_OK), false);
1598 if (NILP (tem))
1599 report_file_error ("Searching for program", program);
1600 tem = Fexpand_file_name (tem, Qnil);
1602 else
1604 if (!NILP (Ffile_directory_p (program)))
1605 error ("Specified program for new process is a directory");
1606 tem = program;
1609 /* Remove "/:" from TEM. */
1610 tem = remove_slash_colon (tem);
1612 Lisp_Object arg_encoding = Qnil;
1614 /* Encode the file name and put it in NEW_ARGV.
1615 That's where the child will use it to execute the program. */
1616 tem = list1 (ENCODE_FILE (tem));
1617 ptrdiff_t new_argc = 1;
1619 /* Here we encode arguments by the coding system used for sending
1620 data to the process. We don't support using different coding
1621 systems for encoding arguments and for encoding data sent to the
1622 process. */
1624 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1626 Lisp_Object arg = XCAR (tem2);
1627 CHECK_STRING (arg);
1628 if (STRING_MULTIBYTE (arg))
1630 if (NILP (arg_encoding))
1631 arg_encoding = (complement_process_encoding_system
1632 (XPROCESS (proc)->encode_coding_system));
1633 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1635 tem = Fcons (arg, tem);
1636 new_argc++;
1639 /* Now that everything is encoded we can collect the strings into
1640 NEW_ARGV. */
1641 char **new_argv;
1642 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1643 new_argv[new_argc] = 0;
1645 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1647 new_argv[i] = SSDATA (XCAR (tem));
1648 tem = XCDR (tem);
1651 create_process (proc, new_argv, current_dir);
1653 else
1654 create_pty (proc);
1656 SAFE_FREE ();
1657 return unbind_to (count, proc);
1660 /* This function is the unwind_protect form for Fstart_process. If
1661 PROC doesn't have its pid set, then we know someone has signaled
1662 an error and the process wasn't started successfully, so we should
1663 remove it from the process list. */
1664 static void
1665 start_process_unwind (Lisp_Object proc)
1667 if (!PROCESSP (proc))
1668 emacs_abort ();
1670 /* Was PROC started successfully?
1671 -2 is used for a pty with no process, eg for gdb. */
1672 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1673 remove_process (proc);
1676 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1678 static void
1679 close_process_fd (int *fd_addr)
1681 int fd = *fd_addr;
1682 if (0 <= fd)
1684 *fd_addr = -1;
1685 emacs_close (fd);
1689 /* Indexes of file descriptors in open_fds. */
1690 enum
1692 /* The pipe from Emacs to its subprocess. */
1693 SUBPROCESS_STDIN,
1694 WRITE_TO_SUBPROCESS,
1696 /* The main pipe from the subprocess to Emacs. */
1697 READ_FROM_SUBPROCESS,
1698 SUBPROCESS_STDOUT,
1700 /* The pipe from the subprocess to Emacs that is closed when the
1701 subprocess execs. */
1702 READ_FROM_EXEC_MONITOR,
1703 EXEC_MONITOR_OUTPUT
1706 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1708 static void
1709 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1711 struct Lisp_Process *p = XPROCESS (process);
1712 int inchannel, outchannel;
1713 pid_t pid;
1714 int vfork_errno;
1715 int forkin, forkout, forkerr = -1;
1716 bool pty_flag = 0;
1717 char pty_name[PTY_NAME_SIZE];
1718 Lisp_Object lisp_pty_name = Qnil;
1719 sigset_t oldset;
1721 inchannel = outchannel = -1;
1723 if (p->pty_flag)
1724 outchannel = inchannel = allocate_pty (pty_name);
1726 if (inchannel >= 0)
1728 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1729 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1730 /* On most USG systems it does not work to open the pty's tty here,
1731 then close it and reopen it in the child. */
1732 /* Don't let this terminal become our controlling terminal
1733 (in case we don't have one). */
1734 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1735 if (forkin < 0)
1736 report_file_error ("Opening pty", Qnil);
1737 p->open_fd[SUBPROCESS_STDIN] = forkin;
1738 #else
1739 forkin = forkout = -1;
1740 #endif /* not USG, or USG_SUBTTY_WORKS */
1741 pty_flag = 1;
1742 lisp_pty_name = build_string (pty_name);
1744 else
1746 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1747 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1748 report_file_error ("Creating pipe", Qnil);
1749 forkin = p->open_fd[SUBPROCESS_STDIN];
1750 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1751 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1752 forkout = p->open_fd[SUBPROCESS_STDOUT];
1754 if (!NILP (p->stderrproc))
1756 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
1758 forkerr = pp->open_fd[SUBPROCESS_STDOUT];
1760 /* Close unnecessary file descriptors. */
1761 close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
1762 close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
1766 #ifndef WINDOWSNT
1767 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1768 report_file_error ("Creating pipe", Qnil);
1769 #endif
1771 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1772 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1774 /* Record this as an active process, with its channels. */
1775 chan_process[inchannel] = process;
1776 p->infd = inchannel;
1777 p->outfd = outchannel;
1779 /* Previously we recorded the tty descriptor used in the subprocess.
1780 It was only used for getting the foreground tty process, so now
1781 we just reopen the device (see emacs_get_tty_pgrp) as this is
1782 more portable (see USG_SUBTTY_WORKS above). */
1784 p->pty_flag = pty_flag;
1785 pset_status (p, Qrun);
1787 if (!EQ (p->command, Qt))
1789 FD_SET (inchannel, &input_wait_mask);
1790 FD_SET (inchannel, &non_keyboard_wait_mask);
1793 if (inchannel > max_process_desc)
1794 max_process_desc = inchannel;
1796 /* This may signal an error. */
1797 setup_process_coding_systems (process);
1799 block_input ();
1800 block_child_signal (&oldset);
1802 #ifndef WINDOWSNT
1803 /* vfork, and prevent local vars from being clobbered by the vfork. */
1804 Lisp_Object volatile current_dir_volatile = current_dir;
1805 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1806 char **volatile new_argv_volatile = new_argv;
1807 int volatile forkin_volatile = forkin;
1808 int volatile forkout_volatile = forkout;
1809 int volatile forkerr_volatile = forkerr;
1810 struct Lisp_Process *p_volatile = p;
1812 pid = vfork ();
1814 current_dir = current_dir_volatile;
1815 lisp_pty_name = lisp_pty_name_volatile;
1816 new_argv = new_argv_volatile;
1817 forkin = forkin_volatile;
1818 forkout = forkout_volatile;
1819 forkerr = forkerr_volatile;
1820 p = p_volatile;
1822 pty_flag = p->pty_flag;
1824 if (pid == 0)
1825 #endif /* not WINDOWSNT */
1827 /* Make the pty be the controlling terminal of the process. */
1828 #ifdef HAVE_PTYS
1829 /* First, disconnect its current controlling terminal. */
1830 /* We tried doing setsid only if pty_flag, but it caused
1831 process_set_signal to fail on SGI when using a pipe. */
1832 setsid ();
1833 /* Make the pty's terminal the controlling terminal. */
1834 if (pty_flag && forkin >= 0)
1836 #ifdef TIOCSCTTY
1837 /* We ignore the return value
1838 because faith@cs.unc.edu says that is necessary on Linux. */
1839 ioctl (forkin, TIOCSCTTY, 0);
1840 #endif
1842 #if defined (LDISC1)
1843 if (pty_flag && forkin >= 0)
1845 struct termios t;
1846 tcgetattr (forkin, &t);
1847 t.c_lflag = LDISC1;
1848 if (tcsetattr (forkin, TCSANOW, &t) < 0)
1849 emacs_perror ("create_process/tcsetattr LDISC1");
1851 #else
1852 #if defined (NTTYDISC) && defined (TIOCSETD)
1853 if (pty_flag && forkin >= 0)
1855 /* Use new line discipline. */
1856 int ldisc = NTTYDISC;
1857 ioctl (forkin, TIOCSETD, &ldisc);
1859 #endif
1860 #endif
1861 #ifdef TIOCNOTTY
1862 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1863 can do TIOCSPGRP only to the process's controlling tty. */
1864 if (pty_flag)
1866 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1867 I can't test it since I don't have 4.3. */
1868 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1869 if (j >= 0)
1871 ioctl (j, TIOCNOTTY, 0);
1872 emacs_close (j);
1875 #endif /* TIOCNOTTY */
1877 #if !defined (DONT_REOPEN_PTY)
1878 /*** There is a suggestion that this ought to be a
1879 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1880 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1881 that system does seem to need this code, even though
1882 both TIOCSCTTY is defined. */
1883 /* Now close the pty (if we had it open) and reopen it.
1884 This makes the pty the controlling terminal of the subprocess. */
1885 if (pty_flag)
1888 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1889 would work? */
1890 if (forkin >= 0)
1891 emacs_close (forkin);
1892 forkout = forkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1894 if (forkin < 0)
1896 emacs_perror (SSDATA (lisp_pty_name));
1897 _exit (EXIT_CANCELED);
1901 #endif /* not DONT_REOPEN_PTY */
1903 #ifdef SETUP_SLAVE_PTY
1904 if (pty_flag)
1906 SETUP_SLAVE_PTY;
1908 #endif /* SETUP_SLAVE_PTY */
1909 #endif /* HAVE_PTYS */
1911 signal (SIGINT, SIG_DFL);
1912 signal (SIGQUIT, SIG_DFL);
1913 #ifdef SIGPROF
1914 signal (SIGPROF, SIG_DFL);
1915 #endif
1917 /* Emacs ignores SIGPIPE, but the child should not. */
1918 signal (SIGPIPE, SIG_DFL);
1920 /* Stop blocking SIGCHLD in the child. */
1921 unblock_child_signal (&oldset);
1923 if (pty_flag)
1924 child_setup_tty (forkout);
1926 if (forkerr < 0)
1927 forkerr = forkout;
1928 #ifdef WINDOWSNT
1929 pid = child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1930 #else /* not WINDOWSNT */
1931 child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1932 #endif /* not WINDOWSNT */
1935 /* Back in the parent process. */
1937 vfork_errno = errno;
1938 p->pid = pid;
1939 if (pid >= 0)
1940 p->alive = 1;
1942 /* Stop blocking in the parent. */
1943 unblock_child_signal (&oldset);
1944 unblock_input ();
1946 if (pid < 0)
1947 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1948 else
1950 /* vfork succeeded. */
1952 /* Close the pipe ends that the child uses, or the child's pty. */
1953 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
1954 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
1956 #ifdef WINDOWSNT
1957 register_child (pid, inchannel);
1958 #endif /* WINDOWSNT */
1960 pset_tty_name (p, lisp_pty_name);
1962 #ifndef WINDOWSNT
1963 /* Wait for child_setup to complete in case that vfork is
1964 actually defined as fork. The descriptor
1965 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1966 of a pipe is closed at the child side either by close-on-exec
1967 on successful execve or the _exit call in child_setup. */
1969 char dummy;
1971 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
1972 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
1973 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
1975 #endif
1976 if (!NILP (p->stderrproc))
1978 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
1979 close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
1984 static void
1985 create_pty (Lisp_Object process)
1987 struct Lisp_Process *p = XPROCESS (process);
1988 char pty_name[PTY_NAME_SIZE];
1989 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
1991 if (pty_fd >= 0)
1993 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
1994 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1995 /* On most USG systems it does not work to open the pty's tty here,
1996 then close it and reopen it in the child. */
1997 /* Don't let this terminal become our controlling terminal
1998 (in case we don't have one). */
1999 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2000 if (forkout < 0)
2001 report_file_error ("Opening pty", Qnil);
2002 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2003 #if defined (DONT_REOPEN_PTY)
2004 /* In the case that vfork is defined as fork, the parent process
2005 (Emacs) may send some data before the child process completes
2006 tty options setup. So we setup tty before forking. */
2007 child_setup_tty (forkout);
2008 #endif /* DONT_REOPEN_PTY */
2009 #endif /* not USG, or USG_SUBTTY_WORKS */
2011 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2013 /* Record this as an active process, with its channels.
2014 As a result, child_setup will close Emacs's side of the pipes. */
2015 chan_process[pty_fd] = process;
2016 p->infd = pty_fd;
2017 p->outfd = pty_fd;
2019 /* Previously we recorded the tty descriptor used in the subprocess.
2020 It was only used for getting the foreground tty process, so now
2021 we just reopen the device (see emacs_get_tty_pgrp) as this is
2022 more portable (see USG_SUBTTY_WORKS above). */
2024 p->pty_flag = 1;
2025 pset_status (p, Qrun);
2026 setup_process_coding_systems (process);
2028 FD_SET (pty_fd, &input_wait_mask);
2029 FD_SET (pty_fd, &non_keyboard_wait_mask);
2030 if (pty_fd > max_process_desc)
2031 max_process_desc = pty_fd;
2033 pset_tty_name (p, build_string (pty_name));
2036 p->pid = -2;
2039 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2040 0, MANY, 0,
2041 doc: /* Create and return a bidirectional pipe process.
2043 In Emacs, pipes are represented by process objects, so input and
2044 output work as for subprocesses, and `delete-process' closes a pipe.
2045 However, a pipe process has no process id, it cannot be signaled,
2046 and the status codes are different from normal processes.
2048 Arguments are specified as keyword/argument pairs. The following
2049 arguments are defined:
2051 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2053 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2054 with the process. Process output goes at the end of that buffer,
2055 unless you specify an output stream or filter function to handle the
2056 output. If BUFFER is not given, the value of NAME is used.
2058 :coding CODING -- If CODING is a symbol, it specifies the coding
2059 system used for both reading and writing for this process. If CODING
2060 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2061 ENCODING is used for writing.
2063 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2064 the process is running. If BOOL is not given, query before exiting.
2066 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2067 In the stopped state, a pipe process does not accept incoming data,
2068 but you can send outgoing data. The stopped state is cleared by
2069 `continue-process' and set by `stop-process'.
2071 :filter FILTER -- Install FILTER as the process filter.
2073 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2075 usage: (make-pipe-process &rest ARGS) */)
2076 (ptrdiff_t nargs, Lisp_Object *args)
2078 Lisp_Object proc, contact;
2079 struct Lisp_Process *p;
2080 Lisp_Object name, buffer;
2081 Lisp_Object tem;
2082 ptrdiff_t specpdl_count;
2083 int inchannel, outchannel;
2085 if (nargs == 0)
2086 return Qnil;
2088 contact = Flist (nargs, args);
2090 name = Fplist_get (contact, QCname);
2091 CHECK_STRING (name);
2092 proc = make_process (name);
2093 specpdl_count = SPECPDL_INDEX ();
2094 record_unwind_protect (remove_process, proc);
2095 p = XPROCESS (proc);
2097 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2098 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2099 report_file_error ("Creating pipe", Qnil);
2100 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2101 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2103 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2104 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2106 #ifdef WINDOWSNT
2107 register_aux_fd (inchannel);
2108 #endif
2110 /* Record this as an active process, with its channels. */
2111 chan_process[inchannel] = proc;
2112 p->infd = inchannel;
2113 p->outfd = outchannel;
2115 if (inchannel > max_process_desc)
2116 max_process_desc = inchannel;
2118 buffer = Fplist_get (contact, QCbuffer);
2119 if (NILP (buffer))
2120 buffer = name;
2121 buffer = Fget_buffer_create (buffer);
2122 pset_buffer (p, buffer);
2124 pset_childp (p, contact);
2125 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2126 pset_type (p, Qpipe);
2127 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2128 pset_filter (p, Fplist_get (contact, QCfilter));
2129 pset_log (p, Qnil);
2130 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2131 p->kill_without_query = 1;
2132 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2133 pset_command (p, Qt);
2134 eassert (! p->pty_flag);
2136 if (!EQ (p->command, Qt))
2138 FD_SET (inchannel, &input_wait_mask);
2139 FD_SET (inchannel, &non_keyboard_wait_mask);
2141 p->adaptive_read_buffering
2142 = (NILP (Vprocess_adaptive_read_buffering) ? 0
2143 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2145 /* Make the process marker point into the process buffer (if any). */
2146 if (BUFFERP (buffer))
2147 set_marker_both (p->mark, buffer,
2148 BUF_ZV (XBUFFER (buffer)),
2149 BUF_ZV_BYTE (XBUFFER (buffer)));
2152 /* Setup coding systems for communicating with the network stream. */
2154 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2155 Lisp_Object coding_systems = Qt;
2156 Lisp_Object val;
2158 tem = Fplist_get (contact, QCcoding);
2159 val = Qnil;
2160 if (!NILP (tem))
2162 val = tem;
2163 if (CONSP (val))
2164 val = XCAR (val);
2166 else if (!NILP (Vcoding_system_for_read))
2167 val = Vcoding_system_for_read;
2168 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2169 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2170 /* We dare not decode end-of-line format by setting VAL to
2171 Qraw_text, because the existing Emacs Lisp libraries
2172 assume that they receive bare code including a sequence of
2173 CR LF. */
2174 val = Qnil;
2175 else
2177 if (CONSP (coding_systems))
2178 val = XCAR (coding_systems);
2179 else if (CONSP (Vdefault_process_coding_system))
2180 val = XCAR (Vdefault_process_coding_system);
2181 else
2182 val = Qnil;
2184 pset_decode_coding_system (p, val);
2186 if (!NILP (tem))
2188 val = tem;
2189 if (CONSP (val))
2190 val = XCDR (val);
2192 else if (!NILP (Vcoding_system_for_write))
2193 val = Vcoding_system_for_write;
2194 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2195 val = Qnil;
2196 else
2198 if (CONSP (coding_systems))
2199 val = XCDR (coding_systems);
2200 else if (CONSP (Vdefault_process_coding_system))
2201 val = XCDR (Vdefault_process_coding_system);
2202 else
2203 val = Qnil;
2205 pset_encode_coding_system (p, val);
2207 /* This may signal an error. */
2208 setup_process_coding_systems (proc);
2210 specpdl_ptr = specpdl + specpdl_count;
2212 return proc;
2216 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2217 The address family of sa is not included in the result. */
2219 Lisp_Object
2220 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2222 Lisp_Object address;
2223 int i;
2224 unsigned char *cp;
2225 register struct Lisp_Vector *p;
2227 /* Workaround for a bug in getsockname on BSD: Names bound to
2228 sockets in the UNIX domain are inaccessible; getsockname returns
2229 a zero length name. */
2230 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2231 return empty_unibyte_string;
2233 switch (sa->sa_family)
2235 case AF_INET:
2237 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2238 len = sizeof (sin->sin_addr) + 1;
2239 address = Fmake_vector (make_number (len), Qnil);
2240 p = XVECTOR (address);
2241 p->contents[--len] = make_number (ntohs (sin->sin_port));
2242 cp = (unsigned char *) &sin->sin_addr;
2243 break;
2245 #ifdef AF_INET6
2246 case AF_INET6:
2248 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2249 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2250 len = sizeof (sin6->sin6_addr) / 2 + 1;
2251 address = Fmake_vector (make_number (len), Qnil);
2252 p = XVECTOR (address);
2253 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2254 for (i = 0; i < len; i++)
2255 p->contents[i] = make_number (ntohs (ip6[i]));
2256 return address;
2258 #endif
2259 #ifdef HAVE_LOCAL_SOCKETS
2260 case AF_LOCAL:
2262 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2263 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2264 /* If the first byte is NUL, the name is a Linux abstract
2265 socket name, and the name can contain embedded NULs. If
2266 it's not, we have a NUL-terminated string. Be careful not
2267 to walk past the end of the object looking for the name
2268 terminator, however. */
2269 if (name_length > 0 && sockun->sun_path[0] != '\0')
2271 const char *terminator
2272 = memchr (sockun->sun_path, '\0', name_length);
2274 if (terminator)
2275 name_length = terminator - (const char *) sockun->sun_path;
2278 return make_unibyte_string (sockun->sun_path, name_length);
2280 #endif
2281 default:
2282 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2283 address = Fcons (make_number (sa->sa_family),
2284 Fmake_vector (make_number (len), Qnil));
2285 p = XVECTOR (XCDR (address));
2286 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2287 break;
2290 i = 0;
2291 while (i < len)
2292 p->contents[i++] = make_number (*cp++);
2294 return address;
2298 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2300 static int
2301 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2303 register struct Lisp_Vector *p;
2305 if (VECTORP (address))
2307 p = XVECTOR (address);
2308 if (p->header.size == 5)
2310 *familyp = AF_INET;
2311 return sizeof (struct sockaddr_in);
2313 #ifdef AF_INET6
2314 else if (p->header.size == 9)
2316 *familyp = AF_INET6;
2317 return sizeof (struct sockaddr_in6);
2319 #endif
2321 #ifdef HAVE_LOCAL_SOCKETS
2322 else if (STRINGP (address))
2324 *familyp = AF_LOCAL;
2325 return sizeof (struct sockaddr_un);
2327 #endif
2328 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2329 && VECTORP (XCDR (address)))
2331 struct sockaddr *sa;
2332 p = XVECTOR (XCDR (address));
2333 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2334 return 0;
2335 *familyp = XINT (XCAR (address));
2336 return p->header.size + sizeof (sa->sa_family);
2338 return 0;
2341 /* Convert an address object (vector or string) to an internal sockaddr.
2343 The address format has been basically validated by
2344 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2345 it could have come from user data. So if FAMILY is not valid,
2346 we return after zeroing *SA. */
2348 static void
2349 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2351 register struct Lisp_Vector *p;
2352 register unsigned char *cp = NULL;
2353 register int i;
2354 EMACS_INT hostport;
2356 memset (sa, 0, len);
2358 if (VECTORP (address))
2360 p = XVECTOR (address);
2361 if (family == AF_INET)
2363 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2364 len = sizeof (sin->sin_addr) + 1;
2365 hostport = XINT (p->contents[--len]);
2366 sin->sin_port = htons (hostport);
2367 cp = (unsigned char *)&sin->sin_addr;
2368 sa->sa_family = family;
2370 #ifdef AF_INET6
2371 else if (family == AF_INET6)
2373 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2374 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2375 len = sizeof (sin6->sin6_addr) / 2 + 1;
2376 hostport = XINT (p->contents[--len]);
2377 sin6->sin6_port = htons (hostport);
2378 for (i = 0; i < len; i++)
2379 if (INTEGERP (p->contents[i]))
2381 int j = XFASTINT (p->contents[i]) & 0xffff;
2382 ip6[i] = ntohs (j);
2384 sa->sa_family = family;
2385 return;
2387 #endif
2388 else
2389 return;
2391 else if (STRINGP (address))
2393 #ifdef HAVE_LOCAL_SOCKETS
2394 if (family == AF_LOCAL)
2396 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2397 cp = SDATA (address);
2398 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2399 sockun->sun_path[i] = *cp++;
2400 sa->sa_family = family;
2402 #endif
2403 return;
2405 else
2407 p = XVECTOR (XCDR (address));
2408 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2411 for (i = 0; i < len; i++)
2412 if (INTEGERP (p->contents[i]))
2413 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2416 #ifdef DATAGRAM_SOCKETS
2417 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2418 1, 1, 0,
2419 doc: /* Get the current datagram address associated with PROCESS. */)
2420 (Lisp_Object process)
2422 int channel;
2424 CHECK_PROCESS (process);
2426 if (!DATAGRAM_CONN_P (process))
2427 return Qnil;
2429 channel = XPROCESS (process)->infd;
2430 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2431 datagram_address[channel].len);
2434 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2435 2, 2, 0,
2436 doc: /* Set the datagram address for PROCESS to ADDRESS.
2437 Returns nil upon error setting address, ADDRESS otherwise. */)
2438 (Lisp_Object process, Lisp_Object address)
2440 int channel;
2441 int family, len;
2443 CHECK_PROCESS (process);
2445 if (!DATAGRAM_CONN_P (process))
2446 return Qnil;
2448 channel = XPROCESS (process)->infd;
2450 len = get_lisp_to_sockaddr_size (address, &family);
2451 if (len == 0 || datagram_address[channel].len != len)
2452 return Qnil;
2453 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2454 return address;
2456 #endif
2459 static const struct socket_options {
2460 /* The name of this option. Should be lowercase version of option
2461 name without SO_ prefix. */
2462 const char *name;
2463 /* Option level SOL_... */
2464 int optlevel;
2465 /* Option number SO_... */
2466 int optnum;
2467 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2468 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2469 } socket_options[] =
2471 #ifdef SO_BINDTODEVICE
2472 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2473 #endif
2474 #ifdef SO_BROADCAST
2475 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2476 #endif
2477 #ifdef SO_DONTROUTE
2478 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2479 #endif
2480 #ifdef SO_KEEPALIVE
2481 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2482 #endif
2483 #ifdef SO_LINGER
2484 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2485 #endif
2486 #ifdef SO_OOBINLINE
2487 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2488 #endif
2489 #ifdef SO_PRIORITY
2490 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2491 #endif
2492 #ifdef SO_REUSEADDR
2493 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2494 #endif
2495 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2498 /* Set option OPT to value VAL on socket S.
2500 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2501 Signals an error if setting a known option fails.
2504 static int
2505 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2507 char *name;
2508 const struct socket_options *sopt;
2509 int ret = 0;
2511 CHECK_SYMBOL (opt);
2513 name = SSDATA (SYMBOL_NAME (opt));
2514 for (sopt = socket_options; sopt->name; sopt++)
2515 if (strcmp (name, sopt->name) == 0)
2516 break;
2518 switch (sopt->opttype)
2520 case SOPT_BOOL:
2522 int optval;
2523 optval = NILP (val) ? 0 : 1;
2524 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2525 &optval, sizeof (optval));
2526 break;
2529 case SOPT_INT:
2531 int optval;
2532 if (TYPE_RANGED_INTEGERP (int, val))
2533 optval = XINT (val);
2534 else
2535 error ("Bad option value for %s", name);
2536 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2537 &optval, sizeof (optval));
2538 break;
2541 #ifdef SO_BINDTODEVICE
2542 case SOPT_IFNAME:
2544 char devname[IFNAMSIZ + 1];
2546 /* This is broken, at least in the Linux 2.4 kernel.
2547 To unbind, the arg must be a zero integer, not the empty string.
2548 This should work on all systems. KFS. 2003-09-23. */
2549 memset (devname, 0, sizeof devname);
2550 if (STRINGP (val))
2552 char *arg = SSDATA (val);
2553 int len = min (strlen (arg), IFNAMSIZ);
2554 memcpy (devname, arg, len);
2556 else if (!NILP (val))
2557 error ("Bad option value for %s", name);
2558 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2559 devname, IFNAMSIZ);
2560 break;
2562 #endif
2564 #ifdef SO_LINGER
2565 case SOPT_LINGER:
2567 struct linger linger;
2569 linger.l_onoff = 1;
2570 linger.l_linger = 0;
2571 if (TYPE_RANGED_INTEGERP (int, val))
2572 linger.l_linger = XINT (val);
2573 else
2574 linger.l_onoff = NILP (val) ? 0 : 1;
2575 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2576 &linger, sizeof (linger));
2577 break;
2579 #endif
2581 default:
2582 return 0;
2585 if (ret < 0)
2587 int setsockopt_errno = errno;
2588 report_file_errno ("Cannot set network option", list2 (opt, val),
2589 setsockopt_errno);
2592 return (1 << sopt->optbit);
2596 DEFUN ("set-network-process-option",
2597 Fset_network_process_option, Sset_network_process_option,
2598 3, 4, 0,
2599 doc: /* For network process PROCESS set option OPTION to value VALUE.
2600 See `make-network-process' for a list of options and values.
2601 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2602 OPTION is not a supported option, return nil instead; otherwise return t. */)
2603 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2605 int s;
2606 struct Lisp_Process *p;
2608 CHECK_PROCESS (process);
2609 p = XPROCESS (process);
2610 if (!NETCONN1_P (p))
2611 error ("Process is not a network process");
2613 s = p->infd;
2614 if (s < 0)
2615 error ("Process is not running");
2617 if (set_socket_option (s, option, value))
2619 pset_childp (p, Fplist_put (p->childp, option, value));
2620 return Qt;
2623 if (NILP (no_error))
2624 error ("Unknown or unsupported option");
2626 return Qnil;
2630 DEFUN ("serial-process-configure",
2631 Fserial_process_configure,
2632 Sserial_process_configure,
2633 0, MANY, 0,
2634 doc: /* Configure speed, bytesize, etc. of a serial process.
2636 Arguments are specified as keyword/argument pairs. Attributes that
2637 are not given are re-initialized from the process's current
2638 configuration (available via the function `process-contact') or set to
2639 reasonable default values. The following arguments are defined:
2641 :process PROCESS
2642 :name NAME
2643 :buffer BUFFER
2644 :port PORT
2645 -- Any of these arguments can be given to identify the process that is
2646 to be configured. If none of these arguments is given, the current
2647 buffer's process is used.
2649 :speed SPEED -- SPEED is the speed of the serial port in bits per
2650 second, also called baud rate. Any value can be given for SPEED, but
2651 most serial ports work only at a few defined values between 1200 and
2652 115200, with 9600 being the most common value. If SPEED is nil, the
2653 serial port is not configured any further, i.e., all other arguments
2654 are ignored. This may be useful for special serial ports such as
2655 Bluetooth-to-serial converters which can only be configured through AT
2656 commands. A value of nil for SPEED can be used only when passed
2657 through `make-serial-process' or `serial-term'.
2659 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2660 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2662 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2663 `odd' (use odd parity), or the symbol `even' (use even parity). If
2664 PARITY is not given, no parity is used.
2666 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2667 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2668 is not given or nil, 1 stopbit is used.
2670 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2671 flowcontrol to be used, which is either nil (don't use flowcontrol),
2672 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2673 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2674 flowcontrol is used.
2676 `serial-process-configure' is called by `make-serial-process' for the
2677 initial configuration of the serial port.
2679 Examples:
2681 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2683 \(serial-process-configure
2684 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2686 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2688 usage: (serial-process-configure &rest ARGS) */)
2689 (ptrdiff_t nargs, Lisp_Object *args)
2691 struct Lisp_Process *p;
2692 Lisp_Object contact = Qnil;
2693 Lisp_Object proc = Qnil;
2695 contact = Flist (nargs, args);
2697 proc = Fplist_get (contact, QCprocess);
2698 if (NILP (proc))
2699 proc = Fplist_get (contact, QCname);
2700 if (NILP (proc))
2701 proc = Fplist_get (contact, QCbuffer);
2702 if (NILP (proc))
2703 proc = Fplist_get (contact, QCport);
2704 proc = get_process (proc);
2705 p = XPROCESS (proc);
2706 if (!EQ (p->type, Qserial))
2707 error ("Not a serial process");
2709 if (NILP (Fplist_get (p->childp, QCspeed)))
2710 return Qnil;
2712 serial_configure (p, contact);
2713 return Qnil;
2716 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2717 0, MANY, 0,
2718 doc: /* Create and return a serial port process.
2720 In Emacs, serial port connections are represented by process objects,
2721 so input and output work as for subprocesses, and `delete-process'
2722 closes a serial port connection. However, a serial process has no
2723 process id, it cannot be signaled, and the status codes are different
2724 from normal processes.
2726 `make-serial-process' creates a process and a buffer, on which you
2727 probably want to use `process-send-string'. Try \\[serial-term] for
2728 an interactive terminal. See below for examples.
2730 Arguments are specified as keyword/argument pairs. The following
2731 arguments are defined:
2733 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2734 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2735 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2736 the backslashes in strings).
2738 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2739 which this function calls.
2741 :name NAME -- NAME is the name of the process. If NAME is not given,
2742 the value of PORT is used.
2744 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2745 with the process. Process output goes at the end of that buffer,
2746 unless you specify an output stream or filter function to handle the
2747 output. If BUFFER is not given, the value of NAME is used.
2749 :coding CODING -- If CODING is a symbol, it specifies the coding
2750 system used for both reading and writing for this process. If CODING
2751 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2752 ENCODING is used for writing.
2754 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2755 the process is running. If BOOL is not given, query before exiting.
2757 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2758 In the stopped state, a serial process does not accept incoming data,
2759 but you can send outgoing data. The stopped state is cleared by
2760 `continue-process' and set by `stop-process'.
2762 :filter FILTER -- Install FILTER as the process filter.
2764 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2766 :plist PLIST -- Install PLIST as the initial plist of the process.
2768 :bytesize
2769 :parity
2770 :stopbits
2771 :flowcontrol
2772 -- This function calls `serial-process-configure' to handle these
2773 arguments.
2775 The original argument list, possibly modified by later configuration,
2776 is available via the function `process-contact'.
2778 Examples:
2780 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2782 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2784 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2786 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2788 usage: (make-serial-process &rest ARGS) */)
2789 (ptrdiff_t nargs, Lisp_Object *args)
2791 int fd = -1;
2792 Lisp_Object proc, contact, port;
2793 struct Lisp_Process *p;
2794 Lisp_Object name, buffer;
2795 Lisp_Object tem, val;
2796 ptrdiff_t specpdl_count;
2798 if (nargs == 0)
2799 return Qnil;
2801 contact = Flist (nargs, args);
2803 port = Fplist_get (contact, QCport);
2804 if (NILP (port))
2805 error ("No port specified");
2806 CHECK_STRING (port);
2808 if (NILP (Fplist_member (contact, QCspeed)))
2809 error (":speed not specified");
2810 if (!NILP (Fplist_get (contact, QCspeed)))
2811 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2813 name = Fplist_get (contact, QCname);
2814 if (NILP (name))
2815 name = port;
2816 CHECK_STRING (name);
2817 proc = make_process (name);
2818 specpdl_count = SPECPDL_INDEX ();
2819 record_unwind_protect (remove_process, proc);
2820 p = XPROCESS (proc);
2822 fd = serial_open (port);
2823 p->open_fd[SUBPROCESS_STDIN] = fd;
2824 p->infd = fd;
2825 p->outfd = fd;
2826 if (fd > max_process_desc)
2827 max_process_desc = fd;
2828 chan_process[fd] = proc;
2830 buffer = Fplist_get (contact, QCbuffer);
2831 if (NILP (buffer))
2832 buffer = name;
2833 buffer = Fget_buffer_create (buffer);
2834 pset_buffer (p, buffer);
2836 pset_childp (p, contact);
2837 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2838 pset_type (p, Qserial);
2839 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2840 pset_filter (p, Fplist_get (contact, QCfilter));
2841 pset_log (p, Qnil);
2842 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2843 p->kill_without_query = 1;
2844 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2845 pset_command (p, Qt);
2846 eassert (! p->pty_flag);
2848 if (!EQ (p->command, Qt))
2850 FD_SET (fd, &input_wait_mask);
2851 FD_SET (fd, &non_keyboard_wait_mask);
2854 if (BUFFERP (buffer))
2856 set_marker_both (p->mark, buffer,
2857 BUF_ZV (XBUFFER (buffer)),
2858 BUF_ZV_BYTE (XBUFFER (buffer)));
2861 tem = Fplist_member (contact, QCcoding);
2862 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2863 tem = Qnil;
2865 val = Qnil;
2866 if (!NILP (tem))
2868 val = XCAR (XCDR (tem));
2869 if (CONSP (val))
2870 val = XCAR (val);
2872 else if (!NILP (Vcoding_system_for_read))
2873 val = Vcoding_system_for_read;
2874 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2875 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2876 val = Qnil;
2877 pset_decode_coding_system (p, val);
2879 val = Qnil;
2880 if (!NILP (tem))
2882 val = XCAR (XCDR (tem));
2883 if (CONSP (val))
2884 val = XCDR (val);
2886 else if (!NILP (Vcoding_system_for_write))
2887 val = Vcoding_system_for_write;
2888 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2889 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2890 val = Qnil;
2891 pset_encode_coding_system (p, val);
2893 setup_process_coding_systems (proc);
2894 pset_decoding_buf (p, empty_unibyte_string);
2895 p->decoding_carryover = 0;
2896 pset_encoding_buf (p, empty_unibyte_string);
2897 p->inherit_coding_system_flag
2898 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2900 Fserial_process_configure (nargs, args);
2902 specpdl_ptr = specpdl + specpdl_count;
2904 return proc;
2907 /* Create a network stream/datagram client/server process. Treated
2908 exactly like a normal process when reading and writing. Primary
2909 differences are in status display and process deletion. A network
2910 connection has no PID; you cannot signal it. All you can do is
2911 stop/continue it and deactivate/close it via delete-process. */
2913 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2914 0, MANY, 0,
2915 doc: /* Create and return a network server or client process.
2917 In Emacs, network connections are represented by process objects, so
2918 input and output work as for subprocesses and `delete-process' closes
2919 a network connection. However, a network process has no process id,
2920 it cannot be signaled, and the status codes are different from normal
2921 processes.
2923 Arguments are specified as keyword/argument pairs. The following
2924 arguments are defined:
2926 :name NAME -- NAME is name for process. It is modified if necessary
2927 to make it unique.
2929 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2930 with the process. Process output goes at end of that buffer, unless
2931 you specify an output stream or filter function to handle the output.
2932 BUFFER may be also nil, meaning that this process is not associated
2933 with any buffer.
2935 :host HOST -- HOST is name of the host to connect to, or its IP
2936 address. The symbol `local' specifies the local host. If specified
2937 for a server process, it must be a valid name or address for the local
2938 host, and only clients connecting to that address will be accepted.
2940 :service SERVICE -- SERVICE is name of the service desired, or an
2941 integer specifying a port number to connect to. If SERVICE is t,
2942 a random port number is selected for the server. (If Emacs was
2943 compiled with getaddrinfo, a port number can also be specified as a
2944 string, e.g. "80", as well as an integer. This is not portable.)
2946 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2947 stream type connection, `datagram' creates a datagram type connection,
2948 `seqpacket' creates a reliable datagram connection.
2950 :family FAMILY -- FAMILY is the address (and protocol) family for the
2951 service specified by HOST and SERVICE. The default (nil) is to use
2952 whatever address family (IPv4 or IPv6) that is defined for the host
2953 and port number specified by HOST and SERVICE. Other address families
2954 supported are:
2955 local -- for a local (i.e. UNIX) address specified by SERVICE.
2956 ipv4 -- use IPv4 address family only.
2957 ipv6 -- use IPv6 address family only.
2959 :local ADDRESS -- ADDRESS is the local address used for the connection.
2960 This parameter is ignored when opening a client process. When specified
2961 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2963 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2964 connection. This parameter is ignored when opening a stream server
2965 process. For a datagram server process, it specifies the initial
2966 setting of the remote datagram address. When specified for a client
2967 process, the FAMILY, HOST, and SERVICE args are ignored.
2969 The format of ADDRESS depends on the address family:
2970 - An IPv4 address is represented as an vector of integers [A B C D P]
2971 corresponding to numeric IP address A.B.C.D and port number P.
2972 - A local address is represented as a string with the address in the
2973 local address space.
2974 - An "unsupported family" address is represented by a cons (F . AV)
2975 where F is the family number and AV is a vector containing the socket
2976 address data with one element per address data byte. Do not rely on
2977 this format in portable code, as it may depend on implementation
2978 defined constants, data sizes, and data structure alignment.
2980 :coding CODING -- If CODING is a symbol, it specifies the coding
2981 system used for both reading and writing for this process. If CODING
2982 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2983 ENCODING is used for writing.
2985 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2986 return without waiting for the connection to complete; instead, the
2987 sentinel function will be called with second arg matching "open" (if
2988 successful) or "failed" when the connect completes. Default is to use
2989 a blocking connect (i.e. wait) for stream type connections.
2991 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2992 running when Emacs is exited.
2994 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2995 In the stopped state, a server process does not accept new
2996 connections, and a client process does not handle incoming traffic.
2997 The stopped state is cleared by `continue-process' and set by
2998 `stop-process'.
3000 :filter FILTER -- Install FILTER as the process filter.
3002 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3003 process filter are multibyte, otherwise they are unibyte.
3004 If this keyword is not specified, the strings are multibyte if
3005 the default value of `enable-multibyte-characters' is non-nil.
3007 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3009 :log LOG -- Install LOG as the server process log function. This
3010 function is called when the server accepts a network connection from a
3011 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3012 is the server process, CLIENT is the new process for the connection,
3013 and MESSAGE is a string.
3015 :plist PLIST -- Install PLIST as the new process's initial plist.
3017 :server QLEN -- if QLEN is non-nil, create a server process for the
3018 specified FAMILY, SERVICE, and connection type (stream or datagram).
3019 If QLEN is an integer, it is used as the max. length of the server's
3020 pending connection queue (also known as the backlog); the default
3021 queue length is 5. Default is to create a client process.
3023 The following network options can be specified for this connection:
3025 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3026 :dontroute BOOL -- Only send to directly connected hosts.
3027 :keepalive BOOL -- Send keep-alive messages on network stream.
3028 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3029 :oobinline BOOL -- Place out-of-band data in receive data stream.
3030 :priority INT -- Set protocol defined priority for sent packets.
3031 :reuseaddr BOOL -- Allow reusing a recently used local address
3032 (this is allowed by default for a server process).
3033 :bindtodevice NAME -- bind to interface NAME. Using this may require
3034 special privileges on some systems.
3036 Consult the relevant system programmer's manual pages for more
3037 information on using these options.
3040 A server process will listen for and accept connections from clients.
3041 When a client connection is accepted, a new network process is created
3042 for the connection with the following parameters:
3044 - The client's process name is constructed by concatenating the server
3045 process's NAME and a client identification string.
3046 - If the FILTER argument is non-nil, the client process will not get a
3047 separate process buffer; otherwise, the client's process buffer is a newly
3048 created buffer named after the server process's BUFFER name or process
3049 NAME concatenated with the client identification string.
3050 - The connection type and the process filter and sentinel parameters are
3051 inherited from the server process's TYPE, FILTER and SENTINEL.
3052 - The client process's contact info is set according to the client's
3053 addressing information (typically an IP address and a port number).
3054 - The client process's plist is initialized from the server's plist.
3056 Notice that the FILTER and SENTINEL args are never used directly by
3057 the server process. Also, the BUFFER argument is not used directly by
3058 the server process, but via the optional :log function, accepted (and
3059 failed) connections may be logged in the server process's buffer.
3061 The original argument list, modified with the actual connection
3062 information, is available via the `process-contact' function.
3064 usage: (make-network-process &rest ARGS) */)
3065 (ptrdiff_t nargs, Lisp_Object *args)
3067 Lisp_Object proc;
3068 Lisp_Object contact;
3069 struct Lisp_Process *p;
3070 #ifdef HAVE_GETADDRINFO
3071 struct addrinfo ai, *res, *lres;
3072 struct addrinfo hints;
3073 const char *portstring;
3074 char portbuf[128];
3075 #else /* HAVE_GETADDRINFO */
3076 struct _emacs_addrinfo
3078 int ai_family;
3079 int ai_socktype;
3080 int ai_protocol;
3081 int ai_addrlen;
3082 struct sockaddr *ai_addr;
3083 struct _emacs_addrinfo *ai_next;
3084 } ai, *res, *lres;
3085 #endif /* HAVE_GETADDRINFO */
3086 struct sockaddr_in address_in;
3087 #ifdef HAVE_LOCAL_SOCKETS
3088 struct sockaddr_un address_un;
3089 #endif
3090 int port;
3091 int ret = 0;
3092 int xerrno = 0;
3093 int s = -1, outch, inch;
3094 ptrdiff_t count = SPECPDL_INDEX ();
3095 ptrdiff_t count1;
3096 Lisp_Object colon_address; /* Either QClocal or QCremote. */
3097 Lisp_Object tem;
3098 Lisp_Object name, buffer, host, service, address;
3099 Lisp_Object filter, sentinel;
3100 bool is_non_blocking_client = 0;
3101 bool is_server = 0;
3102 int backlog = 5;
3103 int socktype;
3104 int family = -1;
3106 if (nargs == 0)
3107 return Qnil;
3109 /* Save arguments for process-contact and clone-process. */
3110 contact = Flist (nargs, args);
3112 #ifdef WINDOWSNT
3113 /* Ensure socket support is loaded if available. */
3114 init_winsock (TRUE);
3115 #endif
3117 /* :type TYPE (nil: stream, datagram */
3118 tem = Fplist_get (contact, QCtype);
3119 if (NILP (tem))
3120 socktype = SOCK_STREAM;
3121 #ifdef DATAGRAM_SOCKETS
3122 else if (EQ (tem, Qdatagram))
3123 socktype = SOCK_DGRAM;
3124 #endif
3125 #ifdef HAVE_SEQPACKET
3126 else if (EQ (tem, Qseqpacket))
3127 socktype = SOCK_SEQPACKET;
3128 #endif
3129 else
3130 error ("Unsupported connection type");
3132 /* :server BOOL */
3133 tem = Fplist_get (contact, QCserver);
3134 if (!NILP (tem))
3136 /* Don't support network sockets when non-blocking mode is
3137 not available, since a blocked Emacs is not useful. */
3138 is_server = 1;
3139 if (TYPE_RANGED_INTEGERP (int, tem))
3140 backlog = XINT (tem);
3143 /* Make colon_address an alias for :local (server) or :remote (client). */
3144 colon_address = is_server ? QClocal : QCremote;
3146 /* :nowait BOOL */
3147 if (!is_server && socktype != SOCK_DGRAM
3148 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3150 #ifndef NON_BLOCKING_CONNECT
3151 error ("Non-blocking connect not supported");
3152 #else
3153 is_non_blocking_client = 1;
3154 #endif
3157 name = Fplist_get (contact, QCname);
3158 buffer = Fplist_get (contact, QCbuffer);
3159 filter = Fplist_get (contact, QCfilter);
3160 sentinel = Fplist_get (contact, QCsentinel);
3162 CHECK_STRING (name);
3164 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3165 ai.ai_socktype = socktype;
3166 ai.ai_protocol = 0;
3167 ai.ai_next = NULL;
3168 res = &ai;
3170 /* :local ADDRESS or :remote ADDRESS */
3171 address = Fplist_get (contact, colon_address);
3172 if (!NILP (address))
3174 host = service = Qnil;
3176 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3177 error ("Malformed :address");
3178 ai.ai_family = family;
3179 ai.ai_addr = alloca (ai.ai_addrlen);
3180 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3181 goto open_socket;
3184 /* :family FAMILY -- nil (for Inet), local, or integer. */
3185 tem = Fplist_get (contact, QCfamily);
3186 if (NILP (tem))
3188 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3189 family = AF_UNSPEC;
3190 #else
3191 family = AF_INET;
3192 #endif
3194 #ifdef HAVE_LOCAL_SOCKETS
3195 else if (EQ (tem, Qlocal))
3196 family = AF_LOCAL;
3197 #endif
3198 #ifdef AF_INET6
3199 else if (EQ (tem, Qipv6))
3200 family = AF_INET6;
3201 #endif
3202 else if (EQ (tem, Qipv4))
3203 family = AF_INET;
3204 else if (TYPE_RANGED_INTEGERP (int, tem))
3205 family = XINT (tem);
3206 else
3207 error ("Unknown address family");
3209 ai.ai_family = family;
3211 /* :service SERVICE -- string, integer (port number), or t (random port). */
3212 service = Fplist_get (contact, QCservice);
3214 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3215 host = Fplist_get (contact, QChost);
3216 if (!NILP (host))
3218 if (EQ (host, Qlocal))
3219 /* Depending on setup, "localhost" may map to different IPv4 and/or
3220 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3221 host = build_string ("127.0.0.1");
3222 CHECK_STRING (host);
3225 #ifdef HAVE_LOCAL_SOCKETS
3226 if (family == AF_LOCAL)
3228 if (!NILP (host))
3230 message (":family local ignores the :host property");
3231 contact = Fplist_put (contact, QChost, Qnil);
3232 host = Qnil;
3234 CHECK_STRING (service);
3235 memset (&address_un, 0, sizeof address_un);
3236 address_un.sun_family = AF_LOCAL;
3237 if (sizeof address_un.sun_path <= SBYTES (service))
3238 error ("Service name too long");
3239 lispstpcpy (address_un.sun_path, service);
3240 ai.ai_addr = (struct sockaddr *) &address_un;
3241 ai.ai_addrlen = sizeof address_un;
3242 goto open_socket;
3244 #endif
3246 /* Slow down polling to every ten seconds.
3247 Some kernels have a bug which causes retrying connect to fail
3248 after a connect. Polling can interfere with gethostbyname too. */
3249 #ifdef POLL_FOR_INPUT
3250 if (socktype != SOCK_DGRAM)
3252 record_unwind_protect_void (run_all_atimers);
3253 bind_polling_period (10);
3255 #endif
3257 #ifdef HAVE_GETADDRINFO
3258 /* If we have a host, use getaddrinfo to resolve both host and service.
3259 Otherwise, use getservbyname to lookup the service. */
3260 if (!NILP (host))
3263 /* SERVICE can either be a string or int.
3264 Convert to a C string for later use by getaddrinfo. */
3265 if (EQ (service, Qt))
3266 portstring = "0";
3267 else if (INTEGERP (service))
3269 sprintf (portbuf, "%"pI"d", XINT (service));
3270 portstring = portbuf;
3272 else
3274 CHECK_STRING (service);
3275 portstring = SSDATA (service);
3278 immediate_quit = 1;
3279 QUIT;
3280 memset (&hints, 0, sizeof (hints));
3281 hints.ai_flags = 0;
3282 hints.ai_family = family;
3283 hints.ai_socktype = socktype;
3284 hints.ai_protocol = 0;
3286 #ifdef HAVE_RES_INIT
3287 res_init ();
3288 #endif
3290 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3291 if (ret)
3292 #ifdef HAVE_GAI_STRERROR
3293 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3294 #else
3295 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3296 #endif
3297 immediate_quit = 0;
3299 goto open_socket;
3301 #endif /* HAVE_GETADDRINFO */
3303 /* We end up here if getaddrinfo is not defined, or in case no hostname
3304 has been specified (e.g. for a local server process). */
3306 if (EQ (service, Qt))
3307 port = 0;
3308 else if (INTEGERP (service))
3309 port = htons ((unsigned short) XINT (service));
3310 else
3312 struct servent *svc_info;
3313 CHECK_STRING (service);
3314 svc_info = getservbyname (SSDATA (service),
3315 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3316 if (svc_info == 0)
3317 error ("Unknown service: %s", SDATA (service));
3318 port = svc_info->s_port;
3321 memset (&address_in, 0, sizeof address_in);
3322 address_in.sin_family = family;
3323 address_in.sin_addr.s_addr = INADDR_ANY;
3324 address_in.sin_port = port;
3326 #ifndef HAVE_GETADDRINFO
3327 if (!NILP (host))
3329 struct hostent *host_info_ptr;
3331 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3332 as it may `hang' Emacs for a very long time. */
3333 immediate_quit = 1;
3334 QUIT;
3336 #ifdef HAVE_RES_INIT
3337 res_init ();
3338 #endif
3340 host_info_ptr = gethostbyname (SDATA (host));
3341 immediate_quit = 0;
3343 if (host_info_ptr)
3345 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3346 host_info_ptr->h_length);
3347 family = host_info_ptr->h_addrtype;
3348 address_in.sin_family = family;
3350 else
3351 /* Attempt to interpret host as numeric inet address. */
3353 unsigned long numeric_addr;
3354 numeric_addr = inet_addr (SSDATA (host));
3355 if (numeric_addr == -1)
3356 error ("Unknown host \"%s\"", SDATA (host));
3358 memcpy (&address_in.sin_addr, &numeric_addr,
3359 sizeof (address_in.sin_addr));
3363 #endif /* not HAVE_GETADDRINFO */
3365 ai.ai_family = family;
3366 ai.ai_addr = (struct sockaddr *) &address_in;
3367 ai.ai_addrlen = sizeof address_in;
3369 open_socket:
3371 /* Do this in case we never enter the for-loop below. */
3372 count1 = SPECPDL_INDEX ();
3373 s = -1;
3375 for (lres = res; lres; lres = lres->ai_next)
3377 ptrdiff_t optn;
3378 int optbits;
3380 #ifdef WINDOWSNT
3381 retry_connect:
3382 #endif
3384 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3385 lres->ai_protocol);
3386 if (s < 0)
3388 xerrno = errno;
3389 continue;
3392 #ifdef DATAGRAM_SOCKETS
3393 if (!is_server && socktype == SOCK_DGRAM)
3394 break;
3395 #endif /* DATAGRAM_SOCKETS */
3397 #ifdef NON_BLOCKING_CONNECT
3398 if (is_non_blocking_client)
3400 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3401 if (ret < 0)
3403 xerrno = errno;
3404 emacs_close (s);
3405 s = -1;
3406 continue;
3409 #endif
3411 /* Make us close S if quit. */
3412 record_unwind_protect_int (close_file_unwind, s);
3414 /* Parse network options in the arg list.
3415 We simply ignore anything which isn't a known option (including other keywords).
3416 An error is signaled if setting a known option fails. */
3417 for (optn = optbits = 0; optn < nargs - 1; optn += 2)
3418 optbits |= set_socket_option (s, args[optn], args[optn + 1]);
3420 if (is_server)
3422 /* Configure as a server socket. */
3424 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3425 explicit :reuseaddr key to override this. */
3426 #ifdef HAVE_LOCAL_SOCKETS
3427 if (family != AF_LOCAL)
3428 #endif
3429 if (!(optbits & (1 << OPIX_REUSEADDR)))
3431 int optval = 1;
3432 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3433 report_file_error ("Cannot set reuse option on server socket", Qnil);
3436 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3437 report_file_error ("Cannot bind server socket", Qnil);
3439 #ifdef HAVE_GETSOCKNAME
3440 if (EQ (service, Qt))
3442 struct sockaddr_in sa1;
3443 socklen_t len1 = sizeof (sa1);
3444 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3446 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3447 service = make_number (ntohs (sa1.sin_port));
3448 contact = Fplist_put (contact, QCservice, service);
3451 #endif
3453 if (socktype != SOCK_DGRAM && listen (s, backlog))
3454 report_file_error ("Cannot listen on server socket", Qnil);
3456 break;
3459 immediate_quit = 1;
3460 QUIT;
3462 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3463 xerrno = errno;
3465 if (ret == 0 || xerrno == EISCONN)
3467 /* The unwind-protect will be discarded afterwards.
3468 Likewise for immediate_quit. */
3469 break;
3472 #ifdef NON_BLOCKING_CONNECT
3473 #ifdef EINPROGRESS
3474 if (is_non_blocking_client && xerrno == EINPROGRESS)
3475 break;
3476 #else
3477 #ifdef EWOULDBLOCK
3478 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3479 break;
3480 #endif
3481 #endif
3482 #endif
3484 #ifndef WINDOWSNT
3485 if (xerrno == EINTR)
3487 /* Unlike most other syscalls connect() cannot be called
3488 again. (That would return EALREADY.) The proper way to
3489 wait for completion is pselect(). */
3490 int sc;
3491 socklen_t len;
3492 fd_set fdset;
3493 retry_select:
3494 FD_ZERO (&fdset);
3495 FD_SET (s, &fdset);
3496 QUIT;
3497 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3498 if (sc == -1)
3500 if (errno == EINTR)
3501 goto retry_select;
3502 else
3503 report_file_error ("Failed select", Qnil);
3505 eassert (sc > 0);
3507 len = sizeof xerrno;
3508 eassert (FD_ISSET (s, &fdset));
3509 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3510 report_file_error ("Failed getsockopt", Qnil);
3511 if (xerrno)
3512 report_file_errno ("Failed connect", Qnil, xerrno);
3513 break;
3515 #endif /* !WINDOWSNT */
3517 immediate_quit = 0;
3519 /* Discard the unwind protect closing S. */
3520 specpdl_ptr = specpdl + count1;
3521 emacs_close (s);
3522 s = -1;
3524 #ifdef WINDOWSNT
3525 if (xerrno == EINTR)
3526 goto retry_connect;
3527 #endif
3530 if (s >= 0)
3532 #ifdef DATAGRAM_SOCKETS
3533 if (socktype == SOCK_DGRAM)
3535 if (datagram_address[s].sa)
3536 emacs_abort ();
3537 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3538 datagram_address[s].len = lres->ai_addrlen;
3539 if (is_server)
3541 Lisp_Object remote;
3542 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3543 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3545 int rfamily, rlen;
3546 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3547 if (rlen != 0 && rfamily == lres->ai_family
3548 && rlen == lres->ai_addrlen)
3549 conv_lisp_to_sockaddr (rfamily, remote,
3550 datagram_address[s].sa, rlen);
3553 else
3554 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3556 #endif
3557 contact = Fplist_put (contact, colon_address,
3558 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3559 #ifdef HAVE_GETSOCKNAME
3560 if (!is_server)
3562 struct sockaddr_in sa1;
3563 socklen_t len1 = sizeof (sa1);
3564 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3565 contact = Fplist_put (contact, QClocal,
3566 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3568 #endif
3571 immediate_quit = 0;
3573 #ifdef HAVE_GETADDRINFO
3574 if (res != &ai)
3576 block_input ();
3577 freeaddrinfo (res);
3578 unblock_input ();
3580 #endif
3582 if (s < 0)
3584 /* If non-blocking got this far - and failed - assume non-blocking is
3585 not supported after all. This is probably a wrong assumption, but
3586 the normal blocking calls to open-network-stream handles this error
3587 better. */
3588 if (is_non_blocking_client)
3589 return Qnil;
3591 report_file_errno ((is_server
3592 ? "make server process failed"
3593 : "make client process failed"),
3594 contact, xerrno);
3597 inch = s;
3598 outch = s;
3600 if (!NILP (buffer))
3601 buffer = Fget_buffer_create (buffer);
3602 proc = make_process (name);
3604 chan_process[inch] = proc;
3606 fcntl (inch, F_SETFL, O_NONBLOCK);
3608 p = XPROCESS (proc);
3610 pset_childp (p, contact);
3611 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3612 pset_type (p, Qnetwork);
3614 pset_buffer (p, buffer);
3615 pset_sentinel (p, sentinel);
3616 pset_filter (p, filter);
3617 pset_log (p, Fplist_get (contact, QClog));
3618 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3619 p->kill_without_query = 1;
3620 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3621 pset_command (p, Qt);
3622 p->pid = 0;
3624 p->open_fd[SUBPROCESS_STDIN] = inch;
3625 p->infd = inch;
3626 p->outfd = outch;
3628 /* Discard the unwind protect for closing S, if any. */
3629 specpdl_ptr = specpdl + count1;
3631 /* Unwind bind_polling_period and request_sigio. */
3632 unbind_to (count, Qnil);
3634 if (is_server && socktype != SOCK_DGRAM)
3635 pset_status (p, Qlisten);
3637 /* Make the process marker point into the process buffer (if any). */
3638 if (BUFFERP (buffer))
3639 set_marker_both (p->mark, buffer,
3640 BUF_ZV (XBUFFER (buffer)),
3641 BUF_ZV_BYTE (XBUFFER (buffer)));
3643 #ifdef NON_BLOCKING_CONNECT
3644 if (is_non_blocking_client)
3646 /* We may get here if connect did succeed immediately. However,
3647 in that case, we still need to signal this like a non-blocking
3648 connection. */
3649 pset_status (p, Qconnect);
3650 if (!FD_ISSET (inch, &connect_wait_mask))
3652 FD_SET (inch, &connect_wait_mask);
3653 FD_SET (inch, &write_mask);
3654 num_pending_connects++;
3657 else
3658 #endif
3659 /* A server may have a client filter setting of Qt, but it must
3660 still listen for incoming connects unless it is stopped. */
3661 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3662 || (EQ (p->status, Qlisten) && NILP (p->command)))
3664 FD_SET (inch, &input_wait_mask);
3665 FD_SET (inch, &non_keyboard_wait_mask);
3668 if (inch > max_process_desc)
3669 max_process_desc = inch;
3671 tem = Fplist_member (contact, QCcoding);
3672 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3673 tem = Qnil; /* No error message (too late!). */
3676 /* Setup coding systems for communicating with the network stream. */
3677 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3678 Lisp_Object coding_systems = Qt;
3679 Lisp_Object val;
3681 if (!NILP (tem))
3683 val = XCAR (XCDR (tem));
3684 if (CONSP (val))
3685 val = XCAR (val);
3687 else if (!NILP (Vcoding_system_for_read))
3688 val = Vcoding_system_for_read;
3689 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3690 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3691 /* We dare not decode end-of-line format by setting VAL to
3692 Qraw_text, because the existing Emacs Lisp libraries
3693 assume that they receive bare code including a sequence of
3694 CR LF. */
3695 val = Qnil;
3696 else
3698 if (NILP (host) || NILP (service))
3699 coding_systems = Qnil;
3700 else
3701 coding_systems = CALLN (Ffind_operation_coding_system,
3702 Qopen_network_stream, name, buffer,
3703 host, service);
3704 if (CONSP (coding_systems))
3705 val = XCAR (coding_systems);
3706 else if (CONSP (Vdefault_process_coding_system))
3707 val = XCAR (Vdefault_process_coding_system);
3708 else
3709 val = Qnil;
3711 pset_decode_coding_system (p, val);
3713 if (!NILP (tem))
3715 val = XCAR (XCDR (tem));
3716 if (CONSP (val))
3717 val = XCDR (val);
3719 else if (!NILP (Vcoding_system_for_write))
3720 val = Vcoding_system_for_write;
3721 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3722 val = Qnil;
3723 else
3725 if (EQ (coding_systems, Qt))
3727 if (NILP (host) || NILP (service))
3728 coding_systems = Qnil;
3729 else
3730 coding_systems = CALLN (Ffind_operation_coding_system,
3731 Qopen_network_stream, name, buffer,
3732 host, service);
3734 if (CONSP (coding_systems))
3735 val = XCDR (coding_systems);
3736 else if (CONSP (Vdefault_process_coding_system))
3737 val = XCDR (Vdefault_process_coding_system);
3738 else
3739 val = Qnil;
3741 pset_encode_coding_system (p, val);
3743 setup_process_coding_systems (proc);
3745 pset_decoding_buf (p, empty_unibyte_string);
3746 p->decoding_carryover = 0;
3747 pset_encoding_buf (p, empty_unibyte_string);
3749 p->inherit_coding_system_flag
3750 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3752 return proc;
3756 #ifdef HAVE_NET_IF_H
3758 #ifdef SIOCGIFCONF
3759 static Lisp_Object
3760 network_interface_list (void)
3762 struct ifconf ifconf;
3763 struct ifreq *ifreq;
3764 void *buf = NULL;
3765 ptrdiff_t buf_size = 512;
3766 int s;
3767 Lisp_Object res;
3768 ptrdiff_t count;
3770 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3771 if (s < 0)
3772 return Qnil;
3773 count = SPECPDL_INDEX ();
3774 record_unwind_protect_int (close_file_unwind, s);
3778 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3779 ifconf.ifc_buf = buf;
3780 ifconf.ifc_len = buf_size;
3781 if (ioctl (s, SIOCGIFCONF, &ifconf))
3783 emacs_close (s);
3784 xfree (buf);
3785 return Qnil;
3788 while (ifconf.ifc_len == buf_size);
3790 res = unbind_to (count, Qnil);
3791 ifreq = ifconf.ifc_req;
3792 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3794 struct ifreq *ifq = ifreq;
3795 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3796 #define SIZEOF_IFREQ(sif) \
3797 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3798 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3800 int len = SIZEOF_IFREQ (ifq);
3801 #else
3802 int len = sizeof (*ifreq);
3803 #endif
3804 char namebuf[sizeof (ifq->ifr_name) + 1];
3805 ifreq = (struct ifreq *) ((char *) ifreq + len);
3807 if (ifq->ifr_addr.sa_family != AF_INET)
3808 continue;
3810 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3811 namebuf[sizeof (ifq->ifr_name)] = 0;
3812 res = Fcons (Fcons (build_string (namebuf),
3813 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3814 sizeof (struct sockaddr))),
3815 res);
3818 xfree (buf);
3819 return res;
3821 #endif /* SIOCGIFCONF */
3823 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3825 struct ifflag_def {
3826 int flag_bit;
3827 const char *flag_sym;
3830 static const struct ifflag_def ifflag_table[] = {
3831 #ifdef IFF_UP
3832 { IFF_UP, "up" },
3833 #endif
3834 #ifdef IFF_BROADCAST
3835 { IFF_BROADCAST, "broadcast" },
3836 #endif
3837 #ifdef IFF_DEBUG
3838 { IFF_DEBUG, "debug" },
3839 #endif
3840 #ifdef IFF_LOOPBACK
3841 { IFF_LOOPBACK, "loopback" },
3842 #endif
3843 #ifdef IFF_POINTOPOINT
3844 { IFF_POINTOPOINT, "pointopoint" },
3845 #endif
3846 #ifdef IFF_RUNNING
3847 { IFF_RUNNING, "running" },
3848 #endif
3849 #ifdef IFF_NOARP
3850 { IFF_NOARP, "noarp" },
3851 #endif
3852 #ifdef IFF_PROMISC
3853 { IFF_PROMISC, "promisc" },
3854 #endif
3855 #ifdef IFF_NOTRAILERS
3856 #ifdef NS_IMPL_COCOA
3857 /* Really means smart, notrailers is obsolete. */
3858 { IFF_NOTRAILERS, "smart" },
3859 #else
3860 { IFF_NOTRAILERS, "notrailers" },
3861 #endif
3862 #endif
3863 #ifdef IFF_ALLMULTI
3864 { IFF_ALLMULTI, "allmulti" },
3865 #endif
3866 #ifdef IFF_MASTER
3867 { IFF_MASTER, "master" },
3868 #endif
3869 #ifdef IFF_SLAVE
3870 { IFF_SLAVE, "slave" },
3871 #endif
3872 #ifdef IFF_MULTICAST
3873 { IFF_MULTICAST, "multicast" },
3874 #endif
3875 #ifdef IFF_PORTSEL
3876 { IFF_PORTSEL, "portsel" },
3877 #endif
3878 #ifdef IFF_AUTOMEDIA
3879 { IFF_AUTOMEDIA, "automedia" },
3880 #endif
3881 #ifdef IFF_DYNAMIC
3882 { IFF_DYNAMIC, "dynamic" },
3883 #endif
3884 #ifdef IFF_OACTIVE
3885 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
3886 #endif
3887 #ifdef IFF_SIMPLEX
3888 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
3889 #endif
3890 #ifdef IFF_LINK0
3891 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
3892 #endif
3893 #ifdef IFF_LINK1
3894 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
3895 #endif
3896 #ifdef IFF_LINK2
3897 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
3898 #endif
3899 { 0, 0 }
3902 static Lisp_Object
3903 network_interface_info (Lisp_Object ifname)
3905 struct ifreq rq;
3906 Lisp_Object res = Qnil;
3907 Lisp_Object elt;
3908 int s;
3909 bool any = 0;
3910 ptrdiff_t count;
3911 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3912 && defined HAVE_GETIFADDRS && defined LLADDR)
3913 struct ifaddrs *ifap;
3914 #endif
3916 CHECK_STRING (ifname);
3918 if (sizeof rq.ifr_name <= SBYTES (ifname))
3919 error ("interface name too long");
3920 lispstpcpy (rq.ifr_name, ifname);
3922 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3923 if (s < 0)
3924 return Qnil;
3925 count = SPECPDL_INDEX ();
3926 record_unwind_protect_int (close_file_unwind, s);
3928 elt = Qnil;
3929 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3930 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3932 int flags = rq.ifr_flags;
3933 const struct ifflag_def *fp;
3934 int fnum;
3936 /* If flags is smaller than int (i.e. short) it may have the high bit set
3937 due to IFF_MULTICAST. In that case, sign extending it into
3938 an int is wrong. */
3939 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3940 flags = (unsigned short) rq.ifr_flags;
3942 any = 1;
3943 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3945 if (flags & fp->flag_bit)
3947 elt = Fcons (intern (fp->flag_sym), elt);
3948 flags -= fp->flag_bit;
3951 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3953 if (flags & 1)
3955 elt = Fcons (make_number (fnum), elt);
3959 #endif
3960 res = Fcons (elt, res);
3962 elt = Qnil;
3963 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3964 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3966 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3967 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3968 int n;
3970 any = 1;
3971 for (n = 0; n < 6; n++)
3972 p->contents[n] = make_number (((unsigned char *)
3973 &rq.ifr_hwaddr.sa_data[0])
3974 [n]);
3975 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3977 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3978 if (getifaddrs (&ifap) != -1)
3980 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3981 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3982 struct ifaddrs *it;
3984 for (it = ifap; it != NULL; it = it->ifa_next)
3986 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3987 unsigned char linkaddr[6];
3988 int n;
3990 if (it->ifa_addr->sa_family != AF_LINK
3991 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3992 || sdl->sdl_alen != 6)
3993 continue;
3995 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3996 for (n = 0; n < 6; n++)
3997 p->contents[n] = make_number (linkaddr[n]);
3999 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4000 break;
4003 #ifdef HAVE_FREEIFADDRS
4004 freeifaddrs (ifap);
4005 #endif
4007 #endif /* HAVE_GETIFADDRS && LLADDR */
4009 res = Fcons (elt, res);
4011 elt = Qnil;
4012 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4013 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4015 any = 1;
4016 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4017 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4018 #else
4019 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4020 #endif
4022 #endif
4023 res = Fcons (elt, res);
4025 elt = Qnil;
4026 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4027 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4029 any = 1;
4030 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4032 #endif
4033 res = Fcons (elt, res);
4035 elt = Qnil;
4036 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4037 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4039 any = 1;
4040 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4042 #endif
4043 res = Fcons (elt, res);
4045 return unbind_to (count, any ? res : Qnil);
4047 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4048 #endif /* defined (HAVE_NET_IF_H) */
4050 DEFUN ("network-interface-list", Fnetwork_interface_list,
4051 Snetwork_interface_list, 0, 0, 0,
4052 doc: /* Return an alist of all network interfaces and their network address.
4053 Each element is a cons, the car of which is a string containing the
4054 interface name, and the cdr is the network address in internal
4055 format; see the description of ADDRESS in `make-network-process'.
4057 If the information is not available, return nil. */)
4058 (void)
4060 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4061 return network_interface_list ();
4062 #else
4063 return Qnil;
4064 #endif
4067 DEFUN ("network-interface-info", Fnetwork_interface_info,
4068 Snetwork_interface_info, 1, 1, 0,
4069 doc: /* Return information about network interface named IFNAME.
4070 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4071 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4072 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4073 FLAGS is the current flags of the interface.
4075 Data that is unavailable is returned as nil. */)
4076 (Lisp_Object ifname)
4078 #if ((defined HAVE_NET_IF_H \
4079 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4080 || defined SIOCGIFFLAGS)) \
4081 || defined WINDOWSNT)
4082 return network_interface_info (ifname);
4083 #else
4084 return Qnil;
4085 #endif
4088 /* Turn off input and output for process PROC. */
4090 static void
4091 deactivate_process (Lisp_Object proc)
4093 int inchannel;
4094 struct Lisp_Process *p = XPROCESS (proc);
4095 int i;
4097 #ifdef HAVE_GNUTLS
4098 /* Delete GnuTLS structures in PROC, if any. */
4099 emacs_gnutls_deinit (proc);
4100 #endif /* HAVE_GNUTLS */
4102 if (p->read_output_delay > 0)
4104 if (--process_output_delay_count < 0)
4105 process_output_delay_count = 0;
4106 p->read_output_delay = 0;
4107 p->read_output_skip = 0;
4110 /* Beware SIGCHLD hereabouts. */
4112 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4113 close_process_fd (&p->open_fd[i]);
4115 inchannel = p->infd;
4116 if (inchannel >= 0)
4118 p->infd = -1;
4119 p->outfd = -1;
4120 #ifdef DATAGRAM_SOCKETS
4121 if (DATAGRAM_CHAN_P (inchannel))
4123 xfree (datagram_address[inchannel].sa);
4124 datagram_address[inchannel].sa = 0;
4125 datagram_address[inchannel].len = 0;
4127 #endif
4128 chan_process[inchannel] = Qnil;
4129 FD_CLR (inchannel, &input_wait_mask);
4130 FD_CLR (inchannel, &non_keyboard_wait_mask);
4131 #ifdef NON_BLOCKING_CONNECT
4132 if (FD_ISSET (inchannel, &connect_wait_mask))
4134 FD_CLR (inchannel, &connect_wait_mask);
4135 FD_CLR (inchannel, &write_mask);
4136 if (--num_pending_connects < 0)
4137 emacs_abort ();
4139 #endif
4140 if (inchannel == max_process_desc)
4142 /* We just closed the highest-numbered process input descriptor,
4143 so recompute the highest-numbered one now. */
4144 int i = inchannel;
4146 i--;
4147 while (0 <= i && NILP (chan_process[i]));
4149 max_process_desc = i;
4155 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4156 0, 4, 0,
4157 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4158 It is given to their filter functions.
4159 Optional argument PROCESS means do not return until output has been
4160 received from PROCESS.
4162 Optional second argument SECONDS and third argument MILLISEC
4163 specify a timeout; return after that much time even if there is
4164 no subprocess output. If SECONDS is a floating point number,
4165 it specifies a fractional number of seconds to wait.
4166 The MILLISEC argument is obsolete and should be avoided.
4168 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4169 from PROCESS only, suspending reading output from other processes.
4170 If JUST-THIS-ONE is an integer, don't run any timers either.
4171 Return non-nil if we received any output from PROCESS (or, if PROCESS
4172 is nil, from any process) before the timeout expired. */)
4173 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4175 intmax_t secs;
4176 int nsecs;
4178 if (! NILP (process))
4179 CHECK_PROCESS (process);
4180 else
4181 just_this_one = Qnil;
4183 if (!NILP (millisec))
4184 { /* Obsolete calling convention using integers rather than floats. */
4185 CHECK_NUMBER (millisec);
4186 if (NILP (seconds))
4187 seconds = make_float (XINT (millisec) / 1000.0);
4188 else
4190 CHECK_NUMBER (seconds);
4191 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4195 secs = 0;
4196 nsecs = -1;
4198 if (!NILP (seconds))
4200 if (INTEGERP (seconds))
4202 if (XINT (seconds) > 0)
4204 secs = XINT (seconds);
4205 nsecs = 0;
4208 else if (FLOATP (seconds))
4210 if (XFLOAT_DATA (seconds) > 0)
4212 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4213 secs = min (t.tv_sec, WAIT_READING_MAX);
4214 nsecs = t.tv_nsec;
4217 else
4218 wrong_type_argument (Qnumberp, seconds);
4220 else if (! NILP (process))
4221 nsecs = 0;
4223 return
4224 ((wait_reading_process_output (secs, nsecs, 0, 0,
4225 Qnil,
4226 !NILP (process) ? XPROCESS (process) : NULL,
4227 (NILP (just_this_one) ? 0
4228 : !INTEGERP (just_this_one) ? 1 : -1))
4229 <= 0)
4230 ? Qnil : Qt);
4233 /* Accept a connection for server process SERVER on CHANNEL. */
4235 static EMACS_INT connect_counter = 0;
4237 static void
4238 server_accept_connection (Lisp_Object server, int channel)
4240 Lisp_Object proc, caller, name, buffer;
4241 Lisp_Object contact, host, service;
4242 struct Lisp_Process *ps = XPROCESS (server);
4243 struct Lisp_Process *p;
4244 int s;
4245 union u_sockaddr {
4246 struct sockaddr sa;
4247 struct sockaddr_in in;
4248 #ifdef AF_INET6
4249 struct sockaddr_in6 in6;
4250 #endif
4251 #ifdef HAVE_LOCAL_SOCKETS
4252 struct sockaddr_un un;
4253 #endif
4254 } saddr;
4255 socklen_t len = sizeof saddr;
4256 ptrdiff_t count;
4258 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4260 if (s < 0)
4262 int code = errno;
4264 if (code == EAGAIN)
4265 return;
4266 #ifdef EWOULDBLOCK
4267 if (code == EWOULDBLOCK)
4268 return;
4269 #endif
4271 if (!NILP (ps->log))
4272 call3 (ps->log, server, Qnil,
4273 concat3 (build_string ("accept failed with code"),
4274 Fnumber_to_string (make_number (code)),
4275 build_string ("\n")));
4276 return;
4279 count = SPECPDL_INDEX ();
4280 record_unwind_protect_int (close_file_unwind, s);
4282 connect_counter++;
4284 /* Setup a new process to handle the connection. */
4286 /* Generate a unique identification of the caller, and build contact
4287 information for this process. */
4288 host = Qt;
4289 service = Qnil;
4290 switch (saddr.sa.sa_family)
4292 case AF_INET:
4294 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4296 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4297 host = CALLN (Fformat, ipv4_format,
4298 make_number (ip[0]), make_number (ip[1]),
4299 make_number (ip[2]), make_number (ip[3]));
4300 service = make_number (ntohs (saddr.in.sin_port));
4301 AUTO_STRING (caller_format, " <%s:%d>");
4302 caller = CALLN (Fformat, caller_format, host, service);
4304 break;
4306 #ifdef AF_INET6
4307 case AF_INET6:
4309 Lisp_Object args[9];
4310 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4311 int i;
4313 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4314 args[0] = ipv6_format;
4315 for (i = 0; i < 8; i++)
4316 args[i + 1] = make_number (ntohs (ip6[i]));
4317 host = CALLMANY (Fformat, args);
4318 service = make_number (ntohs (saddr.in.sin_port));
4319 AUTO_STRING (caller_format, " <[%s]:%d>");
4320 caller = CALLN (Fformat, caller_format, host, service);
4322 break;
4323 #endif
4325 #ifdef HAVE_LOCAL_SOCKETS
4326 case AF_LOCAL:
4327 #endif
4328 default:
4329 caller = Fnumber_to_string (make_number (connect_counter));
4330 AUTO_STRING (space_less_than, " <");
4331 AUTO_STRING (greater_than, ">");
4332 caller = concat3 (space_less_than, caller, greater_than);
4333 break;
4336 /* Create a new buffer name for this process if it doesn't have a
4337 filter. The new buffer name is based on the buffer name or
4338 process name of the server process concatenated with the caller
4339 identification. */
4341 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4342 || EQ (ps->filter, Qt)))
4343 buffer = Qnil;
4344 else
4346 buffer = ps->buffer;
4347 if (!NILP (buffer))
4348 buffer = Fbuffer_name (buffer);
4349 else
4350 buffer = ps->name;
4351 if (!NILP (buffer))
4353 buffer = concat2 (buffer, caller);
4354 buffer = Fget_buffer_create (buffer);
4358 /* Generate a unique name for the new server process. Combine the
4359 server process name with the caller identification. */
4361 name = concat2 (ps->name, caller);
4362 proc = make_process (name);
4364 chan_process[s] = proc;
4366 fcntl (s, F_SETFL, O_NONBLOCK);
4368 p = XPROCESS (proc);
4370 /* Build new contact information for this setup. */
4371 contact = Fcopy_sequence (ps->childp);
4372 contact = Fplist_put (contact, QCserver, Qnil);
4373 contact = Fplist_put (contact, QChost, host);
4374 if (!NILP (service))
4375 contact = Fplist_put (contact, QCservice, service);
4376 contact = Fplist_put (contact, QCremote,
4377 conv_sockaddr_to_lisp (&saddr.sa, len));
4378 #ifdef HAVE_GETSOCKNAME
4379 len = sizeof saddr;
4380 if (getsockname (s, &saddr.sa, &len) == 0)
4381 contact = Fplist_put (contact, QClocal,
4382 conv_sockaddr_to_lisp (&saddr.sa, len));
4383 #endif
4385 pset_childp (p, contact);
4386 pset_plist (p, Fcopy_sequence (ps->plist));
4387 pset_type (p, Qnetwork);
4389 pset_buffer (p, buffer);
4390 pset_sentinel (p, ps->sentinel);
4391 pset_filter (p, ps->filter);
4392 pset_command (p, Qnil);
4393 p->pid = 0;
4395 /* Discard the unwind protect for closing S. */
4396 specpdl_ptr = specpdl + count;
4398 p->open_fd[SUBPROCESS_STDIN] = s;
4399 p->infd = s;
4400 p->outfd = s;
4401 pset_status (p, Qrun);
4403 /* Client processes for accepted connections are not stopped initially. */
4404 if (!EQ (p->filter, Qt))
4406 FD_SET (s, &input_wait_mask);
4407 FD_SET (s, &non_keyboard_wait_mask);
4410 if (s > max_process_desc)
4411 max_process_desc = s;
4413 /* Setup coding system for new process based on server process.
4414 This seems to be the proper thing to do, as the coding system
4415 of the new process should reflect the settings at the time the
4416 server socket was opened; not the current settings. */
4418 pset_decode_coding_system (p, ps->decode_coding_system);
4419 pset_encode_coding_system (p, ps->encode_coding_system);
4420 setup_process_coding_systems (proc);
4422 pset_decoding_buf (p, empty_unibyte_string);
4423 p->decoding_carryover = 0;
4424 pset_encoding_buf (p, empty_unibyte_string);
4426 p->inherit_coding_system_flag
4427 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4429 AUTO_STRING (dash, "-");
4430 AUTO_STRING (nl, "\n");
4431 Lisp_Object host_string = STRINGP (host) ? host : dash;
4433 if (!NILP (ps->log))
4435 AUTO_STRING (accept_from, "accept from ");
4436 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4439 AUTO_STRING (open_from, "open from ");
4440 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4443 /* This variable is different from waiting_for_input in keyboard.c.
4444 It is used to communicate to a lisp process-filter/sentinel (via the
4445 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4446 for user-input when that process-filter was called.
4447 waiting_for_input cannot be used as that is by definition 0 when
4448 lisp code is being evalled.
4449 This is also used in record_asynch_buffer_change.
4450 For that purpose, this must be 0
4451 when not inside wait_reading_process_output. */
4452 static int waiting_for_user_input_p;
4454 static void
4455 wait_reading_process_output_unwind (int data)
4457 waiting_for_user_input_p = data;
4460 /* This is here so breakpoints can be put on it. */
4461 static void
4462 wait_reading_process_output_1 (void)
4466 /* Read and dispose of subprocess output while waiting for timeout to
4467 elapse and/or keyboard input to be available.
4469 TIME_LIMIT is:
4470 timeout in seconds
4471 If negative, gobble data immediately available but don't wait for any.
4473 NSECS is:
4474 an additional duration to wait, measured in nanoseconds
4475 If TIME_LIMIT is zero, then:
4476 If NSECS == 0, there is no limit.
4477 If NSECS > 0, the timeout consists of NSECS only.
4478 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4480 READ_KBD is:
4481 0 to ignore keyboard input, or
4482 1 to return when input is available, or
4483 -1 meaning caller will actually read the input, so don't throw to
4484 the quit handler, or
4486 DO_DISPLAY means redisplay should be done to show subprocess
4487 output that arrives.
4489 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4490 (and gobble terminal input into the buffer if any arrives).
4492 If WAIT_PROC is specified, wait until something arrives from that
4493 process.
4495 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4496 (suspending output from other processes). A negative value
4497 means don't run any timers either.
4499 Return positive if we received input from WAIT_PROC (or from any
4500 process if WAIT_PROC is null), zero if we attempted to receive
4501 input but got none, and negative if we didn't even try. */
4504 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4505 bool do_display,
4506 Lisp_Object wait_for_cell,
4507 struct Lisp_Process *wait_proc, int just_wait_proc)
4509 int channel, nfds;
4510 fd_set Available;
4511 fd_set Writeok;
4512 bool check_write;
4513 int check_delay;
4514 bool no_avail;
4515 int xerrno;
4516 Lisp_Object proc;
4517 struct timespec timeout, end_time, timer_delay;
4518 struct timespec got_output_end_time = invalid_timespec ();
4519 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
4520 int got_some_output = -1;
4521 ptrdiff_t count = SPECPDL_INDEX ();
4523 /* Close to the current time if known, an invalid timespec otherwise. */
4524 struct timespec now = invalid_timespec ();
4526 FD_ZERO (&Available);
4527 FD_ZERO (&Writeok);
4529 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4530 && !(CONSP (wait_proc->status)
4531 && EQ (XCAR (wait_proc->status), Qexit)))
4532 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4534 record_unwind_protect_int (wait_reading_process_output_unwind,
4535 waiting_for_user_input_p);
4536 waiting_for_user_input_p = read_kbd;
4538 if (TYPE_MAXIMUM (time_t) < time_limit)
4539 time_limit = TYPE_MAXIMUM (time_t);
4541 if (time_limit < 0 || nsecs < 0)
4542 wait = MINIMUM;
4543 else if (time_limit > 0 || nsecs > 0)
4545 wait = TIMEOUT;
4546 now = current_timespec ();
4547 end_time = timespec_add (now, make_timespec (time_limit, nsecs));
4549 else
4550 wait = INFINITY;
4552 while (1)
4554 bool process_skipped = false;
4556 /* If calling from keyboard input, do not quit
4557 since we want to return C-g as an input character.
4558 Otherwise, do pending quit if requested. */
4559 if (read_kbd >= 0)
4560 QUIT;
4561 else if (pending_signals)
4562 process_pending_signals ();
4564 /* Exit now if the cell we're waiting for became non-nil. */
4565 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4566 break;
4568 /* Compute time from now till when time limit is up. */
4569 /* Exit if already run out. */
4570 if (wait == TIMEOUT)
4572 if (!timespec_valid_p (now))
4573 now = current_timespec ();
4574 if (timespec_cmp (end_time, now) <= 0)
4575 break;
4576 timeout = timespec_sub (end_time, now);
4578 else
4579 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
4581 /* Normally we run timers here.
4582 But not if wait_for_cell; in those cases,
4583 the wait is supposed to be short,
4584 and those callers cannot handle running arbitrary Lisp code here. */
4585 if (NILP (wait_for_cell)
4586 && just_wait_proc >= 0)
4590 unsigned old_timers_run = timers_run;
4591 struct buffer *old_buffer = current_buffer;
4592 Lisp_Object old_window = selected_window;
4594 timer_delay = timer_check ();
4596 /* If a timer has run, this might have changed buffers
4597 an alike. Make read_key_sequence aware of that. */
4598 if (timers_run != old_timers_run
4599 && (old_buffer != current_buffer
4600 || !EQ (old_window, selected_window))
4601 && waiting_for_user_input_p == -1)
4602 record_asynch_buffer_change ();
4604 if (timers_run != old_timers_run && do_display)
4605 /* We must retry, since a timer may have requeued itself
4606 and that could alter the time_delay. */
4607 redisplay_preserve_echo_area (9);
4608 else
4609 break;
4611 while (!detect_input_pending ());
4613 /* If there is unread keyboard input, also return. */
4614 if (read_kbd != 0
4615 && requeued_events_pending_p ())
4616 break;
4618 /* This is so a breakpoint can be put here. */
4619 if (!timespec_valid_p (timer_delay))
4620 wait_reading_process_output_1 ();
4623 /* Cause C-g and alarm signals to take immediate action,
4624 and cause input available signals to zero out timeout.
4626 It is important that we do this before checking for process
4627 activity. If we get a SIGCHLD after the explicit checks for
4628 process activity, timeout is the only way we will know. */
4629 if (read_kbd < 0)
4630 set_waiting_for_input (&timeout);
4632 /* If status of something has changed, and no input is
4633 available, notify the user of the change right away. After
4634 this explicit check, we'll let the SIGCHLD handler zap
4635 timeout to get our attention. */
4636 if (update_tick != process_tick)
4638 fd_set Atemp;
4639 fd_set Ctemp;
4641 if (kbd_on_hold_p ())
4642 FD_ZERO (&Atemp);
4643 else
4644 Atemp = input_wait_mask;
4645 Ctemp = write_mask;
4647 timeout = make_timespec (0, 0);
4648 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4649 &Atemp,
4650 #ifdef NON_BLOCKING_CONNECT
4651 (num_pending_connects > 0 ? &Ctemp : NULL),
4652 #else
4653 NULL,
4654 #endif
4655 NULL, &timeout, NULL)
4656 <= 0))
4658 /* It's okay for us to do this and then continue with
4659 the loop, since timeout has already been zeroed out. */
4660 clear_waiting_for_input ();
4661 got_some_output = status_notify (NULL, wait_proc);
4662 if (do_display) redisplay_preserve_echo_area (13);
4666 /* Don't wait for output from a non-running process. Just
4667 read whatever data has already been received. */
4668 if (wait_proc && wait_proc->raw_status_new)
4669 update_status (wait_proc);
4670 if (wait_proc
4671 && ! EQ (wait_proc->status, Qrun)
4672 && ! EQ (wait_proc->status, Qconnect))
4674 bool read_some_bytes = false;
4676 clear_waiting_for_input ();
4678 /* If data can be read from the process, do so until exhausted. */
4679 if (wait_proc->infd >= 0)
4681 XSETPROCESS (proc, wait_proc);
4683 while (true)
4685 int nread = read_process_output (proc, wait_proc->infd);
4686 if (nread < 0)
4688 if (errno == EIO || errno == EAGAIN)
4689 break;
4690 #ifdef EWOULDBLOCK
4691 if (errno == EWOULDBLOCK)
4692 break;
4693 #endif
4695 else
4697 if (got_some_output < nread)
4698 got_some_output = nread;
4699 if (nread == 0)
4700 break;
4701 read_some_bytes = true;
4706 if (read_some_bytes && do_display)
4707 redisplay_preserve_echo_area (10);
4709 break;
4712 /* Wait till there is something to do. */
4714 if (wait_proc && just_wait_proc)
4716 if (wait_proc->infd < 0) /* Terminated. */
4717 break;
4718 FD_SET (wait_proc->infd, &Available);
4719 check_delay = 0;
4720 check_write = 0;
4722 else if (!NILP (wait_for_cell))
4724 Available = non_process_wait_mask;
4725 check_delay = 0;
4726 check_write = 0;
4728 else
4730 if (! read_kbd)
4731 Available = non_keyboard_wait_mask;
4732 else
4733 Available = input_wait_mask;
4734 Writeok = write_mask;
4735 check_delay = wait_proc ? 0 : process_output_delay_count;
4736 check_write = true;
4739 /* If frame size has changed or the window is newly mapped,
4740 redisplay now, before we start to wait. There is a race
4741 condition here; if a SIGIO arrives between now and the select
4742 and indicates that a frame is trashed, the select may block
4743 displaying a trashed screen. */
4744 if (frame_garbaged && do_display)
4746 clear_waiting_for_input ();
4747 redisplay_preserve_echo_area (11);
4748 if (read_kbd < 0)
4749 set_waiting_for_input (&timeout);
4752 /* Skip the `select' call if input is available and we're
4753 waiting for keyboard input or a cell change (which can be
4754 triggered by processing X events). In the latter case, set
4755 nfds to 1 to avoid breaking the loop. */
4756 no_avail = 0;
4757 if ((read_kbd || !NILP (wait_for_cell))
4758 && detect_input_pending ())
4760 nfds = read_kbd ? 0 : 1;
4761 no_avail = 1;
4762 FD_ZERO (&Available);
4764 else
4766 /* Set the timeout for adaptive read buffering if any
4767 process has non-zero read_output_skip and non-zero
4768 read_output_delay, and we are not reading output for a
4769 specific process. It is not executed if
4770 Vprocess_adaptive_read_buffering is nil. */
4771 if (process_output_skip && check_delay > 0)
4773 int adaptive_nsecs = timeout.tv_nsec;
4774 if (timeout.tv_sec > 0 || adaptive_nsecs > READ_OUTPUT_DELAY_MAX)
4775 adaptive_nsecs = READ_OUTPUT_DELAY_MAX;
4776 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4778 proc = chan_process[channel];
4779 if (NILP (proc))
4780 continue;
4781 /* Find minimum non-zero read_output_delay among the
4782 processes with non-zero read_output_skip. */
4783 if (XPROCESS (proc)->read_output_delay > 0)
4785 check_delay--;
4786 if (!XPROCESS (proc)->read_output_skip)
4787 continue;
4788 FD_CLR (channel, &Available);
4789 process_skipped = true;
4790 XPROCESS (proc)->read_output_skip = 0;
4791 if (XPROCESS (proc)->read_output_delay < adaptive_nsecs)
4792 adaptive_nsecs = XPROCESS (proc)->read_output_delay;
4795 timeout = make_timespec (0, adaptive_nsecs);
4796 process_output_skip = 0;
4799 /* If we've got some output and haven't limited our timeout
4800 with adaptive read buffering, limit it. */
4801 if (got_some_output > 0 && !process_skipped
4802 && (timeout.tv_sec
4803 || timeout.tv_nsec > READ_OUTPUT_DELAY_INCREMENT))
4804 timeout = make_timespec (0, READ_OUTPUT_DELAY_INCREMENT);
4807 if (NILP (wait_for_cell) && just_wait_proc >= 0
4808 && timespec_valid_p (timer_delay)
4809 && timespec_cmp (timer_delay, timeout) < 0)
4811 if (!timespec_valid_p (now))
4812 now = current_timespec ();
4813 struct timespec timeout_abs = timespec_add (now, timeout);
4814 if (!timespec_valid_p (got_output_end_time)
4815 || timespec_cmp (timeout_abs, got_output_end_time) < 0)
4816 got_output_end_time = timeout_abs;
4817 timeout = timer_delay;
4819 else
4820 got_output_end_time = invalid_timespec ();
4822 /* NOW can become inaccurate if time can pass during pselect. */
4823 if (timeout.tv_sec > 0 || timeout.tv_nsec > 0)
4824 now = invalid_timespec ();
4826 #if defined (HAVE_NS)
4827 nfds = ns_select
4828 #elif defined (HAVE_GLIB)
4829 nfds = xg_select
4830 #else
4831 nfds = pselect
4832 #endif
4833 (max (max_process_desc, max_input_desc) + 1,
4834 &Available,
4835 (check_write ? &Writeok : 0),
4836 NULL, &timeout, NULL);
4838 #ifdef HAVE_GNUTLS
4839 /* GnuTLS buffers data internally. In lowat mode it leaves
4840 some data in the TCP buffers so that select works, but
4841 with custom pull/push functions we need to check if some
4842 data is available in the buffers manually. */
4843 if (nfds == 0)
4845 fd_set tls_available;
4846 int set = 0;
4848 FD_ZERO (&tls_available);
4849 if (! wait_proc)
4851 /* We're not waiting on a specific process, so loop
4852 through all the channels and check for data.
4853 This is a workaround needed for some versions of
4854 the gnutls library -- 2.12.14 has been confirmed
4855 to need it. See
4856 http://comments.gmane.org/gmane.emacs.devel/145074 */
4857 for (channel = 0; channel < FD_SETSIZE; ++channel)
4858 if (! NILP (chan_process[channel]))
4860 struct Lisp_Process *p =
4861 XPROCESS (chan_process[channel]);
4862 if (p && p->gnutls_p && p->gnutls_state
4863 && ((emacs_gnutls_record_check_pending
4864 (p->gnutls_state))
4865 > 0))
4867 nfds++;
4868 eassert (p->infd == channel);
4869 FD_SET (p->infd, &tls_available);
4870 set++;
4874 else
4876 /* Check this specific channel. */
4877 if (wait_proc->gnutls_p /* Check for valid process. */
4878 && wait_proc->gnutls_state
4879 /* Do we have pending data? */
4880 && ((emacs_gnutls_record_check_pending
4881 (wait_proc->gnutls_state))
4882 > 0))
4884 nfds = 1;
4885 eassert (0 <= wait_proc->infd);
4886 /* Set to Available. */
4887 FD_SET (wait_proc->infd, &tls_available);
4888 set++;
4891 if (set)
4892 Available = tls_available;
4894 #endif
4897 xerrno = errno;
4899 /* Make C-g and alarm signals set flags again. */
4900 clear_waiting_for_input ();
4902 /* If we woke up due to SIGWINCH, actually change size now. */
4903 do_pending_window_change (0);
4905 if (nfds == 0)
4907 /* Exit the main loop if we've passed the requested timeout,
4908 or aren't skipping processes and got some output and
4909 haven't lowered our timeout due to timers or SIGIO and
4910 have waited a long amount of time due to repeated
4911 timers. */
4912 if (wait < TIMEOUT)
4913 break;
4914 struct timespec cmp_time
4915 = (wait == TIMEOUT
4916 ? end_time
4917 : (!process_skipped && got_some_output > 0
4918 && (timeout.tv_sec > 0 || timeout.tv_nsec > 0))
4919 ? got_output_end_time
4920 : invalid_timespec ());
4921 if (timespec_valid_p (cmp_time))
4923 now = current_timespec ();
4924 if (timespec_cmp (cmp_time, now) <= 0)
4925 break;
4929 if (nfds < 0)
4931 if (xerrno == EINTR)
4932 no_avail = 1;
4933 else if (xerrno == EBADF)
4934 emacs_abort ();
4935 else
4936 report_file_errno ("Failed select", Qnil, xerrno);
4939 /* Check for keyboard input. */
4940 /* If there is any, return immediately
4941 to give it higher priority than subprocesses. */
4943 if (read_kbd != 0)
4945 unsigned old_timers_run = timers_run;
4946 struct buffer *old_buffer = current_buffer;
4947 Lisp_Object old_window = selected_window;
4948 bool leave = false;
4950 if (detect_input_pending_run_timers (do_display))
4952 swallow_events (do_display);
4953 if (detect_input_pending_run_timers (do_display))
4954 leave = true;
4957 /* If a timer has run, this might have changed buffers
4958 an alike. Make read_key_sequence aware of that. */
4959 if (timers_run != old_timers_run
4960 && waiting_for_user_input_p == -1
4961 && (old_buffer != current_buffer
4962 || !EQ (old_window, selected_window)))
4963 record_asynch_buffer_change ();
4965 if (leave)
4966 break;
4969 /* If there is unread keyboard input, also return. */
4970 if (read_kbd != 0
4971 && requeued_events_pending_p ())
4972 break;
4974 /* If we are not checking for keyboard input now,
4975 do process events (but don't run any timers).
4976 This is so that X events will be processed.
4977 Otherwise they may have to wait until polling takes place.
4978 That would causes delays in pasting selections, for example.
4980 (We used to do this only if wait_for_cell.) */
4981 if (read_kbd == 0 && detect_input_pending ())
4983 swallow_events (do_display);
4984 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4985 if (detect_input_pending ())
4986 break;
4987 #endif
4990 /* Exit now if the cell we're waiting for became non-nil. */
4991 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4992 break;
4994 #ifdef USABLE_SIGIO
4995 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4996 go read it. This can happen with X on BSD after logging out.
4997 In that case, there really is no input and no SIGIO,
4998 but select says there is input. */
5000 if (read_kbd && interrupt_input
5001 && keyboard_bit_set (&Available) && ! noninteractive)
5002 handle_input_available_signal (SIGIO);
5003 #endif
5005 /* If checking input just got us a size-change event from X,
5006 obey it now if we should. */
5007 if (read_kbd || ! NILP (wait_for_cell))
5008 do_pending_window_change (0);
5010 /* Check for data from a process. */
5011 if (no_avail || nfds == 0)
5012 continue;
5014 for (channel = 0; channel <= max_input_desc; ++channel)
5016 struct fd_callback_data *d = &fd_callback_info[channel];
5017 if (d->func
5018 && ((d->condition & FOR_READ
5019 && FD_ISSET (channel, &Available))
5020 || (d->condition & FOR_WRITE
5021 && FD_ISSET (channel, &write_mask))))
5022 d->func (channel, d->data);
5025 for (channel = 0; channel <= max_process_desc; channel++)
5027 if (FD_ISSET (channel, &Available)
5028 && FD_ISSET (channel, &non_keyboard_wait_mask)
5029 && !FD_ISSET (channel, &non_process_wait_mask))
5031 int nread;
5033 /* If waiting for this channel, arrange to return as
5034 soon as no more input to be processed. No more
5035 waiting. */
5036 proc = chan_process[channel];
5037 if (NILP (proc))
5038 continue;
5040 /* If this is a server stream socket, accept connection. */
5041 if (EQ (XPROCESS (proc)->status, Qlisten))
5043 server_accept_connection (proc, channel);
5044 continue;
5047 /* Read data from the process, starting with our
5048 buffered-ahead character if we have one. */
5050 nread = read_process_output (proc, channel);
5051 if ((!wait_proc || wait_proc == XPROCESS (proc))
5052 && got_some_output < nread)
5053 got_some_output = nread;
5054 if (nread > 0)
5056 /* Vacuum up any leftovers without waiting. */
5057 if (wait_proc == XPROCESS (proc))
5058 wait = MINIMUM;
5059 /* Since read_process_output can run a filter,
5060 which can call accept-process-output,
5061 don't try to read from any other processes
5062 before doing the select again. */
5063 FD_ZERO (&Available);
5065 if (do_display)
5066 redisplay_preserve_echo_area (12);
5068 #ifdef EWOULDBLOCK
5069 else if (nread == -1 && errno == EWOULDBLOCK)
5071 #endif
5072 else if (nread == -1 && errno == EAGAIN)
5074 #ifdef WINDOWSNT
5075 /* FIXME: Is this special case still needed? */
5076 /* Note that we cannot distinguish between no input
5077 available now and a closed pipe.
5078 With luck, a closed pipe will be accompanied by
5079 subprocess termination and SIGCHLD. */
5080 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5081 && !PIPECONN_P (proc))
5083 #endif
5084 #ifdef HAVE_PTYS
5085 /* On some OSs with ptys, when the process on one end of
5086 a pty exits, the other end gets an error reading with
5087 errno = EIO instead of getting an EOF (0 bytes read).
5088 Therefore, if we get an error reading and errno =
5089 EIO, just continue, because the child process has
5090 exited and should clean itself up soon (e.g. when we
5091 get a SIGCHLD). */
5092 else if (nread == -1 && errno == EIO)
5094 struct Lisp_Process *p = XPROCESS (proc);
5096 /* Clear the descriptor now, so we only raise the
5097 signal once. */
5098 FD_CLR (channel, &input_wait_mask);
5099 FD_CLR (channel, &non_keyboard_wait_mask);
5101 if (p->pid == -2)
5103 /* If the EIO occurs on a pty, the SIGCHLD handler's
5104 waitpid call will not find the process object to
5105 delete. Do it here. */
5106 p->tick = ++process_tick;
5107 pset_status (p, Qfailed);
5110 #endif /* HAVE_PTYS */
5111 /* If we can detect process termination, don't consider the
5112 process gone just because its pipe is closed. */
5113 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5114 && !PIPECONN_P (proc))
5116 else if (nread == 0 && PIPECONN_P (proc))
5118 /* Preserve status of processes already terminated. */
5119 XPROCESS (proc)->tick = ++process_tick;
5120 deactivate_process (proc);
5121 if (EQ (XPROCESS (proc)->status, Qrun))
5122 pset_status (XPROCESS (proc),
5123 list2 (Qexit, make_number (0)));
5125 else
5127 /* Preserve status of processes already terminated. */
5128 XPROCESS (proc)->tick = ++process_tick;
5129 deactivate_process (proc);
5130 if (XPROCESS (proc)->raw_status_new)
5131 update_status (XPROCESS (proc));
5132 if (EQ (XPROCESS (proc)->status, Qrun))
5133 pset_status (XPROCESS (proc),
5134 list2 (Qexit, make_number (256)));
5137 #ifdef NON_BLOCKING_CONNECT
5138 if (FD_ISSET (channel, &Writeok)
5139 && FD_ISSET (channel, &connect_wait_mask))
5141 struct Lisp_Process *p;
5143 FD_CLR (channel, &connect_wait_mask);
5144 FD_CLR (channel, &write_mask);
5145 if (--num_pending_connects < 0)
5146 emacs_abort ();
5148 proc = chan_process[channel];
5149 if (NILP (proc))
5150 continue;
5152 p = XPROCESS (proc);
5154 #ifdef GNU_LINUX
5155 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5156 So only use it on systems where it is known to work. */
5158 socklen_t xlen = sizeof (xerrno);
5159 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5160 xerrno = errno;
5162 #else
5164 struct sockaddr pname;
5165 socklen_t pnamelen = sizeof (pname);
5167 /* If connection failed, getpeername will fail. */
5168 xerrno = 0;
5169 if (getpeername (channel, &pname, &pnamelen) < 0)
5171 /* Obtain connect failure code through error slippage. */
5172 char dummy;
5173 xerrno = errno;
5174 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5175 xerrno = errno;
5178 #endif
5179 if (xerrno)
5181 p->tick = ++process_tick;
5182 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5183 deactivate_process (proc);
5185 else
5187 pset_status (p, Qrun);
5188 /* Execute the sentinel here. If we had relied on
5189 status_notify to do it later, it will read input
5190 from the process before calling the sentinel. */
5191 exec_sentinel (proc, build_string ("open\n"));
5192 if (0 <= p->infd && !EQ (p->filter, Qt)
5193 && !EQ (p->command, Qt))
5195 FD_SET (p->infd, &input_wait_mask);
5196 FD_SET (p->infd, &non_keyboard_wait_mask);
5200 #endif /* NON_BLOCKING_CONNECT */
5201 } /* End for each file descriptor. */
5202 } /* End while exit conditions not met. */
5204 unbind_to (count, Qnil);
5206 /* If calling from keyboard input, do not quit
5207 since we want to return C-g as an input character.
5208 Otherwise, do pending quit if requested. */
5209 if (read_kbd >= 0)
5211 /* Prevent input_pending from remaining set if we quit. */
5212 clear_input_pending ();
5213 QUIT;
5216 return got_some_output;
5219 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5221 static Lisp_Object
5222 read_process_output_call (Lisp_Object fun_and_args)
5224 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5227 static Lisp_Object
5228 read_process_output_error_handler (Lisp_Object error_val)
5230 cmd_error_internal (error_val, "error in process filter: ");
5231 Vinhibit_quit = Qt;
5232 update_echo_area ();
5233 Fsleep_for (make_number (2), Qnil);
5234 return Qt;
5237 static void
5238 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5239 ssize_t nbytes,
5240 struct coding_system *coding);
5242 /* Read pending output from the process channel,
5243 starting with our buffered-ahead character if we have one.
5244 Yield number of decoded characters read.
5246 This function reads at most 4096 characters.
5247 If you want to read all available subprocess output,
5248 you must call it repeatedly until it returns zero.
5250 The characters read are decoded according to PROC's coding-system
5251 for decoding. */
5253 static int
5254 read_process_output (Lisp_Object proc, int channel)
5256 ssize_t nbytes;
5257 struct Lisp_Process *p = XPROCESS (proc);
5258 struct coding_system *coding = proc_decode_coding_system[channel];
5259 int carryover = p->decoding_carryover;
5260 enum { readmax = 4096 };
5261 ptrdiff_t count = SPECPDL_INDEX ();
5262 Lisp_Object odeactivate;
5263 char chars[sizeof coding->carryover + readmax];
5265 if (carryover)
5266 /* See the comment above. */
5267 memcpy (chars, SDATA (p->decoding_buf), carryover);
5269 #ifdef DATAGRAM_SOCKETS
5270 /* We have a working select, so proc_buffered_char is always -1. */
5271 if (DATAGRAM_CHAN_P (channel))
5273 socklen_t len = datagram_address[channel].len;
5274 nbytes = recvfrom (channel, chars + carryover, readmax,
5275 0, datagram_address[channel].sa, &len);
5277 else
5278 #endif
5280 bool buffered = proc_buffered_char[channel] >= 0;
5281 if (buffered)
5283 chars[carryover] = proc_buffered_char[channel];
5284 proc_buffered_char[channel] = -1;
5286 #ifdef HAVE_GNUTLS
5287 if (p->gnutls_p && p->gnutls_state)
5288 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5289 readmax - buffered);
5290 else
5291 #endif
5292 nbytes = emacs_read (channel, chars + carryover + buffered,
5293 readmax - buffered);
5294 if (nbytes > 0 && p->adaptive_read_buffering)
5296 int delay = p->read_output_delay;
5297 if (nbytes < 256)
5299 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5301 if (delay == 0)
5302 process_output_delay_count++;
5303 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5306 else if (delay > 0 && nbytes == readmax - buffered)
5308 delay -= READ_OUTPUT_DELAY_INCREMENT;
5309 if (delay == 0)
5310 process_output_delay_count--;
5312 p->read_output_delay = delay;
5313 if (delay)
5315 p->read_output_skip = 1;
5316 process_output_skip = 1;
5319 nbytes += buffered;
5320 nbytes += buffered && nbytes <= 0;
5323 p->decoding_carryover = 0;
5325 /* At this point, NBYTES holds number of bytes just received
5326 (including the one in proc_buffered_char[channel]). */
5327 if (nbytes <= 0)
5329 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5330 return nbytes;
5331 coding->mode |= CODING_MODE_LAST_BLOCK;
5334 /* Now set NBYTES how many bytes we must decode. */
5335 nbytes += carryover;
5337 odeactivate = Vdeactivate_mark;
5338 /* There's no good reason to let process filters change the current
5339 buffer, and many callers of accept-process-output, sit-for, and
5340 friends don't expect current-buffer to be changed from under them. */
5341 record_unwind_current_buffer ();
5343 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5345 /* Handling the process output should not deactivate the mark. */
5346 Vdeactivate_mark = odeactivate;
5348 unbind_to (count, Qnil);
5349 return nbytes;
5352 static void
5353 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5354 ssize_t nbytes,
5355 struct coding_system *coding)
5357 Lisp_Object outstream = p->filter;
5358 Lisp_Object text;
5359 bool outer_running_asynch_code = running_asynch_code;
5360 int waiting = waiting_for_user_input_p;
5362 #if 0
5363 Lisp_Object obuffer, okeymap;
5364 XSETBUFFER (obuffer, current_buffer);
5365 okeymap = BVAR (current_buffer, keymap);
5366 #endif
5368 /* We inhibit quit here instead of just catching it so that
5369 hitting ^G when a filter happens to be running won't screw
5370 it up. */
5371 specbind (Qinhibit_quit, Qt);
5372 specbind (Qlast_nonmenu_event, Qt);
5374 /* In case we get recursively called,
5375 and we already saved the match data nonrecursively,
5376 save the same match data in safely recursive fashion. */
5377 if (outer_running_asynch_code)
5379 Lisp_Object tem;
5380 /* Don't clobber the CURRENT match data, either! */
5381 tem = Fmatch_data (Qnil, Qnil, Qnil);
5382 restore_search_regs ();
5383 record_unwind_save_match_data ();
5384 Fset_match_data (tem, Qt);
5387 /* For speed, if a search happens within this code,
5388 save the match data in a special nonrecursive fashion. */
5389 running_asynch_code = 1;
5391 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5392 text = coding->dst_object;
5393 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5394 /* A new coding system might be found. */
5395 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5397 pset_decode_coding_system (p, Vlast_coding_system_used);
5399 /* Don't call setup_coding_system for
5400 proc_decode_coding_system[channel] here. It is done in
5401 detect_coding called via decode_coding above. */
5403 /* If a coding system for encoding is not yet decided, we set
5404 it as the same as coding-system for decoding.
5406 But, before doing that we must check if
5407 proc_encode_coding_system[p->outfd] surely points to a
5408 valid memory because p->outfd will be changed once EOF is
5409 sent to the process. */
5410 if (NILP (p->encode_coding_system) && p->outfd >= 0
5411 && proc_encode_coding_system[p->outfd])
5413 pset_encode_coding_system
5414 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5415 setup_coding_system (p->encode_coding_system,
5416 proc_encode_coding_system[p->outfd]);
5420 if (coding->carryover_bytes > 0)
5422 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5423 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5424 memcpy (SDATA (p->decoding_buf), coding->carryover,
5425 coding->carryover_bytes);
5426 p->decoding_carryover = coding->carryover_bytes;
5428 if (SBYTES (text) > 0)
5429 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5430 sometimes it's simply wrong to wrap (e.g. when called from
5431 accept-process-output). */
5432 internal_condition_case_1 (read_process_output_call,
5433 list3 (outstream, make_lisp_proc (p), text),
5434 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5435 read_process_output_error_handler);
5437 /* If we saved the match data nonrecursively, restore it now. */
5438 restore_search_regs ();
5439 running_asynch_code = outer_running_asynch_code;
5441 /* Restore waiting_for_user_input_p as it was
5442 when we were called, in case the filter clobbered it. */
5443 waiting_for_user_input_p = waiting;
5445 #if 0 /* Call record_asynch_buffer_change unconditionally,
5446 because we might have changed minor modes or other things
5447 that affect key bindings. */
5448 if (! EQ (Fcurrent_buffer (), obuffer)
5449 || ! EQ (current_buffer->keymap, okeymap))
5450 #endif
5451 /* But do it only if the caller is actually going to read events.
5452 Otherwise there's no need to make him wake up, and it could
5453 cause trouble (for example it would make sit_for return). */
5454 if (waiting_for_user_input_p == -1)
5455 record_asynch_buffer_change ();
5458 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5459 Sinternal_default_process_filter, 2, 2, 0,
5460 doc: /* Function used as default process filter.
5461 This inserts the process's output into its buffer, if there is one.
5462 Otherwise it discards the output. */)
5463 (Lisp_Object proc, Lisp_Object text)
5465 struct Lisp_Process *p;
5466 ptrdiff_t opoint;
5468 CHECK_PROCESS (proc);
5469 p = XPROCESS (proc);
5470 CHECK_STRING (text);
5472 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5474 Lisp_Object old_read_only;
5475 ptrdiff_t old_begv, old_zv;
5476 ptrdiff_t old_begv_byte, old_zv_byte;
5477 ptrdiff_t before, before_byte;
5478 ptrdiff_t opoint_byte;
5479 struct buffer *b;
5481 Fset_buffer (p->buffer);
5482 opoint = PT;
5483 opoint_byte = PT_BYTE;
5484 old_read_only = BVAR (current_buffer, read_only);
5485 old_begv = BEGV;
5486 old_zv = ZV;
5487 old_begv_byte = BEGV_BYTE;
5488 old_zv_byte = ZV_BYTE;
5490 bset_read_only (current_buffer, Qnil);
5492 /* Insert new output into buffer at the current end-of-output
5493 marker, thus preserving logical ordering of input and output. */
5494 if (XMARKER (p->mark)->buffer)
5495 set_point_from_marker (p->mark);
5496 else
5497 SET_PT_BOTH (ZV, ZV_BYTE);
5498 before = PT;
5499 before_byte = PT_BYTE;
5501 /* If the output marker is outside of the visible region, save
5502 the restriction and widen. */
5503 if (! (BEGV <= PT && PT <= ZV))
5504 Fwiden ();
5506 /* Adjust the multibyteness of TEXT to that of the buffer. */
5507 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5508 != ! STRING_MULTIBYTE (text))
5509 text = (STRING_MULTIBYTE (text)
5510 ? Fstring_as_unibyte (text)
5511 : Fstring_to_multibyte (text));
5512 /* Insert before markers in case we are inserting where
5513 the buffer's mark is, and the user's next command is Meta-y. */
5514 insert_from_string_before_markers (text, 0, 0,
5515 SCHARS (text), SBYTES (text), 0);
5517 /* Make sure the process marker's position is valid when the
5518 process buffer is changed in the signal_after_change above.
5519 W3 is known to do that. */
5520 if (BUFFERP (p->buffer)
5521 && (b = XBUFFER (p->buffer), b != current_buffer))
5522 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5523 else
5524 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5526 update_mode_lines = 23;
5528 /* Make sure opoint and the old restrictions
5529 float ahead of any new text just as point would. */
5530 if (opoint >= before)
5532 opoint += PT - before;
5533 opoint_byte += PT_BYTE - before_byte;
5535 if (old_begv > before)
5537 old_begv += PT - before;
5538 old_begv_byte += PT_BYTE - before_byte;
5540 if (old_zv >= before)
5542 old_zv += PT - before;
5543 old_zv_byte += PT_BYTE - before_byte;
5546 /* If the restriction isn't what it should be, set it. */
5547 if (old_begv != BEGV || old_zv != ZV)
5548 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5550 bset_read_only (current_buffer, old_read_only);
5551 SET_PT_BOTH (opoint, opoint_byte);
5553 return Qnil;
5556 /* Sending data to subprocess. */
5558 /* In send_process, when a write fails temporarily,
5559 wait_reading_process_output is called. It may execute user code,
5560 e.g. timers, that attempts to write new data to the same process.
5561 We must ensure that data is sent in the right order, and not
5562 interspersed half-completed with other writes (Bug#10815). This is
5563 handled by the write_queue element of struct process. It is a list
5564 with each entry having the form
5566 (string . (offset . length))
5568 where STRING is a lisp string, OFFSET is the offset into the
5569 string's byte sequence from which we should begin to send, and
5570 LENGTH is the number of bytes left to send. */
5572 /* Create a new entry in write_queue.
5573 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5574 BUF is a pointer to the string sequence of the input_obj or a C
5575 string in case of Qt or Qnil. */
5577 static void
5578 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5579 const char *buf, ptrdiff_t len, bool front)
5581 ptrdiff_t offset;
5582 Lisp_Object entry, obj;
5584 if (STRINGP (input_obj))
5586 offset = buf - SSDATA (input_obj);
5587 obj = input_obj;
5589 else
5591 offset = 0;
5592 obj = make_unibyte_string (buf, len);
5595 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5597 if (front)
5598 pset_write_queue (p, Fcons (entry, p->write_queue));
5599 else
5600 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5603 /* Remove the first element in the write_queue of process P, put its
5604 contents in OBJ, BUF and LEN, and return true. If the
5605 write_queue is empty, return false. */
5607 static bool
5608 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5609 const char **buf, ptrdiff_t *len)
5611 Lisp_Object entry, offset_length;
5612 ptrdiff_t offset;
5614 if (NILP (p->write_queue))
5615 return 0;
5617 entry = XCAR (p->write_queue);
5618 pset_write_queue (p, XCDR (p->write_queue));
5620 *obj = XCAR (entry);
5621 offset_length = XCDR (entry);
5623 *len = XINT (XCDR (offset_length));
5624 offset = XINT (XCAR (offset_length));
5625 *buf = SSDATA (*obj) + offset;
5627 return 1;
5630 /* Send some data to process PROC.
5631 BUF is the beginning of the data; LEN is the number of characters.
5632 OBJECT is the Lisp object that the data comes from. If OBJECT is
5633 nil or t, it means that the data comes from C string.
5635 If OBJECT is not nil, the data is encoded by PROC's coding-system
5636 for encoding before it is sent.
5638 This function can evaluate Lisp code and can garbage collect. */
5640 static void
5641 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5642 Lisp_Object object)
5644 struct Lisp_Process *p = XPROCESS (proc);
5645 ssize_t rv;
5646 struct coding_system *coding;
5648 if (p->raw_status_new)
5649 update_status (p);
5650 if (! EQ (p->status, Qrun))
5651 error ("Process %s not running", SDATA (p->name));
5652 if (p->outfd < 0)
5653 error ("Output file descriptor of %s is closed", SDATA (p->name));
5655 coding = proc_encode_coding_system[p->outfd];
5656 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5658 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5659 || (BUFFERP (object)
5660 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5661 || EQ (object, Qt))
5663 pset_encode_coding_system
5664 (p, complement_process_encoding_system (p->encode_coding_system));
5665 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5667 /* The coding system for encoding was changed to raw-text
5668 because we sent a unibyte text previously. Now we are
5669 sending a multibyte text, thus we must encode it by the
5670 original coding system specified for the current process.
5672 Another reason we come here is that the coding system
5673 was just complemented and a new one was returned by
5674 complement_process_encoding_system. */
5675 setup_coding_system (p->encode_coding_system, coding);
5676 Vlast_coding_system_used = p->encode_coding_system;
5678 coding->src_multibyte = 1;
5680 else
5682 coding->src_multibyte = 0;
5683 /* For sending a unibyte text, character code conversion should
5684 not take place but EOL conversion should. So, setup raw-text
5685 or one of the subsidiary if we have not yet done it. */
5686 if (CODING_REQUIRE_ENCODING (coding))
5688 if (CODING_REQUIRE_FLUSHING (coding))
5690 /* But, before changing the coding, we must flush out data. */
5691 coding->mode |= CODING_MODE_LAST_BLOCK;
5692 send_process (proc, "", 0, Qt);
5693 coding->mode &= CODING_MODE_LAST_BLOCK;
5695 setup_coding_system (raw_text_coding_system
5696 (Vlast_coding_system_used),
5697 coding);
5698 coding->src_multibyte = 0;
5701 coding->dst_multibyte = 0;
5703 if (CODING_REQUIRE_ENCODING (coding))
5705 coding->dst_object = Qt;
5706 if (BUFFERP (object))
5708 ptrdiff_t from_byte, from, to;
5709 ptrdiff_t save_pt, save_pt_byte;
5710 struct buffer *cur = current_buffer;
5712 set_buffer_internal (XBUFFER (object));
5713 save_pt = PT, save_pt_byte = PT_BYTE;
5715 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5716 from = BYTE_TO_CHAR (from_byte);
5717 to = BYTE_TO_CHAR (from_byte + len);
5718 TEMP_SET_PT_BOTH (from, from_byte);
5719 encode_coding_object (coding, object, from, from_byte,
5720 to, from_byte + len, Qt);
5721 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5722 set_buffer_internal (cur);
5724 else if (STRINGP (object))
5726 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5727 SBYTES (object), Qt);
5729 else
5731 coding->dst_object = make_unibyte_string (buf, len);
5732 coding->produced = len;
5735 len = coding->produced;
5736 object = coding->dst_object;
5737 buf = SSDATA (object);
5740 /* If there is already data in the write_queue, put the new data
5741 in the back of queue. Otherwise, ignore it. */
5742 if (!NILP (p->write_queue))
5743 write_queue_push (p, object, buf, len, 0);
5745 do /* while !NILP (p->write_queue) */
5747 ptrdiff_t cur_len = -1;
5748 const char *cur_buf;
5749 Lisp_Object cur_object;
5751 /* If write_queue is empty, ignore it. */
5752 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5754 cur_len = len;
5755 cur_buf = buf;
5756 cur_object = object;
5759 while (cur_len > 0)
5761 /* Send this batch, using one or more write calls. */
5762 ptrdiff_t written = 0;
5763 int outfd = p->outfd;
5764 #ifdef DATAGRAM_SOCKETS
5765 if (DATAGRAM_CHAN_P (outfd))
5767 rv = sendto (outfd, cur_buf, cur_len,
5768 0, datagram_address[outfd].sa,
5769 datagram_address[outfd].len);
5770 if (rv >= 0)
5771 written = rv;
5772 else if (errno == EMSGSIZE)
5773 report_file_error ("Sending datagram", proc);
5775 else
5776 #endif
5778 #ifdef HAVE_GNUTLS
5779 if (p->gnutls_p && p->gnutls_state)
5780 written = emacs_gnutls_write (p, cur_buf, cur_len);
5781 else
5782 #endif
5783 written = emacs_write_sig (outfd, cur_buf, cur_len);
5784 rv = (written ? 0 : -1);
5785 if (p->read_output_delay > 0
5786 && p->adaptive_read_buffering == 1)
5788 p->read_output_delay = 0;
5789 process_output_delay_count--;
5790 p->read_output_skip = 0;
5794 if (rv < 0)
5796 if (errno == EAGAIN
5797 #ifdef EWOULDBLOCK
5798 || errno == EWOULDBLOCK
5799 #endif
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 process, inhibit handling of incoming
6152 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);