Fix customization type of `even-window-sizes'.
[emacs.git] / src / process.c
blob9d8fa2237f38b7ff32f9cc950cfc9d07655404f3
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2015 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
27 #include <sys/file.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30 #include <fcntl.h>
32 #include "lisp.h"
34 /* Only MS-DOS does not define `subprocesses'. */
35 #ifdef subprocesses
37 #include <sys/socket.h>
38 #include <netdb.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
42 /* Are local (unix) sockets supported? */
43 #if defined (HAVE_SYS_UN_H)
44 #if !defined (AF_LOCAL) && defined (AF_UNIX)
45 #define AF_LOCAL AF_UNIX
46 #endif
47 #ifdef AF_LOCAL
48 #define HAVE_LOCAL_SOCKETS
49 #include <sys/un.h>
50 #endif
51 #endif
53 #include <sys/ioctl.h>
54 #if defined (HAVE_NET_IF_H)
55 #include <net/if.h>
56 #endif /* HAVE_NET_IF_H */
58 #if defined (HAVE_IFADDRS_H)
59 /* Must be after net/if.h */
60 #include <ifaddrs.h>
62 /* We only use structs from this header when we use getifaddrs. */
63 #if defined (HAVE_NET_IF_DL_H)
64 #include <net/if_dl.h>
65 #endif
67 #endif
69 #ifdef NEED_BSDTTY
70 #include <bsdtty.h>
71 #endif
73 #ifdef USG5_4
74 # include <sys/stream.h>
75 # include <sys/stropts.h>
76 #endif
78 #ifdef HAVE_RES_INIT
79 #include <arpa/nameser.h>
80 #include <resolv.h>
81 #endif
83 #ifdef HAVE_UTIL_H
84 #include <util.h>
85 #endif
87 #ifdef HAVE_PTY_H
88 #include <pty.h>
89 #endif
91 #include <c-ctype.h>
92 #include <sig2str.h>
93 #include <verify.h>
95 #endif /* subprocesses */
97 #include "systime.h"
98 #include "systty.h"
100 #include "window.h"
101 #include "character.h"
102 #include "buffer.h"
103 #include "coding.h"
104 #include "process.h"
105 #include "frame.h"
106 #include "termhooks.h"
107 #include "termopts.h"
108 #include "commands.h"
109 #include "keyboard.h"
110 #include "blockinput.h"
111 #include "dispextern.h"
112 #include "composite.h"
113 #include "atimer.h"
114 #include "sysselect.h"
115 #include "syssignal.h"
116 #include "syswait.h"
117 #ifdef HAVE_GNUTLS
118 #include "gnutls.h"
119 #endif
121 #ifdef HAVE_WINDOW_SYSTEM
122 #include TERM_HEADER
123 #endif /* HAVE_WINDOW_SYSTEM */
125 #ifdef HAVE_GLIB
126 #include "xgselect.h"
127 #ifndef WINDOWSNT
128 #include <glib.h>
129 #endif
130 #endif
132 #ifdef WINDOWSNT
133 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
134 struct timespec *, void *);
135 #endif
137 /* Work around GCC 4.7.0 bug with strict overflow checking; see
138 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
139 This bug appears to be fixed in GCC 5.1, so don't work around it there. */
140 #if __GNUC__ == 4 && __GNUC_MINOR__ >= 3
141 # pragma GCC diagnostic ignored "-Wstrict-overflow"
142 #endif
144 /* True if keyboard input is on hold, zero otherwise. */
146 static bool kbd_is_on_hold;
148 /* Nonzero means don't run process sentinels. This is used
149 when exiting. */
150 bool inhibit_sentinels;
152 #ifdef subprocesses
154 #ifndef SOCK_CLOEXEC
155 # define SOCK_CLOEXEC 0
156 #endif
158 #ifndef HAVE_ACCEPT4
160 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
162 static int
163 close_on_exec (int fd)
165 if (0 <= fd)
166 fcntl (fd, F_SETFD, FD_CLOEXEC);
167 return fd;
170 # undef accept4
171 # define accept4(sockfd, addr, addrlen, flags) \
172 process_accept4 (sockfd, addr, addrlen, flags)
173 static int
174 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
176 return close_on_exec (accept (sockfd, addr, addrlen));
179 static int
180 process_socket (int domain, int type, int protocol)
182 return close_on_exec (socket (domain, type, protocol));
184 # undef socket
185 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
186 #endif
188 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
189 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
190 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
191 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
192 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
193 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
195 /* Number of events of change of status of a process. */
196 static EMACS_INT process_tick;
197 /* Number of events for which the user or sentinel has been notified. */
198 static EMACS_INT update_tick;
200 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects.
201 The code can be simplified by assuming NON_BLOCKING_CONNECT once
202 Emacs starts assuming POSIX 1003.1-2001 or later. */
204 #if (defined HAVE_SELECT \
205 && (defined GNU_LINUX || defined HAVE_GETPEERNAME) \
206 && (defined EWOULDBLOCK || defined EINPROGRESS))
207 # define NON_BLOCKING_CONNECT
208 #endif
210 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
211 this system. We need to read full packets, so we need a
212 "non-destructive" select. So we require either native select,
213 or emulation of select using FIONREAD. */
215 #ifndef BROKEN_DATAGRAM_SOCKETS
216 # if defined HAVE_SELECT || defined USABLE_FIONREAD
217 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
218 # define DATAGRAM_SOCKETS
219 # endif
220 # endif
221 #endif
223 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
224 # define HAVE_SEQPACKET
225 #endif
227 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
228 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
229 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
231 /* Number of processes which have a non-zero read_output_delay,
232 and therefore might be delayed for adaptive read buffering. */
234 static int process_output_delay_count;
236 /* True if any process has non-nil read_output_skip. */
238 static bool process_output_skip;
240 static void create_process (Lisp_Object, char **, Lisp_Object);
241 #ifdef USABLE_SIGIO
242 static bool keyboard_bit_set (fd_set *);
243 #endif
244 static void deactivate_process (Lisp_Object);
245 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
246 static int read_process_output (Lisp_Object, int);
247 static void handle_child_signal (int);
248 static void create_pty (Lisp_Object);
250 static Lisp_Object get_process (register Lisp_Object name);
251 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
253 /* Mask of bits indicating the descriptors that we wait for input on. */
255 static fd_set input_wait_mask;
257 /* Mask that excludes keyboard input descriptor(s). */
259 static fd_set non_keyboard_wait_mask;
261 /* Mask that excludes process input descriptor(s). */
263 static fd_set non_process_wait_mask;
265 /* Mask for selecting for write. */
267 static fd_set write_mask;
269 #ifdef NON_BLOCKING_CONNECT
270 /* Mask of bits indicating the descriptors that we wait for connect to
271 complete on. Once they complete, they are removed from this mask
272 and added to the input_wait_mask and non_keyboard_wait_mask. */
274 static fd_set connect_wait_mask;
276 /* Number of bits set in connect_wait_mask. */
277 static int num_pending_connects;
278 #endif /* NON_BLOCKING_CONNECT */
280 /* The largest descriptor currently in use for a process object; -1 if none. */
281 static int max_process_desc;
283 /* The largest descriptor currently in use for input; -1 if none. */
284 static int max_input_desc;
286 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
287 static Lisp_Object chan_process[FD_SETSIZE];
289 /* Alist of elements (NAME . PROCESS). */
290 static Lisp_Object Vprocess_alist;
292 /* Buffered-ahead input char from process, indexed by channel.
293 -1 means empty (no char is buffered).
294 Used on sys V where the only way to tell if there is any
295 output from the process is to read at least one char.
296 Always -1 on systems that support FIONREAD. */
298 static int proc_buffered_char[FD_SETSIZE];
300 /* Table of `struct coding-system' for each process. */
301 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
302 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
304 #ifdef DATAGRAM_SOCKETS
305 /* Table of `partner address' for datagram sockets. */
306 static struct sockaddr_and_len {
307 struct sockaddr *sa;
308 int len;
309 } datagram_address[FD_SETSIZE];
310 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
311 #define DATAGRAM_CONN_P(proc) \
312 (PROCESSP (proc) && \
313 XPROCESS (proc)->infd >= 0 && \
314 datagram_address[XPROCESS (proc)->infd].sa != 0)
315 #else
316 #define DATAGRAM_CHAN_P(chan) (0)
317 #define DATAGRAM_CONN_P(proc) (0)
318 #endif
320 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
321 a `for' loop which iterates over processes from Vprocess_alist. */
323 #define FOR_EACH_PROCESS(list_var, proc_var) \
324 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
326 /* These setters are used only in this file, so they can be private. */
327 static void
328 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
330 p->buffer = val;
332 static void
333 pset_command (struct Lisp_Process *p, Lisp_Object val)
335 p->command = val;
337 static void
338 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
340 p->decode_coding_system = val;
342 static void
343 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
345 p->decoding_buf = val;
347 static void
348 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
350 p->encode_coding_system = val;
352 static void
353 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
355 p->encoding_buf = val;
357 static void
358 pset_filter (struct Lisp_Process *p, Lisp_Object val)
360 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
362 static void
363 pset_log (struct Lisp_Process *p, Lisp_Object val)
365 p->log = val;
367 static void
368 pset_mark (struct Lisp_Process *p, Lisp_Object val)
370 p->mark = val;
372 static void
373 pset_name (struct Lisp_Process *p, Lisp_Object val)
375 p->name = val;
377 static void
378 pset_plist (struct Lisp_Process *p, Lisp_Object val)
380 p->plist = val;
382 static void
383 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
385 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
387 static void
388 pset_status (struct Lisp_Process *p, Lisp_Object val)
390 p->status = val;
392 static void
393 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
395 p->tty_name = val;
397 static void
398 pset_type (struct Lisp_Process *p, Lisp_Object val)
400 p->type = val;
402 static void
403 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
405 p->write_queue = val;
407 static void
408 pset_stderrproc (struct Lisp_Process *p, Lisp_Object val)
410 p->stderrproc = val;
414 static Lisp_Object
415 make_lisp_proc (struct Lisp_Process *p)
417 return make_lisp_ptr (p, Lisp_Vectorlike);
420 static struct fd_callback_data
422 fd_callback func;
423 void *data;
424 #define FOR_READ 1
425 #define FOR_WRITE 2
426 int condition; /* Mask of the defines above. */
427 } fd_callback_info[FD_SETSIZE];
430 /* Add a file descriptor FD to be monitored for when read is possible.
431 When read is possible, call FUNC with argument DATA. */
433 void
434 add_read_fd (int fd, fd_callback func, void *data)
436 add_keyboard_wait_descriptor (fd);
438 fd_callback_info[fd].func = func;
439 fd_callback_info[fd].data = data;
440 fd_callback_info[fd].condition |= FOR_READ;
443 /* Stop monitoring file descriptor FD for when read is possible. */
445 void
446 delete_read_fd (int fd)
448 delete_keyboard_wait_descriptor (fd);
450 fd_callback_info[fd].condition &= ~FOR_READ;
451 if (fd_callback_info[fd].condition == 0)
453 fd_callback_info[fd].func = 0;
454 fd_callback_info[fd].data = 0;
458 /* Add a file descriptor FD to be monitored for when write is possible.
459 When write is possible, call FUNC with argument DATA. */
461 void
462 add_write_fd (int fd, fd_callback func, void *data)
464 FD_SET (fd, &write_mask);
465 if (fd > max_input_desc)
466 max_input_desc = fd;
468 fd_callback_info[fd].func = func;
469 fd_callback_info[fd].data = data;
470 fd_callback_info[fd].condition |= FOR_WRITE;
473 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
475 static void
476 delete_input_desc (int fd)
478 if (fd == max_input_desc)
481 fd--;
482 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
483 || FD_ISSET (fd, &write_mask)));
485 max_input_desc = fd;
489 /* Stop monitoring file descriptor FD for when write is possible. */
491 void
492 delete_write_fd (int fd)
494 FD_CLR (fd, &write_mask);
495 fd_callback_info[fd].condition &= ~FOR_WRITE;
496 if (fd_callback_info[fd].condition == 0)
498 fd_callback_info[fd].func = 0;
499 fd_callback_info[fd].data = 0;
500 delete_input_desc (fd);
505 /* Compute the Lisp form of the process status, p->status, from
506 the numeric status that was returned by `wait'. */
508 static Lisp_Object status_convert (int);
510 static void
511 update_status (struct Lisp_Process *p)
513 eassert (p->raw_status_new);
514 pset_status (p, status_convert (p->raw_status));
515 p->raw_status_new = 0;
518 /* Convert a process status word in Unix format to
519 the list that we use internally. */
521 static Lisp_Object
522 status_convert (int w)
524 if (WIFSTOPPED (w))
525 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
526 else if (WIFEXITED (w))
527 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
528 WCOREDUMP (w) ? Qt : Qnil));
529 else if (WIFSIGNALED (w))
530 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
531 WCOREDUMP (w) ? Qt : Qnil));
532 else
533 return Qrun;
536 /* Given a status-list, extract the three pieces of information
537 and store them individually through the three pointers. */
539 static void
540 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
542 Lisp_Object tem;
544 if (SYMBOLP (l))
546 *symbol = l;
547 *code = 0;
548 *coredump = 0;
550 else
552 *symbol = XCAR (l);
553 tem = XCDR (l);
554 *code = XFASTINT (XCAR (tem));
555 tem = XCDR (tem);
556 *coredump = !NILP (tem);
560 /* Return a string describing a process status list. */
562 static Lisp_Object
563 status_message (struct Lisp_Process *p)
565 Lisp_Object status = p->status;
566 Lisp_Object symbol;
567 int code;
568 bool coredump;
569 Lisp_Object string;
571 decode_status (status, &symbol, &code, &coredump);
573 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
575 char const *signame;
576 synchronize_system_messages_locale ();
577 signame = strsignal (code);
578 if (signame == 0)
579 string = build_string ("unknown");
580 else
582 int c1, c2;
584 string = build_unibyte_string (signame);
585 if (! NILP (Vlocale_coding_system))
586 string = (code_convert_string_norecord
587 (string, Vlocale_coding_system, 0));
588 c1 = STRING_CHAR (SDATA (string));
589 c2 = downcase (c1);
590 if (c1 != c2)
591 Faset (string, make_number (0), make_number (c2));
593 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
594 return concat2 (string, suffix);
596 else if (EQ (symbol, Qexit))
598 if (NETCONN1_P (p))
599 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
600 if (code == 0)
601 return build_string ("finished\n");
602 AUTO_STRING (prefix, "exited abnormally with code ");
603 string = Fnumber_to_string (make_number (code));
604 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
605 return concat3 (prefix, string, suffix);
607 else if (EQ (symbol, Qfailed))
609 AUTO_STRING (prefix, "failed with code ");
610 string = Fnumber_to_string (make_number (code));
611 AUTO_STRING (suffix, "\n");
612 return concat3 (prefix, string, suffix);
614 else
615 return Fcopy_sequence (Fsymbol_name (symbol));
618 enum { PTY_NAME_SIZE = 24 };
620 /* Open an available pty, returning a file descriptor.
621 Store into PTY_NAME the file name of the terminal corresponding to the pty.
622 Return -1 on failure. */
624 static int
625 allocate_pty (char pty_name[PTY_NAME_SIZE])
627 #ifdef HAVE_PTYS
628 int fd;
630 #ifdef PTY_ITERATION
631 PTY_ITERATION
632 #else
633 register int c, i;
634 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
635 for (i = 0; i < 16; i++)
636 #endif
638 #ifdef PTY_NAME_SPRINTF
639 PTY_NAME_SPRINTF
640 #else
641 sprintf (pty_name, "/dev/pty%c%x", c, i);
642 #endif /* no PTY_NAME_SPRINTF */
644 #ifdef PTY_OPEN
645 PTY_OPEN;
646 #else /* no PTY_OPEN */
647 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
648 #endif /* no PTY_OPEN */
650 if (fd >= 0)
652 #ifdef PTY_TTY_NAME_SPRINTF
653 PTY_TTY_NAME_SPRINTF
654 #else
655 sprintf (pty_name, "/dev/tty%c%x", c, i);
656 #endif /* no PTY_TTY_NAME_SPRINTF */
658 /* Set FD's close-on-exec flag. This is needed even if
659 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
660 doesn't require support for that combination.
661 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
662 doesn't work if the close-on-exec flag is set (Bug#20555).
663 Multithreaded platforms where posix_openpt ignores
664 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
665 have a race condition between the PTY_OPEN and here. */
666 fcntl (fd, F_SETFD, FD_CLOEXEC);
668 /* Check to make certain that both sides are available.
669 This avoids a nasty yet stupid bug in rlogins. */
670 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
672 emacs_close (fd);
673 # ifndef __sgi
674 continue;
675 # else
676 return -1;
677 # endif /* __sgi */
679 setup_pty (fd);
680 return fd;
683 #endif /* HAVE_PTYS */
684 return -1;
687 /* Allocate basically initialized process. */
689 static struct Lisp_Process *
690 allocate_process (void)
692 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
695 static Lisp_Object
696 make_process (Lisp_Object name)
698 register Lisp_Object val, tem, name1;
699 register struct Lisp_Process *p;
700 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
701 printmax_t i;
703 p = allocate_process ();
704 /* Initialize Lisp data. Note that allocate_process initializes all
705 Lisp data to nil, so do it only for slots which should not be nil. */
706 pset_status (p, Qrun);
707 pset_mark (p, Fmake_marker ());
709 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
710 non-Lisp data, so do it only for slots which should not be zero. */
711 p->infd = -1;
712 p->outfd = -1;
713 for (i = 0; i < PROCESS_OPEN_FDS; i++)
714 p->open_fd[i] = -1;
716 #ifdef HAVE_GNUTLS
717 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
718 #endif
720 /* If name is already in use, modify it until it is unused. */
722 name1 = name;
723 for (i = 1; ; i++)
725 tem = Fget_process (name1);
726 if (NILP (tem)) break;
727 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
729 name = name1;
730 pset_name (p, name);
731 pset_sentinel (p, Qinternal_default_process_sentinel);
732 pset_filter (p, Qinternal_default_process_filter);
733 XSETPROCESS (val, p);
734 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
735 return val;
738 static void
739 remove_process (register Lisp_Object proc)
741 register Lisp_Object pair;
743 pair = Frassq (proc, Vprocess_alist);
744 Vprocess_alist = Fdelq (pair, Vprocess_alist);
746 deactivate_process (proc);
750 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
751 doc: /* Return t if OBJECT is a process. */)
752 (Lisp_Object object)
754 return PROCESSP (object) ? Qt : Qnil;
757 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
758 doc: /* Return the process named NAME, or nil if there is none. */)
759 (register Lisp_Object name)
761 if (PROCESSP (name))
762 return name;
763 CHECK_STRING (name);
764 return Fcdr (Fassoc (name, Vprocess_alist));
767 /* This is how commands for the user decode process arguments. It
768 accepts a process, a process name, a buffer, a buffer name, or nil.
769 Buffers denote the first process in the buffer, and nil denotes the
770 current buffer. */
772 static Lisp_Object
773 get_process (register Lisp_Object name)
775 register Lisp_Object proc, obj;
776 if (STRINGP (name))
778 obj = Fget_process (name);
779 if (NILP (obj))
780 obj = Fget_buffer (name);
781 if (NILP (obj))
782 error ("Process %s does not exist", SDATA (name));
784 else if (NILP (name))
785 obj = Fcurrent_buffer ();
786 else
787 obj = name;
789 /* Now obj should be either a buffer object or a process object. */
790 if (BUFFERP (obj))
792 if (NILP (BVAR (XBUFFER (obj), name)))
793 error ("Attempt to get process for a dead buffer");
794 proc = Fget_buffer_process (obj);
795 if (NILP (proc))
796 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
798 else
800 CHECK_PROCESS (obj);
801 proc = obj;
803 return proc;
807 /* Fdelete_process promises to immediately forget about the process, but in
808 reality, Emacs needs to remember those processes until they have been
809 treated by the SIGCHLD handler and waitpid has been invoked on them;
810 otherwise they might fill up the kernel's process table.
812 Some processes created by call-process are also put onto this list.
814 Members of this list are (process-ID . filename) pairs. The
815 process-ID is a number; the filename, if a string, is a file that
816 needs to be removed after the process exits. */
817 static Lisp_Object deleted_pid_list;
819 void
820 record_deleted_pid (pid_t pid, Lisp_Object filename)
822 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
823 /* GC treated elements set to nil. */
824 Fdelq (Qnil, deleted_pid_list));
828 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
829 doc: /* Delete PROCESS: kill it and forget about it immediately.
830 PROCESS may be a process, a buffer, the name of a process or buffer, or
831 nil, indicating the current buffer's process. */)
832 (register Lisp_Object process)
834 register struct Lisp_Process *p;
836 process = get_process (process);
837 p = XPROCESS (process);
839 p->raw_status_new = 0;
840 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
842 pset_status (p, list2 (Qexit, make_number (0)));
843 p->tick = ++process_tick;
844 status_notify (p, NULL);
845 redisplay_preserve_echo_area (13);
847 else
849 if (p->alive)
850 record_kill_process (p, Qnil);
852 if (p->infd >= 0)
854 /* Update P's status, since record_kill_process will make the
855 SIGCHLD handler update deleted_pid_list, not *P. */
856 Lisp_Object symbol;
857 if (p->raw_status_new)
858 update_status (p);
859 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
860 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
861 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
863 p->tick = ++process_tick;
864 status_notify (p, NULL);
865 redisplay_preserve_echo_area (13);
868 remove_process (process);
869 return Qnil;
872 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
873 doc: /* Return the status of PROCESS.
874 The returned value is one of the following symbols:
875 run -- for a process that is running.
876 stop -- for a process stopped but continuable.
877 exit -- for a process that has exited.
878 signal -- for a process that has got a fatal signal.
879 open -- for a network stream connection that is open.
880 listen -- for a network stream server that is listening.
881 closed -- for a network stream connection that is closed.
882 connect -- when waiting for a non-blocking connection to complete.
883 failed -- when a non-blocking connection has failed.
884 nil -- if arg is a process name and no such process exists.
885 PROCESS may be a process, a buffer, the name of a process, or
886 nil, indicating the current buffer's process. */)
887 (register Lisp_Object process)
889 register struct Lisp_Process *p;
890 register Lisp_Object status;
892 if (STRINGP (process))
893 process = Fget_process (process);
894 else
895 process = get_process (process);
897 if (NILP (process))
898 return process;
900 p = XPROCESS (process);
901 if (p->raw_status_new)
902 update_status (p);
903 status = p->status;
904 if (CONSP (status))
905 status = XCAR (status);
906 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
908 if (EQ (status, Qexit))
909 status = Qclosed;
910 else if (EQ (p->command, Qt))
911 status = Qstop;
912 else if (EQ (status, Qrun))
913 status = Qopen;
915 return status;
918 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
919 1, 1, 0,
920 doc: /* Return the exit status of PROCESS or the signal number that killed it.
921 If PROCESS has not yet exited or died, return 0. */)
922 (register Lisp_Object process)
924 CHECK_PROCESS (process);
925 if (XPROCESS (process)->raw_status_new)
926 update_status (XPROCESS (process));
927 if (CONSP (XPROCESS (process)->status))
928 return XCAR (XCDR (XPROCESS (process)->status));
929 return make_number (0);
932 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
933 doc: /* Return the process id of PROCESS.
934 This is the pid of the external process which PROCESS uses or talks to.
935 For a network connection, this value is nil. */)
936 (register Lisp_Object process)
938 pid_t pid;
940 CHECK_PROCESS (process);
941 pid = XPROCESS (process)->pid;
942 return (pid ? make_fixnum_or_float (pid) : Qnil);
945 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
946 doc: /* Return the name of PROCESS, as a string.
947 This is the name of the program invoked in PROCESS,
948 possibly modified to make it unique among process names. */)
949 (register Lisp_Object process)
951 CHECK_PROCESS (process);
952 return XPROCESS (process)->name;
955 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
956 doc: /* Return the command that was executed to start PROCESS.
957 This is a list of strings, the first string being the program executed
958 and the rest of the strings being the arguments given to it.
959 For a network or serial process, this is nil (process is running) or t
960 \(process is stopped). */)
961 (register Lisp_Object process)
963 CHECK_PROCESS (process);
964 return XPROCESS (process)->command;
967 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
968 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
969 This is the terminal that the process itself reads and writes on,
970 not the name of the pty that Emacs uses to talk with that terminal. */)
971 (register Lisp_Object process)
973 CHECK_PROCESS (process);
974 return XPROCESS (process)->tty_name;
977 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
978 2, 2, 0,
979 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
980 Return BUFFER. */)
981 (register Lisp_Object process, Lisp_Object buffer)
983 struct Lisp_Process *p;
985 CHECK_PROCESS (process);
986 if (!NILP (buffer))
987 CHECK_BUFFER (buffer);
988 p = XPROCESS (process);
989 pset_buffer (p, buffer);
990 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
991 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
992 setup_process_coding_systems (process);
993 return buffer;
996 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
997 1, 1, 0,
998 doc: /* Return the buffer PROCESS is associated with.
999 The default process filter inserts output from PROCESS into this buffer. */)
1000 (register Lisp_Object process)
1002 CHECK_PROCESS (process);
1003 return XPROCESS (process)->buffer;
1006 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1007 1, 1, 0,
1008 doc: /* Return the marker for the end of the last output from PROCESS. */)
1009 (register Lisp_Object process)
1011 CHECK_PROCESS (process);
1012 return XPROCESS (process)->mark;
1015 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1016 2, 2, 0,
1017 doc: /* Give PROCESS the filter function FILTER; nil means default.
1018 A value of t means stop accepting output from the process.
1020 When a process has a non-default filter, its buffer is not used for output.
1021 Instead, each time it does output, the entire string of output is
1022 passed to the filter.
1024 The filter gets two arguments: the process and the string of output.
1025 The string argument is normally a multibyte string, except:
1026 - if the process's input coding system is no-conversion or raw-text,
1027 it is a unibyte string (the non-converted input), or else
1028 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1029 string (the result of converting the decoded input multibyte
1030 string to unibyte with `string-make-unibyte'). */)
1031 (register Lisp_Object process, Lisp_Object filter)
1033 struct Lisp_Process *p;
1035 CHECK_PROCESS (process);
1036 p = XPROCESS (process);
1038 /* Don't signal an error if the process's input file descriptor
1039 is closed. This could make debugging Lisp more difficult,
1040 for example when doing something like
1042 (setq process (start-process ...))
1043 (debug)
1044 (set-process-filter process ...) */
1046 if (NILP (filter))
1047 filter = Qinternal_default_process_filter;
1049 if (p->infd >= 0)
1051 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1053 FD_CLR (p->infd, &input_wait_mask);
1054 FD_CLR (p->infd, &non_keyboard_wait_mask);
1056 else if (EQ (p->filter, Qt)
1057 /* Network or serial process not stopped: */
1058 && !EQ (p->command, Qt))
1060 FD_SET (p->infd, &input_wait_mask);
1061 FD_SET (p->infd, &non_keyboard_wait_mask);
1065 pset_filter (p, filter);
1066 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1067 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1068 setup_process_coding_systems (process);
1069 return filter;
1072 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1073 1, 1, 0,
1074 doc: /* Return the filter function of PROCESS.
1075 See `set-process-filter' for more info on filter functions. */)
1076 (register Lisp_Object process)
1078 CHECK_PROCESS (process);
1079 return XPROCESS (process)->filter;
1082 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1083 2, 2, 0,
1084 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1085 The sentinel is called as a function when the process changes state.
1086 It gets two arguments: the process, and a string describing the change. */)
1087 (register Lisp_Object process, Lisp_Object sentinel)
1089 struct Lisp_Process *p;
1091 CHECK_PROCESS (process);
1092 p = XPROCESS (process);
1094 if (NILP (sentinel))
1095 sentinel = Qinternal_default_process_sentinel;
1097 pset_sentinel (p, sentinel);
1098 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1099 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1100 return sentinel;
1103 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1104 1, 1, 0,
1105 doc: /* Return the sentinel of PROCESS.
1106 See `set-process-sentinel' for more info on sentinels. */)
1107 (register Lisp_Object process)
1109 CHECK_PROCESS (process);
1110 return XPROCESS (process)->sentinel;
1113 DEFUN ("set-process-window-size", Fset_process_window_size,
1114 Sset_process_window_size, 3, 3, 0,
1115 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1116 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1118 CHECK_PROCESS (process);
1120 /* All known platforms store window sizes as 'unsigned short'. */
1121 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1122 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1124 if (XPROCESS (process)->infd < 0
1125 || (set_window_size (XPROCESS (process)->infd,
1126 XINT (height), XINT (width))
1127 < 0))
1128 return Qnil;
1129 else
1130 return Qt;
1133 DEFUN ("set-process-inherit-coding-system-flag",
1134 Fset_process_inherit_coding_system_flag,
1135 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1136 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1137 If the second argument FLAG is non-nil, then the variable
1138 `buffer-file-coding-system' of the buffer associated with PROCESS
1139 will be bound to the value of the coding system used to decode
1140 the process output.
1142 This is useful when the coding system specified for the process buffer
1143 leaves either the character code conversion or the end-of-line conversion
1144 unspecified, or if the coding system used to decode the process output
1145 is more appropriate for saving the process buffer.
1147 Binding the variable `inherit-process-coding-system' to non-nil before
1148 starting the process is an alternative way of setting the inherit flag
1149 for the process which will run.
1151 This function returns FLAG. */)
1152 (register Lisp_Object process, Lisp_Object flag)
1154 CHECK_PROCESS (process);
1155 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1156 return flag;
1159 DEFUN ("set-process-query-on-exit-flag",
1160 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1161 2, 2, 0,
1162 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1163 If the second argument FLAG is non-nil, Emacs will query the user before
1164 exiting or killing a buffer if PROCESS is running. This function
1165 returns FLAG. */)
1166 (register Lisp_Object process, Lisp_Object flag)
1168 CHECK_PROCESS (process);
1169 XPROCESS (process)->kill_without_query = NILP (flag);
1170 return flag;
1173 DEFUN ("process-query-on-exit-flag",
1174 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1175 1, 1, 0,
1176 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1177 (register Lisp_Object process)
1179 CHECK_PROCESS (process);
1180 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1183 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1184 1, 2, 0,
1185 doc: /* Return the contact info of PROCESS; t for a real child.
1186 For a network or serial connection, the value depends on the optional
1187 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1188 SERVICE) for a network connection or (PORT SPEED) for a serial
1189 connection. If KEY is t, the complete contact information for the
1190 connection is returned, else the specific value for the keyword KEY is
1191 returned. See `make-network-process' or `make-serial-process' for a
1192 list of keywords. */)
1193 (register Lisp_Object process, Lisp_Object key)
1195 Lisp_Object contact;
1197 CHECK_PROCESS (process);
1198 contact = XPROCESS (process)->childp;
1200 #ifdef DATAGRAM_SOCKETS
1201 if (DATAGRAM_CONN_P (process)
1202 && (EQ (key, Qt) || EQ (key, QCremote)))
1203 contact = Fplist_put (contact, QCremote,
1204 Fprocess_datagram_address (process));
1205 #endif
1207 if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1208 || EQ (key, Qt))
1209 return contact;
1210 if (NILP (key) && NETCONN_P (process))
1211 return list2 (Fplist_get (contact, QChost),
1212 Fplist_get (contact, QCservice));
1213 if (NILP (key) && SERIALCONN_P (process))
1214 return list2 (Fplist_get (contact, QCport),
1215 Fplist_get (contact, QCspeed));
1216 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1217 if the pipe process is useful for purposes other than receiving
1218 stderr. */
1219 if (NILP (key) && PIPECONN_P (process))
1220 return Qt;
1221 return Fplist_get (contact, key);
1224 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1225 1, 1, 0,
1226 doc: /* Return the plist of PROCESS. */)
1227 (register Lisp_Object process)
1229 CHECK_PROCESS (process);
1230 return XPROCESS (process)->plist;
1233 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1234 2, 2, 0,
1235 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1236 (register Lisp_Object process, Lisp_Object plist)
1238 CHECK_PROCESS (process);
1239 CHECK_LIST (plist);
1241 pset_plist (XPROCESS (process), plist);
1242 return plist;
1245 #if 0 /* Turned off because we don't currently record this info
1246 in the process. Perhaps add it. */
1247 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1248 doc: /* Return the connection type of PROCESS.
1249 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1250 a socket connection. */)
1251 (Lisp_Object process)
1253 return XPROCESS (process)->type;
1255 #endif
1257 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1258 doc: /* Return the connection type of PROCESS.
1259 The value is either the symbol `real', `network', or `serial'.
1260 PROCESS may be a process, a buffer, the name of a process or buffer, or
1261 nil, indicating the current buffer's process. */)
1262 (Lisp_Object process)
1264 Lisp_Object proc;
1265 proc = get_process (process);
1266 return XPROCESS (proc)->type;
1269 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1270 1, 2, 0,
1271 doc: /* Convert network ADDRESS from internal format to a string.
1272 A 4 or 5 element vector represents an IPv4 address (with port number).
1273 An 8 or 9 element vector represents an IPv6 address (with port number).
1274 If optional second argument OMIT-PORT is non-nil, don't include a port
1275 number in the string, even when present in ADDRESS.
1276 Returns nil if format of ADDRESS is invalid. */)
1277 (Lisp_Object address, Lisp_Object omit_port)
1279 if (NILP (address))
1280 return Qnil;
1282 if (STRINGP (address)) /* AF_LOCAL */
1283 return address;
1285 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1287 register struct Lisp_Vector *p = XVECTOR (address);
1288 ptrdiff_t size = p->header.size;
1289 Lisp_Object args[10];
1290 int nargs, i;
1291 char const *format;
1293 if (size == 4 || (size == 5 && !NILP (omit_port)))
1295 format = "%d.%d.%d.%d";
1296 nargs = 4;
1298 else if (size == 5)
1300 format = "%d.%d.%d.%d:%d";
1301 nargs = 5;
1303 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1305 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1306 nargs = 8;
1308 else if (size == 9)
1310 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1311 nargs = 9;
1313 else
1314 return Qnil;
1316 AUTO_STRING (format_obj, format);
1317 args[0] = format_obj;
1319 for (i = 0; i < nargs; i++)
1321 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1322 return Qnil;
1324 if (nargs <= 5 /* IPv4 */
1325 && i < 4 /* host, not port */
1326 && XINT (p->contents[i]) > 255)
1327 return Qnil;
1329 args[i + 1] = p->contents[i];
1332 return Fformat (nargs + 1, args);
1335 if (CONSP (address))
1337 AUTO_STRING (format, "<Family %d>");
1338 return CALLN (Fformat, format, Fcar (address));
1341 return Qnil;
1344 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1345 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1346 (void)
1348 return Fmapcar (Qcdr, Vprocess_alist);
1351 /* Starting asynchronous inferior processes. */
1353 static void start_process_unwind (Lisp_Object proc);
1355 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1356 doc: /* Start a program in a subprocess. Return the process object for it.
1358 This is similar to `start-process', but arguments are specified as
1359 keyword/argument pairs. The following arguments are defined:
1361 :name NAME -- NAME is name for process. It is modified if necessary
1362 to make it unique.
1364 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1365 with the process. Process output goes at end of that buffer, unless
1366 you specify an output stream or filter function to handle the output.
1367 BUFFER may be also nil, meaning that this process is not associated
1368 with any buffer.
1370 :command COMMAND -- COMMAND is a list starting with the program file
1371 name, followed by strings to give to the program as arguments.
1373 :coding CODING -- If CODING is a symbol, it specifies the coding
1374 system used for both reading and writing for this process. If CODING
1375 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1376 ENCODING is used for writing.
1378 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1379 the process is running. If BOOL is not given, query before exiting.
1381 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1382 In the stopped state, a process does not accept incoming data, but you
1383 can send outgoing data. The stopped state is cleared by
1384 `continue-process' and set by `stop-process'.
1386 :connection-type TYPE -- TYPE is control type of device used to
1387 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1388 to use a pty, or nil to use the default specified through
1389 `process-connection-type'.
1391 :filter FILTER -- Install FILTER as the process filter.
1393 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1395 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1396 to the standard error of subprocess. Specifying this implies
1397 `:connection-type' is set to `pipe'.
1399 usage: (make-process &rest ARGS) */)
1400 (ptrdiff_t nargs, Lisp_Object *args)
1402 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1403 Lisp_Object xstderr, stderrproc;
1404 ptrdiff_t count = SPECPDL_INDEX ();
1405 struct gcpro gcpro1;
1406 USE_SAFE_ALLOCA;
1408 if (nargs == 0)
1409 return Qnil;
1411 /* Save arguments for process-contact and clone-process. */
1412 contact = Flist (nargs, args);
1413 GCPRO1 (contact);
1415 buffer = Fplist_get (contact, QCbuffer);
1416 if (!NILP (buffer))
1417 buffer = Fget_buffer_create (buffer);
1419 /* Make sure that the child will be able to chdir to the current
1420 buffer's current directory, or its unhandled equivalent. We
1421 can't just have the child check for an error when it does the
1422 chdir, since it's in a vfork.
1424 We have to GCPRO around this because Fexpand_file_name and
1425 Funhandled_file_name_directory might call a file name handling
1426 function. The argument list is protected by the caller, so all
1427 we really have to worry about is buffer. */
1429 struct gcpro gcpro1;
1430 GCPRO1 (buffer);
1431 current_dir = encode_current_directory ();
1432 UNGCPRO;
1435 name = Fplist_get (contact, QCname);
1436 CHECK_STRING (name);
1438 command = Fplist_get (contact, QCcommand);
1439 if (CONSP (command))
1440 program = XCAR (command);
1441 else
1442 program = Qnil;
1444 if (!NILP (program))
1445 CHECK_STRING (program);
1447 stderrproc = Qnil;
1448 xstderr = Fplist_get (contact, QCstderr);
1449 if (PROCESSP (xstderr))
1451 if (!PIPECONN_P (xstderr))
1452 error ("Process is not a pipe process");
1453 stderrproc = xstderr;
1455 else if (!NILP (xstderr))
1457 struct gcpro gcpro1, gcpro2;
1458 CHECK_STRING (program);
1459 GCPRO2 (buffer, current_dir);
1460 stderrproc = CALLN (Fmake_pipe_process,
1461 QCname,
1462 concat2 (name, build_string (" stderr")),
1463 QCbuffer,
1464 Fget_buffer_create (xstderr));
1465 UNGCPRO;
1468 proc = make_process (name);
1469 /* If an error occurs and we can't start the process, we want to
1470 remove it from the process list. This means that each error
1471 check in create_process doesn't need to call remove_process
1472 itself; it's all taken care of here. */
1473 record_unwind_protect (start_process_unwind, proc);
1475 pset_childp (XPROCESS (proc), Qt);
1476 pset_plist (XPROCESS (proc), Qnil);
1477 pset_type (XPROCESS (proc), Qreal);
1478 pset_buffer (XPROCESS (proc), buffer);
1479 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1480 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1481 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1483 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
1484 XPROCESS (proc)->kill_without_query = 1;
1485 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1486 pset_command (XPROCESS (proc), Qt);
1488 tem = Fplist_get (contact, QCconnection_type);
1489 if (EQ (tem, Qpty))
1490 XPROCESS (proc)->pty_flag = true;
1491 else if (EQ (tem, Qpipe))
1492 XPROCESS (proc)->pty_flag = false;
1493 else if (NILP (tem))
1494 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1495 else
1496 report_file_error ("Unknown connection type", tem);
1498 if (!NILP (stderrproc))
1500 pset_stderrproc (XPROCESS (proc), stderrproc);
1502 XPROCESS (proc)->pty_flag = false;
1505 #ifdef HAVE_GNUTLS
1506 /* AKA GNUTLS_INITSTAGE(proc). */
1507 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1508 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1509 #endif
1511 XPROCESS (proc)->adaptive_read_buffering
1512 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1513 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1515 /* Make the process marker point into the process buffer (if any). */
1516 if (BUFFERP (buffer))
1517 set_marker_both (XPROCESS (proc)->mark, buffer,
1518 BUF_ZV (XBUFFER (buffer)),
1519 BUF_ZV_BYTE (XBUFFER (buffer)));
1522 /* Decide coding systems for communicating with the process. Here
1523 we don't setup the structure coding_system nor pay attention to
1524 unibyte mode. They are done in create_process. */
1526 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1527 Lisp_Object coding_systems = Qt;
1528 Lisp_Object val, *args2;
1529 struct gcpro gcpro1, gcpro2;
1531 tem = Fplist_get (contact, QCcoding);
1532 if (!NILP (tem))
1534 val = tem;
1535 if (CONSP (val))
1536 val = XCAR (val);
1538 else
1539 val = Vcoding_system_for_read;
1540 if (NILP (val))
1542 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1543 Lisp_Object tem2;
1544 SAFE_ALLOCA_LISP (args2, nargs2);
1545 ptrdiff_t i = 0;
1546 args2[i++] = Qstart_process;
1547 args2[i++] = name;
1548 args2[i++] = buffer;
1549 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1550 args2[i++] = XCAR (tem2);
1551 GCPRO2 (proc, current_dir);
1552 if (!NILP (program))
1553 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1554 UNGCPRO;
1555 if (CONSP (coding_systems))
1556 val = XCAR (coding_systems);
1557 else if (CONSP (Vdefault_process_coding_system))
1558 val = XCAR (Vdefault_process_coding_system);
1560 pset_decode_coding_system (XPROCESS (proc), val);
1562 if (!NILP (tem))
1564 val = tem;
1565 if (CONSP (val))
1566 val = XCDR (val);
1568 else
1569 val = Vcoding_system_for_write;
1570 if (NILP (val))
1572 if (EQ (coding_systems, Qt))
1574 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1575 Lisp_Object tem2;
1576 SAFE_ALLOCA_LISP (args2, nargs2);
1577 ptrdiff_t i = 0;
1578 args2[i++] = Qstart_process;
1579 args2[i++] = name;
1580 args2[i++] = buffer;
1581 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1582 args2[i++] = XCAR (tem2);
1583 GCPRO2 (proc, current_dir);
1584 if (!NILP (program))
1585 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1586 UNGCPRO;
1588 if (CONSP (coding_systems))
1589 val = XCDR (coding_systems);
1590 else if (CONSP (Vdefault_process_coding_system))
1591 val = XCDR (Vdefault_process_coding_system);
1593 pset_encode_coding_system (XPROCESS (proc), val);
1594 /* Note: At this moment, the above coding system may leave
1595 text-conversion or eol-conversion unspecified. They will be
1596 decided after we read output from the process and decode it by
1597 some coding system, or just before we actually send a text to
1598 the process. */
1602 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1603 XPROCESS (proc)->decoding_carryover = 0;
1604 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1606 XPROCESS (proc)->inherit_coding_system_flag
1607 = !(NILP (buffer) || !inherit_process_coding_system);
1609 if (!NILP (program))
1611 Lisp_Object program_args = XCDR (command);
1613 /* If program file name is not absolute, search our path for it.
1614 Put the name we will really use in TEM. */
1615 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1616 && !(SCHARS (program) > 1
1617 && IS_DEVICE_SEP (SREF (program, 1))))
1619 struct gcpro gcpro1, gcpro2;
1621 tem = Qnil;
1622 GCPRO2 (buffer, current_dir);
1623 openp (Vexec_path, program, Vexec_suffixes, &tem,
1624 make_number (X_OK), false);
1625 UNGCPRO;
1626 if (NILP (tem))
1627 report_file_error ("Searching for program", program);
1628 tem = Fexpand_file_name (tem, Qnil);
1630 else
1632 if (!NILP (Ffile_directory_p (program)))
1633 error ("Specified program for new process is a directory");
1634 tem = program;
1637 /* Remove "/:" from TEM. */
1638 tem = remove_slash_colon (tem);
1640 Lisp_Object arg_encoding = Qnil;
1641 struct gcpro gcpro1;
1642 GCPRO1 (tem);
1644 /* Encode the file name and put it in NEW_ARGV.
1645 That's where the child will use it to execute the program. */
1646 tem = list1 (ENCODE_FILE (tem));
1647 ptrdiff_t new_argc = 1;
1649 /* Here we encode arguments by the coding system used for sending
1650 data to the process. We don't support using different coding
1651 systems for encoding arguments and for encoding data sent to the
1652 process. */
1654 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1656 Lisp_Object arg = XCAR (tem2);
1657 CHECK_STRING (arg);
1658 if (STRING_MULTIBYTE (arg))
1660 if (NILP (arg_encoding))
1661 arg_encoding = (complement_process_encoding_system
1662 (XPROCESS (proc)->encode_coding_system));
1663 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1665 tem = Fcons (arg, tem);
1666 new_argc++;
1669 UNGCPRO;
1671 /* Now that everything is encoded we can collect the strings into
1672 NEW_ARGV. */
1673 char **new_argv;
1674 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1675 new_argv[new_argc] = 0;
1677 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1679 new_argv[i] = SSDATA (XCAR (tem));
1680 tem = XCDR (tem);
1683 create_process (proc, new_argv, current_dir);
1685 else
1686 create_pty (proc);
1688 UNGCPRO;
1689 SAFE_FREE ();
1690 return unbind_to (count, proc);
1693 /* This function is the unwind_protect form for Fstart_process. If
1694 PROC doesn't have its pid set, then we know someone has signaled
1695 an error and the process wasn't started successfully, so we should
1696 remove it from the process list. */
1697 static void
1698 start_process_unwind (Lisp_Object proc)
1700 if (!PROCESSP (proc))
1701 emacs_abort ();
1703 /* Was PROC started successfully?
1704 -2 is used for a pty with no process, eg for gdb. */
1705 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1706 remove_process (proc);
1709 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1711 static void
1712 close_process_fd (int *fd_addr)
1714 int fd = *fd_addr;
1715 if (0 <= fd)
1717 *fd_addr = -1;
1718 emacs_close (fd);
1722 /* Indexes of file descriptors in open_fds. */
1723 enum
1725 /* The pipe from Emacs to its subprocess. */
1726 SUBPROCESS_STDIN,
1727 WRITE_TO_SUBPROCESS,
1729 /* The main pipe from the subprocess to Emacs. */
1730 READ_FROM_SUBPROCESS,
1731 SUBPROCESS_STDOUT,
1733 /* The pipe from the subprocess to Emacs that is closed when the
1734 subprocess execs. */
1735 READ_FROM_EXEC_MONITOR,
1736 EXEC_MONITOR_OUTPUT
1739 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1741 static void
1742 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1744 struct Lisp_Process *p = XPROCESS (process);
1745 int inchannel, outchannel;
1746 pid_t pid;
1747 int vfork_errno;
1748 int forkin, forkout, forkerr = -1;
1749 bool pty_flag = 0;
1750 char pty_name[PTY_NAME_SIZE];
1751 Lisp_Object lisp_pty_name = Qnil;
1752 sigset_t oldset;
1754 inchannel = outchannel = -1;
1756 if (p->pty_flag)
1757 outchannel = inchannel = allocate_pty (pty_name);
1759 if (inchannel >= 0)
1761 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1762 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1763 /* On most USG systems it does not work to open the pty's tty here,
1764 then close it and reopen it in the child. */
1765 /* Don't let this terminal become our controlling terminal
1766 (in case we don't have one). */
1767 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1768 if (forkin < 0)
1769 report_file_error ("Opening pty", Qnil);
1770 p->open_fd[SUBPROCESS_STDIN] = forkin;
1771 #else
1772 forkin = forkout = -1;
1773 #endif /* not USG, or USG_SUBTTY_WORKS */
1774 pty_flag = 1;
1775 lisp_pty_name = build_string (pty_name);
1777 else
1779 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1780 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1781 report_file_error ("Creating pipe", Qnil);
1782 forkin = p->open_fd[SUBPROCESS_STDIN];
1783 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1784 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1785 forkout = p->open_fd[SUBPROCESS_STDOUT];
1787 if (!NILP (p->stderrproc))
1789 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
1791 forkerr = pp->open_fd[SUBPROCESS_STDOUT];
1793 /* Close unnecessary file descriptors. */
1794 close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
1795 close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
1799 #ifndef WINDOWSNT
1800 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1801 report_file_error ("Creating pipe", Qnil);
1802 #endif
1804 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1805 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1807 /* Record this as an active process, with its channels. */
1808 chan_process[inchannel] = process;
1809 p->infd = inchannel;
1810 p->outfd = outchannel;
1812 /* Previously we recorded the tty descriptor used in the subprocess.
1813 It was only used for getting the foreground tty process, so now
1814 we just reopen the device (see emacs_get_tty_pgrp) as this is
1815 more portable (see USG_SUBTTY_WORKS above). */
1817 p->pty_flag = pty_flag;
1818 pset_status (p, Qrun);
1820 if (!EQ (p->command, Qt))
1822 FD_SET (inchannel, &input_wait_mask);
1823 FD_SET (inchannel, &non_keyboard_wait_mask);
1826 if (inchannel > max_process_desc)
1827 max_process_desc = inchannel;
1829 /* This may signal an error. */
1830 setup_process_coding_systems (process);
1832 block_input ();
1833 block_child_signal (&oldset);
1835 #ifndef WINDOWSNT
1836 /* vfork, and prevent local vars from being clobbered by the vfork. */
1837 Lisp_Object volatile current_dir_volatile = current_dir;
1838 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1839 char **volatile new_argv_volatile = new_argv;
1840 int volatile forkin_volatile = forkin;
1841 int volatile forkout_volatile = forkout;
1842 int volatile forkerr_volatile = forkerr;
1843 struct Lisp_Process *p_volatile = p;
1845 pid = vfork ();
1847 current_dir = current_dir_volatile;
1848 lisp_pty_name = lisp_pty_name_volatile;
1849 new_argv = new_argv_volatile;
1850 forkin = forkin_volatile;
1851 forkout = forkout_volatile;
1852 forkerr = forkerr_volatile;
1853 p = p_volatile;
1855 pty_flag = p->pty_flag;
1857 if (pid == 0)
1858 #endif /* not WINDOWSNT */
1860 /* Make the pty be the controlling terminal of the process. */
1861 #ifdef HAVE_PTYS
1862 /* First, disconnect its current controlling terminal. */
1863 /* We tried doing setsid only if pty_flag, but it caused
1864 process_set_signal to fail on SGI when using a pipe. */
1865 setsid ();
1866 /* Make the pty's terminal the controlling terminal. */
1867 if (pty_flag && forkin >= 0)
1869 #ifdef TIOCSCTTY
1870 /* We ignore the return value
1871 because faith@cs.unc.edu says that is necessary on Linux. */
1872 ioctl (forkin, TIOCSCTTY, 0);
1873 #endif
1875 #if defined (LDISC1)
1876 if (pty_flag && forkin >= 0)
1878 struct termios t;
1879 tcgetattr (forkin, &t);
1880 t.c_lflag = LDISC1;
1881 if (tcsetattr (forkin, TCSANOW, &t) < 0)
1882 emacs_perror ("create_process/tcsetattr LDISC1");
1884 #else
1885 #if defined (NTTYDISC) && defined (TIOCSETD)
1886 if (pty_flag && forkin >= 0)
1888 /* Use new line discipline. */
1889 int ldisc = NTTYDISC;
1890 ioctl (forkin, TIOCSETD, &ldisc);
1892 #endif
1893 #endif
1894 #ifdef TIOCNOTTY
1895 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1896 can do TIOCSPGRP only to the process's controlling tty. */
1897 if (pty_flag)
1899 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1900 I can't test it since I don't have 4.3. */
1901 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1902 if (j >= 0)
1904 ioctl (j, TIOCNOTTY, 0);
1905 emacs_close (j);
1908 #endif /* TIOCNOTTY */
1910 #if !defined (DONT_REOPEN_PTY)
1911 /*** There is a suggestion that this ought to be a
1912 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1913 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1914 that system does seem to need this code, even though
1915 both TIOCSCTTY is defined. */
1916 /* Now close the pty (if we had it open) and reopen it.
1917 This makes the pty the controlling terminal of the subprocess. */
1918 if (pty_flag)
1921 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1922 would work? */
1923 if (forkin >= 0)
1924 emacs_close (forkin);
1925 forkout = forkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1927 if (forkin < 0)
1929 emacs_perror (SSDATA (lisp_pty_name));
1930 _exit (EXIT_CANCELED);
1934 #endif /* not DONT_REOPEN_PTY */
1936 #ifdef SETUP_SLAVE_PTY
1937 if (pty_flag)
1939 SETUP_SLAVE_PTY;
1941 #endif /* SETUP_SLAVE_PTY */
1942 #endif /* HAVE_PTYS */
1944 signal (SIGINT, SIG_DFL);
1945 signal (SIGQUIT, SIG_DFL);
1946 #ifdef SIGPROF
1947 signal (SIGPROF, SIG_DFL);
1948 #endif
1950 /* Emacs ignores SIGPIPE, but the child should not. */
1951 signal (SIGPIPE, SIG_DFL);
1953 /* Stop blocking SIGCHLD in the child. */
1954 unblock_child_signal (&oldset);
1956 if (pty_flag)
1957 child_setup_tty (forkout);
1959 if (forkerr < 0)
1960 forkerr = forkout;
1961 #ifdef WINDOWSNT
1962 pid = child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1963 #else /* not WINDOWSNT */
1964 child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1965 #endif /* not WINDOWSNT */
1968 /* Back in the parent process. */
1970 vfork_errno = errno;
1971 p->pid = pid;
1972 if (pid >= 0)
1973 p->alive = 1;
1975 /* Stop blocking in the parent. */
1976 unblock_child_signal (&oldset);
1977 unblock_input ();
1979 if (pid < 0)
1980 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1981 else
1983 /* vfork succeeded. */
1985 /* Close the pipe ends that the child uses, or the child's pty. */
1986 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
1987 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
1989 #ifdef WINDOWSNT
1990 register_child (pid, inchannel);
1991 #endif /* WINDOWSNT */
1993 pset_tty_name (p, lisp_pty_name);
1995 #ifndef WINDOWSNT
1996 /* Wait for child_setup to complete in case that vfork is
1997 actually defined as fork. The descriptor
1998 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1999 of a pipe is closed at the child side either by close-on-exec
2000 on successful execve or the _exit call in child_setup. */
2002 char dummy;
2004 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
2005 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
2006 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
2008 #endif
2009 if (!NILP (p->stderrproc))
2011 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2012 close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
2017 static void
2018 create_pty (Lisp_Object process)
2020 struct Lisp_Process *p = XPROCESS (process);
2021 char pty_name[PTY_NAME_SIZE];
2022 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
2024 if (pty_fd >= 0)
2026 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
2027 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2028 /* On most USG systems it does not work to open the pty's tty here,
2029 then close it and reopen it in the child. */
2030 /* Don't let this terminal become our controlling terminal
2031 (in case we don't have one). */
2032 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2033 if (forkout < 0)
2034 report_file_error ("Opening pty", Qnil);
2035 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2036 #if defined (DONT_REOPEN_PTY)
2037 /* In the case that vfork is defined as fork, the parent process
2038 (Emacs) may send some data before the child process completes
2039 tty options setup. So we setup tty before forking. */
2040 child_setup_tty (forkout);
2041 #endif /* DONT_REOPEN_PTY */
2042 #endif /* not USG, or USG_SUBTTY_WORKS */
2044 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2046 /* Record this as an active process, with its channels.
2047 As a result, child_setup will close Emacs's side of the pipes. */
2048 chan_process[pty_fd] = process;
2049 p->infd = pty_fd;
2050 p->outfd = pty_fd;
2052 /* Previously we recorded the tty descriptor used in the subprocess.
2053 It was only used for getting the foreground tty process, so now
2054 we just reopen the device (see emacs_get_tty_pgrp) as this is
2055 more portable (see USG_SUBTTY_WORKS above). */
2057 p->pty_flag = 1;
2058 pset_status (p, Qrun);
2059 setup_process_coding_systems (process);
2061 FD_SET (pty_fd, &input_wait_mask);
2062 FD_SET (pty_fd, &non_keyboard_wait_mask);
2063 if (pty_fd > max_process_desc)
2064 max_process_desc = pty_fd;
2066 pset_tty_name (p, build_string (pty_name));
2069 p->pid = -2;
2072 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2073 0, MANY, 0,
2074 doc: /* Create and return a bidirectional pipe process.
2076 In Emacs, pipes are represented by process objects, so input and
2077 output work as for subprocesses, and `delete-process' closes a pipe.
2078 However, a pipe process has no process id, it cannot be signaled,
2079 and the status codes are different from normal processes.
2081 Arguments are specified as keyword/argument pairs. The following
2082 arguments are defined:
2084 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2086 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2087 with the process. Process output goes at the end of that buffer,
2088 unless you specify an output stream or filter function to handle the
2089 output. If BUFFER is not given, the value of NAME is used.
2091 :coding CODING -- If CODING is a symbol, it specifies the coding
2092 system used for both reading and writing for this process. If CODING
2093 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2094 ENCODING is used for writing.
2096 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2097 the process is running. If BOOL is not given, query before exiting.
2099 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2100 In the stopped state, a pipe process does not accept incoming data,
2101 but you can send outgoing data. The stopped state is cleared by
2102 `continue-process' and set by `stop-process'.
2104 :filter FILTER -- Install FILTER as the process filter.
2106 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2108 usage: (make-pipe-process &rest ARGS) */)
2109 (ptrdiff_t nargs, Lisp_Object *args)
2111 Lisp_Object proc, contact;
2112 struct Lisp_Process *p;
2113 struct gcpro gcpro1;
2114 Lisp_Object name, buffer;
2115 Lisp_Object tem;
2116 ptrdiff_t specpdl_count;
2117 int inchannel, outchannel;
2119 if (nargs == 0)
2120 return Qnil;
2122 contact = Flist (nargs, args);
2123 GCPRO1 (contact);
2125 name = Fplist_get (contact, QCname);
2126 CHECK_STRING (name);
2127 proc = make_process (name);
2128 specpdl_count = SPECPDL_INDEX ();
2129 record_unwind_protect (remove_process, proc);
2130 p = XPROCESS (proc);
2132 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2133 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2134 report_file_error ("Creating pipe", Qnil);
2135 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2136 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2138 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2139 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2141 #ifdef WINDOWSNT
2142 register_aux_fd (inchannel);
2143 #endif
2145 /* Record this as an active process, with its channels. */
2146 chan_process[inchannel] = proc;
2147 p->infd = inchannel;
2148 p->outfd = outchannel;
2150 if (inchannel > max_process_desc)
2151 max_process_desc = inchannel;
2153 buffer = Fplist_get (contact, QCbuffer);
2154 if (NILP (buffer))
2155 buffer = name;
2156 buffer = Fget_buffer_create (buffer);
2157 pset_buffer (p, buffer);
2159 pset_childp (p, contact);
2160 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2161 pset_type (p, Qpipe);
2162 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2163 pset_filter (p, Fplist_get (contact, QCfilter));
2164 pset_log (p, Qnil);
2165 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2166 p->kill_without_query = 1;
2167 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2168 pset_command (p, Qt);
2169 eassert (! p->pty_flag);
2171 if (!EQ (p->command, Qt))
2173 FD_SET (inchannel, &input_wait_mask);
2174 FD_SET (inchannel, &non_keyboard_wait_mask);
2176 p->adaptive_read_buffering
2177 = (NILP (Vprocess_adaptive_read_buffering) ? 0
2178 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2180 /* Make the process marker point into the process buffer (if any). */
2181 if (BUFFERP (buffer))
2182 set_marker_both (p->mark, buffer,
2183 BUF_ZV (XBUFFER (buffer)),
2184 BUF_ZV_BYTE (XBUFFER (buffer)));
2187 /* Setup coding systems for communicating with the network stream. */
2189 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2190 Lisp_Object coding_systems = Qt;
2191 Lisp_Object val;
2193 tem = Fplist_get (contact, QCcoding);
2194 val = Qnil;
2195 if (!NILP (tem))
2197 val = tem;
2198 if (CONSP (val))
2199 val = XCAR (val);
2201 else if (!NILP (Vcoding_system_for_read))
2202 val = Vcoding_system_for_read;
2203 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2204 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2205 /* We dare not decode end-of-line format by setting VAL to
2206 Qraw_text, because the existing Emacs Lisp libraries
2207 assume that they receive bare code including a sequence of
2208 CR LF. */
2209 val = Qnil;
2210 else
2212 if (CONSP (coding_systems))
2213 val = XCAR (coding_systems);
2214 else if (CONSP (Vdefault_process_coding_system))
2215 val = XCAR (Vdefault_process_coding_system);
2216 else
2217 val = Qnil;
2219 pset_decode_coding_system (p, val);
2221 if (!NILP (tem))
2223 val = tem;
2224 if (CONSP (val))
2225 val = XCDR (val);
2227 else if (!NILP (Vcoding_system_for_write))
2228 val = Vcoding_system_for_write;
2229 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2230 val = Qnil;
2231 else
2233 if (CONSP (coding_systems))
2234 val = XCDR (coding_systems);
2235 else if (CONSP (Vdefault_process_coding_system))
2236 val = XCDR (Vdefault_process_coding_system);
2237 else
2238 val = Qnil;
2240 pset_encode_coding_system (p, val);
2242 /* This may signal an error. */
2243 setup_process_coding_systems (proc);
2245 specpdl_ptr = specpdl + specpdl_count;
2247 UNGCPRO;
2248 return proc;
2252 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2253 The address family of sa is not included in the result. */
2255 Lisp_Object
2256 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2258 Lisp_Object address;
2259 int i;
2260 unsigned char *cp;
2261 register struct Lisp_Vector *p;
2263 /* Workaround for a bug in getsockname on BSD: Names bound to
2264 sockets in the UNIX domain are inaccessible; getsockname returns
2265 a zero length name. */
2266 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2267 return empty_unibyte_string;
2269 switch (sa->sa_family)
2271 case AF_INET:
2273 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2274 len = sizeof (sin->sin_addr) + 1;
2275 address = Fmake_vector (make_number (len), Qnil);
2276 p = XVECTOR (address);
2277 p->contents[--len] = make_number (ntohs (sin->sin_port));
2278 cp = (unsigned char *) &sin->sin_addr;
2279 break;
2281 #ifdef AF_INET6
2282 case AF_INET6:
2284 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2285 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2286 len = sizeof (sin6->sin6_addr) / 2 + 1;
2287 address = Fmake_vector (make_number (len), Qnil);
2288 p = XVECTOR (address);
2289 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2290 for (i = 0; i < len; i++)
2291 p->contents[i] = make_number (ntohs (ip6[i]));
2292 return address;
2294 #endif
2295 #ifdef HAVE_LOCAL_SOCKETS
2296 case AF_LOCAL:
2298 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2299 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2300 /* If the first byte is NUL, the name is a Linux abstract
2301 socket name, and the name can contain embedded NULs. If
2302 it's not, we have a NUL-terminated string. Be careful not
2303 to walk past the end of the object looking for the name
2304 terminator, however. */
2305 if (name_length > 0 && sockun->sun_path[0] != '\0')
2307 const char *terminator
2308 = memchr (sockun->sun_path, '\0', name_length);
2310 if (terminator)
2311 name_length = terminator - (const char *) sockun->sun_path;
2314 return make_unibyte_string (sockun->sun_path, name_length);
2316 #endif
2317 default:
2318 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2319 address = Fcons (make_number (sa->sa_family),
2320 Fmake_vector (make_number (len), Qnil));
2321 p = XVECTOR (XCDR (address));
2322 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2323 break;
2326 i = 0;
2327 while (i < len)
2328 p->contents[i++] = make_number (*cp++);
2330 return address;
2334 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2336 static int
2337 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2339 register struct Lisp_Vector *p;
2341 if (VECTORP (address))
2343 p = XVECTOR (address);
2344 if (p->header.size == 5)
2346 *familyp = AF_INET;
2347 return sizeof (struct sockaddr_in);
2349 #ifdef AF_INET6
2350 else if (p->header.size == 9)
2352 *familyp = AF_INET6;
2353 return sizeof (struct sockaddr_in6);
2355 #endif
2357 #ifdef HAVE_LOCAL_SOCKETS
2358 else if (STRINGP (address))
2360 *familyp = AF_LOCAL;
2361 return sizeof (struct sockaddr_un);
2363 #endif
2364 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2365 && VECTORP (XCDR (address)))
2367 struct sockaddr *sa;
2368 p = XVECTOR (XCDR (address));
2369 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2370 return 0;
2371 *familyp = XINT (XCAR (address));
2372 return p->header.size + sizeof (sa->sa_family);
2374 return 0;
2377 /* Convert an address object (vector or string) to an internal sockaddr.
2379 The address format has been basically validated by
2380 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2381 it could have come from user data. So if FAMILY is not valid,
2382 we return after zeroing *SA. */
2384 static void
2385 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2387 register struct Lisp_Vector *p;
2388 register unsigned char *cp = NULL;
2389 register int i;
2390 EMACS_INT hostport;
2392 memset (sa, 0, len);
2394 if (VECTORP (address))
2396 p = XVECTOR (address);
2397 if (family == AF_INET)
2399 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2400 len = sizeof (sin->sin_addr) + 1;
2401 hostport = XINT (p->contents[--len]);
2402 sin->sin_port = htons (hostport);
2403 cp = (unsigned char *)&sin->sin_addr;
2404 sa->sa_family = family;
2406 #ifdef AF_INET6
2407 else if (family == AF_INET6)
2409 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2410 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2411 len = sizeof (sin6->sin6_addr) + 1;
2412 hostport = XINT (p->contents[--len]);
2413 sin6->sin6_port = htons (hostport);
2414 for (i = 0; i < len; i++)
2415 if (INTEGERP (p->contents[i]))
2417 int j = XFASTINT (p->contents[i]) & 0xffff;
2418 ip6[i] = ntohs (j);
2420 sa->sa_family = family;
2421 return;
2423 #endif
2424 else
2425 return;
2427 else if (STRINGP (address))
2429 #ifdef HAVE_LOCAL_SOCKETS
2430 if (family == AF_LOCAL)
2432 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2433 cp = SDATA (address);
2434 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2435 sockun->sun_path[i] = *cp++;
2436 sa->sa_family = family;
2438 #endif
2439 return;
2441 else
2443 p = XVECTOR (XCDR (address));
2444 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2447 for (i = 0; i < len; i++)
2448 if (INTEGERP (p->contents[i]))
2449 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2452 #ifdef DATAGRAM_SOCKETS
2453 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2454 1, 1, 0,
2455 doc: /* Get the current datagram address associated with PROCESS. */)
2456 (Lisp_Object process)
2458 int channel;
2460 CHECK_PROCESS (process);
2462 if (!DATAGRAM_CONN_P (process))
2463 return Qnil;
2465 channel = XPROCESS (process)->infd;
2466 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2467 datagram_address[channel].len);
2470 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2471 2, 2, 0,
2472 doc: /* Set the datagram address for PROCESS to ADDRESS.
2473 Returns nil upon error setting address, ADDRESS otherwise. */)
2474 (Lisp_Object process, Lisp_Object address)
2476 int channel;
2477 int family, len;
2479 CHECK_PROCESS (process);
2481 if (!DATAGRAM_CONN_P (process))
2482 return Qnil;
2484 channel = XPROCESS (process)->infd;
2486 len = get_lisp_to_sockaddr_size (address, &family);
2487 if (len == 0 || datagram_address[channel].len != len)
2488 return Qnil;
2489 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2490 return address;
2492 #endif
2495 static const struct socket_options {
2496 /* The name of this option. Should be lowercase version of option
2497 name without SO_ prefix. */
2498 const char *name;
2499 /* Option level SOL_... */
2500 int optlevel;
2501 /* Option number SO_... */
2502 int optnum;
2503 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2504 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2505 } socket_options[] =
2507 #ifdef SO_BINDTODEVICE
2508 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2509 #endif
2510 #ifdef SO_BROADCAST
2511 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2512 #endif
2513 #ifdef SO_DONTROUTE
2514 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2515 #endif
2516 #ifdef SO_KEEPALIVE
2517 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2518 #endif
2519 #ifdef SO_LINGER
2520 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2521 #endif
2522 #ifdef SO_OOBINLINE
2523 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2524 #endif
2525 #ifdef SO_PRIORITY
2526 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2527 #endif
2528 #ifdef SO_REUSEADDR
2529 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2530 #endif
2531 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2534 /* Set option OPT to value VAL on socket S.
2536 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2537 Signals an error if setting a known option fails.
2540 static int
2541 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2543 char *name;
2544 const struct socket_options *sopt;
2545 int ret = 0;
2547 CHECK_SYMBOL (opt);
2549 name = SSDATA (SYMBOL_NAME (opt));
2550 for (sopt = socket_options; sopt->name; sopt++)
2551 if (strcmp (name, sopt->name) == 0)
2552 break;
2554 switch (sopt->opttype)
2556 case SOPT_BOOL:
2558 int optval;
2559 optval = NILP (val) ? 0 : 1;
2560 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2561 &optval, sizeof (optval));
2562 break;
2565 case SOPT_INT:
2567 int optval;
2568 if (TYPE_RANGED_INTEGERP (int, val))
2569 optval = XINT (val);
2570 else
2571 error ("Bad option value for %s", name);
2572 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2573 &optval, sizeof (optval));
2574 break;
2577 #ifdef SO_BINDTODEVICE
2578 case SOPT_IFNAME:
2580 char devname[IFNAMSIZ + 1];
2582 /* This is broken, at least in the Linux 2.4 kernel.
2583 To unbind, the arg must be a zero integer, not the empty string.
2584 This should work on all systems. KFS. 2003-09-23. */
2585 memset (devname, 0, sizeof devname);
2586 if (STRINGP (val))
2588 char *arg = SSDATA (val);
2589 int len = min (strlen (arg), IFNAMSIZ);
2590 memcpy (devname, arg, len);
2592 else if (!NILP (val))
2593 error ("Bad option value for %s", name);
2594 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2595 devname, IFNAMSIZ);
2596 break;
2598 #endif
2600 #ifdef SO_LINGER
2601 case SOPT_LINGER:
2603 struct linger linger;
2605 linger.l_onoff = 1;
2606 linger.l_linger = 0;
2607 if (TYPE_RANGED_INTEGERP (int, val))
2608 linger.l_linger = XINT (val);
2609 else
2610 linger.l_onoff = NILP (val) ? 0 : 1;
2611 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2612 &linger, sizeof (linger));
2613 break;
2615 #endif
2617 default:
2618 return 0;
2621 if (ret < 0)
2623 int setsockopt_errno = errno;
2624 report_file_errno ("Cannot set network option", list2 (opt, val),
2625 setsockopt_errno);
2628 return (1 << sopt->optbit);
2632 DEFUN ("set-network-process-option",
2633 Fset_network_process_option, Sset_network_process_option,
2634 3, 4, 0,
2635 doc: /* For network process PROCESS set option OPTION to value VALUE.
2636 See `make-network-process' for a list of options and values.
2637 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2638 OPTION is not a supported option, return nil instead; otherwise return t. */)
2639 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2641 int s;
2642 struct Lisp_Process *p;
2644 CHECK_PROCESS (process);
2645 p = XPROCESS (process);
2646 if (!NETCONN1_P (p))
2647 error ("Process is not a network process");
2649 s = p->infd;
2650 if (s < 0)
2651 error ("Process is not running");
2653 if (set_socket_option (s, option, value))
2655 pset_childp (p, Fplist_put (p->childp, option, value));
2656 return Qt;
2659 if (NILP (no_error))
2660 error ("Unknown or unsupported option");
2662 return Qnil;
2666 DEFUN ("serial-process-configure",
2667 Fserial_process_configure,
2668 Sserial_process_configure,
2669 0, MANY, 0,
2670 doc: /* Configure speed, bytesize, etc. of a serial process.
2672 Arguments are specified as keyword/argument pairs. Attributes that
2673 are not given are re-initialized from the process's current
2674 configuration (available via the function `process-contact') or set to
2675 reasonable default values. The following arguments are defined:
2677 :process PROCESS
2678 :name NAME
2679 :buffer BUFFER
2680 :port PORT
2681 -- Any of these arguments can be given to identify the process that is
2682 to be configured. If none of these arguments is given, the current
2683 buffer's process is used.
2685 :speed SPEED -- SPEED is the speed of the serial port in bits per
2686 second, also called baud rate. Any value can be given for SPEED, but
2687 most serial ports work only at a few defined values between 1200 and
2688 115200, with 9600 being the most common value. If SPEED is nil, the
2689 serial port is not configured any further, i.e., all other arguments
2690 are ignored. This may be useful for special serial ports such as
2691 Bluetooth-to-serial converters which can only be configured through AT
2692 commands. A value of nil for SPEED can be used only when passed
2693 through `make-serial-process' or `serial-term'.
2695 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2696 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2698 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2699 `odd' (use odd parity), or the symbol `even' (use even parity). If
2700 PARITY is not given, no parity is used.
2702 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2703 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2704 is not given or nil, 1 stopbit is used.
2706 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2707 flowcontrol to be used, which is either nil (don't use flowcontrol),
2708 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2709 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2710 flowcontrol is used.
2712 `serial-process-configure' is called by `make-serial-process' for the
2713 initial configuration of the serial port.
2715 Examples:
2717 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2719 \(serial-process-configure
2720 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2722 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2724 usage: (serial-process-configure &rest ARGS) */)
2725 (ptrdiff_t nargs, Lisp_Object *args)
2727 struct Lisp_Process *p;
2728 Lisp_Object contact = Qnil;
2729 Lisp_Object proc = Qnil;
2730 struct gcpro gcpro1;
2732 contact = Flist (nargs, args);
2733 GCPRO1 (contact);
2735 proc = Fplist_get (contact, QCprocess);
2736 if (NILP (proc))
2737 proc = Fplist_get (contact, QCname);
2738 if (NILP (proc))
2739 proc = Fplist_get (contact, QCbuffer);
2740 if (NILP (proc))
2741 proc = Fplist_get (contact, QCport);
2742 proc = get_process (proc);
2743 p = XPROCESS (proc);
2744 if (!EQ (p->type, Qserial))
2745 error ("Not a serial process");
2747 if (NILP (Fplist_get (p->childp, QCspeed)))
2749 UNGCPRO;
2750 return Qnil;
2753 serial_configure (p, contact);
2755 UNGCPRO;
2756 return Qnil;
2759 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2760 0, MANY, 0,
2761 doc: /* Create and return a serial port process.
2763 In Emacs, serial port connections are represented by process objects,
2764 so input and output work as for subprocesses, and `delete-process'
2765 closes a serial port connection. However, a serial process has no
2766 process id, it cannot be signaled, and the status codes are different
2767 from normal processes.
2769 `make-serial-process' creates a process and a buffer, on which you
2770 probably want to use `process-send-string'. Try \\[serial-term] for
2771 an interactive terminal. See below for examples.
2773 Arguments are specified as keyword/argument pairs. The following
2774 arguments are defined:
2776 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2777 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2778 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2779 the backslashes in strings).
2781 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2782 which this function calls.
2784 :name NAME -- NAME is the name of the process. If NAME is not given,
2785 the value of PORT is used.
2787 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2788 with the process. Process output goes at the end of that buffer,
2789 unless you specify an output stream or filter function to handle the
2790 output. If BUFFER is not given, the value of NAME is used.
2792 :coding CODING -- If CODING is a symbol, it specifies the coding
2793 system used for both reading and writing for this process. If CODING
2794 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2795 ENCODING is used for writing.
2797 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2798 the process is running. If BOOL is not given, query before exiting.
2800 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2801 In the stopped state, a serial process does not accept incoming data,
2802 but you can send outgoing data. The stopped state is cleared by
2803 `continue-process' and set by `stop-process'.
2805 :filter FILTER -- Install FILTER as the process filter.
2807 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2809 :plist PLIST -- Install PLIST as the initial plist of the process.
2811 :bytesize
2812 :parity
2813 :stopbits
2814 :flowcontrol
2815 -- This function calls `serial-process-configure' to handle these
2816 arguments.
2818 The original argument list, possibly modified by later configuration,
2819 is available via the function `process-contact'.
2821 Examples:
2823 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2825 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2827 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2829 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2831 usage: (make-serial-process &rest ARGS) */)
2832 (ptrdiff_t nargs, Lisp_Object *args)
2834 int fd = -1;
2835 Lisp_Object proc, contact, port;
2836 struct Lisp_Process *p;
2837 struct gcpro gcpro1;
2838 Lisp_Object name, buffer;
2839 Lisp_Object tem, val;
2840 ptrdiff_t specpdl_count;
2842 if (nargs == 0)
2843 return Qnil;
2845 contact = Flist (nargs, args);
2846 GCPRO1 (contact);
2848 port = Fplist_get (contact, QCport);
2849 if (NILP (port))
2850 error ("No port specified");
2851 CHECK_STRING (port);
2853 if (NILP (Fplist_member (contact, QCspeed)))
2854 error (":speed not specified");
2855 if (!NILP (Fplist_get (contact, QCspeed)))
2856 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2858 name = Fplist_get (contact, QCname);
2859 if (NILP (name))
2860 name = port;
2861 CHECK_STRING (name);
2862 proc = make_process (name);
2863 specpdl_count = SPECPDL_INDEX ();
2864 record_unwind_protect (remove_process, proc);
2865 p = XPROCESS (proc);
2867 fd = serial_open (port);
2868 p->open_fd[SUBPROCESS_STDIN] = fd;
2869 p->infd = fd;
2870 p->outfd = fd;
2871 if (fd > max_process_desc)
2872 max_process_desc = fd;
2873 chan_process[fd] = proc;
2875 buffer = Fplist_get (contact, QCbuffer);
2876 if (NILP (buffer))
2877 buffer = name;
2878 buffer = Fget_buffer_create (buffer);
2879 pset_buffer (p, buffer);
2881 pset_childp (p, contact);
2882 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2883 pset_type (p, Qserial);
2884 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2885 pset_filter (p, Fplist_get (contact, QCfilter));
2886 pset_log (p, Qnil);
2887 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2888 p->kill_without_query = 1;
2889 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2890 pset_command (p, Qt);
2891 eassert (! p->pty_flag);
2893 if (!EQ (p->command, Qt))
2895 FD_SET (fd, &input_wait_mask);
2896 FD_SET (fd, &non_keyboard_wait_mask);
2899 if (BUFFERP (buffer))
2901 set_marker_both (p->mark, buffer,
2902 BUF_ZV (XBUFFER (buffer)),
2903 BUF_ZV_BYTE (XBUFFER (buffer)));
2906 tem = Fplist_member (contact, QCcoding);
2907 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2908 tem = Qnil;
2910 val = Qnil;
2911 if (!NILP (tem))
2913 val = XCAR (XCDR (tem));
2914 if (CONSP (val))
2915 val = XCAR (val);
2917 else if (!NILP (Vcoding_system_for_read))
2918 val = Vcoding_system_for_read;
2919 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2920 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2921 val = Qnil;
2922 pset_decode_coding_system (p, val);
2924 val = Qnil;
2925 if (!NILP (tem))
2927 val = XCAR (XCDR (tem));
2928 if (CONSP (val))
2929 val = XCDR (val);
2931 else if (!NILP (Vcoding_system_for_write))
2932 val = Vcoding_system_for_write;
2933 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2934 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2935 val = Qnil;
2936 pset_encode_coding_system (p, val);
2938 setup_process_coding_systems (proc);
2939 pset_decoding_buf (p, empty_unibyte_string);
2940 p->decoding_carryover = 0;
2941 pset_encoding_buf (p, empty_unibyte_string);
2942 p->inherit_coding_system_flag
2943 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2945 Fserial_process_configure (nargs, args);
2947 specpdl_ptr = specpdl + specpdl_count;
2949 UNGCPRO;
2950 return proc;
2953 /* Create a network stream/datagram client/server process. Treated
2954 exactly like a normal process when reading and writing. Primary
2955 differences are in status display and process deletion. A network
2956 connection has no PID; you cannot signal it. All you can do is
2957 stop/continue it and deactivate/close it via delete-process. */
2959 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2960 0, MANY, 0,
2961 doc: /* Create and return a network server or client process.
2963 In Emacs, network connections are represented by process objects, so
2964 input and output work as for subprocesses and `delete-process' closes
2965 a network connection. However, a network process has no process id,
2966 it cannot be signaled, and the status codes are different from normal
2967 processes.
2969 Arguments are specified as keyword/argument pairs. The following
2970 arguments are defined:
2972 :name NAME -- NAME is name for process. It is modified if necessary
2973 to make it unique.
2975 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2976 with the process. Process output goes at end of that buffer, unless
2977 you specify an output stream or filter function to handle the output.
2978 BUFFER may be also nil, meaning that this process is not associated
2979 with any buffer.
2981 :host HOST -- HOST is name of the host to connect to, or its IP
2982 address. The symbol `local' specifies the local host. If specified
2983 for a server process, it must be a valid name or address for the local
2984 host, and only clients connecting to that address will be accepted.
2986 :service SERVICE -- SERVICE is name of the service desired, or an
2987 integer specifying a port number to connect to. If SERVICE is t,
2988 a random port number is selected for the server. (If Emacs was
2989 compiled with getaddrinfo, a port number can also be specified as a
2990 string, e.g. "80", as well as an integer. This is not portable.)
2992 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2993 stream type connection, `datagram' creates a datagram type connection,
2994 `seqpacket' creates a reliable datagram connection.
2996 :family FAMILY -- FAMILY is the address (and protocol) family for the
2997 service specified by HOST and SERVICE. The default (nil) is to use
2998 whatever address family (IPv4 or IPv6) that is defined for the host
2999 and port number specified by HOST and SERVICE. Other address families
3000 supported are:
3001 local -- for a local (i.e. UNIX) address specified by SERVICE.
3002 ipv4 -- use IPv4 address family only.
3003 ipv6 -- use IPv6 address family only.
3005 :local ADDRESS -- ADDRESS is the local address used for the connection.
3006 This parameter is ignored when opening a client process. When specified
3007 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3009 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3010 connection. This parameter is ignored when opening a stream server
3011 process. For a datagram server process, it specifies the initial
3012 setting of the remote datagram address. When specified for a client
3013 process, the FAMILY, HOST, and SERVICE args are ignored.
3015 The format of ADDRESS depends on the address family:
3016 - An IPv4 address is represented as an vector of integers [A B C D P]
3017 corresponding to numeric IP address A.B.C.D and port number P.
3018 - A local address is represented as a string with the address in the
3019 local address space.
3020 - An "unsupported family" address is represented by a cons (F . AV)
3021 where F is the family number and AV is a vector containing the socket
3022 address data with one element per address data byte. Do not rely on
3023 this format in portable code, as it may depend on implementation
3024 defined constants, data sizes, and data structure alignment.
3026 :coding CODING -- If CODING is a symbol, it specifies the coding
3027 system used for both reading and writing for this process. If CODING
3028 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3029 ENCODING is used for writing.
3031 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3032 return without waiting for the connection to complete; instead, the
3033 sentinel function will be called with second arg matching "open" (if
3034 successful) or "failed" when the connect completes. Default is to use
3035 a blocking connect (i.e. wait) for stream type connections.
3037 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3038 running when Emacs is exited.
3040 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3041 In the stopped state, a server process does not accept new
3042 connections, and a client process does not handle incoming traffic.
3043 The stopped state is cleared by `continue-process' and set by
3044 `stop-process'.
3046 :filter FILTER -- Install FILTER as the process filter.
3048 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3049 process filter are multibyte, otherwise they are unibyte.
3050 If this keyword is not specified, the strings are multibyte if
3051 the default value of `enable-multibyte-characters' is non-nil.
3053 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3055 :log LOG -- Install LOG as the server process log function. This
3056 function is called when the server accepts a network connection from a
3057 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3058 is the server process, CLIENT is the new process for the connection,
3059 and MESSAGE is a string.
3061 :plist PLIST -- Install PLIST as the new process's initial plist.
3063 :server QLEN -- if QLEN is non-nil, create a server process for the
3064 specified FAMILY, SERVICE, and connection type (stream or datagram).
3065 If QLEN is an integer, it is used as the max. length of the server's
3066 pending connection queue (also known as the backlog); the default
3067 queue length is 5. Default is to create a client process.
3069 The following network options can be specified for this connection:
3071 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3072 :dontroute BOOL -- Only send to directly connected hosts.
3073 :keepalive BOOL -- Send keep-alive messages on network stream.
3074 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3075 :oobinline BOOL -- Place out-of-band data in receive data stream.
3076 :priority INT -- Set protocol defined priority for sent packets.
3077 :reuseaddr BOOL -- Allow reusing a recently used local address
3078 (this is allowed by default for a server process).
3079 :bindtodevice NAME -- bind to interface NAME. Using this may require
3080 special privileges on some systems.
3082 Consult the relevant system programmer's manual pages for more
3083 information on using these options.
3086 A server process will listen for and accept connections from clients.
3087 When a client connection is accepted, a new network process is created
3088 for the connection with the following parameters:
3090 - The client's process name is constructed by concatenating the server
3091 process's NAME and a client identification string.
3092 - If the FILTER argument is non-nil, the client process will not get a
3093 separate process buffer; otherwise, the client's process buffer is a newly
3094 created buffer named after the server process's BUFFER name or process
3095 NAME concatenated with the client identification string.
3096 - The connection type and the process filter and sentinel parameters are
3097 inherited from the server process's TYPE, FILTER and SENTINEL.
3098 - The client process's contact info is set according to the client's
3099 addressing information (typically an IP address and a port number).
3100 - The client process's plist is initialized from the server's plist.
3102 Notice that the FILTER and SENTINEL args are never used directly by
3103 the server process. Also, the BUFFER argument is not used directly by
3104 the server process, but via the optional :log function, accepted (and
3105 failed) connections may be logged in the server process's buffer.
3107 The original argument list, modified with the actual connection
3108 information, is available via the `process-contact' function.
3110 usage: (make-network-process &rest ARGS) */)
3111 (ptrdiff_t nargs, Lisp_Object *args)
3113 Lisp_Object proc;
3114 Lisp_Object contact;
3115 struct Lisp_Process *p;
3116 #ifdef HAVE_GETADDRINFO
3117 struct addrinfo ai, *res, *lres;
3118 struct addrinfo hints;
3119 const char *portstring;
3120 char portbuf[128];
3121 #else /* HAVE_GETADDRINFO */
3122 struct _emacs_addrinfo
3124 int ai_family;
3125 int ai_socktype;
3126 int ai_protocol;
3127 int ai_addrlen;
3128 struct sockaddr *ai_addr;
3129 struct _emacs_addrinfo *ai_next;
3130 } ai, *res, *lres;
3131 #endif /* HAVE_GETADDRINFO */
3132 struct sockaddr_in address_in;
3133 #ifdef HAVE_LOCAL_SOCKETS
3134 struct sockaddr_un address_un;
3135 #endif
3136 int port;
3137 int ret = 0;
3138 int xerrno = 0;
3139 int s = -1, outch, inch;
3140 struct gcpro gcpro1;
3141 ptrdiff_t count = SPECPDL_INDEX ();
3142 ptrdiff_t count1;
3143 Lisp_Object colon_address; /* Either QClocal or QCremote. */
3144 Lisp_Object tem;
3145 Lisp_Object name, buffer, host, service, address;
3146 Lisp_Object filter, sentinel;
3147 bool is_non_blocking_client = 0;
3148 bool is_server = 0;
3149 int backlog = 5;
3150 int socktype;
3151 int family = -1;
3153 if (nargs == 0)
3154 return Qnil;
3156 /* Save arguments for process-contact and clone-process. */
3157 contact = Flist (nargs, args);
3158 GCPRO1 (contact);
3160 #ifdef WINDOWSNT
3161 /* Ensure socket support is loaded if available. */
3162 init_winsock (TRUE);
3163 #endif
3165 /* :type TYPE (nil: stream, datagram */
3166 tem = Fplist_get (contact, QCtype);
3167 if (NILP (tem))
3168 socktype = SOCK_STREAM;
3169 #ifdef DATAGRAM_SOCKETS
3170 else if (EQ (tem, Qdatagram))
3171 socktype = SOCK_DGRAM;
3172 #endif
3173 #ifdef HAVE_SEQPACKET
3174 else if (EQ (tem, Qseqpacket))
3175 socktype = SOCK_SEQPACKET;
3176 #endif
3177 else
3178 error ("Unsupported connection type");
3180 /* :server BOOL */
3181 tem = Fplist_get (contact, QCserver);
3182 if (!NILP (tem))
3184 /* Don't support network sockets when non-blocking mode is
3185 not available, since a blocked Emacs is not useful. */
3186 is_server = 1;
3187 if (TYPE_RANGED_INTEGERP (int, tem))
3188 backlog = XINT (tem);
3191 /* Make colon_address an alias for :local (server) or :remote (client). */
3192 colon_address = is_server ? QClocal : QCremote;
3194 /* :nowait BOOL */
3195 if (!is_server && socktype != SOCK_DGRAM
3196 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3198 #ifndef NON_BLOCKING_CONNECT
3199 error ("Non-blocking connect not supported");
3200 #else
3201 is_non_blocking_client = 1;
3202 #endif
3205 name = Fplist_get (contact, QCname);
3206 buffer = Fplist_get (contact, QCbuffer);
3207 filter = Fplist_get (contact, QCfilter);
3208 sentinel = Fplist_get (contact, QCsentinel);
3210 CHECK_STRING (name);
3212 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3213 ai.ai_socktype = socktype;
3214 ai.ai_protocol = 0;
3215 ai.ai_next = NULL;
3216 res = &ai;
3218 /* :local ADDRESS or :remote ADDRESS */
3219 address = Fplist_get (contact, colon_address);
3220 if (!NILP (address))
3222 host = service = Qnil;
3224 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3225 error ("Malformed :address");
3226 ai.ai_family = family;
3227 ai.ai_addr = alloca (ai.ai_addrlen);
3228 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3229 goto open_socket;
3232 /* :family FAMILY -- nil (for Inet), local, or integer. */
3233 tem = Fplist_get (contact, QCfamily);
3234 if (NILP (tem))
3236 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3237 family = AF_UNSPEC;
3238 #else
3239 family = AF_INET;
3240 #endif
3242 #ifdef HAVE_LOCAL_SOCKETS
3243 else if (EQ (tem, Qlocal))
3244 family = AF_LOCAL;
3245 #endif
3246 #ifdef AF_INET6
3247 else if (EQ (tem, Qipv6))
3248 family = AF_INET6;
3249 #endif
3250 else if (EQ (tem, Qipv4))
3251 family = AF_INET;
3252 else if (TYPE_RANGED_INTEGERP (int, tem))
3253 family = XINT (tem);
3254 else
3255 error ("Unknown address family");
3257 ai.ai_family = family;
3259 /* :service SERVICE -- string, integer (port number), or t (random port). */
3260 service = Fplist_get (contact, QCservice);
3262 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3263 host = Fplist_get (contact, QChost);
3264 if (!NILP (host))
3266 if (EQ (host, Qlocal))
3267 /* Depending on setup, "localhost" may map to different IPv4 and/or
3268 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3269 host = build_string ("127.0.0.1");
3270 CHECK_STRING (host);
3273 #ifdef HAVE_LOCAL_SOCKETS
3274 if (family == AF_LOCAL)
3276 if (!NILP (host))
3278 message (":family local ignores the :host property");
3279 contact = Fplist_put (contact, QChost, Qnil);
3280 host = Qnil;
3282 CHECK_STRING (service);
3283 memset (&address_un, 0, sizeof address_un);
3284 address_un.sun_family = AF_LOCAL;
3285 if (sizeof address_un.sun_path <= SBYTES (service))
3286 error ("Service name too long");
3287 lispstpcpy (address_un.sun_path, service);
3288 ai.ai_addr = (struct sockaddr *) &address_un;
3289 ai.ai_addrlen = sizeof address_un;
3290 goto open_socket;
3292 #endif
3294 /* Slow down polling to every ten seconds.
3295 Some kernels have a bug which causes retrying connect to fail
3296 after a connect. Polling can interfere with gethostbyname too. */
3297 #ifdef POLL_FOR_INPUT
3298 if (socktype != SOCK_DGRAM)
3300 record_unwind_protect_void (run_all_atimers);
3301 bind_polling_period (10);
3303 #endif
3305 #ifdef HAVE_GETADDRINFO
3306 /* If we have a host, use getaddrinfo to resolve both host and service.
3307 Otherwise, use getservbyname to lookup the service. */
3308 if (!NILP (host))
3311 /* SERVICE can either be a string or int.
3312 Convert to a C string for later use by getaddrinfo. */
3313 if (EQ (service, Qt))
3314 portstring = "0";
3315 else if (INTEGERP (service))
3317 sprintf (portbuf, "%"pI"d", XINT (service));
3318 portstring = portbuf;
3320 else
3322 CHECK_STRING (service);
3323 portstring = SSDATA (service);
3326 immediate_quit = 1;
3327 QUIT;
3328 memset (&hints, 0, sizeof (hints));
3329 hints.ai_flags = 0;
3330 hints.ai_family = family;
3331 hints.ai_socktype = socktype;
3332 hints.ai_protocol = 0;
3334 #ifdef HAVE_RES_INIT
3335 res_init ();
3336 #endif
3338 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3339 if (ret)
3340 #ifdef HAVE_GAI_STRERROR
3341 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3342 #else
3343 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3344 #endif
3345 immediate_quit = 0;
3347 goto open_socket;
3349 #endif /* HAVE_GETADDRINFO */
3351 /* We end up here if getaddrinfo is not defined, or in case no hostname
3352 has been specified (e.g. for a local server process). */
3354 if (EQ (service, Qt))
3355 port = 0;
3356 else if (INTEGERP (service))
3357 port = htons ((unsigned short) XINT (service));
3358 else
3360 struct servent *svc_info;
3361 CHECK_STRING (service);
3362 svc_info = getservbyname (SSDATA (service),
3363 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3364 if (svc_info == 0)
3365 error ("Unknown service: %s", SDATA (service));
3366 port = svc_info->s_port;
3369 memset (&address_in, 0, sizeof address_in);
3370 address_in.sin_family = family;
3371 address_in.sin_addr.s_addr = INADDR_ANY;
3372 address_in.sin_port = port;
3374 #ifndef HAVE_GETADDRINFO
3375 if (!NILP (host))
3377 struct hostent *host_info_ptr;
3379 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3380 as it may `hang' Emacs for a very long time. */
3381 immediate_quit = 1;
3382 QUIT;
3384 #ifdef HAVE_RES_INIT
3385 res_init ();
3386 #endif
3388 host_info_ptr = gethostbyname (SDATA (host));
3389 immediate_quit = 0;
3391 if (host_info_ptr)
3393 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3394 host_info_ptr->h_length);
3395 family = host_info_ptr->h_addrtype;
3396 address_in.sin_family = family;
3398 else
3399 /* Attempt to interpret host as numeric inet address. */
3401 unsigned long numeric_addr;
3402 numeric_addr = inet_addr (SSDATA (host));
3403 if (numeric_addr == -1)
3404 error ("Unknown host \"%s\"", SDATA (host));
3406 memcpy (&address_in.sin_addr, &numeric_addr,
3407 sizeof (address_in.sin_addr));
3411 #endif /* not HAVE_GETADDRINFO */
3413 ai.ai_family = family;
3414 ai.ai_addr = (struct sockaddr *) &address_in;
3415 ai.ai_addrlen = sizeof address_in;
3417 open_socket:
3419 /* Do this in case we never enter the for-loop below. */
3420 count1 = SPECPDL_INDEX ();
3421 s = -1;
3423 for (lres = res; lres; lres = lres->ai_next)
3425 ptrdiff_t optn;
3426 int optbits;
3428 #ifdef WINDOWSNT
3429 retry_connect:
3430 #endif
3432 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3433 lres->ai_protocol);
3434 if (s < 0)
3436 xerrno = errno;
3437 continue;
3440 #ifdef DATAGRAM_SOCKETS
3441 if (!is_server && socktype == SOCK_DGRAM)
3442 break;
3443 #endif /* DATAGRAM_SOCKETS */
3445 #ifdef NON_BLOCKING_CONNECT
3446 if (is_non_blocking_client)
3448 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3449 if (ret < 0)
3451 xerrno = errno;
3452 emacs_close (s);
3453 s = -1;
3454 continue;
3457 #endif
3459 /* Make us close S if quit. */
3460 record_unwind_protect_int (close_file_unwind, s);
3462 /* Parse network options in the arg list.
3463 We simply ignore anything which isn't a known option (including other keywords).
3464 An error is signaled if setting a known option fails. */
3465 for (optn = optbits = 0; optn < nargs - 1; optn += 2)
3466 optbits |= set_socket_option (s, args[optn], args[optn + 1]);
3468 if (is_server)
3470 /* Configure as a server socket. */
3472 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3473 explicit :reuseaddr key to override this. */
3474 #ifdef HAVE_LOCAL_SOCKETS
3475 if (family != AF_LOCAL)
3476 #endif
3477 if (!(optbits & (1 << OPIX_REUSEADDR)))
3479 int optval = 1;
3480 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3481 report_file_error ("Cannot set reuse option on server socket", Qnil);
3484 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3485 report_file_error ("Cannot bind server socket", Qnil);
3487 #ifdef HAVE_GETSOCKNAME
3488 if (EQ (service, Qt))
3490 struct sockaddr_in sa1;
3491 socklen_t len1 = sizeof (sa1);
3492 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3494 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3495 service = make_number (ntohs (sa1.sin_port));
3496 contact = Fplist_put (contact, QCservice, service);
3499 #endif
3501 if (socktype != SOCK_DGRAM && listen (s, backlog))
3502 report_file_error ("Cannot listen on server socket", Qnil);
3504 break;
3507 immediate_quit = 1;
3508 QUIT;
3510 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3511 xerrno = errno;
3513 if (ret == 0 || xerrno == EISCONN)
3515 /* The unwind-protect will be discarded afterwards.
3516 Likewise for immediate_quit. */
3517 break;
3520 #ifdef NON_BLOCKING_CONNECT
3521 #ifdef EINPROGRESS
3522 if (is_non_blocking_client && xerrno == EINPROGRESS)
3523 break;
3524 #else
3525 #ifdef EWOULDBLOCK
3526 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3527 break;
3528 #endif
3529 #endif
3530 #endif
3532 #ifndef WINDOWSNT
3533 if (xerrno == EINTR)
3535 /* Unlike most other syscalls connect() cannot be called
3536 again. (That would return EALREADY.) The proper way to
3537 wait for completion is pselect(). */
3538 int sc;
3539 socklen_t len;
3540 fd_set fdset;
3541 retry_select:
3542 FD_ZERO (&fdset);
3543 FD_SET (s, &fdset);
3544 QUIT;
3545 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3546 if (sc == -1)
3548 if (errno == EINTR)
3549 goto retry_select;
3550 else
3551 report_file_error ("Failed select", Qnil);
3553 eassert (sc > 0);
3555 len = sizeof xerrno;
3556 eassert (FD_ISSET (s, &fdset));
3557 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3558 report_file_error ("Failed getsockopt", Qnil);
3559 if (xerrno)
3560 report_file_errno ("Failed connect", Qnil, xerrno);
3561 break;
3563 #endif /* !WINDOWSNT */
3565 immediate_quit = 0;
3567 /* Discard the unwind protect closing S. */
3568 specpdl_ptr = specpdl + count1;
3569 emacs_close (s);
3570 s = -1;
3572 #ifdef WINDOWSNT
3573 if (xerrno == EINTR)
3574 goto retry_connect;
3575 #endif
3578 if (s >= 0)
3580 #ifdef DATAGRAM_SOCKETS
3581 if (socktype == SOCK_DGRAM)
3583 if (datagram_address[s].sa)
3584 emacs_abort ();
3585 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3586 datagram_address[s].len = lres->ai_addrlen;
3587 if (is_server)
3589 Lisp_Object remote;
3590 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3591 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3593 int rfamily, rlen;
3594 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3595 if (rlen != 0 && rfamily == lres->ai_family
3596 && rlen == lres->ai_addrlen)
3597 conv_lisp_to_sockaddr (rfamily, remote,
3598 datagram_address[s].sa, rlen);
3601 else
3602 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3604 #endif
3605 contact = Fplist_put (contact, colon_address,
3606 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3607 #ifdef HAVE_GETSOCKNAME
3608 if (!is_server)
3610 struct sockaddr_in sa1;
3611 socklen_t len1 = sizeof (sa1);
3612 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3613 contact = Fplist_put (contact, QClocal,
3614 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3616 #endif
3619 immediate_quit = 0;
3621 #ifdef HAVE_GETADDRINFO
3622 if (res != &ai)
3624 block_input ();
3625 freeaddrinfo (res);
3626 unblock_input ();
3628 #endif
3630 if (s < 0)
3632 /* If non-blocking got this far - and failed - assume non-blocking is
3633 not supported after all. This is probably a wrong assumption, but
3634 the normal blocking calls to open-network-stream handles this error
3635 better. */
3636 if (is_non_blocking_client)
3637 return Qnil;
3639 report_file_errno ((is_server
3640 ? "make server process failed"
3641 : "make client process failed"),
3642 contact, xerrno);
3645 inch = s;
3646 outch = s;
3648 if (!NILP (buffer))
3649 buffer = Fget_buffer_create (buffer);
3650 proc = make_process (name);
3652 chan_process[inch] = proc;
3654 fcntl (inch, F_SETFL, O_NONBLOCK);
3656 p = XPROCESS (proc);
3658 pset_childp (p, contact);
3659 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3660 pset_type (p, Qnetwork);
3662 pset_buffer (p, buffer);
3663 pset_sentinel (p, sentinel);
3664 pset_filter (p, filter);
3665 pset_log (p, Fplist_get (contact, QClog));
3666 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3667 p->kill_without_query = 1;
3668 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3669 pset_command (p, Qt);
3670 p->pid = 0;
3672 p->open_fd[SUBPROCESS_STDIN] = inch;
3673 p->infd = inch;
3674 p->outfd = outch;
3676 /* Discard the unwind protect for closing S, if any. */
3677 specpdl_ptr = specpdl + count1;
3679 /* Unwind bind_polling_period and request_sigio. */
3680 unbind_to (count, Qnil);
3682 if (is_server && socktype != SOCK_DGRAM)
3683 pset_status (p, Qlisten);
3685 /* Make the process marker point into the process buffer (if any). */
3686 if (BUFFERP (buffer))
3687 set_marker_both (p->mark, buffer,
3688 BUF_ZV (XBUFFER (buffer)),
3689 BUF_ZV_BYTE (XBUFFER (buffer)));
3691 #ifdef NON_BLOCKING_CONNECT
3692 if (is_non_blocking_client)
3694 /* We may get here if connect did succeed immediately. However,
3695 in that case, we still need to signal this like a non-blocking
3696 connection. */
3697 pset_status (p, Qconnect);
3698 if (!FD_ISSET (inch, &connect_wait_mask))
3700 FD_SET (inch, &connect_wait_mask);
3701 FD_SET (inch, &write_mask);
3702 num_pending_connects++;
3705 else
3706 #endif
3707 /* A server may have a client filter setting of Qt, but it must
3708 still listen for incoming connects unless it is stopped. */
3709 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3710 || (EQ (p->status, Qlisten) && NILP (p->command)))
3712 FD_SET (inch, &input_wait_mask);
3713 FD_SET (inch, &non_keyboard_wait_mask);
3716 if (inch > max_process_desc)
3717 max_process_desc = inch;
3719 tem = Fplist_member (contact, QCcoding);
3720 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3721 tem = Qnil; /* No error message (too late!). */
3724 /* Setup coding systems for communicating with the network stream. */
3725 struct gcpro gcpro1;
3726 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3727 Lisp_Object coding_systems = Qt;
3728 Lisp_Object val;
3730 if (!NILP (tem))
3732 val = XCAR (XCDR (tem));
3733 if (CONSP (val))
3734 val = XCAR (val);
3736 else if (!NILP (Vcoding_system_for_read))
3737 val = Vcoding_system_for_read;
3738 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3739 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3740 /* We dare not decode end-of-line format by setting VAL to
3741 Qraw_text, because the existing Emacs Lisp libraries
3742 assume that they receive bare code including a sequence of
3743 CR LF. */
3744 val = Qnil;
3745 else
3747 if (NILP (host) || NILP (service))
3748 coding_systems = Qnil;
3749 else
3751 GCPRO1 (proc);
3752 coding_systems = CALLN (Ffind_operation_coding_system,
3753 Qopen_network_stream, name, buffer,
3754 host, service);
3755 UNGCPRO;
3757 if (CONSP (coding_systems))
3758 val = XCAR (coding_systems);
3759 else if (CONSP (Vdefault_process_coding_system))
3760 val = XCAR (Vdefault_process_coding_system);
3761 else
3762 val = Qnil;
3764 pset_decode_coding_system (p, val);
3766 if (!NILP (tem))
3768 val = XCAR (XCDR (tem));
3769 if (CONSP (val))
3770 val = XCDR (val);
3772 else if (!NILP (Vcoding_system_for_write))
3773 val = Vcoding_system_for_write;
3774 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3775 val = Qnil;
3776 else
3778 if (EQ (coding_systems, Qt))
3780 if (NILP (host) || NILP (service))
3781 coding_systems = Qnil;
3782 else
3784 GCPRO1 (proc);
3785 coding_systems = CALLN (Ffind_operation_coding_system,
3786 Qopen_network_stream, name, buffer,
3787 host, service);
3788 UNGCPRO;
3791 if (CONSP (coding_systems))
3792 val = XCDR (coding_systems);
3793 else if (CONSP (Vdefault_process_coding_system))
3794 val = XCDR (Vdefault_process_coding_system);
3795 else
3796 val = Qnil;
3798 pset_encode_coding_system (p, val);
3800 setup_process_coding_systems (proc);
3802 pset_decoding_buf (p, empty_unibyte_string);
3803 p->decoding_carryover = 0;
3804 pset_encoding_buf (p, empty_unibyte_string);
3806 p->inherit_coding_system_flag
3807 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3809 UNGCPRO;
3810 return proc;
3814 #ifdef HAVE_NET_IF_H
3816 #ifdef SIOCGIFCONF
3817 static Lisp_Object
3818 network_interface_list (void)
3820 struct ifconf ifconf;
3821 struct ifreq *ifreq;
3822 void *buf = NULL;
3823 ptrdiff_t buf_size = 512;
3824 int s;
3825 Lisp_Object res;
3826 ptrdiff_t count;
3828 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3829 if (s < 0)
3830 return Qnil;
3831 count = SPECPDL_INDEX ();
3832 record_unwind_protect_int (close_file_unwind, s);
3836 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3837 ifconf.ifc_buf = buf;
3838 ifconf.ifc_len = buf_size;
3839 if (ioctl (s, SIOCGIFCONF, &ifconf))
3841 emacs_close (s);
3842 xfree (buf);
3843 return Qnil;
3846 while (ifconf.ifc_len == buf_size);
3848 res = unbind_to (count, Qnil);
3849 ifreq = ifconf.ifc_req;
3850 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3852 struct ifreq *ifq = ifreq;
3853 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3854 #define SIZEOF_IFREQ(sif) \
3855 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3856 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3858 int len = SIZEOF_IFREQ (ifq);
3859 #else
3860 int len = sizeof (*ifreq);
3861 #endif
3862 char namebuf[sizeof (ifq->ifr_name) + 1];
3863 ifreq = (struct ifreq *) ((char *) ifreq + len);
3865 if (ifq->ifr_addr.sa_family != AF_INET)
3866 continue;
3868 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3869 namebuf[sizeof (ifq->ifr_name)] = 0;
3870 res = Fcons (Fcons (build_string (namebuf),
3871 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3872 sizeof (struct sockaddr))),
3873 res);
3876 xfree (buf);
3877 return res;
3879 #endif /* SIOCGIFCONF */
3881 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3883 struct ifflag_def {
3884 int flag_bit;
3885 const char *flag_sym;
3888 static const struct ifflag_def ifflag_table[] = {
3889 #ifdef IFF_UP
3890 { IFF_UP, "up" },
3891 #endif
3892 #ifdef IFF_BROADCAST
3893 { IFF_BROADCAST, "broadcast" },
3894 #endif
3895 #ifdef IFF_DEBUG
3896 { IFF_DEBUG, "debug" },
3897 #endif
3898 #ifdef IFF_LOOPBACK
3899 { IFF_LOOPBACK, "loopback" },
3900 #endif
3901 #ifdef IFF_POINTOPOINT
3902 { IFF_POINTOPOINT, "pointopoint" },
3903 #endif
3904 #ifdef IFF_RUNNING
3905 { IFF_RUNNING, "running" },
3906 #endif
3907 #ifdef IFF_NOARP
3908 { IFF_NOARP, "noarp" },
3909 #endif
3910 #ifdef IFF_PROMISC
3911 { IFF_PROMISC, "promisc" },
3912 #endif
3913 #ifdef IFF_NOTRAILERS
3914 #ifdef NS_IMPL_COCOA
3915 /* Really means smart, notrailers is obsolete. */
3916 { IFF_NOTRAILERS, "smart" },
3917 #else
3918 { IFF_NOTRAILERS, "notrailers" },
3919 #endif
3920 #endif
3921 #ifdef IFF_ALLMULTI
3922 { IFF_ALLMULTI, "allmulti" },
3923 #endif
3924 #ifdef IFF_MASTER
3925 { IFF_MASTER, "master" },
3926 #endif
3927 #ifdef IFF_SLAVE
3928 { IFF_SLAVE, "slave" },
3929 #endif
3930 #ifdef IFF_MULTICAST
3931 { IFF_MULTICAST, "multicast" },
3932 #endif
3933 #ifdef IFF_PORTSEL
3934 { IFF_PORTSEL, "portsel" },
3935 #endif
3936 #ifdef IFF_AUTOMEDIA
3937 { IFF_AUTOMEDIA, "automedia" },
3938 #endif
3939 #ifdef IFF_DYNAMIC
3940 { IFF_DYNAMIC, "dynamic" },
3941 #endif
3942 #ifdef IFF_OACTIVE
3943 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
3944 #endif
3945 #ifdef IFF_SIMPLEX
3946 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
3947 #endif
3948 #ifdef IFF_LINK0
3949 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
3950 #endif
3951 #ifdef IFF_LINK1
3952 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
3953 #endif
3954 #ifdef IFF_LINK2
3955 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
3956 #endif
3957 { 0, 0 }
3960 static Lisp_Object
3961 network_interface_info (Lisp_Object ifname)
3963 struct ifreq rq;
3964 Lisp_Object res = Qnil;
3965 Lisp_Object elt;
3966 int s;
3967 bool any = 0;
3968 ptrdiff_t count;
3969 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3970 && defined HAVE_GETIFADDRS && defined LLADDR)
3971 struct ifaddrs *ifap;
3972 #endif
3974 CHECK_STRING (ifname);
3976 if (sizeof rq.ifr_name <= SBYTES (ifname))
3977 error ("interface name too long");
3978 lispstpcpy (rq.ifr_name, ifname);
3980 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3981 if (s < 0)
3982 return Qnil;
3983 count = SPECPDL_INDEX ();
3984 record_unwind_protect_int (close_file_unwind, s);
3986 elt = Qnil;
3987 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3988 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3990 int flags = rq.ifr_flags;
3991 const struct ifflag_def *fp;
3992 int fnum;
3994 /* If flags is smaller than int (i.e. short) it may have the high bit set
3995 due to IFF_MULTICAST. In that case, sign extending it into
3996 an int is wrong. */
3997 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3998 flags = (unsigned short) rq.ifr_flags;
4000 any = 1;
4001 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4003 if (flags & fp->flag_bit)
4005 elt = Fcons (intern (fp->flag_sym), elt);
4006 flags -= fp->flag_bit;
4009 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
4011 if (flags & 1)
4013 elt = Fcons (make_number (fnum), elt);
4017 #endif
4018 res = Fcons (elt, res);
4020 elt = Qnil;
4021 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4022 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4024 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4025 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4026 int n;
4028 any = 1;
4029 for (n = 0; n < 6; n++)
4030 p->contents[n] = make_number (((unsigned char *)
4031 &rq.ifr_hwaddr.sa_data[0])
4032 [n]);
4033 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4035 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4036 if (getifaddrs (&ifap) != -1)
4038 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4039 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4040 struct ifaddrs *it;
4042 for (it = ifap; it != NULL; it = it->ifa_next)
4044 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
4045 unsigned char linkaddr[6];
4046 int n;
4048 if (it->ifa_addr->sa_family != AF_LINK
4049 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4050 || sdl->sdl_alen != 6)
4051 continue;
4053 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4054 for (n = 0; n < 6; n++)
4055 p->contents[n] = make_number (linkaddr[n]);
4057 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4058 break;
4061 #ifdef HAVE_FREEIFADDRS
4062 freeifaddrs (ifap);
4063 #endif
4065 #endif /* HAVE_GETIFADDRS && LLADDR */
4067 res = Fcons (elt, res);
4069 elt = Qnil;
4070 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4071 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4073 any = 1;
4074 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4075 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4076 #else
4077 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4078 #endif
4080 #endif
4081 res = Fcons (elt, res);
4083 elt = Qnil;
4084 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4085 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4087 any = 1;
4088 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4090 #endif
4091 res = Fcons (elt, res);
4093 elt = Qnil;
4094 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4095 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4097 any = 1;
4098 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4100 #endif
4101 res = Fcons (elt, res);
4103 return unbind_to (count, any ? res : Qnil);
4105 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4106 #endif /* defined (HAVE_NET_IF_H) */
4108 DEFUN ("network-interface-list", Fnetwork_interface_list,
4109 Snetwork_interface_list, 0, 0, 0,
4110 doc: /* Return an alist of all network interfaces and their network address.
4111 Each element is a cons, the car of which is a string containing the
4112 interface name, and the cdr is the network address in internal
4113 format; see the description of ADDRESS in `make-network-process'.
4115 If the information is not available, return nil. */)
4116 (void)
4118 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4119 return network_interface_list ();
4120 #else
4121 return Qnil;
4122 #endif
4125 DEFUN ("network-interface-info", Fnetwork_interface_info,
4126 Snetwork_interface_info, 1, 1, 0,
4127 doc: /* Return information about network interface named IFNAME.
4128 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4129 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4130 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4131 FLAGS is the current flags of the interface.
4133 Data that is unavailable is returned as nil. */)
4134 (Lisp_Object ifname)
4136 #if ((defined HAVE_NET_IF_H \
4137 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4138 || defined SIOCGIFFLAGS)) \
4139 || defined WINDOWSNT)
4140 return network_interface_info (ifname);
4141 #else
4142 return Qnil;
4143 #endif
4146 /* If program file NAME starts with /: for quoting a magic
4147 name, remove that, preserving the multibyteness of NAME. */
4149 Lisp_Object
4150 remove_slash_colon (Lisp_Object name)
4152 return
4153 ((SBYTES (name) > 2 && SREF (name, 0) == '/' && SREF (name, 1) == ':')
4154 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
4155 SBYTES (name) - 2, STRING_MULTIBYTE (name))
4156 : name);
4159 /* Turn off input and output for process PROC. */
4161 static void
4162 deactivate_process (Lisp_Object proc)
4164 int inchannel;
4165 struct Lisp_Process *p = XPROCESS (proc);
4166 int i;
4168 #ifdef HAVE_GNUTLS
4169 /* Delete GnuTLS structures in PROC, if any. */
4170 emacs_gnutls_deinit (proc);
4171 #endif /* HAVE_GNUTLS */
4173 if (p->read_output_delay > 0)
4175 if (--process_output_delay_count < 0)
4176 process_output_delay_count = 0;
4177 p->read_output_delay = 0;
4178 p->read_output_skip = 0;
4181 /* Beware SIGCHLD hereabouts. */
4183 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4184 close_process_fd (&p->open_fd[i]);
4186 inchannel = p->infd;
4187 if (inchannel >= 0)
4189 p->infd = -1;
4190 p->outfd = -1;
4191 #ifdef DATAGRAM_SOCKETS
4192 if (DATAGRAM_CHAN_P (inchannel))
4194 xfree (datagram_address[inchannel].sa);
4195 datagram_address[inchannel].sa = 0;
4196 datagram_address[inchannel].len = 0;
4198 #endif
4199 chan_process[inchannel] = Qnil;
4200 FD_CLR (inchannel, &input_wait_mask);
4201 FD_CLR (inchannel, &non_keyboard_wait_mask);
4202 #ifdef NON_BLOCKING_CONNECT
4203 if (FD_ISSET (inchannel, &connect_wait_mask))
4205 FD_CLR (inchannel, &connect_wait_mask);
4206 FD_CLR (inchannel, &write_mask);
4207 if (--num_pending_connects < 0)
4208 emacs_abort ();
4210 #endif
4211 if (inchannel == max_process_desc)
4213 /* We just closed the highest-numbered process input descriptor,
4214 so recompute the highest-numbered one now. */
4215 int i = inchannel;
4217 i--;
4218 while (0 <= i && NILP (chan_process[i]));
4220 max_process_desc = i;
4226 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4227 0, 4, 0,
4228 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4229 It is given to their filter functions.
4230 Optional argument PROCESS means do not return until output has been
4231 received from PROCESS.
4233 Optional second argument SECONDS and third argument MILLISEC
4234 specify a timeout; return after that much time even if there is
4235 no subprocess output. If SECONDS is a floating point number,
4236 it specifies a fractional number of seconds to wait.
4237 The MILLISEC argument is obsolete and should be avoided.
4239 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4240 from PROCESS only, suspending reading output from other processes.
4241 If JUST-THIS-ONE is an integer, don't run any timers either.
4242 Return non-nil if we received any output from PROCESS (or, if PROCESS
4243 is nil, from any process) before the timeout expired. */)
4244 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4246 intmax_t secs;
4247 int nsecs;
4249 if (! NILP (process))
4250 CHECK_PROCESS (process);
4251 else
4252 just_this_one = Qnil;
4254 if (!NILP (millisec))
4255 { /* Obsolete calling convention using integers rather than floats. */
4256 CHECK_NUMBER (millisec);
4257 if (NILP (seconds))
4258 seconds = make_float (XINT (millisec) / 1000.0);
4259 else
4261 CHECK_NUMBER (seconds);
4262 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4266 secs = 0;
4267 nsecs = -1;
4269 if (!NILP (seconds))
4271 if (INTEGERP (seconds))
4273 if (XINT (seconds) > 0)
4275 secs = XINT (seconds);
4276 nsecs = 0;
4279 else if (FLOATP (seconds))
4281 if (XFLOAT_DATA (seconds) > 0)
4283 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4284 secs = min (t.tv_sec, WAIT_READING_MAX);
4285 nsecs = t.tv_nsec;
4288 else
4289 wrong_type_argument (Qnumberp, seconds);
4291 else if (! NILP (process))
4292 nsecs = 0;
4294 return
4295 ((wait_reading_process_output (secs, nsecs, 0, 0,
4296 Qnil,
4297 !NILP (process) ? XPROCESS (process) : NULL,
4298 (NILP (just_this_one) ? 0
4299 : !INTEGERP (just_this_one) ? 1 : -1))
4300 <= 0)
4301 ? Qnil : Qt);
4304 /* Accept a connection for server process SERVER on CHANNEL. */
4306 static EMACS_INT connect_counter = 0;
4308 static void
4309 server_accept_connection (Lisp_Object server, int channel)
4311 Lisp_Object proc, caller, name, buffer;
4312 Lisp_Object contact, host, service;
4313 struct Lisp_Process *ps = XPROCESS (server);
4314 struct Lisp_Process *p;
4315 int s;
4316 union u_sockaddr {
4317 struct sockaddr sa;
4318 struct sockaddr_in in;
4319 #ifdef AF_INET6
4320 struct sockaddr_in6 in6;
4321 #endif
4322 #ifdef HAVE_LOCAL_SOCKETS
4323 struct sockaddr_un un;
4324 #endif
4325 } saddr;
4326 socklen_t len = sizeof saddr;
4327 ptrdiff_t count;
4329 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4331 if (s < 0)
4333 int code = errno;
4335 if (code == EAGAIN)
4336 return;
4337 #ifdef EWOULDBLOCK
4338 if (code == EWOULDBLOCK)
4339 return;
4340 #endif
4342 if (!NILP (ps->log))
4343 call3 (ps->log, server, Qnil,
4344 concat3 (build_string ("accept failed with code"),
4345 Fnumber_to_string (make_number (code)),
4346 build_string ("\n")));
4347 return;
4350 count = SPECPDL_INDEX ();
4351 record_unwind_protect_int (close_file_unwind, s);
4353 connect_counter++;
4355 /* Setup a new process to handle the connection. */
4357 /* Generate a unique identification of the caller, and build contact
4358 information for this process. */
4359 host = Qt;
4360 service = Qnil;
4361 switch (saddr.sa.sa_family)
4363 case AF_INET:
4365 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4367 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4368 host = CALLN (Fformat, ipv4_format,
4369 make_number (ip[0]), make_number (ip[1]),
4370 make_number (ip[2]), make_number (ip[3]));
4371 service = make_number (ntohs (saddr.in.sin_port));
4372 AUTO_STRING (caller_format, " <%s:%d>");
4373 caller = CALLN (Fformat, caller_format, host, service);
4375 break;
4377 #ifdef AF_INET6
4378 case AF_INET6:
4380 Lisp_Object args[9];
4381 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4382 int i;
4384 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4385 args[0] = ipv6_format;
4386 for (i = 0; i < 8; i++)
4387 args[i + 1] = make_number (ntohs (ip6[i]));
4388 host = CALLMANY (Fformat, args);
4389 service = make_number (ntohs (saddr.in.sin_port));
4390 AUTO_STRING (caller_format, " <[%s]:%d>");
4391 caller = CALLN (Fformat, caller_format, host, service);
4393 break;
4394 #endif
4396 #ifdef HAVE_LOCAL_SOCKETS
4397 case AF_LOCAL:
4398 #endif
4399 default:
4400 caller = Fnumber_to_string (make_number (connect_counter));
4401 AUTO_STRING (space_less_than, " <");
4402 AUTO_STRING (greater_than, ">");
4403 caller = concat3 (space_less_than, caller, greater_than);
4404 break;
4407 /* Create a new buffer name for this process if it doesn't have a
4408 filter. The new buffer name is based on the buffer name or
4409 process name of the server process concatenated with the caller
4410 identification. */
4412 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4413 || EQ (ps->filter, Qt)))
4414 buffer = Qnil;
4415 else
4417 buffer = ps->buffer;
4418 if (!NILP (buffer))
4419 buffer = Fbuffer_name (buffer);
4420 else
4421 buffer = ps->name;
4422 if (!NILP (buffer))
4424 buffer = concat2 (buffer, caller);
4425 buffer = Fget_buffer_create (buffer);
4429 /* Generate a unique name for the new server process. Combine the
4430 server process name with the caller identification. */
4432 name = concat2 (ps->name, caller);
4433 proc = make_process (name);
4435 chan_process[s] = proc;
4437 fcntl (s, F_SETFL, O_NONBLOCK);
4439 p = XPROCESS (proc);
4441 /* Build new contact information for this setup. */
4442 contact = Fcopy_sequence (ps->childp);
4443 contact = Fplist_put (contact, QCserver, Qnil);
4444 contact = Fplist_put (contact, QChost, host);
4445 if (!NILP (service))
4446 contact = Fplist_put (contact, QCservice, service);
4447 contact = Fplist_put (contact, QCremote,
4448 conv_sockaddr_to_lisp (&saddr.sa, len));
4449 #ifdef HAVE_GETSOCKNAME
4450 len = sizeof saddr;
4451 if (getsockname (s, &saddr.sa, &len) == 0)
4452 contact = Fplist_put (contact, QClocal,
4453 conv_sockaddr_to_lisp (&saddr.sa, len));
4454 #endif
4456 pset_childp (p, contact);
4457 pset_plist (p, Fcopy_sequence (ps->plist));
4458 pset_type (p, Qnetwork);
4460 pset_buffer (p, buffer);
4461 pset_sentinel (p, ps->sentinel);
4462 pset_filter (p, ps->filter);
4463 pset_command (p, Qnil);
4464 p->pid = 0;
4466 /* Discard the unwind protect for closing S. */
4467 specpdl_ptr = specpdl + count;
4469 p->open_fd[SUBPROCESS_STDIN] = s;
4470 p->infd = s;
4471 p->outfd = s;
4472 pset_status (p, Qrun);
4474 /* Client processes for accepted connections are not stopped initially. */
4475 if (!EQ (p->filter, Qt))
4477 FD_SET (s, &input_wait_mask);
4478 FD_SET (s, &non_keyboard_wait_mask);
4481 if (s > max_process_desc)
4482 max_process_desc = s;
4484 /* Setup coding system for new process based on server process.
4485 This seems to be the proper thing to do, as the coding system
4486 of the new process should reflect the settings at the time the
4487 server socket was opened; not the current settings. */
4489 pset_decode_coding_system (p, ps->decode_coding_system);
4490 pset_encode_coding_system (p, ps->encode_coding_system);
4491 setup_process_coding_systems (proc);
4493 pset_decoding_buf (p, empty_unibyte_string);
4494 p->decoding_carryover = 0;
4495 pset_encoding_buf (p, empty_unibyte_string);
4497 p->inherit_coding_system_flag
4498 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4500 AUTO_STRING (dash, "-");
4501 AUTO_STRING (nl, "\n");
4502 Lisp_Object host_string = STRINGP (host) ? host : dash;
4504 if (!NILP (ps->log))
4506 AUTO_STRING (accept_from, "accept from ");
4507 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4510 AUTO_STRING (open_from, "open from ");
4511 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4514 /* This variable is different from waiting_for_input in keyboard.c.
4515 It is used to communicate to a lisp process-filter/sentinel (via the
4516 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4517 for user-input when that process-filter was called.
4518 waiting_for_input cannot be used as that is by definition 0 when
4519 lisp code is being evalled.
4520 This is also used in record_asynch_buffer_change.
4521 For that purpose, this must be 0
4522 when not inside wait_reading_process_output. */
4523 static int waiting_for_user_input_p;
4525 static void
4526 wait_reading_process_output_unwind (int data)
4528 waiting_for_user_input_p = data;
4531 /* This is here so breakpoints can be put on it. */
4532 static void
4533 wait_reading_process_output_1 (void)
4537 /* Read and dispose of subprocess output while waiting for timeout to
4538 elapse and/or keyboard input to be available.
4540 TIME_LIMIT is:
4541 timeout in seconds
4542 If negative, gobble data immediately available but don't wait for any.
4544 NSECS is:
4545 an additional duration to wait, measured in nanoseconds
4546 If TIME_LIMIT is zero, then:
4547 If NSECS == 0, there is no limit.
4548 If NSECS > 0, the timeout consists of NSECS only.
4549 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4551 READ_KBD is:
4552 0 to ignore keyboard input, or
4553 1 to return when input is available, or
4554 -1 meaning caller will actually read the input, so don't throw to
4555 the quit handler, or
4557 DO_DISPLAY means redisplay should be done to show subprocess
4558 output that arrives.
4560 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4561 (and gobble terminal input into the buffer if any arrives).
4563 If WAIT_PROC is specified, wait until something arrives from that
4564 process.
4566 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4567 (suspending output from other processes). A negative value
4568 means don't run any timers either.
4570 Return positive if we received input from WAIT_PROC (or from any
4571 process if WAIT_PROC is null), zero if we attempted to receive
4572 input but got none, and negative if we didn't even try. */
4575 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4576 bool do_display,
4577 Lisp_Object wait_for_cell,
4578 struct Lisp_Process *wait_proc, int just_wait_proc)
4580 int channel, nfds;
4581 fd_set Available;
4582 fd_set Writeok;
4583 bool check_write;
4584 int check_delay;
4585 bool no_avail;
4586 int xerrno;
4587 Lisp_Object proc;
4588 struct timespec timeout, end_time, timer_delay;
4589 struct timespec got_output_end_time = invalid_timespec ();
4590 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
4591 int got_some_output = -1;
4592 ptrdiff_t count = SPECPDL_INDEX ();
4594 /* Close to the current time if known, an invalid timespec otherwise. */
4595 struct timespec now = invalid_timespec ();
4597 FD_ZERO (&Available);
4598 FD_ZERO (&Writeok);
4600 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4601 && !(CONSP (wait_proc->status)
4602 && EQ (XCAR (wait_proc->status), Qexit)))
4603 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4605 record_unwind_protect_int (wait_reading_process_output_unwind,
4606 waiting_for_user_input_p);
4607 waiting_for_user_input_p = read_kbd;
4609 if (TYPE_MAXIMUM (time_t) < time_limit)
4610 time_limit = TYPE_MAXIMUM (time_t);
4612 if (time_limit < 0 || nsecs < 0)
4613 wait = MINIMUM;
4614 else if (time_limit > 0 || nsecs > 0)
4616 wait = TIMEOUT;
4617 now = current_timespec ();
4618 end_time = timespec_add (now, make_timespec (time_limit, nsecs));
4620 else
4621 wait = INFINITY;
4623 while (1)
4625 bool process_skipped = false;
4627 /* If calling from keyboard input, do not quit
4628 since we want to return C-g as an input character.
4629 Otherwise, do pending quit if requested. */
4630 if (read_kbd >= 0)
4631 QUIT;
4632 else if (pending_signals)
4633 process_pending_signals ();
4635 /* Exit now if the cell we're waiting for became non-nil. */
4636 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4637 break;
4639 /* Compute time from now till when time limit is up. */
4640 /* Exit if already run out. */
4641 if (wait == TIMEOUT)
4643 if (!timespec_valid_p (now))
4644 now = current_timespec ();
4645 if (timespec_cmp (end_time, now) <= 0)
4646 break;
4647 timeout = timespec_sub (end_time, now);
4649 else
4650 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
4652 /* Normally we run timers here.
4653 But not if wait_for_cell; in those cases,
4654 the wait is supposed to be short,
4655 and those callers cannot handle running arbitrary Lisp code here. */
4656 if (NILP (wait_for_cell)
4657 && just_wait_proc >= 0)
4661 unsigned old_timers_run = timers_run;
4662 struct buffer *old_buffer = current_buffer;
4663 Lisp_Object old_window = selected_window;
4665 timer_delay = timer_check ();
4667 /* If a timer has run, this might have changed buffers
4668 an alike. Make read_key_sequence aware of that. */
4669 if (timers_run != old_timers_run
4670 && (old_buffer != current_buffer
4671 || !EQ (old_window, selected_window))
4672 && waiting_for_user_input_p == -1)
4673 record_asynch_buffer_change ();
4675 if (timers_run != old_timers_run && do_display)
4676 /* We must retry, since a timer may have requeued itself
4677 and that could alter the time_delay. */
4678 redisplay_preserve_echo_area (9);
4679 else
4680 break;
4682 while (!detect_input_pending ());
4684 /* If there is unread keyboard input, also return. */
4685 if (read_kbd != 0
4686 && requeued_events_pending_p ())
4687 break;
4689 /* This is so a breakpoint can be put here. */
4690 if (!timespec_valid_p (timer_delay))
4691 wait_reading_process_output_1 ();
4694 /* Cause C-g and alarm signals to take immediate action,
4695 and cause input available signals to zero out timeout.
4697 It is important that we do this before checking for process
4698 activity. If we get a SIGCHLD after the explicit checks for
4699 process activity, timeout is the only way we will know. */
4700 if (read_kbd < 0)
4701 set_waiting_for_input (&timeout);
4703 /* If status of something has changed, and no input is
4704 available, notify the user of the change right away. After
4705 this explicit check, we'll let the SIGCHLD handler zap
4706 timeout to get our attention. */
4707 if (update_tick != process_tick)
4709 fd_set Atemp;
4710 fd_set Ctemp;
4712 if (kbd_on_hold_p ())
4713 FD_ZERO (&Atemp);
4714 else
4715 Atemp = input_wait_mask;
4716 Ctemp = write_mask;
4718 timeout = make_timespec (0, 0);
4719 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4720 &Atemp,
4721 #ifdef NON_BLOCKING_CONNECT
4722 (num_pending_connects > 0 ? &Ctemp : NULL),
4723 #else
4724 NULL,
4725 #endif
4726 NULL, &timeout, NULL)
4727 <= 0))
4729 /* It's okay for us to do this and then continue with
4730 the loop, since timeout has already been zeroed out. */
4731 clear_waiting_for_input ();
4732 got_some_output = status_notify (NULL, wait_proc);
4733 if (do_display) redisplay_preserve_echo_area (13);
4737 /* Don't wait for output from a non-running process. Just
4738 read whatever data has already been received. */
4739 if (wait_proc && wait_proc->raw_status_new)
4740 update_status (wait_proc);
4741 if (wait_proc
4742 && ! EQ (wait_proc->status, Qrun)
4743 && ! EQ (wait_proc->status, Qconnect))
4745 bool read_some_bytes = false;
4747 clear_waiting_for_input ();
4749 /* If data can be read from the process, do so until exhausted. */
4750 if (wait_proc->infd >= 0)
4752 XSETPROCESS (proc, wait_proc);
4754 while (true)
4756 int nread = read_process_output (proc, wait_proc->infd);
4757 if (nread < 0)
4759 if (errno == EIO || errno == EAGAIN)
4760 break;
4761 #ifdef EWOULDBLOCK
4762 if (errno == EWOULDBLOCK)
4763 break;
4764 #endif
4766 else
4768 if (got_some_output < nread)
4769 got_some_output = nread;
4770 if (nread == 0)
4771 break;
4772 read_some_bytes = true;
4777 if (read_some_bytes && do_display)
4778 redisplay_preserve_echo_area (10);
4780 break;
4783 /* Wait till there is something to do. */
4785 if (wait_proc && just_wait_proc)
4787 if (wait_proc->infd < 0) /* Terminated. */
4788 break;
4789 FD_SET (wait_proc->infd, &Available);
4790 check_delay = 0;
4791 check_write = 0;
4793 else if (!NILP (wait_for_cell))
4795 Available = non_process_wait_mask;
4796 check_delay = 0;
4797 check_write = 0;
4799 else
4801 if (! read_kbd)
4802 Available = non_keyboard_wait_mask;
4803 else
4804 Available = input_wait_mask;
4805 Writeok = write_mask;
4806 check_delay = wait_proc ? 0 : process_output_delay_count;
4807 check_write = true;
4810 /* If frame size has changed or the window is newly mapped,
4811 redisplay now, before we start to wait. There is a race
4812 condition here; if a SIGIO arrives between now and the select
4813 and indicates that a frame is trashed, the select may block
4814 displaying a trashed screen. */
4815 if (frame_garbaged && do_display)
4817 clear_waiting_for_input ();
4818 redisplay_preserve_echo_area (11);
4819 if (read_kbd < 0)
4820 set_waiting_for_input (&timeout);
4823 /* Skip the `select' call if input is available and we're
4824 waiting for keyboard input or a cell change (which can be
4825 triggered by processing X events). In the latter case, set
4826 nfds to 1 to avoid breaking the loop. */
4827 no_avail = 0;
4828 if ((read_kbd || !NILP (wait_for_cell))
4829 && detect_input_pending ())
4831 nfds = read_kbd ? 0 : 1;
4832 no_avail = 1;
4833 FD_ZERO (&Available);
4835 else
4837 /* Set the timeout for adaptive read buffering if any
4838 process has non-zero read_output_skip and non-zero
4839 read_output_delay, and we are not reading output for a
4840 specific process. It is not executed if
4841 Vprocess_adaptive_read_buffering is nil. */
4842 if (process_output_skip && check_delay > 0)
4844 int adaptive_nsecs = timeout.tv_nsec;
4845 if (timeout.tv_sec > 0 || adaptive_nsecs > READ_OUTPUT_DELAY_MAX)
4846 adaptive_nsecs = READ_OUTPUT_DELAY_MAX;
4847 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4849 proc = chan_process[channel];
4850 if (NILP (proc))
4851 continue;
4852 /* Find minimum non-zero read_output_delay among the
4853 processes with non-zero read_output_skip. */
4854 if (XPROCESS (proc)->read_output_delay > 0)
4856 check_delay--;
4857 if (!XPROCESS (proc)->read_output_skip)
4858 continue;
4859 FD_CLR (channel, &Available);
4860 process_skipped = true;
4861 XPROCESS (proc)->read_output_skip = 0;
4862 if (XPROCESS (proc)->read_output_delay < adaptive_nsecs)
4863 adaptive_nsecs = XPROCESS (proc)->read_output_delay;
4866 timeout = make_timespec (0, adaptive_nsecs);
4867 process_output_skip = 0;
4870 /* If we've got some output and haven't limited our timeout
4871 with adaptive read buffering, limit it. */
4872 if (got_some_output > 0 && !process_skipped
4873 && (timeout.tv_sec
4874 || timeout.tv_nsec > READ_OUTPUT_DELAY_INCREMENT))
4875 timeout = make_timespec (0, READ_OUTPUT_DELAY_INCREMENT);
4878 if (NILP (wait_for_cell) && just_wait_proc >= 0
4879 && timespec_valid_p (timer_delay)
4880 && timespec_cmp (timer_delay, timeout) < 0)
4882 if (!timespec_valid_p (now))
4883 now = current_timespec ();
4884 struct timespec timeout_abs = timespec_add (now, timeout);
4885 if (!timespec_valid_p (got_output_end_time)
4886 || timespec_cmp (timeout_abs, got_output_end_time) < 0)
4887 got_output_end_time = timeout_abs;
4888 timeout = timer_delay;
4890 else
4891 got_output_end_time = invalid_timespec ();
4893 /* NOW can become inaccurate if time can pass during pselect. */
4894 if (timeout.tv_sec > 0 || timeout.tv_nsec > 0)
4895 now = invalid_timespec ();
4897 #if defined (HAVE_NS)
4898 nfds = ns_select
4899 #elif defined (HAVE_GLIB)
4900 nfds = xg_select
4901 #else
4902 nfds = pselect
4903 #endif
4904 (max (max_process_desc, max_input_desc) + 1,
4905 &Available,
4906 (check_write ? &Writeok : 0),
4907 NULL, &timeout, NULL);
4909 #ifdef HAVE_GNUTLS
4910 /* GnuTLS buffers data internally. In lowat mode it leaves
4911 some data in the TCP buffers so that select works, but
4912 with custom pull/push functions we need to check if some
4913 data is available in the buffers manually. */
4914 if (nfds == 0)
4916 if (! wait_proc)
4918 /* We're not waiting on a specific process, so loop
4919 through all the channels and check for data.
4920 This is a workaround needed for some versions of
4921 the gnutls library -- 2.12.14 has been confirmed
4922 to need it. See
4923 http://comments.gmane.org/gmane.emacs.devel/145074 */
4924 for (channel = 0; channel < FD_SETSIZE; ++channel)
4925 if (! NILP (chan_process[channel]))
4927 struct Lisp_Process *p =
4928 XPROCESS (chan_process[channel]);
4929 if (p && p->gnutls_p && p->gnutls_state
4930 && ((emacs_gnutls_record_check_pending
4931 (p->gnutls_state))
4932 > 0))
4934 nfds++;
4935 eassert (p->infd == channel);
4936 FD_SET (p->infd, &Available);
4940 else
4942 /* Check this specific channel. */
4943 if (wait_proc->gnutls_p /* Check for valid process. */
4944 && wait_proc->gnutls_state
4945 /* Do we have pending data? */
4946 && ((emacs_gnutls_record_check_pending
4947 (wait_proc->gnutls_state))
4948 > 0))
4950 nfds = 1;
4951 eassert (0 <= wait_proc->infd);
4952 /* Set to Available. */
4953 FD_SET (wait_proc->infd, &Available);
4957 #endif
4960 xerrno = errno;
4962 /* Make C-g and alarm signals set flags again. */
4963 clear_waiting_for_input ();
4965 /* If we woke up due to SIGWINCH, actually change size now. */
4966 do_pending_window_change (0);
4968 if (nfds == 0)
4970 /* Exit the main loop if we've passed the requested timeout,
4971 or aren't skipping processes and got some output and
4972 haven't lowered our timeout due to timers or SIGIO and
4973 have waited a long amount of time due to repeated
4974 timers. */
4975 if (wait < TIMEOUT)
4976 break;
4977 struct timespec cmp_time
4978 = (wait == TIMEOUT
4979 ? end_time
4980 : (!process_skipped && got_some_output > 0
4981 && (timeout.tv_sec > 0 || timeout.tv_nsec > 0))
4982 ? got_output_end_time
4983 : invalid_timespec ());
4984 if (timespec_valid_p (cmp_time))
4986 now = current_timespec ();
4987 if (timespec_cmp (cmp_time, now) <= 0)
4988 break;
4992 if (nfds < 0)
4994 if (xerrno == EINTR)
4995 no_avail = 1;
4996 else if (xerrno == EBADF)
4997 emacs_abort ();
4998 else
4999 report_file_errno ("Failed select", Qnil, xerrno);
5002 /* Check for keyboard input. */
5003 /* If there is any, return immediately
5004 to give it higher priority than subprocesses. */
5006 if (read_kbd != 0)
5008 unsigned old_timers_run = timers_run;
5009 struct buffer *old_buffer = current_buffer;
5010 Lisp_Object old_window = selected_window;
5011 bool leave = false;
5013 if (detect_input_pending_run_timers (do_display))
5015 swallow_events (do_display);
5016 if (detect_input_pending_run_timers (do_display))
5017 leave = true;
5020 /* If a timer has run, this might have changed buffers
5021 an alike. Make read_key_sequence aware of that. */
5022 if (timers_run != old_timers_run
5023 && waiting_for_user_input_p == -1
5024 && (old_buffer != current_buffer
5025 || !EQ (old_window, selected_window)))
5026 record_asynch_buffer_change ();
5028 if (leave)
5029 break;
5032 /* If there is unread keyboard input, also return. */
5033 if (read_kbd != 0
5034 && requeued_events_pending_p ())
5035 break;
5037 /* If we are not checking for keyboard input now,
5038 do process events (but don't run any timers).
5039 This is so that X events will be processed.
5040 Otherwise they may have to wait until polling takes place.
5041 That would causes delays in pasting selections, for example.
5043 (We used to do this only if wait_for_cell.) */
5044 if (read_kbd == 0 && detect_input_pending ())
5046 swallow_events (do_display);
5047 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5048 if (detect_input_pending ())
5049 break;
5050 #endif
5053 /* Exit now if the cell we're waiting for became non-nil. */
5054 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5055 break;
5057 #ifdef USABLE_SIGIO
5058 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5059 go read it. This can happen with X on BSD after logging out.
5060 In that case, there really is no input and no SIGIO,
5061 but select says there is input. */
5063 if (read_kbd && interrupt_input
5064 && keyboard_bit_set (&Available) && ! noninteractive)
5065 handle_input_available_signal (SIGIO);
5066 #endif
5068 /* If checking input just got us a size-change event from X,
5069 obey it now if we should. */
5070 if (read_kbd || ! NILP (wait_for_cell))
5071 do_pending_window_change (0);
5073 /* Check for data from a process. */
5074 if (no_avail || nfds == 0)
5075 continue;
5077 for (channel = 0; channel <= max_input_desc; ++channel)
5079 struct fd_callback_data *d = &fd_callback_info[channel];
5080 if (d->func
5081 && ((d->condition & FOR_READ
5082 && FD_ISSET (channel, &Available))
5083 || (d->condition & FOR_WRITE
5084 && FD_ISSET (channel, &write_mask))))
5085 d->func (channel, d->data);
5088 for (channel = 0; channel <= max_process_desc; channel++)
5090 if (FD_ISSET (channel, &Available)
5091 && FD_ISSET (channel, &non_keyboard_wait_mask)
5092 && !FD_ISSET (channel, &non_process_wait_mask))
5094 int nread;
5096 /* If waiting for this channel, arrange to return as
5097 soon as no more input to be processed. No more
5098 waiting. */
5099 proc = chan_process[channel];
5100 if (NILP (proc))
5101 continue;
5103 /* If this is a server stream socket, accept connection. */
5104 if (EQ (XPROCESS (proc)->status, Qlisten))
5106 server_accept_connection (proc, channel);
5107 continue;
5110 /* Read data from the process, starting with our
5111 buffered-ahead character if we have one. */
5113 nread = read_process_output (proc, channel);
5114 if ((!wait_proc || wait_proc == XPROCESS (proc))
5115 && got_some_output < nread)
5116 got_some_output = nread;
5117 if (nread > 0)
5119 /* Vacuum up any leftovers without waiting. */
5120 if (wait_proc == XPROCESS (proc))
5121 wait = MINIMUM;
5122 /* Since read_process_output can run a filter,
5123 which can call accept-process-output,
5124 don't try to read from any other processes
5125 before doing the select again. */
5126 FD_ZERO (&Available);
5128 if (do_display)
5129 redisplay_preserve_echo_area (12);
5131 #ifdef EWOULDBLOCK
5132 else if (nread == -1 && errno == EWOULDBLOCK)
5134 #endif
5135 else if (nread == -1 && errno == EAGAIN)
5137 #ifdef WINDOWSNT
5138 /* FIXME: Is this special case still needed? */
5139 /* Note that we cannot distinguish between no input
5140 available now and a closed pipe.
5141 With luck, a closed pipe will be accompanied by
5142 subprocess termination and SIGCHLD. */
5143 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5144 && !PIPECONN_P (proc))
5146 #endif
5147 #ifdef HAVE_PTYS
5148 /* On some OSs with ptys, when the process on one end of
5149 a pty exits, the other end gets an error reading with
5150 errno = EIO instead of getting an EOF (0 bytes read).
5151 Therefore, if we get an error reading and errno =
5152 EIO, just continue, because the child process has
5153 exited and should clean itself up soon (e.g. when we
5154 get a SIGCHLD). */
5155 else if (nread == -1 && errno == EIO)
5157 struct Lisp_Process *p = XPROCESS (proc);
5159 /* Clear the descriptor now, so we only raise the
5160 signal once. */
5161 FD_CLR (channel, &input_wait_mask);
5162 FD_CLR (channel, &non_keyboard_wait_mask);
5164 if (p->pid == -2)
5166 /* If the EIO occurs on a pty, the SIGCHLD handler's
5167 waitpid call will not find the process object to
5168 delete. Do it here. */
5169 p->tick = ++process_tick;
5170 pset_status (p, Qfailed);
5173 #endif /* HAVE_PTYS */
5174 /* If we can detect process termination, don't consider the
5175 process gone just because its pipe is closed. */
5176 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5177 && !PIPECONN_P (proc))
5179 else if (nread == 0 && PIPECONN_P (proc))
5181 /* Preserve status of processes already terminated. */
5182 XPROCESS (proc)->tick = ++process_tick;
5183 deactivate_process (proc);
5184 if (EQ (XPROCESS (proc)->status, Qrun))
5185 pset_status (XPROCESS (proc),
5186 list2 (Qexit, make_number (0)));
5188 else
5190 /* Preserve status of processes already terminated. */
5191 XPROCESS (proc)->tick = ++process_tick;
5192 deactivate_process (proc);
5193 if (XPROCESS (proc)->raw_status_new)
5194 update_status (XPROCESS (proc));
5195 if (EQ (XPROCESS (proc)->status, Qrun))
5196 pset_status (XPROCESS (proc),
5197 list2 (Qexit, make_number (256)));
5200 #ifdef NON_BLOCKING_CONNECT
5201 if (FD_ISSET (channel, &Writeok)
5202 && FD_ISSET (channel, &connect_wait_mask))
5204 struct Lisp_Process *p;
5206 FD_CLR (channel, &connect_wait_mask);
5207 FD_CLR (channel, &write_mask);
5208 if (--num_pending_connects < 0)
5209 emacs_abort ();
5211 proc = chan_process[channel];
5212 if (NILP (proc))
5213 continue;
5215 p = XPROCESS (proc);
5217 #ifdef GNU_LINUX
5218 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5219 So only use it on systems where it is known to work. */
5221 socklen_t xlen = sizeof (xerrno);
5222 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5223 xerrno = errno;
5225 #else
5227 struct sockaddr pname;
5228 socklen_t pnamelen = sizeof (pname);
5230 /* If connection failed, getpeername will fail. */
5231 xerrno = 0;
5232 if (getpeername (channel, &pname, &pnamelen) < 0)
5234 /* Obtain connect failure code through error slippage. */
5235 char dummy;
5236 xerrno = errno;
5237 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5238 xerrno = errno;
5241 #endif
5242 if (xerrno)
5244 p->tick = ++process_tick;
5245 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5246 deactivate_process (proc);
5248 else
5250 pset_status (p, Qrun);
5251 /* Execute the sentinel here. If we had relied on
5252 status_notify to do it later, it will read input
5253 from the process before calling the sentinel. */
5254 exec_sentinel (proc, build_string ("open\n"));
5255 if (0 <= p->infd && !EQ (p->filter, Qt)
5256 && !EQ (p->command, Qt))
5258 FD_SET (p->infd, &input_wait_mask);
5259 FD_SET (p->infd, &non_keyboard_wait_mask);
5263 #endif /* NON_BLOCKING_CONNECT */
5264 } /* End for each file descriptor. */
5265 } /* End while exit conditions not met. */
5267 unbind_to (count, Qnil);
5269 /* If calling from keyboard input, do not quit
5270 since we want to return C-g as an input character.
5271 Otherwise, do pending quit if requested. */
5272 if (read_kbd >= 0)
5274 /* Prevent input_pending from remaining set if we quit. */
5275 clear_input_pending ();
5276 QUIT;
5279 return got_some_output;
5282 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5284 static Lisp_Object
5285 read_process_output_call (Lisp_Object fun_and_args)
5287 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5290 static Lisp_Object
5291 read_process_output_error_handler (Lisp_Object error_val)
5293 cmd_error_internal (error_val, "error in process filter: ");
5294 Vinhibit_quit = Qt;
5295 update_echo_area ();
5296 Fsleep_for (make_number (2), Qnil);
5297 return Qt;
5300 static void
5301 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5302 ssize_t nbytes,
5303 struct coding_system *coding);
5305 /* Read pending output from the process channel,
5306 starting with our buffered-ahead character if we have one.
5307 Yield number of decoded characters read.
5309 This function reads at most 4096 characters.
5310 If you want to read all available subprocess output,
5311 you must call it repeatedly until it returns zero.
5313 The characters read are decoded according to PROC's coding-system
5314 for decoding. */
5316 static int
5317 read_process_output (Lisp_Object proc, int channel)
5319 ssize_t nbytes;
5320 struct Lisp_Process *p = XPROCESS (proc);
5321 struct coding_system *coding = proc_decode_coding_system[channel];
5322 int carryover = p->decoding_carryover;
5323 enum { readmax = 4096 };
5324 ptrdiff_t count = SPECPDL_INDEX ();
5325 Lisp_Object odeactivate;
5326 char chars[sizeof coding->carryover + readmax];
5328 if (carryover)
5329 /* See the comment above. */
5330 memcpy (chars, SDATA (p->decoding_buf), carryover);
5332 #ifdef DATAGRAM_SOCKETS
5333 /* We have a working select, so proc_buffered_char is always -1. */
5334 if (DATAGRAM_CHAN_P (channel))
5336 socklen_t len = datagram_address[channel].len;
5337 nbytes = recvfrom (channel, chars + carryover, readmax,
5338 0, datagram_address[channel].sa, &len);
5340 else
5341 #endif
5343 bool buffered = proc_buffered_char[channel] >= 0;
5344 if (buffered)
5346 chars[carryover] = proc_buffered_char[channel];
5347 proc_buffered_char[channel] = -1;
5349 #ifdef HAVE_GNUTLS
5350 if (p->gnutls_p && p->gnutls_state)
5351 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5352 readmax - buffered);
5353 else
5354 #endif
5355 nbytes = emacs_read (channel, chars + carryover + buffered,
5356 readmax - buffered);
5357 if (nbytes > 0 && p->adaptive_read_buffering)
5359 int delay = p->read_output_delay;
5360 if (nbytes < 256)
5362 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5364 if (delay == 0)
5365 process_output_delay_count++;
5366 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5369 else if (delay > 0 && nbytes == readmax - buffered)
5371 delay -= READ_OUTPUT_DELAY_INCREMENT;
5372 if (delay == 0)
5373 process_output_delay_count--;
5375 p->read_output_delay = delay;
5376 if (delay)
5378 p->read_output_skip = 1;
5379 process_output_skip = 1;
5382 nbytes += buffered;
5383 nbytes += buffered && nbytes <= 0;
5386 p->decoding_carryover = 0;
5388 /* At this point, NBYTES holds number of bytes just received
5389 (including the one in proc_buffered_char[channel]). */
5390 if (nbytes <= 0)
5392 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5393 return nbytes;
5394 coding->mode |= CODING_MODE_LAST_BLOCK;
5397 /* Now set NBYTES how many bytes we must decode. */
5398 nbytes += carryover;
5400 odeactivate = Vdeactivate_mark;
5401 /* There's no good reason to let process filters change the current
5402 buffer, and many callers of accept-process-output, sit-for, and
5403 friends don't expect current-buffer to be changed from under them. */
5404 record_unwind_current_buffer ();
5406 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5408 /* Handling the process output should not deactivate the mark. */
5409 Vdeactivate_mark = odeactivate;
5411 unbind_to (count, Qnil);
5412 return nbytes;
5415 static void
5416 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5417 ssize_t nbytes,
5418 struct coding_system *coding)
5420 Lisp_Object outstream = p->filter;
5421 Lisp_Object text;
5422 bool outer_running_asynch_code = running_asynch_code;
5423 int waiting = waiting_for_user_input_p;
5425 /* No need to gcpro these, because all we do with them later
5426 is test them for EQness, and none of them should be a string. */
5427 #if 0
5428 Lisp_Object obuffer, okeymap;
5429 XSETBUFFER (obuffer, current_buffer);
5430 okeymap = BVAR (current_buffer, keymap);
5431 #endif
5433 /* We inhibit quit here instead of just catching it so that
5434 hitting ^G when a filter happens to be running won't screw
5435 it up. */
5436 specbind (Qinhibit_quit, Qt);
5437 specbind (Qlast_nonmenu_event, Qt);
5439 /* In case we get recursively called,
5440 and we already saved the match data nonrecursively,
5441 save the same match data in safely recursive fashion. */
5442 if (outer_running_asynch_code)
5444 Lisp_Object tem;
5445 /* Don't clobber the CURRENT match data, either! */
5446 tem = Fmatch_data (Qnil, Qnil, Qnil);
5447 restore_search_regs ();
5448 record_unwind_save_match_data ();
5449 Fset_match_data (tem, Qt);
5452 /* For speed, if a search happens within this code,
5453 save the match data in a special nonrecursive fashion. */
5454 running_asynch_code = 1;
5456 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5457 text = coding->dst_object;
5458 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5459 /* A new coding system might be found. */
5460 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5462 pset_decode_coding_system (p, Vlast_coding_system_used);
5464 /* Don't call setup_coding_system for
5465 proc_decode_coding_system[channel] here. It is done in
5466 detect_coding called via decode_coding above. */
5468 /* If a coding system for encoding is not yet decided, we set
5469 it as the same as coding-system for decoding.
5471 But, before doing that we must check if
5472 proc_encode_coding_system[p->outfd] surely points to a
5473 valid memory because p->outfd will be changed once EOF is
5474 sent to the process. */
5475 if (NILP (p->encode_coding_system) && p->outfd >= 0
5476 && proc_encode_coding_system[p->outfd])
5478 pset_encode_coding_system
5479 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5480 setup_coding_system (p->encode_coding_system,
5481 proc_encode_coding_system[p->outfd]);
5485 if (coding->carryover_bytes > 0)
5487 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5488 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5489 memcpy (SDATA (p->decoding_buf), coding->carryover,
5490 coding->carryover_bytes);
5491 p->decoding_carryover = coding->carryover_bytes;
5493 if (SBYTES (text) > 0)
5494 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5495 sometimes it's simply wrong to wrap (e.g. when called from
5496 accept-process-output). */
5497 internal_condition_case_1 (read_process_output_call,
5498 list3 (outstream, make_lisp_proc (p), text),
5499 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5500 read_process_output_error_handler);
5502 /* If we saved the match data nonrecursively, restore it now. */
5503 restore_search_regs ();
5504 running_asynch_code = outer_running_asynch_code;
5506 /* Restore waiting_for_user_input_p as it was
5507 when we were called, in case the filter clobbered it. */
5508 waiting_for_user_input_p = waiting;
5510 #if 0 /* Call record_asynch_buffer_change unconditionally,
5511 because we might have changed minor modes or other things
5512 that affect key bindings. */
5513 if (! EQ (Fcurrent_buffer (), obuffer)
5514 || ! EQ (current_buffer->keymap, okeymap))
5515 #endif
5516 /* But do it only if the caller is actually going to read events.
5517 Otherwise there's no need to make him wake up, and it could
5518 cause trouble (for example it would make sit_for return). */
5519 if (waiting_for_user_input_p == -1)
5520 record_asynch_buffer_change ();
5523 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5524 Sinternal_default_process_filter, 2, 2, 0,
5525 doc: /* Function used as default process filter.
5526 This inserts the process's output into its buffer, if there is one.
5527 Otherwise it discards the output. */)
5528 (Lisp_Object proc, Lisp_Object text)
5530 struct Lisp_Process *p;
5531 ptrdiff_t opoint;
5533 CHECK_PROCESS (proc);
5534 p = XPROCESS (proc);
5535 CHECK_STRING (text);
5537 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5539 Lisp_Object old_read_only;
5540 ptrdiff_t old_begv, old_zv;
5541 ptrdiff_t old_begv_byte, old_zv_byte;
5542 ptrdiff_t before, before_byte;
5543 ptrdiff_t opoint_byte;
5544 struct buffer *b;
5546 Fset_buffer (p->buffer);
5547 opoint = PT;
5548 opoint_byte = PT_BYTE;
5549 old_read_only = BVAR (current_buffer, read_only);
5550 old_begv = BEGV;
5551 old_zv = ZV;
5552 old_begv_byte = BEGV_BYTE;
5553 old_zv_byte = ZV_BYTE;
5555 bset_read_only (current_buffer, Qnil);
5557 /* Insert new output into buffer at the current end-of-output
5558 marker, thus preserving logical ordering of input and output. */
5559 if (XMARKER (p->mark)->buffer)
5560 set_point_from_marker (p->mark);
5561 else
5562 SET_PT_BOTH (ZV, ZV_BYTE);
5563 before = PT;
5564 before_byte = PT_BYTE;
5566 /* If the output marker is outside of the visible region, save
5567 the restriction and widen. */
5568 if (! (BEGV <= PT && PT <= ZV))
5569 Fwiden ();
5571 /* Adjust the multibyteness of TEXT to that of the buffer. */
5572 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5573 != ! STRING_MULTIBYTE (text))
5574 text = (STRING_MULTIBYTE (text)
5575 ? Fstring_as_unibyte (text)
5576 : Fstring_to_multibyte (text));
5577 /* Insert before markers in case we are inserting where
5578 the buffer's mark is, and the user's next command is Meta-y. */
5579 insert_from_string_before_markers (text, 0, 0,
5580 SCHARS (text), SBYTES (text), 0);
5582 /* Make sure the process marker's position is valid when the
5583 process buffer is changed in the signal_after_change above.
5584 W3 is known to do that. */
5585 if (BUFFERP (p->buffer)
5586 && (b = XBUFFER (p->buffer), b != current_buffer))
5587 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5588 else
5589 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5591 update_mode_lines = 23;
5593 /* Make sure opoint and the old restrictions
5594 float ahead of any new text just as point would. */
5595 if (opoint >= before)
5597 opoint += PT - before;
5598 opoint_byte += PT_BYTE - before_byte;
5600 if (old_begv > before)
5602 old_begv += PT - before;
5603 old_begv_byte += PT_BYTE - before_byte;
5605 if (old_zv >= before)
5607 old_zv += PT - before;
5608 old_zv_byte += PT_BYTE - before_byte;
5611 /* If the restriction isn't what it should be, set it. */
5612 if (old_begv != BEGV || old_zv != ZV)
5613 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5615 bset_read_only (current_buffer, old_read_only);
5616 SET_PT_BOTH (opoint, opoint_byte);
5618 return Qnil;
5621 /* Sending data to subprocess. */
5623 /* In send_process, when a write fails temporarily,
5624 wait_reading_process_output is called. It may execute user code,
5625 e.g. timers, that attempts to write new data to the same process.
5626 We must ensure that data is sent in the right order, and not
5627 interspersed half-completed with other writes (Bug#10815). This is
5628 handled by the write_queue element of struct process. It is a list
5629 with each entry having the form
5631 (string . (offset . length))
5633 where STRING is a lisp string, OFFSET is the offset into the
5634 string's byte sequence from which we should begin to send, and
5635 LENGTH is the number of bytes left to send. */
5637 /* Create a new entry in write_queue.
5638 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5639 BUF is a pointer to the string sequence of the input_obj or a C
5640 string in case of Qt or Qnil. */
5642 static void
5643 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5644 const char *buf, ptrdiff_t len, bool front)
5646 ptrdiff_t offset;
5647 Lisp_Object entry, obj;
5649 if (STRINGP (input_obj))
5651 offset = buf - SSDATA (input_obj);
5652 obj = input_obj;
5654 else
5656 offset = 0;
5657 obj = make_unibyte_string (buf, len);
5660 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5662 if (front)
5663 pset_write_queue (p, Fcons (entry, p->write_queue));
5664 else
5665 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5668 /* Remove the first element in the write_queue of process P, put its
5669 contents in OBJ, BUF and LEN, and return true. If the
5670 write_queue is empty, return false. */
5672 static bool
5673 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5674 const char **buf, ptrdiff_t *len)
5676 Lisp_Object entry, offset_length;
5677 ptrdiff_t offset;
5679 if (NILP (p->write_queue))
5680 return 0;
5682 entry = XCAR (p->write_queue);
5683 pset_write_queue (p, XCDR (p->write_queue));
5685 *obj = XCAR (entry);
5686 offset_length = XCDR (entry);
5688 *len = XINT (XCDR (offset_length));
5689 offset = XINT (XCAR (offset_length));
5690 *buf = SSDATA (*obj) + offset;
5692 return 1;
5695 /* Send some data to process PROC.
5696 BUF is the beginning of the data; LEN is the number of characters.
5697 OBJECT is the Lisp object that the data comes from. If OBJECT is
5698 nil or t, it means that the data comes from C string.
5700 If OBJECT is not nil, the data is encoded by PROC's coding-system
5701 for encoding before it is sent.
5703 This function can evaluate Lisp code and can garbage collect. */
5705 static void
5706 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5707 Lisp_Object object)
5709 struct Lisp_Process *p = XPROCESS (proc);
5710 ssize_t rv;
5711 struct coding_system *coding;
5713 if (p->raw_status_new)
5714 update_status (p);
5715 if (! EQ (p->status, Qrun))
5716 error ("Process %s not running", SDATA (p->name));
5717 if (p->outfd < 0)
5718 error ("Output file descriptor of %s is closed", SDATA (p->name));
5720 coding = proc_encode_coding_system[p->outfd];
5721 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5723 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5724 || (BUFFERP (object)
5725 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5726 || EQ (object, Qt))
5728 pset_encode_coding_system
5729 (p, complement_process_encoding_system (p->encode_coding_system));
5730 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5732 /* The coding system for encoding was changed to raw-text
5733 because we sent a unibyte text previously. Now we are
5734 sending a multibyte text, thus we must encode it by the
5735 original coding system specified for the current process.
5737 Another reason we come here is that the coding system
5738 was just complemented and a new one was returned by
5739 complement_process_encoding_system. */
5740 setup_coding_system (p->encode_coding_system, coding);
5741 Vlast_coding_system_used = p->encode_coding_system;
5743 coding->src_multibyte = 1;
5745 else
5747 coding->src_multibyte = 0;
5748 /* For sending a unibyte text, character code conversion should
5749 not take place but EOL conversion should. So, setup raw-text
5750 or one of the subsidiary if we have not yet done it. */
5751 if (CODING_REQUIRE_ENCODING (coding))
5753 if (CODING_REQUIRE_FLUSHING (coding))
5755 /* But, before changing the coding, we must flush out data. */
5756 coding->mode |= CODING_MODE_LAST_BLOCK;
5757 send_process (proc, "", 0, Qt);
5758 coding->mode &= CODING_MODE_LAST_BLOCK;
5760 setup_coding_system (raw_text_coding_system
5761 (Vlast_coding_system_used),
5762 coding);
5763 coding->src_multibyte = 0;
5766 coding->dst_multibyte = 0;
5768 if (CODING_REQUIRE_ENCODING (coding))
5770 coding->dst_object = Qt;
5771 if (BUFFERP (object))
5773 ptrdiff_t from_byte, from, to;
5774 ptrdiff_t save_pt, save_pt_byte;
5775 struct buffer *cur = current_buffer;
5777 set_buffer_internal (XBUFFER (object));
5778 save_pt = PT, save_pt_byte = PT_BYTE;
5780 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5781 from = BYTE_TO_CHAR (from_byte);
5782 to = BYTE_TO_CHAR (from_byte + len);
5783 TEMP_SET_PT_BOTH (from, from_byte);
5784 encode_coding_object (coding, object, from, from_byte,
5785 to, from_byte + len, Qt);
5786 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5787 set_buffer_internal (cur);
5789 else if (STRINGP (object))
5791 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5792 SBYTES (object), Qt);
5794 else
5796 coding->dst_object = make_unibyte_string (buf, len);
5797 coding->produced = len;
5800 len = coding->produced;
5801 object = coding->dst_object;
5802 buf = SSDATA (object);
5805 /* If there is already data in the write_queue, put the new data
5806 in the back of queue. Otherwise, ignore it. */
5807 if (!NILP (p->write_queue))
5808 write_queue_push (p, object, buf, len, 0);
5810 do /* while !NILP (p->write_queue) */
5812 ptrdiff_t cur_len = -1;
5813 const char *cur_buf;
5814 Lisp_Object cur_object;
5816 /* If write_queue is empty, ignore it. */
5817 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5819 cur_len = len;
5820 cur_buf = buf;
5821 cur_object = object;
5824 while (cur_len > 0)
5826 /* Send this batch, using one or more write calls. */
5827 ptrdiff_t written = 0;
5828 int outfd = p->outfd;
5829 #ifdef DATAGRAM_SOCKETS
5830 if (DATAGRAM_CHAN_P (outfd))
5832 rv = sendto (outfd, cur_buf, cur_len,
5833 0, datagram_address[outfd].sa,
5834 datagram_address[outfd].len);
5835 if (rv >= 0)
5836 written = rv;
5837 else if (errno == EMSGSIZE)
5838 report_file_error ("Sending datagram", proc);
5840 else
5841 #endif
5843 #ifdef HAVE_GNUTLS
5844 if (p->gnutls_p && p->gnutls_state)
5845 written = emacs_gnutls_write (p, cur_buf, cur_len);
5846 else
5847 #endif
5848 written = emacs_write_sig (outfd, cur_buf, cur_len);
5849 rv = (written ? 0 : -1);
5850 if (p->read_output_delay > 0
5851 && p->adaptive_read_buffering == 1)
5853 p->read_output_delay = 0;
5854 process_output_delay_count--;
5855 p->read_output_skip = 0;
5859 if (rv < 0)
5861 if (errno == EAGAIN
5862 #ifdef EWOULDBLOCK
5863 || errno == EWOULDBLOCK
5864 #endif
5866 /* Buffer is full. Wait, accepting input;
5867 that may allow the program
5868 to finish doing output and read more. */
5870 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5871 /* A gross hack to work around a bug in FreeBSD.
5872 In the following sequence, read(2) returns
5873 bogus data:
5875 write(2) 1022 bytes
5876 write(2) 954 bytes, get EAGAIN
5877 read(2) 1024 bytes in process_read_output
5878 read(2) 11 bytes in process_read_output
5880 That is, read(2) returns more bytes than have
5881 ever been written successfully. The 1033 bytes
5882 read are the 1022 bytes written successfully
5883 after processing (for example with CRs added if
5884 the terminal is set up that way which it is
5885 here). The same bytes will be seen again in a
5886 later read(2), without the CRs. */
5888 if (errno == EAGAIN)
5890 int flags = FWRITE;
5891 ioctl (p->outfd, TIOCFLUSH, &flags);
5893 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5895 /* Put what we should have written in wait_queue. */
5896 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5897 wait_reading_process_output (0, 20 * 1000 * 1000,
5898 0, 0, Qnil, NULL, 0);
5899 /* Reread queue, to see what is left. */
5900 break;
5902 else if (errno == EPIPE)
5904 p->raw_status_new = 0;
5905 pset_status (p, list2 (Qexit, make_number (256)));
5906 p->tick = ++process_tick;
5907 deactivate_process (proc);
5908 error ("process %s no longer connected to pipe; closed it",
5909 SDATA (p->name));
5911 else
5912 /* This is a real error. */
5913 report_file_error ("Writing to process", proc);
5915 cur_buf += written;
5916 cur_len -= written;
5919 while (!NILP (p->write_queue));
5922 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5923 3, 3, 0,
5924 doc: /* Send current contents of region as input to PROCESS.
5925 PROCESS may be a process, a buffer, the name of a process or buffer, or
5926 nil, indicating the current buffer's process.
5927 Called from program, takes three arguments, PROCESS, START and END.
5928 If the region is more than 500 characters long,
5929 it is sent in several bunches. This may happen even for shorter regions.
5930 Output from processes can arrive in between bunches. */)
5931 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5933 Lisp_Object proc = get_process (process);
5934 ptrdiff_t start_byte, end_byte;
5936 validate_region (&start, &end);
5938 start_byte = CHAR_TO_BYTE (XINT (start));
5939 end_byte = CHAR_TO_BYTE (XINT (end));
5941 if (XINT (start) < GPT && XINT (end) > GPT)
5942 move_gap_both (XINT (start), start_byte);
5944 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5945 end_byte - start_byte, Fcurrent_buffer ());
5947 return Qnil;
5950 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5951 2, 2, 0,
5952 doc: /* Send PROCESS the contents of STRING as input.
5953 PROCESS may be a process, a buffer, the name of a process or buffer, or
5954 nil, indicating the current buffer's process.
5955 If STRING is more than 500 characters long,
5956 it is sent in several bunches. This may happen even for shorter strings.
5957 Output from processes can arrive in between bunches. */)
5958 (Lisp_Object process, Lisp_Object string)
5960 Lisp_Object proc;
5961 CHECK_STRING (string);
5962 proc = get_process (process);
5963 send_process (proc, SSDATA (string),
5964 SBYTES (string), string);
5965 return Qnil;
5968 /* Return the foreground process group for the tty/pty that
5969 the process P uses. */
5970 static pid_t
5971 emacs_get_tty_pgrp (struct Lisp_Process *p)
5973 pid_t gid = -1;
5975 #ifdef TIOCGPGRP
5976 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5978 int fd;
5979 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5980 master side. Try the slave side. */
5981 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5983 if (fd != -1)
5985 ioctl (fd, TIOCGPGRP, &gid);
5986 emacs_close (fd);
5989 #endif /* defined (TIOCGPGRP ) */
5991 return gid;
5994 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5995 Sprocess_running_child_p, 0, 1, 0,
5996 doc: /* Return non-nil if PROCESS has given the terminal to a
5997 child. If the operating system does not make it possible to find out,
5998 return t. If we can find out, return the numeric ID of the foreground
5999 process group. */)
6000 (Lisp_Object process)
6002 /* Initialize in case ioctl doesn't exist or gives an error,
6003 in a way that will cause returning t. */
6004 pid_t gid;
6005 Lisp_Object proc;
6006 struct Lisp_Process *p;
6008 proc = get_process (process);
6009 p = XPROCESS (proc);
6011 if (!EQ (p->type, Qreal))
6012 error ("Process %s is not a subprocess",
6013 SDATA (p->name));
6014 if (p->infd < 0)
6015 error ("Process %s is not active",
6016 SDATA (p->name));
6018 gid = emacs_get_tty_pgrp (p);
6020 if (gid == p->pid)
6021 return Qnil;
6022 if (gid != -1)
6023 return make_number (gid);
6024 return Qt;
6027 /* Send a signal number SIGNO to PROCESS.
6028 If CURRENT_GROUP is t, that means send to the process group
6029 that currently owns the terminal being used to communicate with PROCESS.
6030 This is used for various commands in shell mode.
6031 If CURRENT_GROUP is lambda, that means send to the process group
6032 that currently owns the terminal, but only if it is NOT the shell itself.
6034 If NOMSG is false, insert signal-announcements into process's buffers
6035 right away.
6037 If we can, we try to signal PROCESS by sending control characters
6038 down the pty. This allows us to signal inferiors who have changed
6039 their uid, for which kill would return an EPERM error. */
6041 static void
6042 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
6043 bool nomsg)
6045 Lisp_Object proc;
6046 struct Lisp_Process *p;
6047 pid_t gid;
6048 bool no_pgrp = 0;
6050 proc = get_process (process);
6051 p = XPROCESS (proc);
6053 if (!EQ (p->type, Qreal))
6054 error ("Process %s is not a subprocess",
6055 SDATA (p->name));
6056 if (p->infd < 0)
6057 error ("Process %s is not active",
6058 SDATA (p->name));
6060 if (!p->pty_flag)
6061 current_group = Qnil;
6063 /* If we are using pgrps, get a pgrp number and make it negative. */
6064 if (NILP (current_group))
6065 /* Send the signal to the shell's process group. */
6066 gid = p->pid;
6067 else
6069 #ifdef SIGNALS_VIA_CHARACTERS
6070 /* If possible, send signals to the entire pgrp
6071 by sending an input character to it. */
6073 struct termios t;
6074 cc_t *sig_char = NULL;
6076 tcgetattr (p->infd, &t);
6078 switch (signo)
6080 case SIGINT:
6081 sig_char = &t.c_cc[VINTR];
6082 break;
6084 case SIGQUIT:
6085 sig_char = &t.c_cc[VQUIT];
6086 break;
6088 case SIGTSTP:
6089 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6090 sig_char = &t.c_cc[VSWTCH];
6091 #else
6092 sig_char = &t.c_cc[VSUSP];
6093 #endif
6094 break;
6097 if (sig_char && *sig_char != CDISABLE)
6099 send_process (proc, (char *) sig_char, 1, Qnil);
6100 return;
6102 /* If we can't send the signal with a character,
6103 fall through and send it another way. */
6105 /* The code above may fall through if it can't
6106 handle the signal. */
6107 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6109 #ifdef TIOCGPGRP
6110 /* Get the current pgrp using the tty itself, if we have that.
6111 Otherwise, use the pty to get the pgrp.
6112 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6113 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6114 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6115 His patch indicates that if TIOCGPGRP returns an error, then
6116 we should just assume that p->pid is also the process group id. */
6118 gid = emacs_get_tty_pgrp (p);
6120 if (gid == -1)
6121 /* If we can't get the information, assume
6122 the shell owns the tty. */
6123 gid = p->pid;
6125 /* It is not clear whether anything really can set GID to -1.
6126 Perhaps on some system one of those ioctls can or could do so.
6127 Or perhaps this is vestigial. */
6128 if (gid == -1)
6129 no_pgrp = 1;
6130 #else /* ! defined (TIOCGPGRP) */
6131 /* Can't select pgrps on this system, so we know that
6132 the child itself heads the pgrp. */
6133 gid = p->pid;
6134 #endif /* ! defined (TIOCGPGRP) */
6136 /* If current_group is lambda, and the shell owns the terminal,
6137 don't send any signal. */
6138 if (EQ (current_group, Qlambda) && gid == p->pid)
6139 return;
6142 #ifdef SIGCONT
6143 if (signo == SIGCONT)
6145 p->raw_status_new = 0;
6146 pset_status (p, Qrun);
6147 p->tick = ++process_tick;
6148 if (!nomsg)
6150 status_notify (NULL, NULL);
6151 redisplay_preserve_echo_area (13);
6154 #endif
6156 #ifdef TIOCSIGSEND
6157 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6158 We don't know whether the bug is fixed in later HP-UX versions. */
6159 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6160 return;
6161 #endif
6163 /* If we don't have process groups, send the signal to the immediate
6164 subprocess. That isn't really right, but it's better than any
6165 obvious alternative. */
6166 pid_t pid = no_pgrp ? gid : - gid;
6168 /* Do not kill an already-reaped process, as that could kill an
6169 innocent bystander that happens to have the same process ID. */
6170 sigset_t oldset;
6171 block_child_signal (&oldset);
6172 if (p->alive)
6173 kill (pid, signo);
6174 unblock_child_signal (&oldset);
6177 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6178 doc: /* Interrupt process PROCESS.
6179 PROCESS may be a process, a buffer, or the name of a process or buffer.
6180 No arg or nil means current buffer's process.
6181 Second arg CURRENT-GROUP non-nil means send signal to
6182 the current process-group of the process's controlling terminal
6183 rather than to the process's own process group.
6184 If the process is a shell, this means interrupt current subjob
6185 rather than the shell.
6187 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6188 don't send the signal. */)
6189 (Lisp_Object process, Lisp_Object current_group)
6191 process_send_signal (process, SIGINT, current_group, 0);
6192 return process;
6195 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6196 doc: /* Kill process PROCESS. May be process or name of one.
6197 See function `interrupt-process' for more details on usage. */)
6198 (Lisp_Object process, Lisp_Object current_group)
6200 process_send_signal (process, SIGKILL, current_group, 0);
6201 return process;
6204 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6205 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6206 See function `interrupt-process' for more details on usage. */)
6207 (Lisp_Object process, Lisp_Object current_group)
6209 process_send_signal (process, SIGQUIT, current_group, 0);
6210 return process;
6213 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6214 doc: /* Stop process PROCESS. May be process or name of one.
6215 See function `interrupt-process' for more details on usage.
6216 If PROCESS is a network or serial process, inhibit handling of incoming
6217 traffic. */)
6218 (Lisp_Object process, Lisp_Object current_group)
6220 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6221 || PIPECONN_P (process)))
6223 struct Lisp_Process *p;
6225 p = XPROCESS (process);
6226 if (NILP (p->command)
6227 && p->infd >= 0)
6229 FD_CLR (p->infd, &input_wait_mask);
6230 FD_CLR (p->infd, &non_keyboard_wait_mask);
6232 pset_command (p, Qt);
6233 return process;
6235 #ifndef SIGTSTP
6236 error ("No SIGTSTP support");
6237 #else
6238 process_send_signal (process, SIGTSTP, current_group, 0);
6239 #endif
6240 return process;
6243 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6244 doc: /* Continue process PROCESS. May be process or name of one.
6245 See function `interrupt-process' for more details on usage.
6246 If PROCESS is a network or serial process, resume handling of incoming
6247 traffic. */)
6248 (Lisp_Object process, Lisp_Object current_group)
6250 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6251 || PIPECONN_P (process)))
6253 struct Lisp_Process *p;
6255 p = XPROCESS (process);
6256 if (EQ (p->command, Qt)
6257 && p->infd >= 0
6258 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6260 FD_SET (p->infd, &input_wait_mask);
6261 FD_SET (p->infd, &non_keyboard_wait_mask);
6262 #ifdef WINDOWSNT
6263 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6264 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6265 #else /* not WINDOWSNT */
6266 tcflush (p->infd, TCIFLUSH);
6267 #endif /* not WINDOWSNT */
6269 pset_command (p, Qnil);
6270 return process;
6272 #ifdef SIGCONT
6273 process_send_signal (process, SIGCONT, current_group, 0);
6274 #else
6275 error ("No SIGCONT support");
6276 #endif
6277 return process;
6280 /* Return the integer value of the signal whose abbreviation is ABBR,
6281 or a negative number if there is no such signal. */
6282 static int
6283 abbr_to_signal (char const *name)
6285 int i, signo;
6286 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6288 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6289 name += 3;
6291 for (i = 0; i < sizeof sigbuf; i++)
6293 sigbuf[i] = c_toupper (name[i]);
6294 if (! sigbuf[i])
6295 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6298 return -1;
6301 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6302 2, 2, "sProcess (name or number): \nnSignal code: ",
6303 doc: /* Send PROCESS the signal with code SIGCODE.
6304 PROCESS may also be a number specifying the process id of the
6305 process to signal; in this case, the process need not be a child of
6306 this Emacs.
6307 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6308 (Lisp_Object process, Lisp_Object sigcode)
6310 pid_t pid;
6311 int signo;
6313 if (STRINGP (process))
6315 Lisp_Object tem = Fget_process (process);
6316 if (NILP (tem))
6318 Lisp_Object process_number
6319 = string_to_number (SSDATA (process), 10, 1);
6320 if (INTEGERP (process_number) || FLOATP (process_number))
6321 tem = process_number;
6323 process = tem;
6325 else if (!NUMBERP (process))
6326 process = get_process (process);
6328 if (NILP (process))
6329 return process;
6331 if (NUMBERP (process))
6332 CONS_TO_INTEGER (process, pid_t, pid);
6333 else
6335 CHECK_PROCESS (process);
6336 pid = XPROCESS (process)->pid;
6337 if (pid <= 0)
6338 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6341 if (INTEGERP (sigcode))
6343 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6344 signo = XINT (sigcode);
6346 else
6348 char *name;
6350 CHECK_SYMBOL (sigcode);
6351 name = SSDATA (SYMBOL_NAME (sigcode));
6353 signo = abbr_to_signal (name);
6354 if (signo < 0)
6355 error ("Undefined signal name %s", name);
6358 return make_number (kill (pid, signo));
6361 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6362 doc: /* Make PROCESS see end-of-file in its input.
6363 EOF comes after any text already sent to it.
6364 PROCESS may be a process, a buffer, the name of a process or buffer, or
6365 nil, indicating the current buffer's process.
6366 If PROCESS is a network connection, or is a process communicating
6367 through a pipe (as opposed to a pty), then you cannot send any more
6368 text to PROCESS after you call this function.
6369 If PROCESS is a serial process, wait until all output written to the
6370 process has been transmitted to the serial port. */)
6371 (Lisp_Object process)
6373 Lisp_Object proc;
6374 struct coding_system *coding = NULL;
6375 int outfd;
6377 if (DATAGRAM_CONN_P (process))
6378 return process;
6380 proc = get_process (process);
6381 outfd = XPROCESS (proc)->outfd;
6382 if (outfd >= 0)
6383 coding = proc_encode_coding_system[outfd];
6385 /* Make sure the process is really alive. */
6386 if (XPROCESS (proc)->raw_status_new)
6387 update_status (XPROCESS (proc));
6388 if (! EQ (XPROCESS (proc)->status, Qrun))
6389 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6391 if (coding && CODING_REQUIRE_FLUSHING (coding))
6393 coding->mode |= CODING_MODE_LAST_BLOCK;
6394 send_process (proc, "", 0, Qnil);
6397 if (XPROCESS (proc)->pty_flag)
6398 send_process (proc, "\004", 1, Qnil);
6399 else if (EQ (XPROCESS (proc)->type, Qserial))
6401 #ifndef WINDOWSNT
6402 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6403 report_file_error ("Failed tcdrain", Qnil);
6404 #endif /* not WINDOWSNT */
6405 /* Do nothing on Windows because writes are blocking. */
6407 else
6409 struct Lisp_Process *p = XPROCESS (proc);
6410 int old_outfd = p->outfd;
6411 int new_outfd;
6413 #ifdef HAVE_SHUTDOWN
6414 /* If this is a network connection, or socketpair is used
6415 for communication with the subprocess, call shutdown to cause EOF.
6416 (In some old system, shutdown to socketpair doesn't work.
6417 Then we just can't win.) */
6418 if (0 <= old_outfd
6419 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6420 shutdown (old_outfd, 1);
6421 #endif
6422 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6423 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6424 if (new_outfd < 0)
6425 report_file_error ("Opening null device", Qnil);
6426 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6427 p->outfd = new_outfd;
6429 if (!proc_encode_coding_system[new_outfd])
6430 proc_encode_coding_system[new_outfd]
6431 = xmalloc (sizeof (struct coding_system));
6432 if (old_outfd >= 0)
6434 *proc_encode_coding_system[new_outfd]
6435 = *proc_encode_coding_system[old_outfd];
6436 memset (proc_encode_coding_system[old_outfd], 0,
6437 sizeof (struct coding_system));
6439 else
6440 setup_coding_system (p->encode_coding_system,
6441 proc_encode_coding_system[new_outfd]);
6443 return process;
6446 /* The main Emacs thread records child processes in three places:
6448 - Vprocess_alist, for asynchronous subprocesses, which are child
6449 processes visible to Lisp.
6451 - deleted_pid_list, for child processes invisible to Lisp,
6452 typically because of delete-process. These are recorded so that
6453 the processes can be reaped when they exit, so that the operating
6454 system's process table is not cluttered by zombies.
6456 - the local variable PID in Fcall_process, call_process_cleanup and
6457 call_process_kill, for synchronous subprocesses.
6458 record_unwind_protect is used to make sure this process is not
6459 forgotten: if the user interrupts call-process and the child
6460 process refuses to exit immediately even with two C-g's,
6461 call_process_kill adds PID's contents to deleted_pid_list before
6462 returning.
6464 The main Emacs thread invokes waitpid only on child processes that
6465 it creates and that have not been reaped. This avoid races on
6466 platforms such as GTK, where other threads create their own
6467 subprocesses which the main thread should not reap. For example,
6468 if the main thread attempted to reap an already-reaped child, it
6469 might inadvertently reap a GTK-created process that happened to
6470 have the same process ID. */
6472 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6473 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6474 keep track of its own children. GNUstep is similar. */
6476 static void dummy_handler (int sig) {}
6477 static signal_handler_t volatile lib_child_handler;
6479 /* Handle a SIGCHLD signal by looking for known child processes of
6480 Emacs whose status have changed. For each one found, record its
6481 new status.
6483 All we do is change the status; we do not run sentinels or print
6484 notifications. That is saved for the next time keyboard input is
6485 done, in order to avoid timing errors.
6487 ** WARNING: this can be called during garbage collection.
6488 Therefore, it must not be fooled by the presence of mark bits in
6489 Lisp objects.
6491 ** USG WARNING: Although it is not obvious from the documentation
6492 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6493 signal() before executing at least one wait(), otherwise the
6494 handler will be called again, resulting in an infinite loop. The
6495 relevant portion of the documentation reads "SIGCLD signals will be
6496 queued and the signal-catching function will be continually
6497 reentered until the queue is empty". Invoking signal() causes the
6498 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6499 Inc.
6501 ** Malloc WARNING: This should never call malloc either directly or
6502 indirectly; if it does, that is a bug. */
6504 static void
6505 handle_child_signal (int sig)
6507 Lisp_Object tail, proc;
6509 /* Find the process that signaled us, and record its status. */
6511 /* The process can have been deleted by Fdelete_process, or have
6512 been started asynchronously by Fcall_process. */
6513 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6515 bool all_pids_are_fixnums
6516 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6517 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6518 Lisp_Object head = XCAR (tail);
6519 Lisp_Object xpid;
6520 if (! CONSP (head))
6521 continue;
6522 xpid = XCAR (head);
6523 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6525 pid_t deleted_pid;
6526 if (INTEGERP (xpid))
6527 deleted_pid = XINT (xpid);
6528 else
6529 deleted_pid = XFLOAT_DATA (xpid);
6530 if (child_status_changed (deleted_pid, 0, 0))
6532 if (STRINGP (XCDR (head)))
6533 unlink (SSDATA (XCDR (head)));
6534 XSETCAR (tail, Qnil);
6539 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6540 FOR_EACH_PROCESS (tail, proc)
6542 struct Lisp_Process *p = XPROCESS (proc);
6543 int status;
6545 if (p->alive
6546 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6548 /* Change the status of the process that was found. */
6549 p->tick = ++process_tick;
6550 p->raw_status = status;
6551 p->raw_status_new = 1;
6553 /* If process has terminated, stop waiting for its output. */
6554 if (WIFSIGNALED (status) || WIFEXITED (status))
6556 bool clear_desc_flag = 0;
6557 p->alive = 0;
6558 if (p->infd >= 0)
6559 clear_desc_flag = 1;
6561 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6562 if (clear_desc_flag)
6564 FD_CLR (p->infd, &input_wait_mask);
6565 FD_CLR (p->infd, &non_keyboard_wait_mask);
6571 lib_child_handler (sig);
6572 #ifdef NS_IMPL_GNUSTEP
6573 /* NSTask in GNUstep sets its child handler each time it is called.
6574 So we must re-set ours. */
6575 catch_child_signal ();
6576 #endif
6579 static void
6580 deliver_child_signal (int sig)
6582 deliver_process_signal (sig, handle_child_signal);
6586 static Lisp_Object
6587 exec_sentinel_error_handler (Lisp_Object error_val)
6589 cmd_error_internal (error_val, "error in process sentinel: ");
6590 Vinhibit_quit = Qt;
6591 update_echo_area ();
6592 Fsleep_for (make_number (2), Qnil);
6593 return Qt;
6596 static void
6597 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6599 Lisp_Object sentinel, odeactivate;
6600 struct Lisp_Process *p = XPROCESS (proc);
6601 ptrdiff_t count = SPECPDL_INDEX ();
6602 bool outer_running_asynch_code = running_asynch_code;
6603 int waiting = waiting_for_user_input_p;
6605 if (inhibit_sentinels)
6606 return;
6608 /* No need to gcpro these, because all we do with them later
6609 is test them for EQness, and none of them should be a string. */
6610 odeactivate = Vdeactivate_mark;
6611 #if 0
6612 Lisp_Object obuffer, okeymap;
6613 XSETBUFFER (obuffer, current_buffer);
6614 okeymap = BVAR (current_buffer, keymap);
6615 #endif
6617 /* There's no good reason to let sentinels change the current
6618 buffer, and many callers of accept-process-output, sit-for, and
6619 friends don't expect current-buffer to be changed from under them. */
6620 record_unwind_current_buffer ();
6622 sentinel = p->sentinel;
6624 /* Inhibit quit so that random quits don't screw up a running filter. */
6625 specbind (Qinhibit_quit, Qt);
6626 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6628 /* In case we get recursively called,
6629 and we already saved the match data nonrecursively,
6630 save the same match data in safely recursive fashion. */
6631 if (outer_running_asynch_code)
6633 Lisp_Object tem;
6634 tem = Fmatch_data (Qnil, Qnil, Qnil);
6635 restore_search_regs ();
6636 record_unwind_save_match_data ();
6637 Fset_match_data (tem, Qt);
6640 /* For speed, if a search happens within this code,
6641 save the match data in a special nonrecursive fashion. */
6642 running_asynch_code = 1;
6644 internal_condition_case_1 (read_process_output_call,
6645 list3 (sentinel, proc, reason),
6646 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6647 exec_sentinel_error_handler);
6649 /* If we saved the match data nonrecursively, restore it now. */
6650 restore_search_regs ();
6651 running_asynch_code = outer_running_asynch_code;
6653 Vdeactivate_mark = odeactivate;
6655 /* Restore waiting_for_user_input_p as it was
6656 when we were called, in case the filter clobbered it. */
6657 waiting_for_user_input_p = waiting;
6659 #if 0
6660 if (! EQ (Fcurrent_buffer (), obuffer)
6661 || ! EQ (current_buffer->keymap, okeymap))
6662 #endif
6663 /* But do it only if the caller is actually going to read events.
6664 Otherwise there's no need to make him wake up, and it could
6665 cause trouble (for example it would make sit_for return). */
6666 if (waiting_for_user_input_p == -1)
6667 record_asynch_buffer_change ();
6669 unbind_to (count, Qnil);
6672 /* Report all recent events of a change in process status
6673 (either run the sentinel or output a message).
6674 This is usually done while Emacs is waiting for keyboard input
6675 but can be done at other times.
6677 Return positive if any input was received from WAIT_PROC (or from
6678 any process if WAIT_PROC is null), zero if input was attempted but
6679 none received, and negative if we didn't even try. */
6681 static int
6682 status_notify (struct Lisp_Process *deleting_process,
6683 struct Lisp_Process *wait_proc)
6685 Lisp_Object proc;
6686 Lisp_Object tail, msg;
6687 struct gcpro gcpro1, gcpro2;
6688 int got_some_output = -1;
6690 tail = Qnil;
6691 msg = Qnil;
6692 /* We need to gcpro tail; if read_process_output calls a filter
6693 which deletes a process and removes the cons to which tail points
6694 from Vprocess_alist, and then causes a GC, tail is an unprotected
6695 reference. */
6696 GCPRO2 (tail, msg);
6698 /* Set this now, so that if new processes are created by sentinels
6699 that we run, we get called again to handle their status changes. */
6700 update_tick = process_tick;
6702 FOR_EACH_PROCESS (tail, proc)
6704 Lisp_Object symbol;
6705 register struct Lisp_Process *p = XPROCESS (proc);
6707 if (p->tick != p->update_tick)
6709 p->update_tick = p->tick;
6711 /* If process is still active, read any output that remains. */
6712 while (! EQ (p->filter, Qt)
6713 && ! EQ (p->status, Qconnect)
6714 && ! EQ (p->status, Qlisten)
6715 /* Network or serial process not stopped: */
6716 && ! EQ (p->command, Qt)
6717 && p->infd >= 0
6718 && p != deleting_process)
6720 int nread = read_process_output (proc, p->infd);
6721 if ((!wait_proc || wait_proc == XPROCESS (proc))
6722 && got_some_output < nread)
6723 got_some_output = nread;
6724 if (nread <= 0)
6725 break;
6728 /* Get the text to use for the message. */
6729 if (p->raw_status_new)
6730 update_status (p);
6731 msg = status_message (p);
6733 /* If process is terminated, deactivate it or delete it. */
6734 symbol = p->status;
6735 if (CONSP (p->status))
6736 symbol = XCAR (p->status);
6738 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6739 || EQ (symbol, Qclosed))
6741 if (delete_exited_processes)
6742 remove_process (proc);
6743 else
6744 deactivate_process (proc);
6747 /* The actions above may have further incremented p->tick.
6748 So set p->update_tick again so that an error in the sentinel will
6749 not cause this code to be run again. */
6750 p->update_tick = p->tick;
6751 /* Now output the message suitably. */
6752 exec_sentinel (proc, msg);
6754 } /* end for */
6756 update_mode_lines = 24; /* In case buffers use %s in mode-line-format. */
6757 UNGCPRO;
6758 return got_some_output;
6761 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6762 Sinternal_default_process_sentinel, 2, 2, 0,
6763 doc: /* Function used as default sentinel for processes.
6764 This inserts a status message into the process's buffer, if there is one. */)
6765 (Lisp_Object proc, Lisp_Object msg)
6767 Lisp_Object buffer, symbol;
6768 struct Lisp_Process *p;
6769 CHECK_PROCESS (proc);
6770 p = XPROCESS (proc);
6771 buffer = p->buffer;
6772 symbol = p->status;
6773 if (CONSP (symbol))
6774 symbol = XCAR (symbol);
6776 if (!EQ (symbol, Qrun) && !NILP (buffer))
6778 Lisp_Object tem;
6779 struct buffer *old = current_buffer;
6780 ptrdiff_t opoint, opoint_byte;
6781 ptrdiff_t before, before_byte;
6783 /* Avoid error if buffer is deleted
6784 (probably that's why the process is dead, too). */
6785 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6786 return Qnil;
6787 Fset_buffer (buffer);
6789 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6790 msg = (code_convert_string_norecord
6791 (msg, Vlocale_coding_system, 1));
6793 opoint = PT;
6794 opoint_byte = PT_BYTE;
6795 /* Insert new output into buffer
6796 at the current end-of-output marker,
6797 thus preserving logical ordering of input and output. */
6798 if (XMARKER (p->mark)->buffer)
6799 Fgoto_char (p->mark);
6800 else
6801 SET_PT_BOTH (ZV, ZV_BYTE);
6803 before = PT;
6804 before_byte = PT_BYTE;
6806 tem = BVAR (current_buffer, read_only);
6807 bset_read_only (current_buffer, Qnil);
6808 insert_string ("\nProcess ");
6809 { /* FIXME: temporary kludge. */
6810 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6811 insert_string (" ");
6812 Finsert (1, &msg);
6813 bset_read_only (current_buffer, tem);
6814 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6816 if (opoint >= before)
6817 SET_PT_BOTH (opoint + (PT - before),
6818 opoint_byte + (PT_BYTE - before_byte));
6819 else
6820 SET_PT_BOTH (opoint, opoint_byte);
6822 set_buffer_internal (old);
6824 return Qnil;
6828 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6829 Sset_process_coding_system, 1, 3, 0,
6830 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6831 DECODING will be used to decode subprocess output and ENCODING to
6832 encode subprocess input. */)
6833 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6835 register struct Lisp_Process *p;
6837 CHECK_PROCESS (process);
6838 p = XPROCESS (process);
6839 if (p->infd < 0)
6840 error ("Input file descriptor of %s closed", SDATA (p->name));
6841 if (p->outfd < 0)
6842 error ("Output file descriptor of %s closed", SDATA (p->name));
6843 Fcheck_coding_system (decoding);
6844 Fcheck_coding_system (encoding);
6845 encoding = coding_inherit_eol_type (encoding, Qnil);
6846 pset_decode_coding_system (p, decoding);
6847 pset_encode_coding_system (p, encoding);
6848 setup_process_coding_systems (process);
6850 return Qnil;
6853 DEFUN ("process-coding-system",
6854 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6855 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6856 (register Lisp_Object process)
6858 CHECK_PROCESS (process);
6859 return Fcons (XPROCESS (process)->decode_coding_system,
6860 XPROCESS (process)->encode_coding_system);
6863 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6864 Sset_process_filter_multibyte, 2, 2, 0,
6865 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6866 If FLAG is non-nil, the filter is given multibyte strings.
6867 If FLAG is nil, the filter is given unibyte strings. In this case,
6868 all character code conversion except for end-of-line conversion is
6869 suppressed. */)
6870 (Lisp_Object process, Lisp_Object flag)
6872 register struct Lisp_Process *p;
6874 CHECK_PROCESS (process);
6875 p = XPROCESS (process);
6876 if (NILP (flag))
6877 pset_decode_coding_system
6878 (p, raw_text_coding_system (p->decode_coding_system));
6879 setup_process_coding_systems (process);
6881 return Qnil;
6884 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6885 Sprocess_filter_multibyte_p, 1, 1, 0,
6886 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6887 (Lisp_Object process)
6889 register struct Lisp_Process *p;
6890 struct coding_system *coding;
6892 CHECK_PROCESS (process);
6893 p = XPROCESS (process);
6894 if (p->infd < 0)
6895 return Qnil;
6896 coding = proc_decode_coding_system[p->infd];
6897 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6903 # ifdef HAVE_GPM
6905 void
6906 add_gpm_wait_descriptor (int desc)
6908 add_keyboard_wait_descriptor (desc);
6911 void
6912 delete_gpm_wait_descriptor (int desc)
6914 delete_keyboard_wait_descriptor (desc);
6917 # endif
6919 # ifdef USABLE_SIGIO
6921 /* Return true if *MASK has a bit set
6922 that corresponds to one of the keyboard input descriptors. */
6924 static bool
6925 keyboard_bit_set (fd_set *mask)
6927 int fd;
6929 for (fd = 0; fd <= max_input_desc; fd++)
6930 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6931 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6932 return 1;
6934 return 0;
6936 # endif
6938 #else /* not subprocesses */
6940 /* Defined in msdos.c. */
6941 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6942 struct timespec *, void *);
6944 /* Implementation of wait_reading_process_output, assuming that there
6945 are no subprocesses. Used only by the MS-DOS build.
6947 Wait for timeout to elapse and/or keyboard input to be available.
6949 TIME_LIMIT is:
6950 timeout in seconds
6951 If negative, gobble data immediately available but don't wait for any.
6953 NSECS is:
6954 an additional duration to wait, measured in nanoseconds
6955 If TIME_LIMIT is zero, then:
6956 If NSECS == 0, there is no limit.
6957 If NSECS > 0, the timeout consists of NSECS only.
6958 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6960 READ_KBD is:
6961 0 to ignore keyboard input, or
6962 1 to return when input is available, or
6963 -1 means caller will actually read the input, so don't throw to
6964 the quit handler.
6966 see full version for other parameters. We know that wait_proc will
6967 always be NULL, since `subprocesses' isn't defined.
6969 DO_DISPLAY means redisplay should be done to show subprocess
6970 output that arrives.
6972 Return -1 signifying we got no output and did not try. */
6975 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6976 bool do_display,
6977 Lisp_Object wait_for_cell,
6978 struct Lisp_Process *wait_proc, int just_wait_proc)
6980 register int nfds;
6981 struct timespec end_time, timeout;
6982 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
6984 if (TYPE_MAXIMUM (time_t) < time_limit)
6985 time_limit = TYPE_MAXIMUM (time_t);
6987 if (time_limit < 0 || nsecs < 0)
6988 wait = MINIMUM;
6989 else if (time_limit > 0 || nsecs > 0)
6991 wait = TIMEOUT;
6992 end_time = timespec_add (current_timespec (),
6993 make_timespec (time_limit, nsecs));
6995 else
6996 wait = INFINITY;
6998 /* Turn off periodic alarms (in case they are in use)
6999 and then turn off any other atimers,
7000 because the select emulator uses alarms. */
7001 stop_polling ();
7002 turn_on_atimers (0);
7004 while (1)
7006 bool timeout_reduced_for_timers = false;
7007 fd_set waitchannels;
7008 int xerrno;
7010 /* If calling from keyboard input, do not quit
7011 since we want to return C-g as an input character.
7012 Otherwise, do pending quit if requested. */
7013 if (read_kbd >= 0)
7014 QUIT;
7016 /* Exit now if the cell we're waiting for became non-nil. */
7017 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7018 break;
7020 /* Compute time from now till when time limit is up. */
7021 /* Exit if already run out. */
7022 if (wait == TIMEOUT)
7024 struct timespec now = current_timespec ();
7025 if (timespec_cmp (end_time, now) <= 0)
7026 break;
7027 timeout = timespec_sub (end_time, now);
7029 else
7030 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
7032 /* If our caller will not immediately handle keyboard events,
7033 run timer events directly.
7034 (Callers that will immediately read keyboard events
7035 call timer_delay on their own.) */
7036 if (NILP (wait_for_cell))
7038 struct timespec timer_delay;
7042 unsigned old_timers_run = timers_run;
7043 timer_delay = timer_check ();
7044 if (timers_run != old_timers_run && do_display)
7045 /* We must retry, since a timer may have requeued itself
7046 and that could alter the time delay. */
7047 redisplay_preserve_echo_area (14);
7048 else
7049 break;
7051 while (!detect_input_pending ());
7053 /* If there is unread keyboard input, also return. */
7054 if (read_kbd != 0
7055 && requeued_events_pending_p ())
7056 break;
7058 if (timespec_valid_p (timer_delay))
7060 if (timespec_cmp (timer_delay, timeout) < 0)
7062 timeout = timer_delay;
7063 timeout_reduced_for_timers = true;
7068 /* Cause C-g and alarm signals to take immediate action,
7069 and cause input available signals to zero out timeout. */
7070 if (read_kbd < 0)
7071 set_waiting_for_input (&timeout);
7073 /* If a frame has been newly mapped and needs updating,
7074 reprocess its display stuff. */
7075 if (frame_garbaged && do_display)
7077 clear_waiting_for_input ();
7078 redisplay_preserve_echo_area (15);
7079 if (read_kbd < 0)
7080 set_waiting_for_input (&timeout);
7083 /* Wait till there is something to do. */
7084 FD_ZERO (&waitchannels);
7085 if (read_kbd && detect_input_pending ())
7086 nfds = 0;
7087 else
7089 if (read_kbd || !NILP (wait_for_cell))
7090 FD_SET (0, &waitchannels);
7091 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7094 xerrno = errno;
7096 /* Make C-g and alarm signals set flags again. */
7097 clear_waiting_for_input ();
7099 /* If we woke up due to SIGWINCH, actually change size now. */
7100 do_pending_window_change (0);
7102 if (wait < INFINITY && nfds == 0 && ! timeout_reduced_for_timers)
7103 /* We waited the full specified time, so return now. */
7104 break;
7106 if (nfds == -1)
7108 /* If the system call was interrupted, then go around the
7109 loop again. */
7110 if (xerrno == EINTR)
7111 FD_ZERO (&waitchannels);
7112 else
7113 report_file_errno ("Failed select", Qnil, xerrno);
7116 /* Check for keyboard input. */
7118 if (read_kbd
7119 && detect_input_pending_run_timers (do_display))
7121 swallow_events (do_display);
7122 if (detect_input_pending_run_timers (do_display))
7123 break;
7126 /* If there is unread keyboard input, also return. */
7127 if (read_kbd
7128 && requeued_events_pending_p ())
7129 break;
7131 /* If wait_for_cell. check for keyboard input
7132 but don't run any timers.
7133 ??? (It seems wrong to me to check for keyboard
7134 input at all when wait_for_cell, but the code
7135 has been this way since July 1994.
7136 Try changing this after version 19.31.) */
7137 if (! NILP (wait_for_cell)
7138 && detect_input_pending ())
7140 swallow_events (do_display);
7141 if (detect_input_pending ())
7142 break;
7145 /* Exit now if the cell we're waiting for became non-nil. */
7146 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7147 break;
7150 start_polling ();
7152 return -1;
7155 #endif /* not subprocesses */
7157 /* The following functions are needed even if async subprocesses are
7158 not supported. Some of them are no-op stubs in that case. */
7160 #ifdef HAVE_TIMERFD
7162 /* Add FD, which is a descriptor returned by timerfd_create,
7163 to the set of non-keyboard input descriptors. */
7165 void
7166 add_timer_wait_descriptor (int fd)
7168 FD_SET (fd, &input_wait_mask);
7169 FD_SET (fd, &non_keyboard_wait_mask);
7170 FD_SET (fd, &non_process_wait_mask);
7171 fd_callback_info[fd].func = timerfd_callback;
7172 fd_callback_info[fd].data = NULL;
7173 fd_callback_info[fd].condition |= FOR_READ;
7174 if (fd > max_input_desc)
7175 max_input_desc = fd;
7178 #endif /* HAVE_TIMERFD */
7180 /* Add DESC to the set of keyboard input descriptors. */
7182 void
7183 add_keyboard_wait_descriptor (int desc)
7185 #ifdef subprocesses /* Actually means "not MSDOS". */
7186 FD_SET (desc, &input_wait_mask);
7187 FD_SET (desc, &non_process_wait_mask);
7188 if (desc > max_input_desc)
7189 max_input_desc = desc;
7190 #endif
7193 /* From now on, do not expect DESC to give keyboard input. */
7195 void
7196 delete_keyboard_wait_descriptor (int desc)
7198 #ifdef subprocesses
7199 FD_CLR (desc, &input_wait_mask);
7200 FD_CLR (desc, &non_process_wait_mask);
7201 delete_input_desc (desc);
7202 #endif
7205 /* Setup coding systems of PROCESS. */
7207 void
7208 setup_process_coding_systems (Lisp_Object process)
7210 #ifdef subprocesses
7211 struct Lisp_Process *p = XPROCESS (process);
7212 int inch = p->infd;
7213 int outch = p->outfd;
7214 Lisp_Object coding_system;
7216 if (inch < 0 || outch < 0)
7217 return;
7219 if (!proc_decode_coding_system[inch])
7220 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7221 coding_system = p->decode_coding_system;
7222 if (EQ (p->filter, Qinternal_default_process_filter)
7223 && BUFFERP (p->buffer))
7225 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7226 coding_system = raw_text_coding_system (coding_system);
7228 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7230 if (!proc_encode_coding_system[outch])
7231 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7232 setup_coding_system (p->encode_coding_system,
7233 proc_encode_coding_system[outch]);
7234 #endif
7237 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7238 doc: /* Return the (or a) process associated with BUFFER.
7239 BUFFER may be a buffer or the name of one. */)
7240 (register Lisp_Object buffer)
7242 #ifdef subprocesses
7243 register Lisp_Object buf, tail, proc;
7245 if (NILP (buffer)) return Qnil;
7246 buf = Fget_buffer (buffer);
7247 if (NILP (buf)) return Qnil;
7249 FOR_EACH_PROCESS (tail, proc)
7250 if (EQ (XPROCESS (proc)->buffer, buf))
7251 return proc;
7252 #endif /* subprocesses */
7253 return Qnil;
7256 DEFUN ("process-inherit-coding-system-flag",
7257 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7258 1, 1, 0,
7259 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7260 If this flag is t, `buffer-file-coding-system' of the buffer
7261 associated with PROCESS will inherit the coding system used to decode
7262 the process output. */)
7263 (register Lisp_Object process)
7265 #ifdef subprocesses
7266 CHECK_PROCESS (process);
7267 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7268 #else
7269 /* Ignore the argument and return the value of
7270 inherit-process-coding-system. */
7271 return inherit_process_coding_system ? Qt : Qnil;
7272 #endif
7275 /* Kill all processes associated with `buffer'.
7276 If `buffer' is nil, kill all processes. */
7278 void
7279 kill_buffer_processes (Lisp_Object buffer)
7281 #ifdef subprocesses
7282 Lisp_Object tail, proc;
7284 FOR_EACH_PROCESS (tail, proc)
7285 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7287 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7288 Fdelete_process (proc);
7289 else if (XPROCESS (proc)->infd >= 0)
7290 process_send_signal (proc, SIGHUP, Qnil, 1);
7292 #else /* subprocesses */
7293 /* Since we have no subprocesses, this does nothing. */
7294 #endif /* subprocesses */
7297 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7298 Swaiting_for_user_input_p, 0, 0, 0,
7299 doc: /* Return non-nil if Emacs is waiting for input from the user.
7300 This is intended for use by asynchronous process output filters and sentinels. */)
7301 (void)
7303 #ifdef subprocesses
7304 return (waiting_for_user_input_p ? Qt : Qnil);
7305 #else
7306 return Qnil;
7307 #endif
7310 /* Stop reading input from keyboard sources. */
7312 void
7313 hold_keyboard_input (void)
7315 kbd_is_on_hold = 1;
7318 /* Resume reading input from keyboard sources. */
7320 void
7321 unhold_keyboard_input (void)
7323 kbd_is_on_hold = 0;
7326 /* Return true if keyboard input is on hold, zero otherwise. */
7328 bool
7329 kbd_on_hold_p (void)
7331 return kbd_is_on_hold;
7335 /* Enumeration of and access to system processes a-la ps(1). */
7337 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7338 0, 0, 0,
7339 doc: /* Return a list of numerical process IDs of all running processes.
7340 If this functionality is unsupported, return nil.
7342 See `process-attributes' for getting attributes of a process given its ID. */)
7343 (void)
7345 return list_system_processes ();
7348 DEFUN ("process-attributes", Fprocess_attributes,
7349 Sprocess_attributes, 1, 1, 0,
7350 doc: /* Return attributes of the process given by its PID, a number.
7352 Value is an alist where each element is a cons cell of the form
7354 \(KEY . VALUE)
7356 If this functionality is unsupported, the value is nil.
7358 See `list-system-processes' for getting a list of all process IDs.
7360 The KEYs of the attributes that this function may return are listed
7361 below, together with the type of the associated VALUE (in parentheses).
7362 Not all platforms support all of these attributes; unsupported
7363 attributes will not appear in the returned alist.
7364 Unless explicitly indicated otherwise, numbers can have either
7365 integer or floating point values.
7367 euid -- Effective user User ID of the process (number)
7368 user -- User name corresponding to euid (string)
7369 egid -- Effective user Group ID of the process (number)
7370 group -- Group name corresponding to egid (string)
7371 comm -- Command name (executable name only) (string)
7372 state -- Process state code, such as "S", "R", or "T" (string)
7373 ppid -- Parent process ID (number)
7374 pgrp -- Process group ID (number)
7375 sess -- Session ID, i.e. process ID of session leader (number)
7376 ttname -- Controlling tty name (string)
7377 tpgid -- ID of foreground process group on the process's tty (number)
7378 minflt -- number of minor page faults (number)
7379 majflt -- number of major page faults (number)
7380 cminflt -- cumulative number of minor page faults (number)
7381 cmajflt -- cumulative number of major page faults (number)
7382 utime -- user time used by the process, in (current-time) format,
7383 which is a list of integers (HIGH LOW USEC PSEC)
7384 stime -- system time used by the process (current-time)
7385 time -- sum of utime and stime (current-time)
7386 cutime -- user time used by the process and its children (current-time)
7387 cstime -- system time used by the process and its children (current-time)
7388 ctime -- sum of cutime and cstime (current-time)
7389 pri -- priority of the process (number)
7390 nice -- nice value of the process (number)
7391 thcount -- process thread count (number)
7392 start -- time the process started (current-time)
7393 vsize -- virtual memory size of the process in KB's (number)
7394 rss -- resident set size of the process in KB's (number)
7395 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7396 pcpu -- percents of CPU time used by the process (floating-point number)
7397 pmem -- percents of total physical memory used by process's resident set
7398 (floating-point number)
7399 args -- command line which invoked the process (string). */)
7400 ( Lisp_Object pid)
7402 return system_process_attributes (pid);
7405 #ifdef subprocesses
7406 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7407 Invoke this after init_process_emacs, and after glib and/or GNUstep
7408 futz with the SIGCHLD handler, but before Emacs forks any children.
7409 This function's caller should block SIGCHLD. */
7411 void
7412 catch_child_signal (void)
7414 struct sigaction action, old_action;
7415 sigset_t oldset;
7416 emacs_sigaction_init (&action, deliver_child_signal);
7417 block_child_signal (&oldset);
7418 sigaction (SIGCHLD, &action, &old_action);
7419 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7420 || ! (old_action.sa_flags & SA_SIGINFO));
7422 if (old_action.sa_handler != deliver_child_signal)
7423 lib_child_handler
7424 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7425 ? dummy_handler
7426 : old_action.sa_handler);
7427 unblock_child_signal (&oldset);
7429 #endif /* subprocesses */
7432 /* This is not called "init_process" because that is the name of a
7433 Mach system call, so it would cause problems on Darwin systems. */
7434 void
7435 init_process_emacs (void)
7437 #ifdef subprocesses
7438 register int i;
7440 inhibit_sentinels = 0;
7442 #ifndef CANNOT_DUMP
7443 if (! noninteractive || initialized)
7444 #endif
7446 #if defined HAVE_GLIB && !defined WINDOWSNT
7447 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7448 this should always fail, but is enough to initialize glib's
7449 private SIGCHLD handler, allowing catch_child_signal to copy
7450 it into lib_child_handler. */
7451 g_source_unref (g_child_watch_source_new (getpid ()));
7452 #endif
7453 catch_child_signal ();
7456 FD_ZERO (&input_wait_mask);
7457 FD_ZERO (&non_keyboard_wait_mask);
7458 FD_ZERO (&non_process_wait_mask);
7459 FD_ZERO (&write_mask);
7460 max_process_desc = max_input_desc = -1;
7461 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7463 #ifdef NON_BLOCKING_CONNECT
7464 FD_ZERO (&connect_wait_mask);
7465 num_pending_connects = 0;
7466 #endif
7468 process_output_delay_count = 0;
7469 process_output_skip = 0;
7471 /* Don't do this, it caused infinite select loops. The display
7472 method should call add_keyboard_wait_descriptor on stdin if it
7473 needs that. */
7474 #if 0
7475 FD_SET (0, &input_wait_mask);
7476 #endif
7478 Vprocess_alist = Qnil;
7479 deleted_pid_list = Qnil;
7480 for (i = 0; i < FD_SETSIZE; i++)
7482 chan_process[i] = Qnil;
7483 proc_buffered_char[i] = -1;
7485 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7486 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7487 #ifdef DATAGRAM_SOCKETS
7488 memset (datagram_address, 0, sizeof datagram_address);
7489 #endif
7491 #if defined (DARWIN_OS)
7492 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7493 processes. As such, we only change the default value. */
7494 if (initialized)
7496 char const *release = (STRINGP (Voperating_system_release)
7497 ? SSDATA (Voperating_system_release)
7498 : 0);
7499 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7500 Vprocess_connection_type = Qnil;
7503 #endif
7504 #endif /* subprocesses */
7505 kbd_is_on_hold = 0;
7508 void
7509 syms_of_process (void)
7511 #ifdef subprocesses
7513 DEFSYM (Qprocessp, "processp");
7514 DEFSYM (Qrun, "run");
7515 DEFSYM (Qstop, "stop");
7516 DEFSYM (Qsignal, "signal");
7518 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7519 here again. */
7521 DEFSYM (Qopen, "open");
7522 DEFSYM (Qclosed, "closed");
7523 DEFSYM (Qconnect, "connect");
7524 DEFSYM (Qfailed, "failed");
7525 DEFSYM (Qlisten, "listen");
7526 DEFSYM (Qlocal, "local");
7527 DEFSYM (Qipv4, "ipv4");
7528 #ifdef AF_INET6
7529 DEFSYM (Qipv6, "ipv6");
7530 #endif
7531 DEFSYM (Qdatagram, "datagram");
7532 DEFSYM (Qseqpacket, "seqpacket");
7534 DEFSYM (QCport, ":port");
7535 DEFSYM (QCspeed, ":speed");
7536 DEFSYM (QCprocess, ":process");
7538 DEFSYM (QCbytesize, ":bytesize");
7539 DEFSYM (QCstopbits, ":stopbits");
7540 DEFSYM (QCparity, ":parity");
7541 DEFSYM (Qodd, "odd");
7542 DEFSYM (Qeven, "even");
7543 DEFSYM (QCflowcontrol, ":flowcontrol");
7544 DEFSYM (Qhw, "hw");
7545 DEFSYM (Qsw, "sw");
7546 DEFSYM (QCsummary, ":summary");
7548 DEFSYM (Qreal, "real");
7549 DEFSYM (Qnetwork, "network");
7550 DEFSYM (Qserial, "serial");
7551 DEFSYM (Qpipe, "pipe");
7552 DEFSYM (QCbuffer, ":buffer");
7553 DEFSYM (QChost, ":host");
7554 DEFSYM (QCservice, ":service");
7555 DEFSYM (QClocal, ":local");
7556 DEFSYM (QCremote, ":remote");
7557 DEFSYM (QCcoding, ":coding");
7558 DEFSYM (QCserver, ":server");
7559 DEFSYM (QCnowait, ":nowait");
7560 DEFSYM (QCsentinel, ":sentinel");
7561 DEFSYM (QClog, ":log");
7562 DEFSYM (QCnoquery, ":noquery");
7563 DEFSYM (QCstop, ":stop");
7564 DEFSYM (QCplist, ":plist");
7565 DEFSYM (QCcommand, ":command");
7566 DEFSYM (QCconnection_type, ":connection-type");
7567 DEFSYM (QCstderr, ":stderr");
7568 DEFSYM (Qpty, "pty");
7569 DEFSYM (Qpipe, "pipe");
7571 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7573 staticpro (&Vprocess_alist);
7574 staticpro (&deleted_pid_list);
7576 #endif /* subprocesses */
7578 DEFSYM (QCname, ":name");
7579 DEFSYM (QCtype, ":type");
7581 DEFSYM (Qeuid, "euid");
7582 DEFSYM (Qegid, "egid");
7583 DEFSYM (Quser, "user");
7584 DEFSYM (Qgroup, "group");
7585 DEFSYM (Qcomm, "comm");
7586 DEFSYM (Qstate, "state");
7587 DEFSYM (Qppid, "ppid");
7588 DEFSYM (Qpgrp, "pgrp");
7589 DEFSYM (Qsess, "sess");
7590 DEFSYM (Qttname, "ttname");
7591 DEFSYM (Qtpgid, "tpgid");
7592 DEFSYM (Qminflt, "minflt");
7593 DEFSYM (Qmajflt, "majflt");
7594 DEFSYM (Qcminflt, "cminflt");
7595 DEFSYM (Qcmajflt, "cmajflt");
7596 DEFSYM (Qutime, "utime");
7597 DEFSYM (Qstime, "stime");
7598 DEFSYM (Qtime, "time");
7599 DEFSYM (Qcutime, "cutime");
7600 DEFSYM (Qcstime, "cstime");
7601 DEFSYM (Qctime, "ctime");
7602 #ifdef subprocesses
7603 DEFSYM (Qinternal_default_process_sentinel,
7604 "internal-default-process-sentinel");
7605 DEFSYM (Qinternal_default_process_filter,
7606 "internal-default-process-filter");
7607 #endif
7608 DEFSYM (Qpri, "pri");
7609 DEFSYM (Qnice, "nice");
7610 DEFSYM (Qthcount, "thcount");
7611 DEFSYM (Qstart, "start");
7612 DEFSYM (Qvsize, "vsize");
7613 DEFSYM (Qrss, "rss");
7614 DEFSYM (Qetime, "etime");
7615 DEFSYM (Qpcpu, "pcpu");
7616 DEFSYM (Qpmem, "pmem");
7617 DEFSYM (Qargs, "args");
7619 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7620 doc: /* Non-nil means delete processes immediately when they exit.
7621 A value of nil means don't delete them until `list-processes' is run. */);
7623 delete_exited_processes = 1;
7625 #ifdef subprocesses
7626 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7627 doc: /* Control type of device used to communicate with subprocesses.
7628 Values are nil to use a pipe, or t or `pty' to use a pty.
7629 The value has no effect if the system has no ptys or if all ptys are busy:
7630 then a pipe is used in any case.
7631 The value takes effect when `start-process' is called. */);
7632 Vprocess_connection_type = Qt;
7634 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7635 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7636 On some systems, when Emacs reads the output from a subprocess, the output data
7637 is read in very small blocks, potentially resulting in very poor performance.
7638 This behavior can be remedied to some extent by setting this variable to a
7639 non-nil value, as it will automatically delay reading from such processes, to
7640 allow them to produce more output before Emacs tries to read it.
7641 If the value is t, the delay is reset after each write to the process; any other
7642 non-nil value means that the delay is not reset on write.
7643 The variable takes effect when `start-process' is called. */);
7644 Vprocess_adaptive_read_buffering = Qt;
7646 defsubr (&Sprocessp);
7647 defsubr (&Sget_process);
7648 defsubr (&Sdelete_process);
7649 defsubr (&Sprocess_status);
7650 defsubr (&Sprocess_exit_status);
7651 defsubr (&Sprocess_id);
7652 defsubr (&Sprocess_name);
7653 defsubr (&Sprocess_tty_name);
7654 defsubr (&Sprocess_command);
7655 defsubr (&Sset_process_buffer);
7656 defsubr (&Sprocess_buffer);
7657 defsubr (&Sprocess_mark);
7658 defsubr (&Sset_process_filter);
7659 defsubr (&Sprocess_filter);
7660 defsubr (&Sset_process_sentinel);
7661 defsubr (&Sprocess_sentinel);
7662 defsubr (&Sset_process_window_size);
7663 defsubr (&Sset_process_inherit_coding_system_flag);
7664 defsubr (&Sset_process_query_on_exit_flag);
7665 defsubr (&Sprocess_query_on_exit_flag);
7666 defsubr (&Sprocess_contact);
7667 defsubr (&Sprocess_plist);
7668 defsubr (&Sset_process_plist);
7669 defsubr (&Sprocess_list);
7670 defsubr (&Smake_process);
7671 defsubr (&Smake_pipe_process);
7672 defsubr (&Sserial_process_configure);
7673 defsubr (&Smake_serial_process);
7674 defsubr (&Sset_network_process_option);
7675 defsubr (&Smake_network_process);
7676 defsubr (&Sformat_network_address);
7677 defsubr (&Snetwork_interface_list);
7678 defsubr (&Snetwork_interface_info);
7679 #ifdef DATAGRAM_SOCKETS
7680 defsubr (&Sprocess_datagram_address);
7681 defsubr (&Sset_process_datagram_address);
7682 #endif
7683 defsubr (&Saccept_process_output);
7684 defsubr (&Sprocess_send_region);
7685 defsubr (&Sprocess_send_string);
7686 defsubr (&Sinterrupt_process);
7687 defsubr (&Skill_process);
7688 defsubr (&Squit_process);
7689 defsubr (&Sstop_process);
7690 defsubr (&Scontinue_process);
7691 defsubr (&Sprocess_running_child_p);
7692 defsubr (&Sprocess_send_eof);
7693 defsubr (&Ssignal_process);
7694 defsubr (&Swaiting_for_user_input_p);
7695 defsubr (&Sprocess_type);
7696 defsubr (&Sinternal_default_process_sentinel);
7697 defsubr (&Sinternal_default_process_filter);
7698 defsubr (&Sset_process_coding_system);
7699 defsubr (&Sprocess_coding_system);
7700 defsubr (&Sset_process_filter_multibyte);
7701 defsubr (&Sprocess_filter_multibyte_p);
7703 #endif /* subprocesses */
7705 defsubr (&Sget_buffer_process);
7706 defsubr (&Sprocess_inherit_coding_system_flag);
7707 defsubr (&Slist_system_processes);
7708 defsubr (&Sprocess_attributes);
7711 Lisp_Object subfeatures = Qnil;
7712 const struct socket_options *sopt;
7714 #define ADD_SUBFEATURE(key, val) \
7715 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7717 #ifdef NON_BLOCKING_CONNECT
7718 ADD_SUBFEATURE (QCnowait, Qt);
7719 #endif
7720 #ifdef DATAGRAM_SOCKETS
7721 ADD_SUBFEATURE (QCtype, Qdatagram);
7722 #endif
7723 #ifdef HAVE_SEQPACKET
7724 ADD_SUBFEATURE (QCtype, Qseqpacket);
7725 #endif
7726 #ifdef HAVE_LOCAL_SOCKETS
7727 ADD_SUBFEATURE (QCfamily, Qlocal);
7728 #endif
7729 ADD_SUBFEATURE (QCfamily, Qipv4);
7730 #ifdef AF_INET6
7731 ADD_SUBFEATURE (QCfamily, Qipv6);
7732 #endif
7733 #ifdef HAVE_GETSOCKNAME
7734 ADD_SUBFEATURE (QCservice, Qt);
7735 #endif
7736 ADD_SUBFEATURE (QCserver, Qt);
7738 for (sopt = socket_options; sopt->name; sopt++)
7739 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7741 Fprovide (intern_c_string ("make-network-process"), subfeatures);