; * lisp/simple: Revert presumably unintentional deletion of special-mode.
[emacs.git] / src / process.c
blob17fe708a954a995b0f925ec2f7b81e36560bad6c
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 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
228 #define ADAPTIVE_READ_BUFFERING
229 #endif
231 #ifdef ADAPTIVE_READ_BUFFERING
232 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
233 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
234 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
236 /* Number of processes which have a non-zero read_output_delay,
237 and therefore might be delayed for adaptive read buffering. */
239 static int process_output_delay_count;
241 /* True if any process has non-nil read_output_skip. */
243 static bool process_output_skip;
245 #else
246 #define process_output_delay_count 0
247 #endif
249 static void create_process (Lisp_Object, char **, Lisp_Object);
250 #ifdef USABLE_SIGIO
251 static bool keyboard_bit_set (fd_set *);
252 #endif
253 static void deactivate_process (Lisp_Object);
254 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
255 static int read_process_output (Lisp_Object, int);
256 static void handle_child_signal (int);
257 static void create_pty (Lisp_Object);
259 static Lisp_Object get_process (register Lisp_Object name);
260 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
262 /* Mask of bits indicating the descriptors that we wait for input on. */
264 static fd_set input_wait_mask;
266 /* Mask that excludes keyboard input descriptor(s). */
268 static fd_set non_keyboard_wait_mask;
270 /* Mask that excludes process input descriptor(s). */
272 static fd_set non_process_wait_mask;
274 /* Mask for selecting for write. */
276 static fd_set write_mask;
278 #ifdef NON_BLOCKING_CONNECT
279 /* Mask of bits indicating the descriptors that we wait for connect to
280 complete on. Once they complete, they are removed from this mask
281 and added to the input_wait_mask and non_keyboard_wait_mask. */
283 static fd_set connect_wait_mask;
285 /* Number of bits set in connect_wait_mask. */
286 static int num_pending_connects;
287 #endif /* NON_BLOCKING_CONNECT */
289 /* The largest descriptor currently in use for a process object; -1 if none. */
290 static int max_process_desc;
292 /* The largest descriptor currently in use for input; -1 if none. */
293 static int max_input_desc;
295 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
296 static Lisp_Object chan_process[FD_SETSIZE];
298 /* Alist of elements (NAME . PROCESS). */
299 static Lisp_Object Vprocess_alist;
301 /* Buffered-ahead input char from process, indexed by channel.
302 -1 means empty (no char is buffered).
303 Used on sys V where the only way to tell if there is any
304 output from the process is to read at least one char.
305 Always -1 on systems that support FIONREAD. */
307 static int proc_buffered_char[FD_SETSIZE];
309 /* Table of `struct coding-system' for each process. */
310 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
311 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
313 #ifdef DATAGRAM_SOCKETS
314 /* Table of `partner address' for datagram sockets. */
315 static struct sockaddr_and_len {
316 struct sockaddr *sa;
317 int len;
318 } datagram_address[FD_SETSIZE];
319 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
320 #define DATAGRAM_CONN_P(proc) \
321 (PROCESSP (proc) && \
322 XPROCESS (proc)->infd >= 0 && \
323 datagram_address[XPROCESS (proc)->infd].sa != 0)
324 #else
325 #define DATAGRAM_CHAN_P(chan) (0)
326 #define DATAGRAM_CONN_P(proc) (0)
327 #endif
329 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
330 a `for' loop which iterates over processes from Vprocess_alist. */
332 #define FOR_EACH_PROCESS(list_var, proc_var) \
333 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
335 /* These setters are used only in this file, so they can be private. */
336 static void
337 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
339 p->buffer = val;
341 static void
342 pset_command (struct Lisp_Process *p, Lisp_Object val)
344 p->command = val;
346 static void
347 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
349 p->decode_coding_system = val;
351 static void
352 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
354 p->decoding_buf = val;
356 static void
357 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
359 p->encode_coding_system = val;
361 static void
362 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
364 p->encoding_buf = val;
366 static void
367 pset_filter (struct Lisp_Process *p, Lisp_Object val)
369 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
371 static void
372 pset_log (struct Lisp_Process *p, Lisp_Object val)
374 p->log = val;
376 static void
377 pset_mark (struct Lisp_Process *p, Lisp_Object val)
379 p->mark = val;
381 static void
382 pset_name (struct Lisp_Process *p, Lisp_Object val)
384 p->name = val;
386 static void
387 pset_plist (struct Lisp_Process *p, Lisp_Object val)
389 p->plist = val;
391 static void
392 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
394 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
396 static void
397 pset_status (struct Lisp_Process *p, Lisp_Object val)
399 p->status = val;
401 static void
402 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
404 p->tty_name = val;
406 static void
407 pset_type (struct Lisp_Process *p, Lisp_Object val)
409 p->type = val;
411 static void
412 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
414 p->write_queue = val;
416 static void
417 pset_stderrproc (struct Lisp_Process *p, Lisp_Object val)
419 p->stderrproc = val;
423 static Lisp_Object
424 make_lisp_proc (struct Lisp_Process *p)
426 return make_lisp_ptr (p, Lisp_Vectorlike);
429 static struct fd_callback_data
431 fd_callback func;
432 void *data;
433 #define FOR_READ 1
434 #define FOR_WRITE 2
435 int condition; /* Mask of the defines above. */
436 } fd_callback_info[FD_SETSIZE];
439 /* Add a file descriptor FD to be monitored for when read is possible.
440 When read is possible, call FUNC with argument DATA. */
442 void
443 add_read_fd (int fd, fd_callback func, void *data)
445 add_keyboard_wait_descriptor (fd);
447 fd_callback_info[fd].func = func;
448 fd_callback_info[fd].data = data;
449 fd_callback_info[fd].condition |= FOR_READ;
452 /* Stop monitoring file descriptor FD for when read is possible. */
454 void
455 delete_read_fd (int fd)
457 delete_keyboard_wait_descriptor (fd);
459 fd_callback_info[fd].condition &= ~FOR_READ;
460 if (fd_callback_info[fd].condition == 0)
462 fd_callback_info[fd].func = 0;
463 fd_callback_info[fd].data = 0;
467 /* Add a file descriptor FD to be monitored for when write is possible.
468 When write is possible, call FUNC with argument DATA. */
470 void
471 add_write_fd (int fd, fd_callback func, void *data)
473 FD_SET (fd, &write_mask);
474 if (fd > max_input_desc)
475 max_input_desc = fd;
477 fd_callback_info[fd].func = func;
478 fd_callback_info[fd].data = data;
479 fd_callback_info[fd].condition |= FOR_WRITE;
482 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
484 static void
485 delete_input_desc (int fd)
487 if (fd == max_input_desc)
490 fd--;
491 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
492 || FD_ISSET (fd, &write_mask)));
494 max_input_desc = fd;
498 /* Stop monitoring file descriptor FD for when write is possible. */
500 void
501 delete_write_fd (int fd)
503 FD_CLR (fd, &write_mask);
504 fd_callback_info[fd].condition &= ~FOR_WRITE;
505 if (fd_callback_info[fd].condition == 0)
507 fd_callback_info[fd].func = 0;
508 fd_callback_info[fd].data = 0;
509 delete_input_desc (fd);
514 /* Compute the Lisp form of the process status, p->status, from
515 the numeric status that was returned by `wait'. */
517 static Lisp_Object status_convert (int);
519 static void
520 update_status (struct Lisp_Process *p)
522 eassert (p->raw_status_new);
523 pset_status (p, status_convert (p->raw_status));
524 p->raw_status_new = 0;
527 /* Convert a process status word in Unix format to
528 the list that we use internally. */
530 static Lisp_Object
531 status_convert (int w)
533 if (WIFSTOPPED (w))
534 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
535 else if (WIFEXITED (w))
536 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
537 WCOREDUMP (w) ? Qt : Qnil));
538 else if (WIFSIGNALED (w))
539 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
540 WCOREDUMP (w) ? Qt : Qnil));
541 else
542 return Qrun;
545 /* Given a status-list, extract the three pieces of information
546 and store them individually through the three pointers. */
548 static void
549 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
551 Lisp_Object tem;
553 if (SYMBOLP (l))
555 *symbol = l;
556 *code = 0;
557 *coredump = 0;
559 else
561 *symbol = XCAR (l);
562 tem = XCDR (l);
563 *code = XFASTINT (XCAR (tem));
564 tem = XCDR (tem);
565 *coredump = !NILP (tem);
569 /* Return a string describing a process status list. */
571 static Lisp_Object
572 status_message (struct Lisp_Process *p)
574 Lisp_Object status = p->status;
575 Lisp_Object symbol;
576 int code;
577 bool coredump;
578 Lisp_Object string;
580 decode_status (status, &symbol, &code, &coredump);
582 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
584 char const *signame;
585 synchronize_system_messages_locale ();
586 signame = strsignal (code);
587 if (signame == 0)
588 string = build_string ("unknown");
589 else
591 int c1, c2;
593 string = build_unibyte_string (signame);
594 if (! NILP (Vlocale_coding_system))
595 string = (code_convert_string_norecord
596 (string, Vlocale_coding_system, 0));
597 c1 = STRING_CHAR (SDATA (string));
598 c2 = downcase (c1);
599 if (c1 != c2)
600 Faset (string, make_number (0), make_number (c2));
602 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
603 return concat2 (string, suffix);
605 else if (EQ (symbol, Qexit))
607 if (NETCONN1_P (p))
608 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
609 if (code == 0)
610 return build_string ("finished\n");
611 AUTO_STRING (prefix, "exited abnormally with code ");
612 string = Fnumber_to_string (make_number (code));
613 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
614 return concat3 (prefix, string, suffix);
616 else if (EQ (symbol, Qfailed))
618 AUTO_STRING (prefix, "failed with code ");
619 string = Fnumber_to_string (make_number (code));
620 AUTO_STRING (suffix, "\n");
621 return concat3 (prefix, string, suffix);
623 else
624 return Fcopy_sequence (Fsymbol_name (symbol));
627 enum { PTY_NAME_SIZE = 24 };
629 /* Open an available pty, returning a file descriptor.
630 Store into PTY_NAME the file name of the terminal corresponding to the pty.
631 Return -1 on failure. */
633 static int
634 allocate_pty (char pty_name[PTY_NAME_SIZE])
636 #ifdef HAVE_PTYS
637 int fd;
639 #ifdef PTY_ITERATION
640 PTY_ITERATION
641 #else
642 register int c, i;
643 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
644 for (i = 0; i < 16; i++)
645 #endif
647 #ifdef PTY_NAME_SPRINTF
648 PTY_NAME_SPRINTF
649 #else
650 sprintf (pty_name, "/dev/pty%c%x", c, i);
651 #endif /* no PTY_NAME_SPRINTF */
653 #ifdef PTY_OPEN
654 PTY_OPEN;
655 #else /* no PTY_OPEN */
656 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
657 #endif /* no PTY_OPEN */
659 if (fd >= 0)
661 #ifdef PTY_OPEN
662 /* Set FD's close-on-exec flag. This is needed even if
663 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
664 doesn't require support for that combination.
665 Multithreaded platforms where posix_openpt ignores
666 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
667 have a race condition between the PTY_OPEN and here. */
668 fcntl (fd, F_SETFD, FD_CLOEXEC);
669 #endif
670 /* Check to make certain that both sides are available
671 this avoids a nasty yet stupid bug in rlogins. */
672 #ifdef PTY_TTY_NAME_SPRINTF
673 PTY_TTY_NAME_SPRINTF
674 #else
675 sprintf (pty_name, "/dev/tty%c%x", c, i);
676 #endif /* no PTY_TTY_NAME_SPRINTF */
677 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
679 emacs_close (fd);
680 # ifndef __sgi
681 continue;
682 # else
683 return -1;
684 # endif /* __sgi */
686 setup_pty (fd);
687 return fd;
690 #endif /* HAVE_PTYS */
691 return -1;
694 /* Allocate basically initialized process. */
696 static struct Lisp_Process *
697 allocate_process (void)
699 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
702 static Lisp_Object
703 make_process (Lisp_Object name)
705 register Lisp_Object val, tem, name1;
706 register struct Lisp_Process *p;
707 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
708 printmax_t i;
710 p = allocate_process ();
711 /* Initialize Lisp data. Note that allocate_process initializes all
712 Lisp data to nil, so do it only for slots which should not be nil. */
713 pset_status (p, Qrun);
714 pset_mark (p, Fmake_marker ());
716 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
717 non-Lisp data, so do it only for slots which should not be zero. */
718 p->infd = -1;
719 p->outfd = -1;
720 for (i = 0; i < PROCESS_OPEN_FDS; i++)
721 p->open_fd[i] = -1;
723 #ifdef HAVE_GNUTLS
724 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
725 #endif
727 /* If name is already in use, modify it until it is unused. */
729 name1 = name;
730 for (i = 1; ; i++)
732 tem = Fget_process (name1);
733 if (NILP (tem)) break;
734 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
736 name = name1;
737 pset_name (p, name);
738 pset_sentinel (p, Qinternal_default_process_sentinel);
739 pset_filter (p, Qinternal_default_process_filter);
740 XSETPROCESS (val, p);
741 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
742 return val;
745 static void
746 remove_process (register Lisp_Object proc)
748 register Lisp_Object pair;
750 pair = Frassq (proc, Vprocess_alist);
751 Vprocess_alist = Fdelq (pair, Vprocess_alist);
753 deactivate_process (proc);
757 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
758 doc: /* Return t if OBJECT is a process. */)
759 (Lisp_Object object)
761 return PROCESSP (object) ? Qt : Qnil;
764 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
765 doc: /* Return the process named NAME, or nil if there is none. */)
766 (register Lisp_Object name)
768 if (PROCESSP (name))
769 return name;
770 CHECK_STRING (name);
771 return Fcdr (Fassoc (name, Vprocess_alist));
774 /* This is how commands for the user decode process arguments. It
775 accepts a process, a process name, a buffer, a buffer name, or nil.
776 Buffers denote the first process in the buffer, and nil denotes the
777 current buffer. */
779 static Lisp_Object
780 get_process (register Lisp_Object name)
782 register Lisp_Object proc, obj;
783 if (STRINGP (name))
785 obj = Fget_process (name);
786 if (NILP (obj))
787 obj = Fget_buffer (name);
788 if (NILP (obj))
789 error ("Process %s does not exist", SDATA (name));
791 else if (NILP (name))
792 obj = Fcurrent_buffer ();
793 else
794 obj = name;
796 /* Now obj should be either a buffer object or a process object. */
797 if (BUFFERP (obj))
799 if (NILP (BVAR (XBUFFER (obj), name)))
800 error ("Attempt to get process for a dead buffer");
801 proc = Fget_buffer_process (obj);
802 if (NILP (proc))
803 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
805 else
807 CHECK_PROCESS (obj);
808 proc = obj;
810 return proc;
814 /* Fdelete_process promises to immediately forget about the process, but in
815 reality, Emacs needs to remember those processes until they have been
816 treated by the SIGCHLD handler and waitpid has been invoked on them;
817 otherwise they might fill up the kernel's process table.
819 Some processes created by call-process are also put onto this list.
821 Members of this list are (process-ID . filename) pairs. The
822 process-ID is a number; the filename, if a string, is a file that
823 needs to be removed after the process exits. */
824 static Lisp_Object deleted_pid_list;
826 void
827 record_deleted_pid (pid_t pid, Lisp_Object filename)
829 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
830 /* GC treated elements set to nil. */
831 Fdelq (Qnil, deleted_pid_list));
835 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
836 doc: /* Delete PROCESS: kill it and forget about it immediately.
837 PROCESS may be a process, a buffer, the name of a process or buffer, or
838 nil, indicating the current buffer's process. */)
839 (register Lisp_Object process)
841 register struct Lisp_Process *p;
843 process = get_process (process);
844 p = XPROCESS (process);
846 p->raw_status_new = 0;
847 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
849 pset_status (p, list2 (Qexit, make_number (0)));
850 p->tick = ++process_tick;
851 status_notify (p, NULL);
852 redisplay_preserve_echo_area (13);
854 else
856 if (p->alive)
857 record_kill_process (p, Qnil);
859 if (p->infd >= 0)
861 /* Update P's status, since record_kill_process will make the
862 SIGCHLD handler update deleted_pid_list, not *P. */
863 Lisp_Object symbol;
864 if (p->raw_status_new)
865 update_status (p);
866 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
867 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
868 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
870 p->tick = ++process_tick;
871 status_notify (p, NULL);
872 redisplay_preserve_echo_area (13);
875 remove_process (process);
876 return Qnil;
879 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
880 doc: /* Return the status of PROCESS.
881 The returned value is one of the following symbols:
882 run -- for a process that is running.
883 stop -- for a process stopped but continuable.
884 exit -- for a process that has exited.
885 signal -- for a process that has got a fatal signal.
886 open -- for a network stream connection that is open.
887 listen -- for a network stream server that is listening.
888 closed -- for a network stream connection that is closed.
889 connect -- when waiting for a non-blocking connection to complete.
890 failed -- when a non-blocking connection has failed.
891 nil -- if arg is a process name and no such process exists.
892 PROCESS may be a process, a buffer, the name of a process, or
893 nil, indicating the current buffer's process. */)
894 (register Lisp_Object process)
896 register struct Lisp_Process *p;
897 register Lisp_Object status;
899 if (STRINGP (process))
900 process = Fget_process (process);
901 else
902 process = get_process (process);
904 if (NILP (process))
905 return process;
907 p = XPROCESS (process);
908 if (p->raw_status_new)
909 update_status (p);
910 status = p->status;
911 if (CONSP (status))
912 status = XCAR (status);
913 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
915 if (EQ (status, Qexit))
916 status = Qclosed;
917 else if (EQ (p->command, Qt))
918 status = Qstop;
919 else if (EQ (status, Qrun))
920 status = Qopen;
922 return status;
925 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
926 1, 1, 0,
927 doc: /* Return the exit status of PROCESS or the signal number that killed it.
928 If PROCESS has not yet exited or died, return 0. */)
929 (register Lisp_Object process)
931 CHECK_PROCESS (process);
932 if (XPROCESS (process)->raw_status_new)
933 update_status (XPROCESS (process));
934 if (CONSP (XPROCESS (process)->status))
935 return XCAR (XCDR (XPROCESS (process)->status));
936 return make_number (0);
939 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
940 doc: /* Return the process id of PROCESS.
941 This is the pid of the external process which PROCESS uses or talks to.
942 For a network connection, this value is nil. */)
943 (register Lisp_Object process)
945 pid_t pid;
947 CHECK_PROCESS (process);
948 pid = XPROCESS (process)->pid;
949 return (pid ? make_fixnum_or_float (pid) : Qnil);
952 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
953 doc: /* Return the name of PROCESS, as a string.
954 This is the name of the program invoked in PROCESS,
955 possibly modified to make it unique among process names. */)
956 (register Lisp_Object process)
958 CHECK_PROCESS (process);
959 return XPROCESS (process)->name;
962 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
963 doc: /* Return the command that was executed to start PROCESS.
964 This is a list of strings, the first string being the program executed
965 and the rest of the strings being the arguments given to it.
966 For a network or serial process, this is nil (process is running) or t
967 \(process is stopped). */)
968 (register Lisp_Object process)
970 CHECK_PROCESS (process);
971 return XPROCESS (process)->command;
974 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
975 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
976 This is the terminal that the process itself reads and writes on,
977 not the name of the pty that Emacs uses to talk with that terminal. */)
978 (register Lisp_Object process)
980 CHECK_PROCESS (process);
981 return XPROCESS (process)->tty_name;
984 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
985 2, 2, 0,
986 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
987 Return BUFFER. */)
988 (register Lisp_Object process, Lisp_Object buffer)
990 struct Lisp_Process *p;
992 CHECK_PROCESS (process);
993 if (!NILP (buffer))
994 CHECK_BUFFER (buffer);
995 p = XPROCESS (process);
996 pset_buffer (p, buffer);
997 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
998 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
999 setup_process_coding_systems (process);
1000 return buffer;
1003 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1004 1, 1, 0,
1005 doc: /* Return the buffer PROCESS is associated with.
1006 The default process filter inserts output from PROCESS into this buffer. */)
1007 (register Lisp_Object process)
1009 CHECK_PROCESS (process);
1010 return XPROCESS (process)->buffer;
1013 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1014 1, 1, 0,
1015 doc: /* Return the marker for the end of the last output from PROCESS. */)
1016 (register Lisp_Object process)
1018 CHECK_PROCESS (process);
1019 return XPROCESS (process)->mark;
1022 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1023 2, 2, 0,
1024 doc: /* Give PROCESS the filter function FILTER; nil means default.
1025 A value of t means stop accepting output from the process.
1027 When a process has a non-default filter, its buffer is not used for output.
1028 Instead, each time it does output, the entire string of output is
1029 passed to the filter.
1031 The filter gets two arguments: the process and the string of output.
1032 The string argument is normally a multibyte string, except:
1033 - if the process's input coding system is no-conversion or raw-text,
1034 it is a unibyte string (the non-converted input), or else
1035 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1036 string (the result of converting the decoded input multibyte
1037 string to unibyte with `string-make-unibyte'). */)
1038 (register Lisp_Object process, Lisp_Object filter)
1040 struct Lisp_Process *p;
1042 CHECK_PROCESS (process);
1043 p = XPROCESS (process);
1045 /* Don't signal an error if the process's input file descriptor
1046 is closed. This could make debugging Lisp more difficult,
1047 for example when doing something like
1049 (setq process (start-process ...))
1050 (debug)
1051 (set-process-filter process ...) */
1053 if (NILP (filter))
1054 filter = Qinternal_default_process_filter;
1056 if (p->infd >= 0)
1058 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1060 FD_CLR (p->infd, &input_wait_mask);
1061 FD_CLR (p->infd, &non_keyboard_wait_mask);
1063 else if (EQ (p->filter, Qt)
1064 /* Network or serial process not stopped: */
1065 && !EQ (p->command, Qt))
1067 FD_SET (p->infd, &input_wait_mask);
1068 FD_SET (p->infd, &non_keyboard_wait_mask);
1072 pset_filter (p, filter);
1073 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1074 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1075 setup_process_coding_systems (process);
1076 return filter;
1079 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1080 1, 1, 0,
1081 doc: /* Return the filter function of PROCESS.
1082 See `set-process-filter' for more info on filter functions. */)
1083 (register Lisp_Object process)
1085 CHECK_PROCESS (process);
1086 return XPROCESS (process)->filter;
1089 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1090 2, 2, 0,
1091 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1092 The sentinel is called as a function when the process changes state.
1093 It gets two arguments: the process, and a string describing the change. */)
1094 (register Lisp_Object process, Lisp_Object sentinel)
1096 struct Lisp_Process *p;
1098 CHECK_PROCESS (process);
1099 p = XPROCESS (process);
1101 if (NILP (sentinel))
1102 sentinel = Qinternal_default_process_sentinel;
1104 pset_sentinel (p, sentinel);
1105 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1106 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1107 return sentinel;
1110 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1111 1, 1, 0,
1112 doc: /* Return the sentinel of PROCESS.
1113 See `set-process-sentinel' for more info on sentinels. */)
1114 (register Lisp_Object process)
1116 CHECK_PROCESS (process);
1117 return XPROCESS (process)->sentinel;
1120 DEFUN ("set-process-window-size", Fset_process_window_size,
1121 Sset_process_window_size, 3, 3, 0,
1122 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1123 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1125 CHECK_PROCESS (process);
1127 /* All known platforms store window sizes as 'unsigned short'. */
1128 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1129 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1131 if (XPROCESS (process)->infd < 0
1132 || (set_window_size (XPROCESS (process)->infd,
1133 XINT (height), XINT (width))
1134 < 0))
1135 return Qnil;
1136 else
1137 return Qt;
1140 DEFUN ("set-process-inherit-coding-system-flag",
1141 Fset_process_inherit_coding_system_flag,
1142 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1143 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1144 If the second argument FLAG is non-nil, then the variable
1145 `buffer-file-coding-system' of the buffer associated with PROCESS
1146 will be bound to the value of the coding system used to decode
1147 the process output.
1149 This is useful when the coding system specified for the process buffer
1150 leaves either the character code conversion or the end-of-line conversion
1151 unspecified, or if the coding system used to decode the process output
1152 is more appropriate for saving the process buffer.
1154 Binding the variable `inherit-process-coding-system' to non-nil before
1155 starting the process is an alternative way of setting the inherit flag
1156 for the process which will run.
1158 This function returns FLAG. */)
1159 (register Lisp_Object process, Lisp_Object flag)
1161 CHECK_PROCESS (process);
1162 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1163 return flag;
1166 DEFUN ("set-process-query-on-exit-flag",
1167 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1168 2, 2, 0,
1169 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1170 If the second argument FLAG is non-nil, Emacs will query the user before
1171 exiting or killing a buffer if PROCESS is running. This function
1172 returns FLAG. */)
1173 (register Lisp_Object process, Lisp_Object flag)
1175 CHECK_PROCESS (process);
1176 XPROCESS (process)->kill_without_query = NILP (flag);
1177 return flag;
1180 DEFUN ("process-query-on-exit-flag",
1181 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1182 1, 1, 0,
1183 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1184 (register Lisp_Object process)
1186 CHECK_PROCESS (process);
1187 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1190 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1191 1, 2, 0,
1192 doc: /* Return the contact info of PROCESS; t for a real child.
1193 For a network or serial connection, the value depends on the optional
1194 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1195 SERVICE) for a network connection or (PORT SPEED) for a serial
1196 connection. If KEY is t, the complete contact information for the
1197 connection is returned, else the specific value for the keyword KEY is
1198 returned. See `make-network-process' or `make-serial-process' for a
1199 list of keywords. */)
1200 (register Lisp_Object process, Lisp_Object key)
1202 Lisp_Object contact;
1204 CHECK_PROCESS (process);
1205 contact = XPROCESS (process)->childp;
1207 #ifdef DATAGRAM_SOCKETS
1208 if (DATAGRAM_CONN_P (process)
1209 && (EQ (key, Qt) || EQ (key, QCremote)))
1210 contact = Fplist_put (contact, QCremote,
1211 Fprocess_datagram_address (process));
1212 #endif
1214 if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1215 || EQ (key, Qt))
1216 return contact;
1217 if (NILP (key) && NETCONN_P (process))
1218 return list2 (Fplist_get (contact, QChost),
1219 Fplist_get (contact, QCservice));
1220 if (NILP (key) && SERIALCONN_P (process))
1221 return list2 (Fplist_get (contact, QCport),
1222 Fplist_get (contact, QCspeed));
1223 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1224 if the pipe process is useful for purposes other than receiving
1225 stderr. */
1226 if (NILP (key) && PIPECONN_P (process))
1227 return Qt;
1228 return Fplist_get (contact, key);
1231 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1232 1, 1, 0,
1233 doc: /* Return the plist of PROCESS. */)
1234 (register Lisp_Object process)
1236 CHECK_PROCESS (process);
1237 return XPROCESS (process)->plist;
1240 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1241 2, 2, 0,
1242 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1243 (register Lisp_Object process, Lisp_Object plist)
1245 CHECK_PROCESS (process);
1246 CHECK_LIST (plist);
1248 pset_plist (XPROCESS (process), plist);
1249 return plist;
1252 #if 0 /* Turned off because we don't currently record this info
1253 in the process. Perhaps add it. */
1254 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1255 doc: /* Return the connection type of PROCESS.
1256 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1257 a socket connection. */)
1258 (Lisp_Object process)
1260 return XPROCESS (process)->type;
1262 #endif
1264 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1265 doc: /* Return the connection type of PROCESS.
1266 The value is either the symbol `real', `network', or `serial'.
1267 PROCESS may be a process, a buffer, the name of a process or buffer, or
1268 nil, indicating the current buffer's process. */)
1269 (Lisp_Object process)
1271 Lisp_Object proc;
1272 proc = get_process (process);
1273 return XPROCESS (proc)->type;
1276 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1277 1, 2, 0,
1278 doc: /* Convert network ADDRESS from internal format to a string.
1279 A 4 or 5 element vector represents an IPv4 address (with port number).
1280 An 8 or 9 element vector represents an IPv6 address (with port number).
1281 If optional second argument OMIT-PORT is non-nil, don't include a port
1282 number in the string, even when present in ADDRESS.
1283 Returns nil if format of ADDRESS is invalid. */)
1284 (Lisp_Object address, Lisp_Object omit_port)
1286 if (NILP (address))
1287 return Qnil;
1289 if (STRINGP (address)) /* AF_LOCAL */
1290 return address;
1292 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1294 register struct Lisp_Vector *p = XVECTOR (address);
1295 ptrdiff_t size = p->header.size;
1296 Lisp_Object args[10];
1297 int nargs, i;
1298 char const *format;
1300 if (size == 4 || (size == 5 && !NILP (omit_port)))
1302 format = "%d.%d.%d.%d";
1303 nargs = 4;
1305 else if (size == 5)
1307 format = "%d.%d.%d.%d:%d";
1308 nargs = 5;
1310 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1312 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1313 nargs = 8;
1315 else if (size == 9)
1317 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1318 nargs = 9;
1320 else
1321 return Qnil;
1323 AUTO_STRING (format_obj, format);
1324 args[0] = format_obj;
1326 for (i = 0; i < nargs; i++)
1328 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1329 return Qnil;
1331 if (nargs <= 5 /* IPv4 */
1332 && i < 4 /* host, not port */
1333 && XINT (p->contents[i]) > 255)
1334 return Qnil;
1336 args[i + 1] = p->contents[i];
1339 return Fformat (nargs + 1, args);
1342 if (CONSP (address))
1344 AUTO_STRING (format, "<Family %d>");
1345 return CALLN (Fformat, format, Fcar (address));
1348 return Qnil;
1351 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1352 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1353 (void)
1355 return Fmapcar (Qcdr, Vprocess_alist);
1358 /* Starting asynchronous inferior processes. */
1360 static void start_process_unwind (Lisp_Object proc);
1362 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1363 doc: /* Start a program in a subprocess. Return the process object for it.
1365 This is similar to `start-process', but arguments are specified as
1366 keyword/argument pairs. The following arguments are defined:
1368 :name NAME -- NAME is name for process. It is modified if necessary
1369 to make it unique.
1371 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1372 with the process. Process output goes at end of that buffer, unless
1373 you specify an output stream or filter function to handle the output.
1374 BUFFER may be also nil, meaning that this process is not associated
1375 with any buffer.
1377 :command COMMAND -- COMMAND is a list starting with the program file
1378 name, followed by strings to give to the program as arguments.
1380 :coding CODING -- If CODING is a symbol, it specifies the coding
1381 system used for both reading and writing for this process. If CODING
1382 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1383 ENCODING is used for writing.
1385 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1386 the process is running. If BOOL is not given, query before exiting.
1388 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1389 In the stopped state, a process does not accept incoming data, but you
1390 can send outgoing data. The stopped state is cleared by
1391 `continue-process' and set by `stop-process'.
1393 :connection-type TYPE -- TYPE is control type of device used to
1394 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1395 to use a pty, or nil to use the default specified through
1396 `process-connection-type'.
1398 :filter FILTER -- Install FILTER as the process filter.
1400 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1402 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1403 to the standard error of subprocess. Specifying this implies
1404 `:connection-type' is set to `pipe'.
1406 usage: (make-process &rest ARGS) */)
1407 (ptrdiff_t nargs, Lisp_Object *args)
1409 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1410 Lisp_Object xstderr, stderrproc;
1411 ptrdiff_t count = SPECPDL_INDEX ();
1412 struct gcpro gcpro1;
1413 USE_SAFE_ALLOCA;
1415 if (nargs == 0)
1416 return Qnil;
1418 /* Save arguments for process-contact and clone-process. */
1419 contact = Flist (nargs, args);
1420 GCPRO1 (contact);
1422 buffer = Fplist_get (contact, QCbuffer);
1423 if (!NILP (buffer))
1424 buffer = Fget_buffer_create (buffer);
1426 /* Make sure that the child will be able to chdir to the current
1427 buffer's current directory, or its unhandled equivalent. We
1428 can't just have the child check for an error when it does the
1429 chdir, since it's in a vfork.
1431 We have to GCPRO around this because Fexpand_file_name and
1432 Funhandled_file_name_directory might call a file name handling
1433 function. The argument list is protected by the caller, so all
1434 we really have to worry about is buffer. */
1436 struct gcpro gcpro1;
1437 GCPRO1 (buffer);
1438 current_dir = encode_current_directory ();
1439 UNGCPRO;
1442 name = Fplist_get (contact, QCname);
1443 CHECK_STRING (name);
1445 command = Fplist_get (contact, QCcommand);
1446 if (CONSP (command))
1447 program = XCAR (command);
1448 else
1449 program = Qnil;
1451 if (!NILP (program))
1452 CHECK_STRING (program);
1454 stderrproc = Qnil;
1455 xstderr = Fplist_get (contact, QCstderr);
1456 if (PROCESSP (xstderr))
1458 if (!PIPECONN_P (xstderr))
1459 error ("Process is not a pipe process");
1460 stderrproc = xstderr;
1462 else if (!NILP (xstderr))
1464 struct gcpro gcpro1, gcpro2;
1465 CHECK_STRING (program);
1466 GCPRO2 (buffer, current_dir);
1467 stderrproc = CALLN (Fmake_pipe_process,
1468 QCname,
1469 concat2 (name, build_string (" stderr")),
1470 QCbuffer,
1471 Fget_buffer_create (xstderr));
1472 UNGCPRO;
1475 proc = make_process (name);
1476 /* If an error occurs and we can't start the process, we want to
1477 remove it from the process list. This means that each error
1478 check in create_process doesn't need to call remove_process
1479 itself; it's all taken care of here. */
1480 record_unwind_protect (start_process_unwind, proc);
1482 pset_childp (XPROCESS (proc), Qt);
1483 pset_plist (XPROCESS (proc), Qnil);
1484 pset_type (XPROCESS (proc), Qreal);
1485 pset_buffer (XPROCESS (proc), buffer);
1486 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1487 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1488 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1490 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
1491 XPROCESS (proc)->kill_without_query = 1;
1492 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1493 pset_command (XPROCESS (proc), Qt);
1495 tem = Fplist_get (contact, QCconnection_type);
1496 if (EQ (tem, Qpty))
1497 XPROCESS (proc)->pty_flag = true;
1498 else if (EQ (tem, Qpipe))
1499 XPROCESS (proc)->pty_flag = false;
1500 else if (NILP (tem))
1501 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1502 else
1503 report_file_error ("Unknown connection type", tem);
1505 if (!NILP (stderrproc))
1507 pset_stderrproc (XPROCESS (proc), stderrproc);
1509 XPROCESS (proc)->pty_flag = false;
1512 #ifdef HAVE_GNUTLS
1513 /* AKA GNUTLS_INITSTAGE(proc). */
1514 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1515 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1516 #endif
1518 #ifdef ADAPTIVE_READ_BUFFERING
1519 XPROCESS (proc)->adaptive_read_buffering
1520 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1521 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1522 #endif
1524 /* Make the process marker point into the process buffer (if any). */
1525 if (BUFFERP (buffer))
1526 set_marker_both (XPROCESS (proc)->mark, buffer,
1527 BUF_ZV (XBUFFER (buffer)),
1528 BUF_ZV_BYTE (XBUFFER (buffer)));
1531 /* Decide coding systems for communicating with the process. Here
1532 we don't setup the structure coding_system nor pay attention to
1533 unibyte mode. They are done in create_process. */
1535 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1536 Lisp_Object coding_systems = Qt;
1537 Lisp_Object val, *args2;
1538 struct gcpro gcpro1, gcpro2;
1540 tem = Fplist_get (contact, QCcoding);
1541 if (!NILP (tem))
1543 val = tem;
1544 if (CONSP (val))
1545 val = XCAR (val);
1547 else
1548 val = Vcoding_system_for_read;
1549 if (NILP (val))
1551 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1552 Lisp_Object tem2;
1553 SAFE_ALLOCA_LISP (args2, nargs2);
1554 ptrdiff_t i = 0;
1555 args2[i++] = Qstart_process;
1556 args2[i++] = name;
1557 args2[i++] = buffer;
1558 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1559 args2[i++] = XCAR (tem2);
1560 GCPRO2 (proc, current_dir);
1561 if (!NILP (program))
1562 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1563 UNGCPRO;
1564 if (CONSP (coding_systems))
1565 val = XCAR (coding_systems);
1566 else if (CONSP (Vdefault_process_coding_system))
1567 val = XCAR (Vdefault_process_coding_system);
1569 pset_decode_coding_system (XPROCESS (proc), val);
1571 if (!NILP (tem))
1573 val = tem;
1574 if (CONSP (val))
1575 val = XCDR (val);
1577 else
1578 val = Vcoding_system_for_write;
1579 if (NILP (val))
1581 if (EQ (coding_systems, Qt))
1583 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1584 Lisp_Object tem2;
1585 SAFE_ALLOCA_LISP (args2, nargs2);
1586 ptrdiff_t i = 0;
1587 args2[i++] = Qstart_process;
1588 args2[i++] = name;
1589 args2[i++] = buffer;
1590 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1591 args2[i++] = XCAR (tem2);
1592 GCPRO2 (proc, current_dir);
1593 if (!NILP (program))
1594 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1595 UNGCPRO;
1597 if (CONSP (coding_systems))
1598 val = XCDR (coding_systems);
1599 else if (CONSP (Vdefault_process_coding_system))
1600 val = XCDR (Vdefault_process_coding_system);
1602 pset_encode_coding_system (XPROCESS (proc), val);
1603 /* Note: At this moment, the above coding system may leave
1604 text-conversion or eol-conversion unspecified. They will be
1605 decided after we read output from the process and decode it by
1606 some coding system, or just before we actually send a text to
1607 the process. */
1611 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1612 XPROCESS (proc)->decoding_carryover = 0;
1613 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1615 XPROCESS (proc)->inherit_coding_system_flag
1616 = !(NILP (buffer) || !inherit_process_coding_system);
1618 if (!NILP (program))
1620 Lisp_Object program_args = XCDR (command);
1622 /* If program file name is not absolute, search our path for it.
1623 Put the name we will really use in TEM. */
1624 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1625 && !(SCHARS (program) > 1
1626 && IS_DEVICE_SEP (SREF (program, 1))))
1628 struct gcpro gcpro1, gcpro2;
1630 tem = Qnil;
1631 GCPRO2 (buffer, current_dir);
1632 openp (Vexec_path, program, Vexec_suffixes, &tem,
1633 make_number (X_OK), false);
1634 UNGCPRO;
1635 if (NILP (tem))
1636 report_file_error ("Searching for program", program);
1637 tem = Fexpand_file_name (tem, Qnil);
1639 else
1641 if (!NILP (Ffile_directory_p (program)))
1642 error ("Specified program for new process is a directory");
1643 tem = program;
1646 /* Remove "/:" from TEM. */
1647 tem = remove_slash_colon (tem);
1649 Lisp_Object arg_encoding = Qnil;
1650 struct gcpro gcpro1;
1651 GCPRO1 (tem);
1653 /* Encode the file name and put it in NEW_ARGV.
1654 That's where the child will use it to execute the program. */
1655 tem = list1 (ENCODE_FILE (tem));
1656 ptrdiff_t new_argc = 1;
1658 /* Here we encode arguments by the coding system used for sending
1659 data to the process. We don't support using different coding
1660 systems for encoding arguments and for encoding data sent to the
1661 process. */
1663 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1665 Lisp_Object arg = XCAR (tem2);
1666 CHECK_STRING (arg);
1667 if (STRING_MULTIBYTE (arg))
1669 if (NILP (arg_encoding))
1670 arg_encoding = (complement_process_encoding_system
1671 (XPROCESS (proc)->encode_coding_system));
1672 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1674 tem = Fcons (arg, tem);
1675 new_argc++;
1678 UNGCPRO;
1680 /* Now that everything is encoded we can collect the strings into
1681 NEW_ARGV. */
1682 char **new_argv;
1683 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1684 new_argv[new_argc] = 0;
1686 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1688 new_argv[i] = SSDATA (XCAR (tem));
1689 tem = XCDR (tem);
1692 create_process (proc, new_argv, current_dir);
1694 else
1695 create_pty (proc);
1697 UNGCPRO;
1698 SAFE_FREE ();
1699 return unbind_to (count, proc);
1702 /* This function is the unwind_protect form for Fstart_process. If
1703 PROC doesn't have its pid set, then we know someone has signaled
1704 an error and the process wasn't started successfully, so we should
1705 remove it from the process list. */
1706 static void
1707 start_process_unwind (Lisp_Object proc)
1709 if (!PROCESSP (proc))
1710 emacs_abort ();
1712 /* Was PROC started successfully?
1713 -2 is used for a pty with no process, eg for gdb. */
1714 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1715 remove_process (proc);
1718 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1720 static void
1721 close_process_fd (int *fd_addr)
1723 int fd = *fd_addr;
1724 if (0 <= fd)
1726 *fd_addr = -1;
1727 emacs_close (fd);
1731 /* Indexes of file descriptors in open_fds. */
1732 enum
1734 /* The pipe from Emacs to its subprocess. */
1735 SUBPROCESS_STDIN,
1736 WRITE_TO_SUBPROCESS,
1738 /* The main pipe from the subprocess to Emacs. */
1739 READ_FROM_SUBPROCESS,
1740 SUBPROCESS_STDOUT,
1742 /* The pipe from the subprocess to Emacs that is closed when the
1743 subprocess execs. */
1744 READ_FROM_EXEC_MONITOR,
1745 EXEC_MONITOR_OUTPUT
1748 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1750 static void
1751 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1753 struct Lisp_Process *p = XPROCESS (process);
1754 int inchannel, outchannel;
1755 pid_t pid;
1756 int vfork_errno;
1757 int forkin, forkout, forkerr = -1;
1758 bool pty_flag = 0;
1759 char pty_name[PTY_NAME_SIZE];
1760 Lisp_Object lisp_pty_name = Qnil;
1761 sigset_t oldset;
1763 inchannel = outchannel = -1;
1765 if (p->pty_flag)
1766 outchannel = inchannel = allocate_pty (pty_name);
1768 if (inchannel >= 0)
1770 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1771 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1772 /* On most USG systems it does not work to open the pty's tty here,
1773 then close it and reopen it in the child. */
1774 /* Don't let this terminal become our controlling terminal
1775 (in case we don't have one). */
1776 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1777 if (forkin < 0)
1778 report_file_error ("Opening pty", Qnil);
1779 p->open_fd[SUBPROCESS_STDIN] = forkin;
1780 #else
1781 forkin = forkout = -1;
1782 #endif /* not USG, or USG_SUBTTY_WORKS */
1783 pty_flag = 1;
1784 lisp_pty_name = build_string (pty_name);
1786 else
1788 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1789 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1790 report_file_error ("Creating pipe", Qnil);
1791 forkin = p->open_fd[SUBPROCESS_STDIN];
1792 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1793 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1794 forkout = p->open_fd[SUBPROCESS_STDOUT];
1796 if (!NILP (p->stderrproc))
1798 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
1800 forkerr = pp->open_fd[SUBPROCESS_STDOUT];
1802 /* Close unnecessary file descriptors. */
1803 close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
1804 close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
1808 #ifndef WINDOWSNT
1809 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1810 report_file_error ("Creating pipe", Qnil);
1811 #endif
1813 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1814 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1816 /* Record this as an active process, with its channels. */
1817 chan_process[inchannel] = process;
1818 p->infd = inchannel;
1819 p->outfd = outchannel;
1821 /* Previously we recorded the tty descriptor used in the subprocess.
1822 It was only used for getting the foreground tty process, so now
1823 we just reopen the device (see emacs_get_tty_pgrp) as this is
1824 more portable (see USG_SUBTTY_WORKS above). */
1826 p->pty_flag = pty_flag;
1827 pset_status (p, Qrun);
1829 if (!EQ (p->command, Qt))
1831 FD_SET (inchannel, &input_wait_mask);
1832 FD_SET (inchannel, &non_keyboard_wait_mask);
1835 if (inchannel > max_process_desc)
1836 max_process_desc = inchannel;
1838 /* This may signal an error. */
1839 setup_process_coding_systems (process);
1841 block_input ();
1842 block_child_signal (&oldset);
1844 #ifndef WINDOWSNT
1845 /* vfork, and prevent local vars from being clobbered by the vfork. */
1847 Lisp_Object volatile current_dir_volatile = current_dir;
1848 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1849 char **volatile new_argv_volatile = new_argv;
1850 int volatile forkin_volatile = forkin;
1851 int volatile forkout_volatile = forkout;
1852 int volatile forkerr_volatile = forkerr;
1853 struct Lisp_Process *p_volatile = p;
1855 pid = vfork ();
1857 current_dir = current_dir_volatile;
1858 lisp_pty_name = lisp_pty_name_volatile;
1859 new_argv = new_argv_volatile;
1860 forkin = forkin_volatile;
1861 forkout = forkout_volatile;
1862 forkerr = forkerr_volatile;
1863 p = p_volatile;
1865 pty_flag = p->pty_flag;
1868 if (pid == 0)
1869 #endif /* not WINDOWSNT */
1871 int xforkin = forkin;
1872 int xforkout = forkout;
1873 int xforkerr = forkerr;
1875 /* Make the pty be the controlling terminal of the process. */
1876 #ifdef HAVE_PTYS
1877 /* First, disconnect its current controlling terminal. */
1878 /* We tried doing setsid only if pty_flag, but it caused
1879 process_set_signal to fail on SGI when using a pipe. */
1880 setsid ();
1881 /* Make the pty's terminal the controlling terminal. */
1882 if (pty_flag && xforkin >= 0)
1884 #ifdef TIOCSCTTY
1885 /* We ignore the return value
1886 because faith@cs.unc.edu says that is necessary on Linux. */
1887 ioctl (xforkin, TIOCSCTTY, 0);
1888 #endif
1890 #if defined (LDISC1)
1891 if (pty_flag && xforkin >= 0)
1893 struct termios t;
1894 tcgetattr (xforkin, &t);
1895 t.c_lflag = LDISC1;
1896 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1897 emacs_perror ("create_process/tcsetattr LDISC1");
1899 #else
1900 #if defined (NTTYDISC) && defined (TIOCSETD)
1901 if (pty_flag && xforkin >= 0)
1903 /* Use new line discipline. */
1904 int ldisc = NTTYDISC;
1905 ioctl (xforkin, TIOCSETD, &ldisc);
1907 #endif
1908 #endif
1909 #ifdef TIOCNOTTY
1910 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1911 can do TIOCSPGRP only to the process's controlling tty. */
1912 if (pty_flag)
1914 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1915 I can't test it since I don't have 4.3. */
1916 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1917 if (j >= 0)
1919 ioctl (j, TIOCNOTTY, 0);
1920 emacs_close (j);
1923 #endif /* TIOCNOTTY */
1925 #if !defined (DONT_REOPEN_PTY)
1926 /*** There is a suggestion that this ought to be a
1927 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1928 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1929 that system does seem to need this code, even though
1930 both TIOCSCTTY is defined. */
1931 /* Now close the pty (if we had it open) and reopen it.
1932 This makes the pty the controlling terminal of the subprocess. */
1933 if (pty_flag)
1936 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1937 would work? */
1938 if (xforkin >= 0)
1939 emacs_close (xforkin);
1940 xforkout = xforkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1942 if (xforkin < 0)
1944 emacs_perror (SSDATA (lisp_pty_name));
1945 _exit (EXIT_CANCELED);
1949 #endif /* not DONT_REOPEN_PTY */
1951 #ifdef SETUP_SLAVE_PTY
1952 if (pty_flag)
1954 SETUP_SLAVE_PTY;
1956 #endif /* SETUP_SLAVE_PTY */
1957 #endif /* HAVE_PTYS */
1959 signal (SIGINT, SIG_DFL);
1960 signal (SIGQUIT, SIG_DFL);
1961 #ifdef SIGPROF
1962 signal (SIGPROF, SIG_DFL);
1963 #endif
1965 /* Emacs ignores SIGPIPE, but the child should not. */
1966 signal (SIGPIPE, SIG_DFL);
1968 /* Stop blocking SIGCHLD in the child. */
1969 unblock_child_signal (&oldset);
1971 if (pty_flag)
1972 child_setup_tty (xforkout);
1974 if (xforkerr < 0)
1975 xforkerr = xforkout;
1976 #ifdef WINDOWSNT
1977 pid = child_setup (xforkin, xforkout, xforkerr, new_argv, 1, current_dir);
1978 #else /* not WINDOWSNT */
1979 child_setup (xforkin, xforkout, xforkerr, new_argv, 1, current_dir);
1980 #endif /* not WINDOWSNT */
1983 /* Back in the parent process. */
1985 vfork_errno = errno;
1986 p->pid = pid;
1987 if (pid >= 0)
1988 p->alive = 1;
1990 /* Stop blocking in the parent. */
1991 unblock_child_signal (&oldset);
1992 unblock_input ();
1994 if (pid < 0)
1995 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1996 else
1998 /* vfork succeeded. */
2000 /* Close the pipe ends that the child uses, or the child's pty. */
2001 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
2002 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
2004 #ifdef WINDOWSNT
2005 register_child (pid, inchannel);
2006 #endif /* WINDOWSNT */
2008 pset_tty_name (p, lisp_pty_name);
2010 #ifndef WINDOWSNT
2011 /* Wait for child_setup to complete in case that vfork is
2012 actually defined as fork. The descriptor
2013 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2014 of a pipe is closed at the child side either by close-on-exec
2015 on successful execve or the _exit call in child_setup. */
2017 char dummy;
2019 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
2020 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
2021 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
2023 #endif
2024 if (!NILP (p->stderrproc))
2026 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2027 close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
2032 static void
2033 create_pty (Lisp_Object process)
2035 struct Lisp_Process *p = XPROCESS (process);
2036 char pty_name[PTY_NAME_SIZE];
2037 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
2039 if (pty_fd >= 0)
2041 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
2042 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2043 /* On most USG systems it does not work to open the pty's tty here,
2044 then close it and reopen it in the child. */
2045 /* Don't let this terminal become our controlling terminal
2046 (in case we don't have one). */
2047 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2048 if (forkout < 0)
2049 report_file_error ("Opening pty", Qnil);
2050 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2051 #if defined (DONT_REOPEN_PTY)
2052 /* In the case that vfork is defined as fork, the parent process
2053 (Emacs) may send some data before the child process completes
2054 tty options setup. So we setup tty before forking. */
2055 child_setup_tty (forkout);
2056 #endif /* DONT_REOPEN_PTY */
2057 #endif /* not USG, or USG_SUBTTY_WORKS */
2059 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2061 /* Record this as an active process, with its channels.
2062 As a result, child_setup will close Emacs's side of the pipes. */
2063 chan_process[pty_fd] = process;
2064 p->infd = pty_fd;
2065 p->outfd = pty_fd;
2067 /* Previously we recorded the tty descriptor used in the subprocess.
2068 It was only used for getting the foreground tty process, so now
2069 we just reopen the device (see emacs_get_tty_pgrp) as this is
2070 more portable (see USG_SUBTTY_WORKS above). */
2072 p->pty_flag = 1;
2073 pset_status (p, Qrun);
2074 setup_process_coding_systems (process);
2076 FD_SET (pty_fd, &input_wait_mask);
2077 FD_SET (pty_fd, &non_keyboard_wait_mask);
2078 if (pty_fd > max_process_desc)
2079 max_process_desc = pty_fd;
2081 pset_tty_name (p, build_string (pty_name));
2084 p->pid = -2;
2087 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2088 0, MANY, 0,
2089 doc: /* Create and return a bidirectional pipe process.
2091 In Emacs, pipes are represented by process objects, so input and
2092 output work as for subprocesses, and `delete-process' closes a pipe.
2093 However, a pipe process has no process id, it cannot be signaled,
2094 and the status codes are different from normal processes.
2096 Arguments are specified as keyword/argument pairs. The following
2097 arguments are defined:
2099 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2101 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2102 with the process. Process output goes at the end of that buffer,
2103 unless you specify an output stream or filter function to handle the
2104 output. If BUFFER is not given, the value of NAME is used.
2106 :coding CODING -- If CODING is a symbol, it specifies the coding
2107 system used for both reading and writing for this process. If CODING
2108 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2109 ENCODING is used for writing.
2111 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2112 the process is running. If BOOL is not given, query before exiting.
2114 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2115 In the stopped state, a pipe process does not accept incoming data,
2116 but you can send outgoing data. The stopped state is cleared by
2117 `continue-process' and set by `stop-process'.
2119 :filter FILTER -- Install FILTER as the process filter.
2121 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2123 usage: (make-pipe-process &rest ARGS) */)
2124 (ptrdiff_t nargs, Lisp_Object *args)
2126 Lisp_Object proc, contact;
2127 struct Lisp_Process *p;
2128 struct gcpro gcpro1;
2129 Lisp_Object name, buffer;
2130 Lisp_Object tem;
2131 ptrdiff_t specpdl_count;
2132 int inchannel, outchannel;
2134 if (nargs == 0)
2135 return Qnil;
2137 contact = Flist (nargs, args);
2138 GCPRO1 (contact);
2140 name = Fplist_get (contact, QCname);
2141 CHECK_STRING (name);
2142 proc = make_process (name);
2143 specpdl_count = SPECPDL_INDEX ();
2144 record_unwind_protect (remove_process, proc);
2145 p = XPROCESS (proc);
2147 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2148 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2149 report_file_error ("Creating pipe", Qnil);
2150 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2151 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2153 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2154 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2156 #ifdef WINDOWSNT
2157 register_aux_fd (inchannel);
2158 #endif
2160 /* Record this as an active process, with its channels. */
2161 chan_process[inchannel] = proc;
2162 p->infd = inchannel;
2163 p->outfd = outchannel;
2165 if (inchannel > max_process_desc)
2166 max_process_desc = inchannel;
2168 buffer = Fplist_get (contact, QCbuffer);
2169 if (NILP (buffer))
2170 buffer = name;
2171 buffer = Fget_buffer_create (buffer);
2172 pset_buffer (p, buffer);
2174 pset_childp (p, contact);
2175 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2176 pset_type (p, Qpipe);
2177 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2178 pset_filter (p, Fplist_get (contact, QCfilter));
2179 pset_log (p, Qnil);
2180 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2181 p->kill_without_query = 1;
2182 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2183 pset_command (p, Qt);
2184 eassert (! p->pty_flag);
2186 if (!EQ (p->command, Qt))
2188 FD_SET (inchannel, &input_wait_mask);
2189 FD_SET (inchannel, &non_keyboard_wait_mask);
2191 #ifdef ADAPTIVE_READ_BUFFERING
2192 p->adaptive_read_buffering
2193 = (NILP (Vprocess_adaptive_read_buffering) ? 0
2194 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2195 #endif
2197 /* Make the process marker point into the process buffer (if any). */
2198 if (BUFFERP (buffer))
2199 set_marker_both (p->mark, buffer,
2200 BUF_ZV (XBUFFER (buffer)),
2201 BUF_ZV_BYTE (XBUFFER (buffer)));
2204 /* Setup coding systems for communicating with the network stream. */
2206 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2207 Lisp_Object coding_systems = Qt;
2208 Lisp_Object val;
2210 tem = Fplist_get (contact, QCcoding);
2211 val = Qnil;
2212 if (!NILP (tem))
2214 val = tem;
2215 if (CONSP (val))
2216 val = XCAR (val);
2218 else if (!NILP (Vcoding_system_for_read))
2219 val = Vcoding_system_for_read;
2220 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2221 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2222 /* We dare not decode end-of-line format by setting VAL to
2223 Qraw_text, because the existing Emacs Lisp libraries
2224 assume that they receive bare code including a sequence of
2225 CR LF. */
2226 val = Qnil;
2227 else
2229 if (CONSP (coding_systems))
2230 val = XCAR (coding_systems);
2231 else if (CONSP (Vdefault_process_coding_system))
2232 val = XCAR (Vdefault_process_coding_system);
2233 else
2234 val = Qnil;
2236 pset_decode_coding_system (p, val);
2238 if (!NILP (tem))
2240 val = tem;
2241 if (CONSP (val))
2242 val = XCDR (val);
2244 else if (!NILP (Vcoding_system_for_write))
2245 val = Vcoding_system_for_write;
2246 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2247 val = Qnil;
2248 else
2250 if (CONSP (coding_systems))
2251 val = XCDR (coding_systems);
2252 else if (CONSP (Vdefault_process_coding_system))
2253 val = XCDR (Vdefault_process_coding_system);
2254 else
2255 val = Qnil;
2257 pset_encode_coding_system (p, val);
2259 /* This may signal an error. */
2260 setup_process_coding_systems (proc);
2262 specpdl_ptr = specpdl + specpdl_count;
2264 UNGCPRO;
2265 return proc;
2269 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2270 The address family of sa is not included in the result. */
2272 Lisp_Object
2273 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2275 Lisp_Object address;
2276 int i;
2277 unsigned char *cp;
2278 register struct Lisp_Vector *p;
2280 /* Workaround for a bug in getsockname on BSD: Names bound to
2281 sockets in the UNIX domain are inaccessible; getsockname returns
2282 a zero length name. */
2283 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2284 return empty_unibyte_string;
2286 switch (sa->sa_family)
2288 case AF_INET:
2290 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2291 len = sizeof (sin->sin_addr) + 1;
2292 address = Fmake_vector (make_number (len), Qnil);
2293 p = XVECTOR (address);
2294 p->contents[--len] = make_number (ntohs (sin->sin_port));
2295 cp = (unsigned char *) &sin->sin_addr;
2296 break;
2298 #ifdef AF_INET6
2299 case AF_INET6:
2301 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2302 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2303 len = sizeof (sin6->sin6_addr) / 2 + 1;
2304 address = Fmake_vector (make_number (len), Qnil);
2305 p = XVECTOR (address);
2306 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2307 for (i = 0; i < len; i++)
2308 p->contents[i] = make_number (ntohs (ip6[i]));
2309 return address;
2311 #endif
2312 #ifdef HAVE_LOCAL_SOCKETS
2313 case AF_LOCAL:
2315 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2316 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2317 /* If the first byte is NUL, the name is a Linux abstract
2318 socket name, and the name can contain embedded NULs. If
2319 it's not, we have a NUL-terminated string. Be careful not
2320 to walk past the end of the object looking for the name
2321 terminator, however. */
2322 if (name_length > 0 && sockun->sun_path[0] != '\0')
2324 const char *terminator
2325 = memchr (sockun->sun_path, '\0', name_length);
2327 if (terminator)
2328 name_length = terminator - (const char *) sockun->sun_path;
2331 return make_unibyte_string (sockun->sun_path, name_length);
2333 #endif
2334 default:
2335 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2336 address = Fcons (make_number (sa->sa_family),
2337 Fmake_vector (make_number (len), Qnil));
2338 p = XVECTOR (XCDR (address));
2339 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2340 break;
2343 i = 0;
2344 while (i < len)
2345 p->contents[i++] = make_number (*cp++);
2347 return address;
2351 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2353 static int
2354 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2356 register struct Lisp_Vector *p;
2358 if (VECTORP (address))
2360 p = XVECTOR (address);
2361 if (p->header.size == 5)
2363 *familyp = AF_INET;
2364 return sizeof (struct sockaddr_in);
2366 #ifdef AF_INET6
2367 else if (p->header.size == 9)
2369 *familyp = AF_INET6;
2370 return sizeof (struct sockaddr_in6);
2372 #endif
2374 #ifdef HAVE_LOCAL_SOCKETS
2375 else if (STRINGP (address))
2377 *familyp = AF_LOCAL;
2378 return sizeof (struct sockaddr_un);
2380 #endif
2381 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2382 && VECTORP (XCDR (address)))
2384 struct sockaddr *sa;
2385 p = XVECTOR (XCDR (address));
2386 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2387 return 0;
2388 *familyp = XINT (XCAR (address));
2389 return p->header.size + sizeof (sa->sa_family);
2391 return 0;
2394 /* Convert an address object (vector or string) to an internal sockaddr.
2396 The address format has been basically validated by
2397 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2398 it could have come from user data. So if FAMILY is not valid,
2399 we return after zeroing *SA. */
2401 static void
2402 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2404 register struct Lisp_Vector *p;
2405 register unsigned char *cp = NULL;
2406 register int i;
2407 EMACS_INT hostport;
2409 memset (sa, 0, len);
2411 if (VECTORP (address))
2413 p = XVECTOR (address);
2414 if (family == AF_INET)
2416 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2417 len = sizeof (sin->sin_addr) + 1;
2418 hostport = XINT (p->contents[--len]);
2419 sin->sin_port = htons (hostport);
2420 cp = (unsigned char *)&sin->sin_addr;
2421 sa->sa_family = family;
2423 #ifdef AF_INET6
2424 else if (family == AF_INET6)
2426 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2427 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2428 len = sizeof (sin6->sin6_addr) + 1;
2429 hostport = XINT (p->contents[--len]);
2430 sin6->sin6_port = htons (hostport);
2431 for (i = 0; i < len; i++)
2432 if (INTEGERP (p->contents[i]))
2434 int j = XFASTINT (p->contents[i]) & 0xffff;
2435 ip6[i] = ntohs (j);
2437 sa->sa_family = family;
2438 return;
2440 #endif
2441 else
2442 return;
2444 else if (STRINGP (address))
2446 #ifdef HAVE_LOCAL_SOCKETS
2447 if (family == AF_LOCAL)
2449 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2450 cp = SDATA (address);
2451 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2452 sockun->sun_path[i] = *cp++;
2453 sa->sa_family = family;
2455 #endif
2456 return;
2458 else
2460 p = XVECTOR (XCDR (address));
2461 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2464 for (i = 0; i < len; i++)
2465 if (INTEGERP (p->contents[i]))
2466 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2469 #ifdef DATAGRAM_SOCKETS
2470 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2471 1, 1, 0,
2472 doc: /* Get the current datagram address associated with PROCESS. */)
2473 (Lisp_Object process)
2475 int channel;
2477 CHECK_PROCESS (process);
2479 if (!DATAGRAM_CONN_P (process))
2480 return Qnil;
2482 channel = XPROCESS (process)->infd;
2483 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2484 datagram_address[channel].len);
2487 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2488 2, 2, 0,
2489 doc: /* Set the datagram address for PROCESS to ADDRESS.
2490 Returns nil upon error setting address, ADDRESS otherwise. */)
2491 (Lisp_Object process, Lisp_Object address)
2493 int channel;
2494 int family, len;
2496 CHECK_PROCESS (process);
2498 if (!DATAGRAM_CONN_P (process))
2499 return Qnil;
2501 channel = XPROCESS (process)->infd;
2503 len = get_lisp_to_sockaddr_size (address, &family);
2504 if (len == 0 || datagram_address[channel].len != len)
2505 return Qnil;
2506 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2507 return address;
2509 #endif
2512 static const struct socket_options {
2513 /* The name of this option. Should be lowercase version of option
2514 name without SO_ prefix. */
2515 const char *name;
2516 /* Option level SOL_... */
2517 int optlevel;
2518 /* Option number SO_... */
2519 int optnum;
2520 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2521 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2522 } socket_options[] =
2524 #ifdef SO_BINDTODEVICE
2525 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2526 #endif
2527 #ifdef SO_BROADCAST
2528 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2529 #endif
2530 #ifdef SO_DONTROUTE
2531 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2532 #endif
2533 #ifdef SO_KEEPALIVE
2534 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2535 #endif
2536 #ifdef SO_LINGER
2537 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2538 #endif
2539 #ifdef SO_OOBINLINE
2540 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2541 #endif
2542 #ifdef SO_PRIORITY
2543 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2544 #endif
2545 #ifdef SO_REUSEADDR
2546 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2547 #endif
2548 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2551 /* Set option OPT to value VAL on socket S.
2553 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2554 Signals an error if setting a known option fails.
2557 static int
2558 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2560 char *name;
2561 const struct socket_options *sopt;
2562 int ret = 0;
2564 CHECK_SYMBOL (opt);
2566 name = SSDATA (SYMBOL_NAME (opt));
2567 for (sopt = socket_options; sopt->name; sopt++)
2568 if (strcmp (name, sopt->name) == 0)
2569 break;
2571 switch (sopt->opttype)
2573 case SOPT_BOOL:
2575 int optval;
2576 optval = NILP (val) ? 0 : 1;
2577 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2578 &optval, sizeof (optval));
2579 break;
2582 case SOPT_INT:
2584 int optval;
2585 if (TYPE_RANGED_INTEGERP (int, val))
2586 optval = XINT (val);
2587 else
2588 error ("Bad option value for %s", name);
2589 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2590 &optval, sizeof (optval));
2591 break;
2594 #ifdef SO_BINDTODEVICE
2595 case SOPT_IFNAME:
2597 char devname[IFNAMSIZ + 1];
2599 /* This is broken, at least in the Linux 2.4 kernel.
2600 To unbind, the arg must be a zero integer, not the empty string.
2601 This should work on all systems. KFS. 2003-09-23. */
2602 memset (devname, 0, sizeof devname);
2603 if (STRINGP (val))
2605 char *arg = SSDATA (val);
2606 int len = min (strlen (arg), IFNAMSIZ);
2607 memcpy (devname, arg, len);
2609 else if (!NILP (val))
2610 error ("Bad option value for %s", name);
2611 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2612 devname, IFNAMSIZ);
2613 break;
2615 #endif
2617 #ifdef SO_LINGER
2618 case SOPT_LINGER:
2620 struct linger linger;
2622 linger.l_onoff = 1;
2623 linger.l_linger = 0;
2624 if (TYPE_RANGED_INTEGERP (int, val))
2625 linger.l_linger = XINT (val);
2626 else
2627 linger.l_onoff = NILP (val) ? 0 : 1;
2628 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2629 &linger, sizeof (linger));
2630 break;
2632 #endif
2634 default:
2635 return 0;
2638 if (ret < 0)
2640 int setsockopt_errno = errno;
2641 report_file_errno ("Cannot set network option", list2 (opt, val),
2642 setsockopt_errno);
2645 return (1 << sopt->optbit);
2649 DEFUN ("set-network-process-option",
2650 Fset_network_process_option, Sset_network_process_option,
2651 3, 4, 0,
2652 doc: /* For network process PROCESS set option OPTION to value VALUE.
2653 See `make-network-process' for a list of options and values.
2654 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2655 OPTION is not a supported option, return nil instead; otherwise return t. */)
2656 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2658 int s;
2659 struct Lisp_Process *p;
2661 CHECK_PROCESS (process);
2662 p = XPROCESS (process);
2663 if (!NETCONN1_P (p))
2664 error ("Process is not a network process");
2666 s = p->infd;
2667 if (s < 0)
2668 error ("Process is not running");
2670 if (set_socket_option (s, option, value))
2672 pset_childp (p, Fplist_put (p->childp, option, value));
2673 return Qt;
2676 if (NILP (no_error))
2677 error ("Unknown or unsupported option");
2679 return Qnil;
2683 DEFUN ("serial-process-configure",
2684 Fserial_process_configure,
2685 Sserial_process_configure,
2686 0, MANY, 0,
2687 doc: /* Configure speed, bytesize, etc. of a serial process.
2689 Arguments are specified as keyword/argument pairs. Attributes that
2690 are not given are re-initialized from the process's current
2691 configuration (available via the function `process-contact') or set to
2692 reasonable default values. The following arguments are defined:
2694 :process PROCESS
2695 :name NAME
2696 :buffer BUFFER
2697 :port PORT
2698 -- Any of these arguments can be given to identify the process that is
2699 to be configured. If none of these arguments is given, the current
2700 buffer's process is used.
2702 :speed SPEED -- SPEED is the speed of the serial port in bits per
2703 second, also called baud rate. Any value can be given for SPEED, but
2704 most serial ports work only at a few defined values between 1200 and
2705 115200, with 9600 being the most common value. If SPEED is nil, the
2706 serial port is not configured any further, i.e., all other arguments
2707 are ignored. This may be useful for special serial ports such as
2708 Bluetooth-to-serial converters which can only be configured through AT
2709 commands. A value of nil for SPEED can be used only when passed
2710 through `make-serial-process' or `serial-term'.
2712 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2713 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2715 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2716 `odd' (use odd parity), or the symbol `even' (use even parity). If
2717 PARITY is not given, no parity is used.
2719 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2720 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2721 is not given or nil, 1 stopbit is used.
2723 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2724 flowcontrol to be used, which is either nil (don't use flowcontrol),
2725 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2726 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2727 flowcontrol is used.
2729 `serial-process-configure' is called by `make-serial-process' for the
2730 initial configuration of the serial port.
2732 Examples:
2734 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2736 \(serial-process-configure
2737 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2739 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2741 usage: (serial-process-configure &rest ARGS) */)
2742 (ptrdiff_t nargs, Lisp_Object *args)
2744 struct Lisp_Process *p;
2745 Lisp_Object contact = Qnil;
2746 Lisp_Object proc = Qnil;
2747 struct gcpro gcpro1;
2749 contact = Flist (nargs, args);
2750 GCPRO1 (contact);
2752 proc = Fplist_get (contact, QCprocess);
2753 if (NILP (proc))
2754 proc = Fplist_get (contact, QCname);
2755 if (NILP (proc))
2756 proc = Fplist_get (contact, QCbuffer);
2757 if (NILP (proc))
2758 proc = Fplist_get (contact, QCport);
2759 proc = get_process (proc);
2760 p = XPROCESS (proc);
2761 if (!EQ (p->type, Qserial))
2762 error ("Not a serial process");
2764 if (NILP (Fplist_get (p->childp, QCspeed)))
2766 UNGCPRO;
2767 return Qnil;
2770 serial_configure (p, contact);
2772 UNGCPRO;
2773 return Qnil;
2776 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2777 0, MANY, 0,
2778 doc: /* Create and return a serial port process.
2780 In Emacs, serial port connections are represented by process objects,
2781 so input and output work as for subprocesses, and `delete-process'
2782 closes a serial port connection. However, a serial process has no
2783 process id, it cannot be signaled, and the status codes are different
2784 from normal processes.
2786 `make-serial-process' creates a process and a buffer, on which you
2787 probably want to use `process-send-string'. Try \\[serial-term] for
2788 an interactive terminal. See below for examples.
2790 Arguments are specified as keyword/argument pairs. The following
2791 arguments are defined:
2793 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2794 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2795 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2796 the backslashes in strings).
2798 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2799 which this function calls.
2801 :name NAME -- NAME is the name of the process. If NAME is not given,
2802 the value of PORT is used.
2804 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2805 with the process. Process output goes at the end of that buffer,
2806 unless you specify an output stream or filter function to handle the
2807 output. If BUFFER is not given, the value of NAME is used.
2809 :coding CODING -- If CODING is a symbol, it specifies the coding
2810 system used for both reading and writing for this process. If CODING
2811 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2812 ENCODING is used for writing.
2814 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2815 the process is running. If BOOL is not given, query before exiting.
2817 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2818 In the stopped state, a serial process does not accept incoming data,
2819 but you can send outgoing data. The stopped state is cleared by
2820 `continue-process' and set by `stop-process'.
2822 :filter FILTER -- Install FILTER as the process filter.
2824 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2826 :plist PLIST -- Install PLIST as the initial plist of the process.
2828 :bytesize
2829 :parity
2830 :stopbits
2831 :flowcontrol
2832 -- This function calls `serial-process-configure' to handle these
2833 arguments.
2835 The original argument list, possibly modified by later configuration,
2836 is available via the function `process-contact'.
2838 Examples:
2840 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2842 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2844 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2846 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2848 usage: (make-serial-process &rest ARGS) */)
2849 (ptrdiff_t nargs, Lisp_Object *args)
2851 int fd = -1;
2852 Lisp_Object proc, contact, port;
2853 struct Lisp_Process *p;
2854 struct gcpro gcpro1;
2855 Lisp_Object name, buffer;
2856 Lisp_Object tem, val;
2857 ptrdiff_t specpdl_count;
2859 if (nargs == 0)
2860 return Qnil;
2862 contact = Flist (nargs, args);
2863 GCPRO1 (contact);
2865 port = Fplist_get (contact, QCport);
2866 if (NILP (port))
2867 error ("No port specified");
2868 CHECK_STRING (port);
2870 if (NILP (Fplist_member (contact, QCspeed)))
2871 error (":speed not specified");
2872 if (!NILP (Fplist_get (contact, QCspeed)))
2873 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2875 name = Fplist_get (contact, QCname);
2876 if (NILP (name))
2877 name = port;
2878 CHECK_STRING (name);
2879 proc = make_process (name);
2880 specpdl_count = SPECPDL_INDEX ();
2881 record_unwind_protect (remove_process, proc);
2882 p = XPROCESS (proc);
2884 fd = serial_open (port);
2885 p->open_fd[SUBPROCESS_STDIN] = fd;
2886 p->infd = fd;
2887 p->outfd = fd;
2888 if (fd > max_process_desc)
2889 max_process_desc = fd;
2890 chan_process[fd] = proc;
2892 buffer = Fplist_get (contact, QCbuffer);
2893 if (NILP (buffer))
2894 buffer = name;
2895 buffer = Fget_buffer_create (buffer);
2896 pset_buffer (p, buffer);
2898 pset_childp (p, contact);
2899 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2900 pset_type (p, Qserial);
2901 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2902 pset_filter (p, Fplist_get (contact, QCfilter));
2903 pset_log (p, Qnil);
2904 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2905 p->kill_without_query = 1;
2906 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2907 pset_command (p, Qt);
2908 eassert (! p->pty_flag);
2910 if (!EQ (p->command, Qt))
2912 FD_SET (fd, &input_wait_mask);
2913 FD_SET (fd, &non_keyboard_wait_mask);
2916 if (BUFFERP (buffer))
2918 set_marker_both (p->mark, buffer,
2919 BUF_ZV (XBUFFER (buffer)),
2920 BUF_ZV_BYTE (XBUFFER (buffer)));
2923 tem = Fplist_member (contact, QCcoding);
2924 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2925 tem = Qnil;
2927 val = Qnil;
2928 if (!NILP (tem))
2930 val = XCAR (XCDR (tem));
2931 if (CONSP (val))
2932 val = XCAR (val);
2934 else if (!NILP (Vcoding_system_for_read))
2935 val = Vcoding_system_for_read;
2936 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2937 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2938 val = Qnil;
2939 pset_decode_coding_system (p, val);
2941 val = Qnil;
2942 if (!NILP (tem))
2944 val = XCAR (XCDR (tem));
2945 if (CONSP (val))
2946 val = XCDR (val);
2948 else if (!NILP (Vcoding_system_for_write))
2949 val = Vcoding_system_for_write;
2950 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2951 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2952 val = Qnil;
2953 pset_encode_coding_system (p, val);
2955 setup_process_coding_systems (proc);
2956 pset_decoding_buf (p, empty_unibyte_string);
2957 p->decoding_carryover = 0;
2958 pset_encoding_buf (p, empty_unibyte_string);
2959 p->inherit_coding_system_flag
2960 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2962 Fserial_process_configure (nargs, args);
2964 specpdl_ptr = specpdl + specpdl_count;
2966 UNGCPRO;
2967 return proc;
2970 /* Create a network stream/datagram client/server process. Treated
2971 exactly like a normal process when reading and writing. Primary
2972 differences are in status display and process deletion. A network
2973 connection has no PID; you cannot signal it. All you can do is
2974 stop/continue it and deactivate/close it via delete-process. */
2976 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2977 0, MANY, 0,
2978 doc: /* Create and return a network server or client process.
2980 In Emacs, network connections are represented by process objects, so
2981 input and output work as for subprocesses and `delete-process' closes
2982 a network connection. However, a network process has no process id,
2983 it cannot be signaled, and the status codes are different from normal
2984 processes.
2986 Arguments are specified as keyword/argument pairs. The following
2987 arguments are defined:
2989 :name NAME -- NAME is name for process. It is modified if necessary
2990 to make it unique.
2992 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2993 with the process. Process output goes at end of that buffer, unless
2994 you specify an output stream or filter function to handle the output.
2995 BUFFER may be also nil, meaning that this process is not associated
2996 with any buffer.
2998 :host HOST -- HOST is name of the host to connect to, or its IP
2999 address. The symbol `local' specifies the local host. If specified
3000 for a server process, it must be a valid name or address for the local
3001 host, and only clients connecting to that address will be accepted.
3003 :service SERVICE -- SERVICE is name of the service desired, or an
3004 integer specifying a port number to connect to. If SERVICE is t,
3005 a random port number is selected for the server. (If Emacs was
3006 compiled with getaddrinfo, a port number can also be specified as a
3007 string, e.g. "80", as well as an integer. This is not portable.)
3009 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3010 stream type connection, `datagram' creates a datagram type connection,
3011 `seqpacket' creates a reliable datagram connection.
3013 :family FAMILY -- FAMILY is the address (and protocol) family for the
3014 service specified by HOST and SERVICE. The default (nil) is to use
3015 whatever address family (IPv4 or IPv6) that is defined for the host
3016 and port number specified by HOST and SERVICE. Other address families
3017 supported are:
3018 local -- for a local (i.e. UNIX) address specified by SERVICE.
3019 ipv4 -- use IPv4 address family only.
3020 ipv6 -- use IPv6 address family only.
3022 :local ADDRESS -- ADDRESS is the local address used for the connection.
3023 This parameter is ignored when opening a client process. When specified
3024 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3026 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3027 connection. This parameter is ignored when opening a stream server
3028 process. For a datagram server process, it specifies the initial
3029 setting of the remote datagram address. When specified for a client
3030 process, the FAMILY, HOST, and SERVICE args are ignored.
3032 The format of ADDRESS depends on the address family:
3033 - An IPv4 address is represented as an vector of integers [A B C D P]
3034 corresponding to numeric IP address A.B.C.D and port number P.
3035 - A local address is represented as a string with the address in the
3036 local address space.
3037 - An "unsupported family" address is represented by a cons (F . AV)
3038 where F is the family number and AV is a vector containing the socket
3039 address data with one element per address data byte. Do not rely on
3040 this format in portable code, as it may depend on implementation
3041 defined constants, data sizes, and data structure alignment.
3043 :coding CODING -- If CODING is a symbol, it specifies the coding
3044 system used for both reading and writing for this process. If CODING
3045 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3046 ENCODING is used for writing.
3048 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3049 return without waiting for the connection to complete; instead, the
3050 sentinel function will be called with second arg matching "open" (if
3051 successful) or "failed" when the connect completes. Default is to use
3052 a blocking connect (i.e. wait) for stream type connections.
3054 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3055 running when Emacs is exited.
3057 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3058 In the stopped state, a server process does not accept new
3059 connections, and a client process does not handle incoming traffic.
3060 The stopped state is cleared by `continue-process' and set by
3061 `stop-process'.
3063 :filter FILTER -- Install FILTER as the process filter.
3065 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3066 process filter are multibyte, otherwise they are unibyte.
3067 If this keyword is not specified, the strings are multibyte if
3068 the default value of `enable-multibyte-characters' is non-nil.
3070 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3072 :log LOG -- Install LOG as the server process log function. This
3073 function is called when the server accepts a network connection from a
3074 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3075 is the server process, CLIENT is the new process for the connection,
3076 and MESSAGE is a string.
3078 :plist PLIST -- Install PLIST as the new process's initial plist.
3080 :server QLEN -- if QLEN is non-nil, create a server process for the
3081 specified FAMILY, SERVICE, and connection type (stream or datagram).
3082 If QLEN is an integer, it is used as the max. length of the server's
3083 pending connection queue (also known as the backlog); the default
3084 queue length is 5. Default is to create a client process.
3086 The following network options can be specified for this connection:
3088 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3089 :dontroute BOOL -- Only send to directly connected hosts.
3090 :keepalive BOOL -- Send keep-alive messages on network stream.
3091 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3092 :oobinline BOOL -- Place out-of-band data in receive data stream.
3093 :priority INT -- Set protocol defined priority for sent packets.
3094 :reuseaddr BOOL -- Allow reusing a recently used local address
3095 (this is allowed by default for a server process).
3096 :bindtodevice NAME -- bind to interface NAME. Using this may require
3097 special privileges on some systems.
3099 Consult the relevant system programmer's manual pages for more
3100 information on using these options.
3103 A server process will listen for and accept connections from clients.
3104 When a client connection is accepted, a new network process is created
3105 for the connection with the following parameters:
3107 - The client's process name is constructed by concatenating the server
3108 process's NAME and a client identification string.
3109 - If the FILTER argument is non-nil, the client process will not get a
3110 separate process buffer; otherwise, the client's process buffer is a newly
3111 created buffer named after the server process's BUFFER name or process
3112 NAME concatenated with the client identification string.
3113 - The connection type and the process filter and sentinel parameters are
3114 inherited from the server process's TYPE, FILTER and SENTINEL.
3115 - The client process's contact info is set according to the client's
3116 addressing information (typically an IP address and a port number).
3117 - The client process's plist is initialized from the server's plist.
3119 Notice that the FILTER and SENTINEL args are never used directly by
3120 the server process. Also, the BUFFER argument is not used directly by
3121 the server process, but via the optional :log function, accepted (and
3122 failed) connections may be logged in the server process's buffer.
3124 The original argument list, modified with the actual connection
3125 information, is available via the `process-contact' function.
3127 usage: (make-network-process &rest ARGS) */)
3128 (ptrdiff_t nargs, Lisp_Object *args)
3130 Lisp_Object proc;
3131 Lisp_Object contact;
3132 struct Lisp_Process *p;
3133 #ifdef HAVE_GETADDRINFO
3134 struct addrinfo ai, *res, *lres;
3135 struct addrinfo hints;
3136 const char *portstring;
3137 char portbuf[128];
3138 #else /* HAVE_GETADDRINFO */
3139 struct _emacs_addrinfo
3141 int ai_family;
3142 int ai_socktype;
3143 int ai_protocol;
3144 int ai_addrlen;
3145 struct sockaddr *ai_addr;
3146 struct _emacs_addrinfo *ai_next;
3147 } ai, *res, *lres;
3148 #endif /* HAVE_GETADDRINFO */
3149 struct sockaddr_in address_in;
3150 #ifdef HAVE_LOCAL_SOCKETS
3151 struct sockaddr_un address_un;
3152 #endif
3153 int port;
3154 int ret = 0;
3155 int xerrno = 0;
3156 int s = -1, outch, inch;
3157 struct gcpro gcpro1;
3158 ptrdiff_t count = SPECPDL_INDEX ();
3159 ptrdiff_t count1;
3160 Lisp_Object colon_address; /* Either QClocal or QCremote. */
3161 Lisp_Object tem;
3162 Lisp_Object name, buffer, host, service, address;
3163 Lisp_Object filter, sentinel;
3164 bool is_non_blocking_client = 0;
3165 bool is_server = 0;
3166 int backlog = 5;
3167 int socktype;
3168 int family = -1;
3170 if (nargs == 0)
3171 return Qnil;
3173 /* Save arguments for process-contact and clone-process. */
3174 contact = Flist (nargs, args);
3175 GCPRO1 (contact);
3177 #ifdef WINDOWSNT
3178 /* Ensure socket support is loaded if available. */
3179 init_winsock (TRUE);
3180 #endif
3182 /* :type TYPE (nil: stream, datagram */
3183 tem = Fplist_get (contact, QCtype);
3184 if (NILP (tem))
3185 socktype = SOCK_STREAM;
3186 #ifdef DATAGRAM_SOCKETS
3187 else if (EQ (tem, Qdatagram))
3188 socktype = SOCK_DGRAM;
3189 #endif
3190 #ifdef HAVE_SEQPACKET
3191 else if (EQ (tem, Qseqpacket))
3192 socktype = SOCK_SEQPACKET;
3193 #endif
3194 else
3195 error ("Unsupported connection type");
3197 /* :server BOOL */
3198 tem = Fplist_get (contact, QCserver);
3199 if (!NILP (tem))
3201 /* Don't support network sockets when non-blocking mode is
3202 not available, since a blocked Emacs is not useful. */
3203 is_server = 1;
3204 if (TYPE_RANGED_INTEGERP (int, tem))
3205 backlog = XINT (tem);
3208 /* Make colon_address an alias for :local (server) or :remote (client). */
3209 colon_address = is_server ? QClocal : QCremote;
3211 /* :nowait BOOL */
3212 if (!is_server && socktype != SOCK_DGRAM
3213 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3215 #ifndef NON_BLOCKING_CONNECT
3216 error ("Non-blocking connect not supported");
3217 #else
3218 is_non_blocking_client = 1;
3219 #endif
3222 name = Fplist_get (contact, QCname);
3223 buffer = Fplist_get (contact, QCbuffer);
3224 filter = Fplist_get (contact, QCfilter);
3225 sentinel = Fplist_get (contact, QCsentinel);
3227 CHECK_STRING (name);
3229 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3230 ai.ai_socktype = socktype;
3231 ai.ai_protocol = 0;
3232 ai.ai_next = NULL;
3233 res = &ai;
3235 /* :local ADDRESS or :remote ADDRESS */
3236 address = Fplist_get (contact, colon_address);
3237 if (!NILP (address))
3239 host = service = Qnil;
3241 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3242 error ("Malformed :address");
3243 ai.ai_family = family;
3244 ai.ai_addr = alloca (ai.ai_addrlen);
3245 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3246 goto open_socket;
3249 /* :family FAMILY -- nil (for Inet), local, or integer. */
3250 tem = Fplist_get (contact, QCfamily);
3251 if (NILP (tem))
3253 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3254 family = AF_UNSPEC;
3255 #else
3256 family = AF_INET;
3257 #endif
3259 #ifdef HAVE_LOCAL_SOCKETS
3260 else if (EQ (tem, Qlocal))
3261 family = AF_LOCAL;
3262 #endif
3263 #ifdef AF_INET6
3264 else if (EQ (tem, Qipv6))
3265 family = AF_INET6;
3266 #endif
3267 else if (EQ (tem, Qipv4))
3268 family = AF_INET;
3269 else if (TYPE_RANGED_INTEGERP (int, tem))
3270 family = XINT (tem);
3271 else
3272 error ("Unknown address family");
3274 ai.ai_family = family;
3276 /* :service SERVICE -- string, integer (port number), or t (random port). */
3277 service = Fplist_get (contact, QCservice);
3279 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3280 host = Fplist_get (contact, QChost);
3281 if (!NILP (host))
3283 if (EQ (host, Qlocal))
3284 /* Depending on setup, "localhost" may map to different IPv4 and/or
3285 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3286 host = build_string ("127.0.0.1");
3287 CHECK_STRING (host);
3290 #ifdef HAVE_LOCAL_SOCKETS
3291 if (family == AF_LOCAL)
3293 if (!NILP (host))
3295 message (":family local ignores the :host property");
3296 contact = Fplist_put (contact, QChost, Qnil);
3297 host = Qnil;
3299 CHECK_STRING (service);
3300 memset (&address_un, 0, sizeof address_un);
3301 address_un.sun_family = AF_LOCAL;
3302 if (sizeof address_un.sun_path <= SBYTES (service))
3303 error ("Service name too long");
3304 lispstpcpy (address_un.sun_path, service);
3305 ai.ai_addr = (struct sockaddr *) &address_un;
3306 ai.ai_addrlen = sizeof address_un;
3307 goto open_socket;
3309 #endif
3311 /* Slow down polling to every ten seconds.
3312 Some kernels have a bug which causes retrying connect to fail
3313 after a connect. Polling can interfere with gethostbyname too. */
3314 #ifdef POLL_FOR_INPUT
3315 if (socktype != SOCK_DGRAM)
3317 record_unwind_protect_void (run_all_atimers);
3318 bind_polling_period (10);
3320 #endif
3322 #ifdef HAVE_GETADDRINFO
3323 /* If we have a host, use getaddrinfo to resolve both host and service.
3324 Otherwise, use getservbyname to lookup the service. */
3325 if (!NILP (host))
3328 /* SERVICE can either be a string or int.
3329 Convert to a C string for later use by getaddrinfo. */
3330 if (EQ (service, Qt))
3331 portstring = "0";
3332 else if (INTEGERP (service))
3334 sprintf (portbuf, "%"pI"d", XINT (service));
3335 portstring = portbuf;
3337 else
3339 CHECK_STRING (service);
3340 portstring = SSDATA (service);
3343 immediate_quit = 1;
3344 QUIT;
3345 memset (&hints, 0, sizeof (hints));
3346 hints.ai_flags = 0;
3347 hints.ai_family = family;
3348 hints.ai_socktype = socktype;
3349 hints.ai_protocol = 0;
3351 #ifdef HAVE_RES_INIT
3352 res_init ();
3353 #endif
3355 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3356 if (ret)
3357 #ifdef HAVE_GAI_STRERROR
3358 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3359 #else
3360 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3361 #endif
3362 immediate_quit = 0;
3364 goto open_socket;
3366 #endif /* HAVE_GETADDRINFO */
3368 /* We end up here if getaddrinfo is not defined, or in case no hostname
3369 has been specified (e.g. for a local server process). */
3371 if (EQ (service, Qt))
3372 port = 0;
3373 else if (INTEGERP (service))
3374 port = htons ((unsigned short) XINT (service));
3375 else
3377 struct servent *svc_info;
3378 CHECK_STRING (service);
3379 svc_info = getservbyname (SSDATA (service),
3380 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3381 if (svc_info == 0)
3382 error ("Unknown service: %s", SDATA (service));
3383 port = svc_info->s_port;
3386 memset (&address_in, 0, sizeof address_in);
3387 address_in.sin_family = family;
3388 address_in.sin_addr.s_addr = INADDR_ANY;
3389 address_in.sin_port = port;
3391 #ifndef HAVE_GETADDRINFO
3392 if (!NILP (host))
3394 struct hostent *host_info_ptr;
3396 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3397 as it may `hang' Emacs for a very long time. */
3398 immediate_quit = 1;
3399 QUIT;
3401 #ifdef HAVE_RES_INIT
3402 res_init ();
3403 #endif
3405 host_info_ptr = gethostbyname (SDATA (host));
3406 immediate_quit = 0;
3408 if (host_info_ptr)
3410 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3411 host_info_ptr->h_length);
3412 family = host_info_ptr->h_addrtype;
3413 address_in.sin_family = family;
3415 else
3416 /* Attempt to interpret host as numeric inet address. */
3418 unsigned long numeric_addr;
3419 numeric_addr = inet_addr (SSDATA (host));
3420 if (numeric_addr == -1)
3421 error ("Unknown host \"%s\"", SDATA (host));
3423 memcpy (&address_in.sin_addr, &numeric_addr,
3424 sizeof (address_in.sin_addr));
3428 #endif /* not HAVE_GETADDRINFO */
3430 ai.ai_family = family;
3431 ai.ai_addr = (struct sockaddr *) &address_in;
3432 ai.ai_addrlen = sizeof address_in;
3434 open_socket:
3436 /* Do this in case we never enter the for-loop below. */
3437 count1 = SPECPDL_INDEX ();
3438 s = -1;
3440 for (lres = res; lres; lres = lres->ai_next)
3442 ptrdiff_t optn;
3443 int optbits;
3445 #ifdef WINDOWSNT
3446 retry_connect:
3447 #endif
3449 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3450 lres->ai_protocol);
3451 if (s < 0)
3453 xerrno = errno;
3454 continue;
3457 #ifdef DATAGRAM_SOCKETS
3458 if (!is_server && socktype == SOCK_DGRAM)
3459 break;
3460 #endif /* DATAGRAM_SOCKETS */
3462 #ifdef NON_BLOCKING_CONNECT
3463 if (is_non_blocking_client)
3465 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3466 if (ret < 0)
3468 xerrno = errno;
3469 emacs_close (s);
3470 s = -1;
3471 continue;
3474 #endif
3476 /* Make us close S if quit. */
3477 record_unwind_protect_int (close_file_unwind, s);
3479 /* Parse network options in the arg list.
3480 We simply ignore anything which isn't a known option (including other keywords).
3481 An error is signaled if setting a known option fails. */
3482 for (optn = optbits = 0; optn < nargs - 1; optn += 2)
3483 optbits |= set_socket_option (s, args[optn], args[optn + 1]);
3485 if (is_server)
3487 /* Configure as a server socket. */
3489 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3490 explicit :reuseaddr key to override this. */
3491 #ifdef HAVE_LOCAL_SOCKETS
3492 if (family != AF_LOCAL)
3493 #endif
3494 if (!(optbits & (1 << OPIX_REUSEADDR)))
3496 int optval = 1;
3497 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3498 report_file_error ("Cannot set reuse option on server socket", Qnil);
3501 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3502 report_file_error ("Cannot bind server socket", Qnil);
3504 #ifdef HAVE_GETSOCKNAME
3505 if (EQ (service, Qt))
3507 struct sockaddr_in sa1;
3508 socklen_t len1 = sizeof (sa1);
3509 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3511 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3512 service = make_number (ntohs (sa1.sin_port));
3513 contact = Fplist_put (contact, QCservice, service);
3516 #endif
3518 if (socktype != SOCK_DGRAM && listen (s, backlog))
3519 report_file_error ("Cannot listen on server socket", Qnil);
3521 break;
3524 immediate_quit = 1;
3525 QUIT;
3527 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3528 xerrno = errno;
3530 if (ret == 0 || xerrno == EISCONN)
3532 /* The unwind-protect will be discarded afterwards.
3533 Likewise for immediate_quit. */
3534 break;
3537 #ifdef NON_BLOCKING_CONNECT
3538 #ifdef EINPROGRESS
3539 if (is_non_blocking_client && xerrno == EINPROGRESS)
3540 break;
3541 #else
3542 #ifdef EWOULDBLOCK
3543 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3544 break;
3545 #endif
3546 #endif
3547 #endif
3549 #ifndef WINDOWSNT
3550 if (xerrno == EINTR)
3552 /* Unlike most other syscalls connect() cannot be called
3553 again. (That would return EALREADY.) The proper way to
3554 wait for completion is pselect(). */
3555 int sc;
3556 socklen_t len;
3557 fd_set fdset;
3558 retry_select:
3559 FD_ZERO (&fdset);
3560 FD_SET (s, &fdset);
3561 QUIT;
3562 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3563 if (sc == -1)
3565 if (errno == EINTR)
3566 goto retry_select;
3567 else
3568 report_file_error ("Failed select", Qnil);
3570 eassert (sc > 0);
3572 len = sizeof xerrno;
3573 eassert (FD_ISSET (s, &fdset));
3574 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3575 report_file_error ("Failed getsockopt", Qnil);
3576 if (xerrno)
3577 report_file_errno ("Failed connect", Qnil, xerrno);
3578 break;
3580 #endif /* !WINDOWSNT */
3582 immediate_quit = 0;
3584 /* Discard the unwind protect closing S. */
3585 specpdl_ptr = specpdl + count1;
3586 emacs_close (s);
3587 s = -1;
3589 #ifdef WINDOWSNT
3590 if (xerrno == EINTR)
3591 goto retry_connect;
3592 #endif
3595 if (s >= 0)
3597 #ifdef DATAGRAM_SOCKETS
3598 if (socktype == SOCK_DGRAM)
3600 if (datagram_address[s].sa)
3601 emacs_abort ();
3602 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3603 datagram_address[s].len = lres->ai_addrlen;
3604 if (is_server)
3606 Lisp_Object remote;
3607 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3608 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3610 int rfamily, rlen;
3611 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3612 if (rlen != 0 && rfamily == lres->ai_family
3613 && rlen == lres->ai_addrlen)
3614 conv_lisp_to_sockaddr (rfamily, remote,
3615 datagram_address[s].sa, rlen);
3618 else
3619 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3621 #endif
3622 contact = Fplist_put (contact, colon_address,
3623 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3624 #ifdef HAVE_GETSOCKNAME
3625 if (!is_server)
3627 struct sockaddr_in sa1;
3628 socklen_t len1 = sizeof (sa1);
3629 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3630 contact = Fplist_put (contact, QClocal,
3631 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3633 #endif
3636 immediate_quit = 0;
3638 #ifdef HAVE_GETADDRINFO
3639 if (res != &ai)
3641 block_input ();
3642 freeaddrinfo (res);
3643 unblock_input ();
3645 #endif
3647 if (s < 0)
3649 /* If non-blocking got this far - and failed - assume non-blocking is
3650 not supported after all. This is probably a wrong assumption, but
3651 the normal blocking calls to open-network-stream handles this error
3652 better. */
3653 if (is_non_blocking_client)
3654 return Qnil;
3656 report_file_errno ((is_server
3657 ? "make server process failed"
3658 : "make client process failed"),
3659 contact, xerrno);
3662 inch = s;
3663 outch = s;
3665 if (!NILP (buffer))
3666 buffer = Fget_buffer_create (buffer);
3667 proc = make_process (name);
3669 chan_process[inch] = proc;
3671 fcntl (inch, F_SETFL, O_NONBLOCK);
3673 p = XPROCESS (proc);
3675 pset_childp (p, contact);
3676 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3677 pset_type (p, Qnetwork);
3679 pset_buffer (p, buffer);
3680 pset_sentinel (p, sentinel);
3681 pset_filter (p, filter);
3682 pset_log (p, Fplist_get (contact, QClog));
3683 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3684 p->kill_without_query = 1;
3685 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3686 pset_command (p, Qt);
3687 p->pid = 0;
3689 p->open_fd[SUBPROCESS_STDIN] = inch;
3690 p->infd = inch;
3691 p->outfd = outch;
3693 /* Discard the unwind protect for closing S, if any. */
3694 specpdl_ptr = specpdl + count1;
3696 /* Unwind bind_polling_period and request_sigio. */
3697 unbind_to (count, Qnil);
3699 if (is_server && socktype != SOCK_DGRAM)
3700 pset_status (p, Qlisten);
3702 /* Make the process marker point into the process buffer (if any). */
3703 if (BUFFERP (buffer))
3704 set_marker_both (p->mark, buffer,
3705 BUF_ZV (XBUFFER (buffer)),
3706 BUF_ZV_BYTE (XBUFFER (buffer)));
3708 #ifdef NON_BLOCKING_CONNECT
3709 if (is_non_blocking_client)
3711 /* We may get here if connect did succeed immediately. However,
3712 in that case, we still need to signal this like a non-blocking
3713 connection. */
3714 pset_status (p, Qconnect);
3715 if (!FD_ISSET (inch, &connect_wait_mask))
3717 FD_SET (inch, &connect_wait_mask);
3718 FD_SET (inch, &write_mask);
3719 num_pending_connects++;
3722 else
3723 #endif
3724 /* A server may have a client filter setting of Qt, but it must
3725 still listen for incoming connects unless it is stopped. */
3726 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3727 || (EQ (p->status, Qlisten) && NILP (p->command)))
3729 FD_SET (inch, &input_wait_mask);
3730 FD_SET (inch, &non_keyboard_wait_mask);
3733 if (inch > max_process_desc)
3734 max_process_desc = inch;
3736 tem = Fplist_member (contact, QCcoding);
3737 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3738 tem = Qnil; /* No error message (too late!). */
3741 /* Setup coding systems for communicating with the network stream. */
3742 struct gcpro gcpro1;
3743 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3744 Lisp_Object coding_systems = Qt;
3745 Lisp_Object val;
3747 if (!NILP (tem))
3749 val = XCAR (XCDR (tem));
3750 if (CONSP (val))
3751 val = XCAR (val);
3753 else if (!NILP (Vcoding_system_for_read))
3754 val = Vcoding_system_for_read;
3755 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3756 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3757 /* We dare not decode end-of-line format by setting VAL to
3758 Qraw_text, because the existing Emacs Lisp libraries
3759 assume that they receive bare code including a sequence of
3760 CR LF. */
3761 val = Qnil;
3762 else
3764 if (NILP (host) || NILP (service))
3765 coding_systems = Qnil;
3766 else
3768 GCPRO1 (proc);
3769 coding_systems = CALLN (Ffind_operation_coding_system,
3770 Qopen_network_stream, name, buffer,
3771 host, service);
3772 UNGCPRO;
3774 if (CONSP (coding_systems))
3775 val = XCAR (coding_systems);
3776 else if (CONSP (Vdefault_process_coding_system))
3777 val = XCAR (Vdefault_process_coding_system);
3778 else
3779 val = Qnil;
3781 pset_decode_coding_system (p, val);
3783 if (!NILP (tem))
3785 val = XCAR (XCDR (tem));
3786 if (CONSP (val))
3787 val = XCDR (val);
3789 else if (!NILP (Vcoding_system_for_write))
3790 val = Vcoding_system_for_write;
3791 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3792 val = Qnil;
3793 else
3795 if (EQ (coding_systems, Qt))
3797 if (NILP (host) || NILP (service))
3798 coding_systems = Qnil;
3799 else
3801 GCPRO1 (proc);
3802 coding_systems = CALLN (Ffind_operation_coding_system,
3803 Qopen_network_stream, name, buffer,
3804 host, service);
3805 UNGCPRO;
3808 if (CONSP (coding_systems))
3809 val = XCDR (coding_systems);
3810 else if (CONSP (Vdefault_process_coding_system))
3811 val = XCDR (Vdefault_process_coding_system);
3812 else
3813 val = Qnil;
3815 pset_encode_coding_system (p, val);
3817 setup_process_coding_systems (proc);
3819 pset_decoding_buf (p, empty_unibyte_string);
3820 p->decoding_carryover = 0;
3821 pset_encoding_buf (p, empty_unibyte_string);
3823 p->inherit_coding_system_flag
3824 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3826 UNGCPRO;
3827 return proc;
3831 #ifdef HAVE_NET_IF_H
3833 #ifdef SIOCGIFCONF
3834 static Lisp_Object
3835 network_interface_list (void)
3837 struct ifconf ifconf;
3838 struct ifreq *ifreq;
3839 void *buf = NULL;
3840 ptrdiff_t buf_size = 512;
3841 int s;
3842 Lisp_Object res;
3843 ptrdiff_t count;
3845 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3846 if (s < 0)
3847 return Qnil;
3848 count = SPECPDL_INDEX ();
3849 record_unwind_protect_int (close_file_unwind, s);
3853 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3854 ifconf.ifc_buf = buf;
3855 ifconf.ifc_len = buf_size;
3856 if (ioctl (s, SIOCGIFCONF, &ifconf))
3858 emacs_close (s);
3859 xfree (buf);
3860 return Qnil;
3863 while (ifconf.ifc_len == buf_size);
3865 res = unbind_to (count, Qnil);
3866 ifreq = ifconf.ifc_req;
3867 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3869 struct ifreq *ifq = ifreq;
3870 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3871 #define SIZEOF_IFREQ(sif) \
3872 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3873 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3875 int len = SIZEOF_IFREQ (ifq);
3876 #else
3877 int len = sizeof (*ifreq);
3878 #endif
3879 char namebuf[sizeof (ifq->ifr_name) + 1];
3880 ifreq = (struct ifreq *) ((char *) ifreq + len);
3882 if (ifq->ifr_addr.sa_family != AF_INET)
3883 continue;
3885 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3886 namebuf[sizeof (ifq->ifr_name)] = 0;
3887 res = Fcons (Fcons (build_string (namebuf),
3888 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3889 sizeof (struct sockaddr))),
3890 res);
3893 xfree (buf);
3894 return res;
3896 #endif /* SIOCGIFCONF */
3898 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3900 struct ifflag_def {
3901 int flag_bit;
3902 const char *flag_sym;
3905 static const struct ifflag_def ifflag_table[] = {
3906 #ifdef IFF_UP
3907 { IFF_UP, "up" },
3908 #endif
3909 #ifdef IFF_BROADCAST
3910 { IFF_BROADCAST, "broadcast" },
3911 #endif
3912 #ifdef IFF_DEBUG
3913 { IFF_DEBUG, "debug" },
3914 #endif
3915 #ifdef IFF_LOOPBACK
3916 { IFF_LOOPBACK, "loopback" },
3917 #endif
3918 #ifdef IFF_POINTOPOINT
3919 { IFF_POINTOPOINT, "pointopoint" },
3920 #endif
3921 #ifdef IFF_RUNNING
3922 { IFF_RUNNING, "running" },
3923 #endif
3924 #ifdef IFF_NOARP
3925 { IFF_NOARP, "noarp" },
3926 #endif
3927 #ifdef IFF_PROMISC
3928 { IFF_PROMISC, "promisc" },
3929 #endif
3930 #ifdef IFF_NOTRAILERS
3931 #ifdef NS_IMPL_COCOA
3932 /* Really means smart, notrailers is obsolete. */
3933 { IFF_NOTRAILERS, "smart" },
3934 #else
3935 { IFF_NOTRAILERS, "notrailers" },
3936 #endif
3937 #endif
3938 #ifdef IFF_ALLMULTI
3939 { IFF_ALLMULTI, "allmulti" },
3940 #endif
3941 #ifdef IFF_MASTER
3942 { IFF_MASTER, "master" },
3943 #endif
3944 #ifdef IFF_SLAVE
3945 { IFF_SLAVE, "slave" },
3946 #endif
3947 #ifdef IFF_MULTICAST
3948 { IFF_MULTICAST, "multicast" },
3949 #endif
3950 #ifdef IFF_PORTSEL
3951 { IFF_PORTSEL, "portsel" },
3952 #endif
3953 #ifdef IFF_AUTOMEDIA
3954 { IFF_AUTOMEDIA, "automedia" },
3955 #endif
3956 #ifdef IFF_DYNAMIC
3957 { IFF_DYNAMIC, "dynamic" },
3958 #endif
3959 #ifdef IFF_OACTIVE
3960 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
3961 #endif
3962 #ifdef IFF_SIMPLEX
3963 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
3964 #endif
3965 #ifdef IFF_LINK0
3966 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
3967 #endif
3968 #ifdef IFF_LINK1
3969 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
3970 #endif
3971 #ifdef IFF_LINK2
3972 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
3973 #endif
3974 { 0, 0 }
3977 static Lisp_Object
3978 network_interface_info (Lisp_Object ifname)
3980 struct ifreq rq;
3981 Lisp_Object res = Qnil;
3982 Lisp_Object elt;
3983 int s;
3984 bool any = 0;
3985 ptrdiff_t count;
3986 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3987 && defined HAVE_GETIFADDRS && defined LLADDR)
3988 struct ifaddrs *ifap;
3989 #endif
3991 CHECK_STRING (ifname);
3993 if (sizeof rq.ifr_name <= SBYTES (ifname))
3994 error ("interface name too long");
3995 lispstpcpy (rq.ifr_name, ifname);
3997 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3998 if (s < 0)
3999 return Qnil;
4000 count = SPECPDL_INDEX ();
4001 record_unwind_protect_int (close_file_unwind, s);
4003 elt = Qnil;
4004 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4005 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4007 int flags = rq.ifr_flags;
4008 const struct ifflag_def *fp;
4009 int fnum;
4011 /* If flags is smaller than int (i.e. short) it may have the high bit set
4012 due to IFF_MULTICAST. In that case, sign extending it into
4013 an int is wrong. */
4014 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
4015 flags = (unsigned short) rq.ifr_flags;
4017 any = 1;
4018 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4020 if (flags & fp->flag_bit)
4022 elt = Fcons (intern (fp->flag_sym), elt);
4023 flags -= fp->flag_bit;
4026 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
4028 if (flags & 1)
4030 elt = Fcons (make_number (fnum), elt);
4034 #endif
4035 res = Fcons (elt, res);
4037 elt = Qnil;
4038 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4039 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4041 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4042 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4043 int n;
4045 any = 1;
4046 for (n = 0; n < 6; n++)
4047 p->contents[n] = make_number (((unsigned char *)
4048 &rq.ifr_hwaddr.sa_data[0])
4049 [n]);
4050 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4052 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4053 if (getifaddrs (&ifap) != -1)
4055 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4056 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4057 struct ifaddrs *it;
4059 for (it = ifap; it != NULL; it = it->ifa_next)
4061 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
4062 unsigned char linkaddr[6];
4063 int n;
4065 if (it->ifa_addr->sa_family != AF_LINK
4066 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4067 || sdl->sdl_alen != 6)
4068 continue;
4070 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4071 for (n = 0; n < 6; n++)
4072 p->contents[n] = make_number (linkaddr[n]);
4074 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4075 break;
4078 #ifdef HAVE_FREEIFADDRS
4079 freeifaddrs (ifap);
4080 #endif
4082 #endif /* HAVE_GETIFADDRS && LLADDR */
4084 res = Fcons (elt, res);
4086 elt = Qnil;
4087 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4088 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4090 any = 1;
4091 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4092 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4093 #else
4094 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4095 #endif
4097 #endif
4098 res = Fcons (elt, res);
4100 elt = Qnil;
4101 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4102 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4104 any = 1;
4105 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4107 #endif
4108 res = Fcons (elt, res);
4110 elt = Qnil;
4111 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4112 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4114 any = 1;
4115 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4117 #endif
4118 res = Fcons (elt, res);
4120 return unbind_to (count, any ? res : Qnil);
4122 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4123 #endif /* defined (HAVE_NET_IF_H) */
4125 DEFUN ("network-interface-list", Fnetwork_interface_list,
4126 Snetwork_interface_list, 0, 0, 0,
4127 doc: /* Return an alist of all network interfaces and their network address.
4128 Each element is a cons, the car of which is a string containing the
4129 interface name, and the cdr is the network address in internal
4130 format; see the description of ADDRESS in `make-network-process'.
4132 If the information is not available, return nil. */)
4133 (void)
4135 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4136 return network_interface_list ();
4137 #else
4138 return Qnil;
4139 #endif
4142 DEFUN ("network-interface-info", Fnetwork_interface_info,
4143 Snetwork_interface_info, 1, 1, 0,
4144 doc: /* Return information about network interface named IFNAME.
4145 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4146 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4147 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4148 FLAGS is the current flags of the interface.
4150 Data that is unavailable is returned as nil. */)
4151 (Lisp_Object ifname)
4153 #if ((defined HAVE_NET_IF_H \
4154 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4155 || defined SIOCGIFFLAGS)) \
4156 || defined WINDOWSNT)
4157 return network_interface_info (ifname);
4158 #else
4159 return Qnil;
4160 #endif
4163 /* If program file NAME starts with /: for quoting a magic
4164 name, remove that, preserving the multibyteness of NAME. */
4166 Lisp_Object
4167 remove_slash_colon (Lisp_Object name)
4169 return
4170 ((SBYTES (name) > 2 && SREF (name, 0) == '/' && SREF (name, 1) == ':')
4171 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
4172 SBYTES (name) - 2, STRING_MULTIBYTE (name))
4173 : name);
4176 /* Turn off input and output for process PROC. */
4178 static void
4179 deactivate_process (Lisp_Object proc)
4181 int inchannel;
4182 struct Lisp_Process *p = XPROCESS (proc);
4183 int i;
4185 #ifdef HAVE_GNUTLS
4186 /* Delete GnuTLS structures in PROC, if any. */
4187 emacs_gnutls_deinit (proc);
4188 #endif /* HAVE_GNUTLS */
4190 #ifdef ADAPTIVE_READ_BUFFERING
4191 if (p->read_output_delay > 0)
4193 if (--process_output_delay_count < 0)
4194 process_output_delay_count = 0;
4195 p->read_output_delay = 0;
4196 p->read_output_skip = 0;
4198 #endif
4200 /* Beware SIGCHLD hereabouts. */
4202 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4203 close_process_fd (&p->open_fd[i]);
4205 inchannel = p->infd;
4206 if (inchannel >= 0)
4208 p->infd = -1;
4209 p->outfd = -1;
4210 #ifdef DATAGRAM_SOCKETS
4211 if (DATAGRAM_CHAN_P (inchannel))
4213 xfree (datagram_address[inchannel].sa);
4214 datagram_address[inchannel].sa = 0;
4215 datagram_address[inchannel].len = 0;
4217 #endif
4218 chan_process[inchannel] = Qnil;
4219 FD_CLR (inchannel, &input_wait_mask);
4220 FD_CLR (inchannel, &non_keyboard_wait_mask);
4221 #ifdef NON_BLOCKING_CONNECT
4222 if (FD_ISSET (inchannel, &connect_wait_mask))
4224 FD_CLR (inchannel, &connect_wait_mask);
4225 FD_CLR (inchannel, &write_mask);
4226 if (--num_pending_connects < 0)
4227 emacs_abort ();
4229 #endif
4230 if (inchannel == max_process_desc)
4232 /* We just closed the highest-numbered process input descriptor,
4233 so recompute the highest-numbered one now. */
4234 int i = inchannel;
4236 i--;
4237 while (0 <= i && NILP (chan_process[i]));
4239 max_process_desc = i;
4245 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4246 0, 4, 0,
4247 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4248 It is given to their filter functions.
4249 Optional argument PROCESS means do not return until output has been
4250 received from PROCESS.
4252 Optional second argument SECONDS and third argument MILLISEC
4253 specify a timeout; return after that much time even if there is
4254 no subprocess output. If SECONDS is a floating point number,
4255 it specifies a fractional number of seconds to wait.
4256 The MILLISEC argument is obsolete and should be avoided.
4258 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4259 from PROCESS only, suspending reading output from other processes.
4260 If JUST-THIS-ONE is an integer, don't run any timers either.
4261 Return non-nil if we received any output from PROCESS (or, if PROCESS
4262 is nil, from any process) before the timeout expired. */)
4263 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4265 intmax_t secs;
4266 int nsecs;
4268 if (! NILP (process))
4269 CHECK_PROCESS (process);
4270 else
4271 just_this_one = Qnil;
4273 if (!NILP (millisec))
4274 { /* Obsolete calling convention using integers rather than floats. */
4275 CHECK_NUMBER (millisec);
4276 if (NILP (seconds))
4277 seconds = make_float (XINT (millisec) / 1000.0);
4278 else
4280 CHECK_NUMBER (seconds);
4281 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4285 secs = 0;
4286 nsecs = -1;
4288 if (!NILP (seconds))
4290 if (INTEGERP (seconds))
4292 if (XINT (seconds) > 0)
4294 secs = XINT (seconds);
4295 nsecs = 0;
4298 else if (FLOATP (seconds))
4300 if (XFLOAT_DATA (seconds) > 0)
4302 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4303 secs = min (t.tv_sec, WAIT_READING_MAX);
4304 nsecs = t.tv_nsec;
4307 else
4308 wrong_type_argument (Qnumberp, seconds);
4310 else if (! NILP (process))
4311 nsecs = 0;
4313 return
4314 ((wait_reading_process_output (secs, nsecs, 0, 0,
4315 Qnil,
4316 !NILP (process) ? XPROCESS (process) : NULL,
4317 (NILP (just_this_one) ? 0
4318 : !INTEGERP (just_this_one) ? 1 : -1))
4319 <= 0)
4320 ? Qnil : Qt);
4323 /* Accept a connection for server process SERVER on CHANNEL. */
4325 static EMACS_INT connect_counter = 0;
4327 static void
4328 server_accept_connection (Lisp_Object server, int channel)
4330 Lisp_Object proc, caller, name, buffer;
4331 Lisp_Object contact, host, service;
4332 struct Lisp_Process *ps = XPROCESS (server);
4333 struct Lisp_Process *p;
4334 int s;
4335 union u_sockaddr {
4336 struct sockaddr sa;
4337 struct sockaddr_in in;
4338 #ifdef AF_INET6
4339 struct sockaddr_in6 in6;
4340 #endif
4341 #ifdef HAVE_LOCAL_SOCKETS
4342 struct sockaddr_un un;
4343 #endif
4344 } saddr;
4345 socklen_t len = sizeof saddr;
4346 ptrdiff_t count;
4348 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4350 if (s < 0)
4352 int code = errno;
4354 if (code == EAGAIN)
4355 return;
4356 #ifdef EWOULDBLOCK
4357 if (code == EWOULDBLOCK)
4358 return;
4359 #endif
4361 if (!NILP (ps->log))
4362 call3 (ps->log, server, Qnil,
4363 concat3 (build_string ("accept failed with code"),
4364 Fnumber_to_string (make_number (code)),
4365 build_string ("\n")));
4366 return;
4369 count = SPECPDL_INDEX ();
4370 record_unwind_protect_int (close_file_unwind, s);
4372 connect_counter++;
4374 /* Setup a new process to handle the connection. */
4376 /* Generate a unique identification of the caller, and build contact
4377 information for this process. */
4378 host = Qt;
4379 service = Qnil;
4380 switch (saddr.sa.sa_family)
4382 case AF_INET:
4384 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4386 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4387 host = CALLN (Fformat, ipv4_format,
4388 make_number (ip[0]), make_number (ip[1]),
4389 make_number (ip[2]), make_number (ip[3]));
4390 service = make_number (ntohs (saddr.in.sin_port));
4391 AUTO_STRING (caller_format, " <%s:%d>");
4392 caller = CALLN (Fformat, caller_format, host, service);
4394 break;
4396 #ifdef AF_INET6
4397 case AF_INET6:
4399 Lisp_Object args[9];
4400 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4401 int i;
4403 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4404 args[0] = ipv6_format;
4405 for (i = 0; i < 8; i++)
4406 args[i + 1] = make_number (ntohs (ip6[i]));
4407 host = CALLMANY (Fformat, args);
4408 service = make_number (ntohs (saddr.in.sin_port));
4409 AUTO_STRING (caller_format, " <[%s]:%d>");
4410 caller = CALLN (Fformat, caller_format, host, service);
4412 break;
4413 #endif
4415 #ifdef HAVE_LOCAL_SOCKETS
4416 case AF_LOCAL:
4417 #endif
4418 default:
4419 caller = Fnumber_to_string (make_number (connect_counter));
4420 AUTO_STRING (space_less_than, " <");
4421 AUTO_STRING (greater_than, ">");
4422 caller = concat3 (space_less_than, caller, greater_than);
4423 break;
4426 /* Create a new buffer name for this process if it doesn't have a
4427 filter. The new buffer name is based on the buffer name or
4428 process name of the server process concatenated with the caller
4429 identification. */
4431 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4432 || EQ (ps->filter, Qt)))
4433 buffer = Qnil;
4434 else
4436 buffer = ps->buffer;
4437 if (!NILP (buffer))
4438 buffer = Fbuffer_name (buffer);
4439 else
4440 buffer = ps->name;
4441 if (!NILP (buffer))
4443 buffer = concat2 (buffer, caller);
4444 buffer = Fget_buffer_create (buffer);
4448 /* Generate a unique name for the new server process. Combine the
4449 server process name with the caller identification. */
4451 name = concat2 (ps->name, caller);
4452 proc = make_process (name);
4454 chan_process[s] = proc;
4456 fcntl (s, F_SETFL, O_NONBLOCK);
4458 p = XPROCESS (proc);
4460 /* Build new contact information for this setup. */
4461 contact = Fcopy_sequence (ps->childp);
4462 contact = Fplist_put (contact, QCserver, Qnil);
4463 contact = Fplist_put (contact, QChost, host);
4464 if (!NILP (service))
4465 contact = Fplist_put (contact, QCservice, service);
4466 contact = Fplist_put (contact, QCremote,
4467 conv_sockaddr_to_lisp (&saddr.sa, len));
4468 #ifdef HAVE_GETSOCKNAME
4469 len = sizeof saddr;
4470 if (getsockname (s, &saddr.sa, &len) == 0)
4471 contact = Fplist_put (contact, QClocal,
4472 conv_sockaddr_to_lisp (&saddr.sa, len));
4473 #endif
4475 pset_childp (p, contact);
4476 pset_plist (p, Fcopy_sequence (ps->plist));
4477 pset_type (p, Qnetwork);
4479 pset_buffer (p, buffer);
4480 pset_sentinel (p, ps->sentinel);
4481 pset_filter (p, ps->filter);
4482 pset_command (p, Qnil);
4483 p->pid = 0;
4485 /* Discard the unwind protect for closing S. */
4486 specpdl_ptr = specpdl + count;
4488 p->open_fd[SUBPROCESS_STDIN] = s;
4489 p->infd = s;
4490 p->outfd = s;
4491 pset_status (p, Qrun);
4493 /* Client processes for accepted connections are not stopped initially. */
4494 if (!EQ (p->filter, Qt))
4496 FD_SET (s, &input_wait_mask);
4497 FD_SET (s, &non_keyboard_wait_mask);
4500 if (s > max_process_desc)
4501 max_process_desc = s;
4503 /* Setup coding system for new process based on server process.
4504 This seems to be the proper thing to do, as the coding system
4505 of the new process should reflect the settings at the time the
4506 server socket was opened; not the current settings. */
4508 pset_decode_coding_system (p, ps->decode_coding_system);
4509 pset_encode_coding_system (p, ps->encode_coding_system);
4510 setup_process_coding_systems (proc);
4512 pset_decoding_buf (p, empty_unibyte_string);
4513 p->decoding_carryover = 0;
4514 pset_encoding_buf (p, empty_unibyte_string);
4516 p->inherit_coding_system_flag
4517 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4519 AUTO_STRING (dash, "-");
4520 AUTO_STRING (nl, "\n");
4521 Lisp_Object host_string = STRINGP (host) ? host : dash;
4523 if (!NILP (ps->log))
4525 AUTO_STRING (accept_from, "accept from ");
4526 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4529 AUTO_STRING (open_from, "open from ");
4530 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4533 /* This variable is different from waiting_for_input in keyboard.c.
4534 It is used to communicate to a lisp process-filter/sentinel (via the
4535 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4536 for user-input when that process-filter was called.
4537 waiting_for_input cannot be used as that is by definition 0 when
4538 lisp code is being evalled.
4539 This is also used in record_asynch_buffer_change.
4540 For that purpose, this must be 0
4541 when not inside wait_reading_process_output. */
4542 static int waiting_for_user_input_p;
4544 static void
4545 wait_reading_process_output_unwind (int data)
4547 waiting_for_user_input_p = data;
4550 /* This is here so breakpoints can be put on it. */
4551 static void
4552 wait_reading_process_output_1 (void)
4556 /* Read and dispose of subprocess output while waiting for timeout to
4557 elapse and/or keyboard input to be available.
4559 TIME_LIMIT is:
4560 timeout in seconds
4561 If negative, gobble data immediately available but don't wait for any.
4563 NSECS is:
4564 an additional duration to wait, measured in nanoseconds
4565 If TIME_LIMIT is zero, then:
4566 If NSECS == 0, there is no limit.
4567 If NSECS > 0, the timeout consists of NSECS only.
4568 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4570 READ_KBD is:
4571 0 to ignore keyboard input, or
4572 1 to return when input is available, or
4573 -1 meaning caller will actually read the input, so don't throw to
4574 the quit handler, or
4576 DO_DISPLAY means redisplay should be done to show subprocess
4577 output that arrives.
4579 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4580 (and gobble terminal input into the buffer if any arrives).
4582 If WAIT_PROC is specified, wait until something arrives from that
4583 process.
4585 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4586 (suspending output from other processes). A negative value
4587 means don't run any timers either.
4589 Return positive if we received input from WAIT_PROC (or from any
4590 process if WAIT_PROC is null), zero if we attempted to receive
4591 input but got none, and negative if we didn't even try. */
4594 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4595 bool do_display,
4596 Lisp_Object wait_for_cell,
4597 struct Lisp_Process *wait_proc, int just_wait_proc)
4599 int channel, nfds;
4600 fd_set Available;
4601 fd_set Writeok;
4602 bool check_write;
4603 int check_delay;
4604 bool no_avail;
4605 int xerrno;
4606 Lisp_Object proc;
4607 struct timespec timeout, end_time;
4608 int got_some_input = -1;
4609 ptrdiff_t count = SPECPDL_INDEX ();
4611 FD_ZERO (&Available);
4612 FD_ZERO (&Writeok);
4614 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4615 && !(CONSP (wait_proc->status)
4616 && EQ (XCAR (wait_proc->status), Qexit)))
4617 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4619 record_unwind_protect_int (wait_reading_process_output_unwind,
4620 waiting_for_user_input_p);
4621 waiting_for_user_input_p = read_kbd;
4623 if (time_limit < 0)
4625 time_limit = 0;
4626 nsecs = -1;
4628 else if (TYPE_MAXIMUM (time_t) < time_limit)
4629 time_limit = TYPE_MAXIMUM (time_t);
4631 /* Since we may need to wait several times,
4632 compute the absolute time to return at. */
4633 if (time_limit || nsecs > 0)
4635 timeout = make_timespec (time_limit, nsecs);
4636 end_time = timespec_add (current_timespec (), timeout);
4639 while (1)
4641 bool timeout_reduced_for_timers = false;
4643 /* If calling from keyboard input, do not quit
4644 since we want to return C-g as an input character.
4645 Otherwise, do pending quit if requested. */
4646 if (read_kbd >= 0)
4647 QUIT;
4648 else if (pending_signals)
4649 process_pending_signals ();
4651 /* Exit now if the cell we're waiting for became non-nil. */
4652 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4653 break;
4655 /* After reading input, vacuum up any leftovers without waiting. */
4656 if (0 <= got_some_input)
4657 nsecs = -1;
4659 /* Compute time from now till when time limit is up. */
4660 /* Exit if already run out. */
4661 if (nsecs < 0)
4663 /* A negative timeout means
4664 gobble output available now
4665 but don't wait at all. */
4667 timeout = make_timespec (0, 0);
4669 else if (time_limit || nsecs > 0)
4671 struct timespec now = current_timespec ();
4672 if (timespec_cmp (end_time, now) <= 0)
4673 break;
4674 timeout = timespec_sub (end_time, now);
4676 else
4678 timeout = make_timespec (100000, 0);
4681 /* Normally we run timers here.
4682 But not if wait_for_cell; in those cases,
4683 the wait is supposed to be short,
4684 and those callers cannot handle running arbitrary Lisp code here. */
4685 if (NILP (wait_for_cell)
4686 && just_wait_proc >= 0)
4688 struct timespec timer_delay;
4692 unsigned old_timers_run = timers_run;
4693 struct buffer *old_buffer = current_buffer;
4694 Lisp_Object old_window = selected_window;
4696 timer_delay = timer_check ();
4698 /* If a timer has run, this might have changed buffers
4699 an alike. Make read_key_sequence aware of that. */
4700 if (timers_run != old_timers_run
4701 && (old_buffer != current_buffer
4702 || !EQ (old_window, selected_window))
4703 && waiting_for_user_input_p == -1)
4704 record_asynch_buffer_change ();
4706 if (timers_run != old_timers_run && do_display)
4707 /* We must retry, since a timer may have requeued itself
4708 and that could alter the time_delay. */
4709 redisplay_preserve_echo_area (9);
4710 else
4711 break;
4713 while (!detect_input_pending ());
4715 /* If there is unread keyboard input, also return. */
4716 if (read_kbd != 0
4717 && requeued_events_pending_p ())
4718 break;
4720 /* A negative timeout means do not wait at all. */
4721 if (nsecs >= 0)
4723 if (timespec_valid_p (timer_delay))
4725 if (timespec_cmp (timer_delay, timeout) < 0)
4727 timeout = timer_delay;
4728 timeout_reduced_for_timers = true;
4731 else
4733 /* This is so a breakpoint can be put here. */
4734 wait_reading_process_output_1 ();
4739 /* Cause C-g and alarm signals to take immediate action,
4740 and cause input available signals to zero out timeout.
4742 It is important that we do this before checking for process
4743 activity. If we get a SIGCHLD after the explicit checks for
4744 process activity, timeout is the only way we will know. */
4745 if (read_kbd < 0)
4746 set_waiting_for_input (&timeout);
4748 /* If status of something has changed, and no input is
4749 available, notify the user of the change right away. After
4750 this explicit check, we'll let the SIGCHLD handler zap
4751 timeout to get our attention. */
4752 if (update_tick != process_tick)
4754 fd_set Atemp;
4755 fd_set Ctemp;
4757 if (kbd_on_hold_p ())
4758 FD_ZERO (&Atemp);
4759 else
4760 Atemp = input_wait_mask;
4761 Ctemp = write_mask;
4763 timeout = make_timespec (0, 0);
4764 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4765 &Atemp,
4766 #ifdef NON_BLOCKING_CONNECT
4767 (num_pending_connects > 0 ? &Ctemp : NULL),
4768 #else
4769 NULL,
4770 #endif
4771 NULL, &timeout, NULL)
4772 <= 0))
4774 /* It's okay for us to do this and then continue with
4775 the loop, since timeout has already been zeroed out. */
4776 clear_waiting_for_input ();
4777 got_some_input = status_notify (NULL, wait_proc);
4778 if (do_display) redisplay_preserve_echo_area (13);
4782 /* Don't wait for output from a non-running process. Just
4783 read whatever data has already been received. */
4784 if (wait_proc && wait_proc->raw_status_new)
4785 update_status (wait_proc);
4786 if (wait_proc
4787 && ! EQ (wait_proc->status, Qrun)
4788 && ! EQ (wait_proc->status, Qconnect))
4790 bool read_some_bytes = false;
4792 clear_waiting_for_input ();
4794 /* If data can be read from the process, do so until exhausted. */
4795 if (wait_proc->infd >= 0)
4797 XSETPROCESS (proc, wait_proc);
4799 while (true)
4801 int nread = read_process_output (proc, wait_proc->infd);
4802 if (nread < 0)
4804 if (errno == EIO || errno == EAGAIN)
4805 break;
4806 #ifdef EWOULDBLOCK
4807 if (errno == EWOULDBLOCK)
4808 break;
4809 #endif
4811 else
4813 if (got_some_input < nread)
4814 got_some_input = nread;
4815 if (nread == 0)
4816 break;
4817 read_some_bytes = true;
4822 if (read_some_bytes && do_display)
4823 redisplay_preserve_echo_area (10);
4825 break;
4828 /* Wait till there is something to do. */
4830 if (wait_proc && just_wait_proc)
4832 if (wait_proc->infd < 0) /* Terminated. */
4833 break;
4834 FD_SET (wait_proc->infd, &Available);
4835 check_delay = 0;
4836 check_write = 0;
4838 else if (!NILP (wait_for_cell))
4840 Available = non_process_wait_mask;
4841 check_delay = 0;
4842 check_write = 0;
4844 else
4846 if (! read_kbd)
4847 Available = non_keyboard_wait_mask;
4848 else
4849 Available = input_wait_mask;
4850 Writeok = write_mask;
4851 check_delay = wait_proc ? 0 : process_output_delay_count;
4852 check_write = true;
4855 /* If frame size has changed or the window is newly mapped,
4856 redisplay now, before we start to wait. There is a race
4857 condition here; if a SIGIO arrives between now and the select
4858 and indicates that a frame is trashed, the select may block
4859 displaying a trashed screen. */
4860 if (frame_garbaged && do_display)
4862 clear_waiting_for_input ();
4863 redisplay_preserve_echo_area (11);
4864 if (read_kbd < 0)
4865 set_waiting_for_input (&timeout);
4868 /* Skip the `select' call if input is available and we're
4869 waiting for keyboard input or a cell change (which can be
4870 triggered by processing X events). In the latter case, set
4871 nfds to 1 to avoid breaking the loop. */
4872 no_avail = 0;
4873 if ((read_kbd || !NILP (wait_for_cell))
4874 && detect_input_pending ())
4876 nfds = read_kbd ? 0 : 1;
4877 no_avail = 1;
4878 FD_ZERO (&Available);
4881 if (!no_avail)
4884 #ifdef ADAPTIVE_READ_BUFFERING
4885 /* Set the timeout for adaptive read buffering if any
4886 process has non-zero read_output_skip and non-zero
4887 read_output_delay, and we are not reading output for a
4888 specific process. It is not executed if
4889 Vprocess_adaptive_read_buffering is nil. */
4890 if (process_output_skip && check_delay > 0)
4892 int nsecs = timeout.tv_nsec;
4893 if (timeout.tv_sec > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4894 nsecs = READ_OUTPUT_DELAY_MAX;
4895 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4897 proc = chan_process[channel];
4898 if (NILP (proc))
4899 continue;
4900 /* Find minimum non-zero read_output_delay among the
4901 processes with non-zero read_output_skip. */
4902 if (XPROCESS (proc)->read_output_delay > 0)
4904 check_delay--;
4905 if (!XPROCESS (proc)->read_output_skip)
4906 continue;
4907 FD_CLR (channel, &Available);
4908 XPROCESS (proc)->read_output_skip = 0;
4909 if (XPROCESS (proc)->read_output_delay < nsecs)
4910 nsecs = XPROCESS (proc)->read_output_delay;
4913 timeout = make_timespec (0, nsecs);
4914 process_output_skip = 0;
4916 #endif
4918 #if defined (HAVE_NS)
4919 nfds = ns_select
4920 #elif defined (HAVE_GLIB)
4921 nfds = xg_select
4922 #else
4923 nfds = pselect
4924 #endif
4925 (max (max_process_desc, max_input_desc) + 1,
4926 &Available,
4927 (check_write ? &Writeok : 0),
4928 NULL, &timeout, NULL);
4930 #ifdef HAVE_GNUTLS
4931 /* GnuTLS buffers data internally. In lowat mode it leaves
4932 some data in the TCP buffers so that select works, but
4933 with custom pull/push functions we need to check if some
4934 data is available in the buffers manually. */
4935 if (nfds == 0)
4937 if (! wait_proc)
4939 /* We're not waiting on a specific process, so loop
4940 through all the channels and check for data.
4941 This is a workaround needed for some versions of
4942 the gnutls library -- 2.12.14 has been confirmed
4943 to need it. See
4944 http://comments.gmane.org/gmane.emacs.devel/145074 */
4945 for (channel = 0; channel < FD_SETSIZE; ++channel)
4946 if (! NILP (chan_process[channel]))
4948 struct Lisp_Process *p =
4949 XPROCESS (chan_process[channel]);
4950 if (p && p->gnutls_p && p->gnutls_state
4951 && ((emacs_gnutls_record_check_pending
4952 (p->gnutls_state))
4953 > 0))
4955 nfds++;
4956 eassert (p->infd == channel);
4957 FD_SET (p->infd, &Available);
4961 else
4963 /* Check this specific channel. */
4964 if (wait_proc->gnutls_p /* Check for valid process. */
4965 && wait_proc->gnutls_state
4966 /* Do we have pending data? */
4967 && ((emacs_gnutls_record_check_pending
4968 (wait_proc->gnutls_state))
4969 > 0))
4971 nfds = 1;
4972 eassert (0 <= wait_proc->infd);
4973 /* Set to Available. */
4974 FD_SET (wait_proc->infd, &Available);
4978 #endif
4981 xerrno = errno;
4983 /* Make C-g and alarm signals set flags again. */
4984 clear_waiting_for_input ();
4986 /* If we woke up due to SIGWINCH, actually change size now. */
4987 do_pending_window_change (0);
4989 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4990 /* We waited the full specified time, so return now. */
4991 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)) && got_some_input < nread)
5115 got_some_input = nread;
5116 if (nread > 0)
5118 /* Since read_process_output can run a filter,
5119 which can call accept-process-output,
5120 don't try to read from any other processes
5121 before doing the select again. */
5122 FD_ZERO (&Available);
5124 if (do_display)
5125 redisplay_preserve_echo_area (12);
5127 #ifdef EWOULDBLOCK
5128 else if (nread == -1 && errno == EWOULDBLOCK)
5130 #endif
5131 else if (nread == -1 && errno == EAGAIN)
5133 #ifdef WINDOWSNT
5134 /* FIXME: Is this special case still needed? */
5135 /* Note that we cannot distinguish between no input
5136 available now and a closed pipe.
5137 With luck, a closed pipe will be accompanied by
5138 subprocess termination and SIGCHLD. */
5139 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5140 && !PIPECONN_P (proc))
5142 #endif
5143 #ifdef HAVE_PTYS
5144 /* On some OSs with ptys, when the process on one end of
5145 a pty exits, the other end gets an error reading with
5146 errno = EIO instead of getting an EOF (0 bytes read).
5147 Therefore, if we get an error reading and errno =
5148 EIO, just continue, because the child process has
5149 exited and should clean itself up soon (e.g. when we
5150 get a SIGCHLD). */
5151 else if (nread == -1 && errno == EIO)
5153 struct Lisp_Process *p = XPROCESS (proc);
5155 /* Clear the descriptor now, so we only raise the
5156 signal once. */
5157 FD_CLR (channel, &input_wait_mask);
5158 FD_CLR (channel, &non_keyboard_wait_mask);
5160 if (p->pid == -2)
5162 /* If the EIO occurs on a pty, the SIGCHLD handler's
5163 waitpid call will not find the process object to
5164 delete. Do it here. */
5165 p->tick = ++process_tick;
5166 pset_status (p, Qfailed);
5169 #endif /* HAVE_PTYS */
5170 /* If we can detect process termination, don't consider the
5171 process gone just because its pipe is closed. */
5172 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5173 && !PIPECONN_P (proc))
5175 else if (nread == 0 && PIPECONN_P (proc))
5177 /* Preserve status of processes already terminated. */
5178 XPROCESS (proc)->tick = ++process_tick;
5179 deactivate_process (proc);
5180 if (EQ (XPROCESS (proc)->status, Qrun))
5181 pset_status (XPROCESS (proc),
5182 list2 (Qexit, make_number (0)));
5184 else
5186 /* Preserve status of processes already terminated. */
5187 XPROCESS (proc)->tick = ++process_tick;
5188 deactivate_process (proc);
5189 if (XPROCESS (proc)->raw_status_new)
5190 update_status (XPROCESS (proc));
5191 if (EQ (XPROCESS (proc)->status, Qrun))
5192 pset_status (XPROCESS (proc),
5193 list2 (Qexit, make_number (256)));
5196 #ifdef NON_BLOCKING_CONNECT
5197 if (FD_ISSET (channel, &Writeok)
5198 && FD_ISSET (channel, &connect_wait_mask))
5200 struct Lisp_Process *p;
5202 FD_CLR (channel, &connect_wait_mask);
5203 FD_CLR (channel, &write_mask);
5204 if (--num_pending_connects < 0)
5205 emacs_abort ();
5207 proc = chan_process[channel];
5208 if (NILP (proc))
5209 continue;
5211 p = XPROCESS (proc);
5213 #ifdef GNU_LINUX
5214 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5215 So only use it on systems where it is known to work. */
5217 socklen_t xlen = sizeof (xerrno);
5218 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5219 xerrno = errno;
5221 #else
5223 struct sockaddr pname;
5224 socklen_t pnamelen = sizeof (pname);
5226 /* If connection failed, getpeername will fail. */
5227 xerrno = 0;
5228 if (getpeername (channel, &pname, &pnamelen) < 0)
5230 /* Obtain connect failure code through error slippage. */
5231 char dummy;
5232 xerrno = errno;
5233 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5234 xerrno = errno;
5237 #endif
5238 if (xerrno)
5240 p->tick = ++process_tick;
5241 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5242 deactivate_process (proc);
5244 else
5246 pset_status (p, Qrun);
5247 /* Execute the sentinel here. If we had relied on
5248 status_notify to do it later, it will read input
5249 from the process before calling the sentinel. */
5250 exec_sentinel (proc, build_string ("open\n"));
5251 if (0 <= p->infd && !EQ (p->filter, Qt)
5252 && !EQ (p->command, Qt))
5254 FD_SET (p->infd, &input_wait_mask);
5255 FD_SET (p->infd, &non_keyboard_wait_mask);
5259 #endif /* NON_BLOCKING_CONNECT */
5260 } /* End for each file descriptor. */
5261 } /* End while exit conditions not met. */
5263 unbind_to (count, Qnil);
5265 /* If calling from keyboard input, do not quit
5266 since we want to return C-g as an input character.
5267 Otherwise, do pending quit if requested. */
5268 if (read_kbd >= 0)
5270 /* Prevent input_pending from remaining set if we quit. */
5271 clear_input_pending ();
5272 QUIT;
5275 return got_some_input;
5278 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5280 static Lisp_Object
5281 read_process_output_call (Lisp_Object fun_and_args)
5283 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5286 static Lisp_Object
5287 read_process_output_error_handler (Lisp_Object error_val)
5289 cmd_error_internal (error_val, "error in process filter: ");
5290 Vinhibit_quit = Qt;
5291 update_echo_area ();
5292 Fsleep_for (make_number (2), Qnil);
5293 return Qt;
5296 static void
5297 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5298 ssize_t nbytes,
5299 struct coding_system *coding);
5301 /* Read pending output from the process channel,
5302 starting with our buffered-ahead character if we have one.
5303 Yield number of decoded characters read.
5305 This function reads at most 4096 characters.
5306 If you want to read all available subprocess output,
5307 you must call it repeatedly until it returns zero.
5309 The characters read are decoded according to PROC's coding-system
5310 for decoding. */
5312 static int
5313 read_process_output (Lisp_Object proc, int channel)
5315 ssize_t nbytes;
5316 struct Lisp_Process *p = XPROCESS (proc);
5317 struct coding_system *coding = proc_decode_coding_system[channel];
5318 int carryover = p->decoding_carryover;
5319 enum { readmax = 4096 };
5320 ptrdiff_t count = SPECPDL_INDEX ();
5321 Lisp_Object odeactivate;
5322 char chars[sizeof coding->carryover + readmax];
5324 if (carryover)
5325 /* See the comment above. */
5326 memcpy (chars, SDATA (p->decoding_buf), carryover);
5328 #ifdef DATAGRAM_SOCKETS
5329 /* We have a working select, so proc_buffered_char is always -1. */
5330 if (DATAGRAM_CHAN_P (channel))
5332 socklen_t len = datagram_address[channel].len;
5333 nbytes = recvfrom (channel, chars + carryover, readmax,
5334 0, datagram_address[channel].sa, &len);
5336 else
5337 #endif
5339 bool buffered = proc_buffered_char[channel] >= 0;
5340 if (buffered)
5342 chars[carryover] = proc_buffered_char[channel];
5343 proc_buffered_char[channel] = -1;
5345 #ifdef HAVE_GNUTLS
5346 if (p->gnutls_p && p->gnutls_state)
5347 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5348 readmax - buffered);
5349 else
5350 #endif
5351 nbytes = emacs_read (channel, chars + carryover + buffered,
5352 readmax - buffered);
5353 #ifdef ADAPTIVE_READ_BUFFERING
5354 if (nbytes > 0 && p->adaptive_read_buffering)
5356 int delay = p->read_output_delay;
5357 if (nbytes < 256)
5359 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5361 if (delay == 0)
5362 process_output_delay_count++;
5363 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5366 else if (delay > 0 && nbytes == readmax - buffered)
5368 delay -= READ_OUTPUT_DELAY_INCREMENT;
5369 if (delay == 0)
5370 process_output_delay_count--;
5372 p->read_output_delay = delay;
5373 if (delay)
5375 p->read_output_skip = 1;
5376 process_output_skip = 1;
5379 #endif
5380 nbytes += buffered;
5381 nbytes += buffered && nbytes <= 0;
5384 p->decoding_carryover = 0;
5386 /* At this point, NBYTES holds number of bytes just received
5387 (including the one in proc_buffered_char[channel]). */
5388 if (nbytes <= 0)
5390 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5391 return nbytes;
5392 coding->mode |= CODING_MODE_LAST_BLOCK;
5395 /* Now set NBYTES how many bytes we must decode. */
5396 nbytes += carryover;
5398 odeactivate = Vdeactivate_mark;
5399 /* There's no good reason to let process filters change the current
5400 buffer, and many callers of accept-process-output, sit-for, and
5401 friends don't expect current-buffer to be changed from under them. */
5402 record_unwind_current_buffer ();
5404 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5406 /* Handling the process output should not deactivate the mark. */
5407 Vdeactivate_mark = odeactivate;
5409 unbind_to (count, Qnil);
5410 return nbytes;
5413 static void
5414 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5415 ssize_t nbytes,
5416 struct coding_system *coding)
5418 Lisp_Object outstream = p->filter;
5419 Lisp_Object text;
5420 bool outer_running_asynch_code = running_asynch_code;
5421 int waiting = waiting_for_user_input_p;
5423 /* No need to gcpro these, because all we do with them later
5424 is test them for EQness, and none of them should be a string. */
5425 #if 0
5426 Lisp_Object obuffer, okeymap;
5427 XSETBUFFER (obuffer, current_buffer);
5428 okeymap = BVAR (current_buffer, keymap);
5429 #endif
5431 /* We inhibit quit here instead of just catching it so that
5432 hitting ^G when a filter happens to be running won't screw
5433 it up. */
5434 specbind (Qinhibit_quit, Qt);
5435 specbind (Qlast_nonmenu_event, Qt);
5437 /* In case we get recursively called,
5438 and we already saved the match data nonrecursively,
5439 save the same match data in safely recursive fashion. */
5440 if (outer_running_asynch_code)
5442 Lisp_Object tem;
5443 /* Don't clobber the CURRENT match data, either! */
5444 tem = Fmatch_data (Qnil, Qnil, Qnil);
5445 restore_search_regs ();
5446 record_unwind_save_match_data ();
5447 Fset_match_data (tem, Qt);
5450 /* For speed, if a search happens within this code,
5451 save the match data in a special nonrecursive fashion. */
5452 running_asynch_code = 1;
5454 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5455 text = coding->dst_object;
5456 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5457 /* A new coding system might be found. */
5458 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5460 pset_decode_coding_system (p, Vlast_coding_system_used);
5462 /* Don't call setup_coding_system for
5463 proc_decode_coding_system[channel] here. It is done in
5464 detect_coding called via decode_coding above. */
5466 /* If a coding system for encoding is not yet decided, we set
5467 it as the same as coding-system for decoding.
5469 But, before doing that we must check if
5470 proc_encode_coding_system[p->outfd] surely points to a
5471 valid memory because p->outfd will be changed once EOF is
5472 sent to the process. */
5473 if (NILP (p->encode_coding_system) && p->outfd >= 0
5474 && proc_encode_coding_system[p->outfd])
5476 pset_encode_coding_system
5477 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5478 setup_coding_system (p->encode_coding_system,
5479 proc_encode_coding_system[p->outfd]);
5483 if (coding->carryover_bytes > 0)
5485 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5486 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5487 memcpy (SDATA (p->decoding_buf), coding->carryover,
5488 coding->carryover_bytes);
5489 p->decoding_carryover = coding->carryover_bytes;
5491 if (SBYTES (text) > 0)
5492 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5493 sometimes it's simply wrong to wrap (e.g. when called from
5494 accept-process-output). */
5495 internal_condition_case_1 (read_process_output_call,
5496 list3 (outstream, make_lisp_proc (p), text),
5497 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5498 read_process_output_error_handler);
5500 /* If we saved the match data nonrecursively, restore it now. */
5501 restore_search_regs ();
5502 running_asynch_code = outer_running_asynch_code;
5504 /* Restore waiting_for_user_input_p as it was
5505 when we were called, in case the filter clobbered it. */
5506 waiting_for_user_input_p = waiting;
5508 #if 0 /* Call record_asynch_buffer_change unconditionally,
5509 because we might have changed minor modes or other things
5510 that affect key bindings. */
5511 if (! EQ (Fcurrent_buffer (), obuffer)
5512 || ! EQ (current_buffer->keymap, okeymap))
5513 #endif
5514 /* But do it only if the caller is actually going to read events.
5515 Otherwise there's no need to make him wake up, and it could
5516 cause trouble (for example it would make sit_for return). */
5517 if (waiting_for_user_input_p == -1)
5518 record_asynch_buffer_change ();
5521 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5522 Sinternal_default_process_filter, 2, 2, 0,
5523 doc: /* Function used as default process filter.
5524 This inserts the process's output into its buffer, if there is one.
5525 Otherwise it discards the output. */)
5526 (Lisp_Object proc, Lisp_Object text)
5528 struct Lisp_Process *p;
5529 ptrdiff_t opoint;
5531 CHECK_PROCESS (proc);
5532 p = XPROCESS (proc);
5533 CHECK_STRING (text);
5535 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5537 Lisp_Object old_read_only;
5538 ptrdiff_t old_begv, old_zv;
5539 ptrdiff_t old_begv_byte, old_zv_byte;
5540 ptrdiff_t before, before_byte;
5541 ptrdiff_t opoint_byte;
5542 struct buffer *b;
5544 Fset_buffer (p->buffer);
5545 opoint = PT;
5546 opoint_byte = PT_BYTE;
5547 old_read_only = BVAR (current_buffer, read_only);
5548 old_begv = BEGV;
5549 old_zv = ZV;
5550 old_begv_byte = BEGV_BYTE;
5551 old_zv_byte = ZV_BYTE;
5553 bset_read_only (current_buffer, Qnil);
5555 /* Insert new output into buffer at the current end-of-output
5556 marker, thus preserving logical ordering of input and output. */
5557 if (XMARKER (p->mark)->buffer)
5558 set_point_from_marker (p->mark);
5559 else
5560 SET_PT_BOTH (ZV, ZV_BYTE);
5561 before = PT;
5562 before_byte = PT_BYTE;
5564 /* If the output marker is outside of the visible region, save
5565 the restriction and widen. */
5566 if (! (BEGV <= PT && PT <= ZV))
5567 Fwiden ();
5569 /* Adjust the multibyteness of TEXT to that of the buffer. */
5570 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5571 != ! STRING_MULTIBYTE (text))
5572 text = (STRING_MULTIBYTE (text)
5573 ? Fstring_as_unibyte (text)
5574 : Fstring_to_multibyte (text));
5575 /* Insert before markers in case we are inserting where
5576 the buffer's mark is, and the user's next command is Meta-y. */
5577 insert_from_string_before_markers (text, 0, 0,
5578 SCHARS (text), SBYTES (text), 0);
5580 /* Make sure the process marker's position is valid when the
5581 process buffer is changed in the signal_after_change above.
5582 W3 is known to do that. */
5583 if (BUFFERP (p->buffer)
5584 && (b = XBUFFER (p->buffer), b != current_buffer))
5585 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5586 else
5587 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5589 update_mode_lines = 23;
5591 /* Make sure opoint and the old restrictions
5592 float ahead of any new text just as point would. */
5593 if (opoint >= before)
5595 opoint += PT - before;
5596 opoint_byte += PT_BYTE - before_byte;
5598 if (old_begv > before)
5600 old_begv += PT - before;
5601 old_begv_byte += PT_BYTE - before_byte;
5603 if (old_zv >= before)
5605 old_zv += PT - before;
5606 old_zv_byte += PT_BYTE - before_byte;
5609 /* If the restriction isn't what it should be, set it. */
5610 if (old_begv != BEGV || old_zv != ZV)
5611 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5613 bset_read_only (current_buffer, old_read_only);
5614 SET_PT_BOTH (opoint, opoint_byte);
5616 return Qnil;
5619 /* Sending data to subprocess. */
5621 /* In send_process, when a write fails temporarily,
5622 wait_reading_process_output is called. It may execute user code,
5623 e.g. timers, that attempts to write new data to the same process.
5624 We must ensure that data is sent in the right order, and not
5625 interspersed half-completed with other writes (Bug#10815). This is
5626 handled by the write_queue element of struct process. It is a list
5627 with each entry having the form
5629 (string . (offset . length))
5631 where STRING is a lisp string, OFFSET is the offset into the
5632 string's byte sequence from which we should begin to send, and
5633 LENGTH is the number of bytes left to send. */
5635 /* Create a new entry in write_queue.
5636 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5637 BUF is a pointer to the string sequence of the input_obj or a C
5638 string in case of Qt or Qnil. */
5640 static void
5641 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5642 const char *buf, ptrdiff_t len, bool front)
5644 ptrdiff_t offset;
5645 Lisp_Object entry, obj;
5647 if (STRINGP (input_obj))
5649 offset = buf - SSDATA (input_obj);
5650 obj = input_obj;
5652 else
5654 offset = 0;
5655 obj = make_unibyte_string (buf, len);
5658 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5660 if (front)
5661 pset_write_queue (p, Fcons (entry, p->write_queue));
5662 else
5663 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5666 /* Remove the first element in the write_queue of process P, put its
5667 contents in OBJ, BUF and LEN, and return true. If the
5668 write_queue is empty, return false. */
5670 static bool
5671 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5672 const char **buf, ptrdiff_t *len)
5674 Lisp_Object entry, offset_length;
5675 ptrdiff_t offset;
5677 if (NILP (p->write_queue))
5678 return 0;
5680 entry = XCAR (p->write_queue);
5681 pset_write_queue (p, XCDR (p->write_queue));
5683 *obj = XCAR (entry);
5684 offset_length = XCDR (entry);
5686 *len = XINT (XCDR (offset_length));
5687 offset = XINT (XCAR (offset_length));
5688 *buf = SSDATA (*obj) + offset;
5690 return 1;
5693 /* Send some data to process PROC.
5694 BUF is the beginning of the data; LEN is the number of characters.
5695 OBJECT is the Lisp object that the data comes from. If OBJECT is
5696 nil or t, it means that the data comes from C string.
5698 If OBJECT is not nil, the data is encoded by PROC's coding-system
5699 for encoding before it is sent.
5701 This function can evaluate Lisp code and can garbage collect. */
5703 static void
5704 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5705 Lisp_Object object)
5707 struct Lisp_Process *p = XPROCESS (proc);
5708 ssize_t rv;
5709 struct coding_system *coding;
5711 if (p->raw_status_new)
5712 update_status (p);
5713 if (! EQ (p->status, Qrun))
5714 error ("Process %s not running", SDATA (p->name));
5715 if (p->outfd < 0)
5716 error ("Output file descriptor of %s is closed", SDATA (p->name));
5718 coding = proc_encode_coding_system[p->outfd];
5719 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5721 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5722 || (BUFFERP (object)
5723 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5724 || EQ (object, Qt))
5726 pset_encode_coding_system
5727 (p, complement_process_encoding_system (p->encode_coding_system));
5728 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5730 /* The coding system for encoding was changed to raw-text
5731 because we sent a unibyte text previously. Now we are
5732 sending a multibyte text, thus we must encode it by the
5733 original coding system specified for the current process.
5735 Another reason we come here is that the coding system
5736 was just complemented and a new one was returned by
5737 complement_process_encoding_system. */
5738 setup_coding_system (p->encode_coding_system, coding);
5739 Vlast_coding_system_used = p->encode_coding_system;
5741 coding->src_multibyte = 1;
5743 else
5745 coding->src_multibyte = 0;
5746 /* For sending a unibyte text, character code conversion should
5747 not take place but EOL conversion should. So, setup raw-text
5748 or one of the subsidiary if we have not yet done it. */
5749 if (CODING_REQUIRE_ENCODING (coding))
5751 if (CODING_REQUIRE_FLUSHING (coding))
5753 /* But, before changing the coding, we must flush out data. */
5754 coding->mode |= CODING_MODE_LAST_BLOCK;
5755 send_process (proc, "", 0, Qt);
5756 coding->mode &= CODING_MODE_LAST_BLOCK;
5758 setup_coding_system (raw_text_coding_system
5759 (Vlast_coding_system_used),
5760 coding);
5761 coding->src_multibyte = 0;
5764 coding->dst_multibyte = 0;
5766 if (CODING_REQUIRE_ENCODING (coding))
5768 coding->dst_object = Qt;
5769 if (BUFFERP (object))
5771 ptrdiff_t from_byte, from, to;
5772 ptrdiff_t save_pt, save_pt_byte;
5773 struct buffer *cur = current_buffer;
5775 set_buffer_internal (XBUFFER (object));
5776 save_pt = PT, save_pt_byte = PT_BYTE;
5778 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5779 from = BYTE_TO_CHAR (from_byte);
5780 to = BYTE_TO_CHAR (from_byte + len);
5781 TEMP_SET_PT_BOTH (from, from_byte);
5782 encode_coding_object (coding, object, from, from_byte,
5783 to, from_byte + len, Qt);
5784 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5785 set_buffer_internal (cur);
5787 else if (STRINGP (object))
5789 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5790 SBYTES (object), Qt);
5792 else
5794 coding->dst_object = make_unibyte_string (buf, len);
5795 coding->produced = len;
5798 len = coding->produced;
5799 object = coding->dst_object;
5800 buf = SSDATA (object);
5803 /* If there is already data in the write_queue, put the new data
5804 in the back of queue. Otherwise, ignore it. */
5805 if (!NILP (p->write_queue))
5806 write_queue_push (p, object, buf, len, 0);
5808 do /* while !NILP (p->write_queue) */
5810 ptrdiff_t cur_len = -1;
5811 const char *cur_buf;
5812 Lisp_Object cur_object;
5814 /* If write_queue is empty, ignore it. */
5815 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5817 cur_len = len;
5818 cur_buf = buf;
5819 cur_object = object;
5822 while (cur_len > 0)
5824 /* Send this batch, using one or more write calls. */
5825 ptrdiff_t written = 0;
5826 int outfd = p->outfd;
5827 #ifdef DATAGRAM_SOCKETS
5828 if (DATAGRAM_CHAN_P (outfd))
5830 rv = sendto (outfd, cur_buf, cur_len,
5831 0, datagram_address[outfd].sa,
5832 datagram_address[outfd].len);
5833 if (rv >= 0)
5834 written = rv;
5835 else if (errno == EMSGSIZE)
5836 report_file_error ("Sending datagram", proc);
5838 else
5839 #endif
5841 #ifdef HAVE_GNUTLS
5842 if (p->gnutls_p && p->gnutls_state)
5843 written = emacs_gnutls_write (p, cur_buf, cur_len);
5844 else
5845 #endif
5846 written = emacs_write_sig (outfd, cur_buf, cur_len);
5847 rv = (written ? 0 : -1);
5848 #ifdef ADAPTIVE_READ_BUFFERING
5849 if (p->read_output_delay > 0
5850 && p->adaptive_read_buffering == 1)
5852 p->read_output_delay = 0;
5853 process_output_delay_count--;
5854 p->read_output_skip = 0;
5856 #endif
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_input = -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 (got_some_input < nread)
6722 got_some_input = nread;
6723 if (nread <= 0)
6724 break;
6727 /* Get the text to use for the message. */
6728 if (p->raw_status_new)
6729 update_status (p);
6730 msg = status_message (p);
6732 /* If process is terminated, deactivate it or delete it. */
6733 symbol = p->status;
6734 if (CONSP (p->status))
6735 symbol = XCAR (p->status);
6737 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6738 || EQ (symbol, Qclosed))
6740 if (delete_exited_processes)
6741 remove_process (proc);
6742 else
6743 deactivate_process (proc);
6746 /* The actions above may have further incremented p->tick.
6747 So set p->update_tick again so that an error in the sentinel will
6748 not cause this code to be run again. */
6749 p->update_tick = p->tick;
6750 /* Now output the message suitably. */
6751 exec_sentinel (proc, msg);
6753 } /* end for */
6755 update_mode_lines = 24; /* In case buffers use %s in mode-line-format. */
6756 UNGCPRO;
6757 return got_some_input;
6760 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6761 Sinternal_default_process_sentinel, 2, 2, 0,
6762 doc: /* Function used as default sentinel for processes.
6763 This inserts a status message into the process's buffer, if there is one. */)
6764 (Lisp_Object proc, Lisp_Object msg)
6766 Lisp_Object buffer, symbol;
6767 struct Lisp_Process *p;
6768 CHECK_PROCESS (proc);
6769 p = XPROCESS (proc);
6770 buffer = p->buffer;
6771 symbol = p->status;
6772 if (CONSP (symbol))
6773 symbol = XCAR (symbol);
6775 if (!EQ (symbol, Qrun) && !NILP (buffer))
6777 Lisp_Object tem;
6778 struct buffer *old = current_buffer;
6779 ptrdiff_t opoint, opoint_byte;
6780 ptrdiff_t before, before_byte;
6782 /* Avoid error if buffer is deleted
6783 (probably that's why the process is dead, too). */
6784 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6785 return Qnil;
6786 Fset_buffer (buffer);
6788 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6789 msg = (code_convert_string_norecord
6790 (msg, Vlocale_coding_system, 1));
6792 opoint = PT;
6793 opoint_byte = PT_BYTE;
6794 /* Insert new output into buffer
6795 at the current end-of-output marker,
6796 thus preserving logical ordering of input and output. */
6797 if (XMARKER (p->mark)->buffer)
6798 Fgoto_char (p->mark);
6799 else
6800 SET_PT_BOTH (ZV, ZV_BYTE);
6802 before = PT;
6803 before_byte = PT_BYTE;
6805 tem = BVAR (current_buffer, read_only);
6806 bset_read_only (current_buffer, Qnil);
6807 insert_string ("\nProcess ");
6808 { /* FIXME: temporary kludge. */
6809 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6810 insert_string (" ");
6811 Finsert (1, &msg);
6812 bset_read_only (current_buffer, tem);
6813 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6815 if (opoint >= before)
6816 SET_PT_BOTH (opoint + (PT - before),
6817 opoint_byte + (PT_BYTE - before_byte));
6818 else
6819 SET_PT_BOTH (opoint, opoint_byte);
6821 set_buffer_internal (old);
6823 return Qnil;
6827 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6828 Sset_process_coding_system, 1, 3, 0,
6829 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6830 DECODING will be used to decode subprocess output and ENCODING to
6831 encode subprocess input. */)
6832 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6834 register struct Lisp_Process *p;
6836 CHECK_PROCESS (process);
6837 p = XPROCESS (process);
6838 if (p->infd < 0)
6839 error ("Input file descriptor of %s closed", SDATA (p->name));
6840 if (p->outfd < 0)
6841 error ("Output file descriptor of %s closed", SDATA (p->name));
6842 Fcheck_coding_system (decoding);
6843 Fcheck_coding_system (encoding);
6844 encoding = coding_inherit_eol_type (encoding, Qnil);
6845 pset_decode_coding_system (p, decoding);
6846 pset_encode_coding_system (p, encoding);
6847 setup_process_coding_systems (process);
6849 return Qnil;
6852 DEFUN ("process-coding-system",
6853 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6854 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6855 (register Lisp_Object process)
6857 CHECK_PROCESS (process);
6858 return Fcons (XPROCESS (process)->decode_coding_system,
6859 XPROCESS (process)->encode_coding_system);
6862 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6863 Sset_process_filter_multibyte, 2, 2, 0,
6864 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6865 If FLAG is non-nil, the filter is given multibyte strings.
6866 If FLAG is nil, the filter is given unibyte strings. In this case,
6867 all character code conversion except for end-of-line conversion is
6868 suppressed. */)
6869 (Lisp_Object process, Lisp_Object flag)
6871 register struct Lisp_Process *p;
6873 CHECK_PROCESS (process);
6874 p = XPROCESS (process);
6875 if (NILP (flag))
6876 pset_decode_coding_system
6877 (p, raw_text_coding_system (p->decode_coding_system));
6878 setup_process_coding_systems (process);
6880 return Qnil;
6883 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6884 Sprocess_filter_multibyte_p, 1, 1, 0,
6885 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6886 (Lisp_Object process)
6888 register struct Lisp_Process *p;
6889 struct coding_system *coding;
6891 CHECK_PROCESS (process);
6892 p = XPROCESS (process);
6893 if (p->infd < 0)
6894 return Qnil;
6895 coding = proc_decode_coding_system[p->infd];
6896 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6902 # ifdef HAVE_GPM
6904 void
6905 add_gpm_wait_descriptor (int desc)
6907 add_keyboard_wait_descriptor (desc);
6910 void
6911 delete_gpm_wait_descriptor (int desc)
6913 delete_keyboard_wait_descriptor (desc);
6916 # endif
6918 # ifdef USABLE_SIGIO
6920 /* Return true if *MASK has a bit set
6921 that corresponds to one of the keyboard input descriptors. */
6923 static bool
6924 keyboard_bit_set (fd_set *mask)
6926 int fd;
6928 for (fd = 0; fd <= max_input_desc; fd++)
6929 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6930 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6931 return 1;
6933 return 0;
6935 # endif
6937 #else /* not subprocesses */
6939 /* Defined in msdos.c. */
6940 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6941 struct timespec *, void *);
6943 /* Implementation of wait_reading_process_output, assuming that there
6944 are no subprocesses. Used only by the MS-DOS build.
6946 Wait for timeout to elapse and/or keyboard input to be available.
6948 TIME_LIMIT is:
6949 timeout in seconds
6950 If negative, gobble data immediately available but don't wait for any.
6952 NSECS is:
6953 an additional duration to wait, measured in nanoseconds
6954 If TIME_LIMIT is zero, then:
6955 If NSECS == 0, there is no limit.
6956 If NSECS > 0, the timeout consists of NSECS only.
6957 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6959 READ_KBD is:
6960 0 to ignore keyboard input, or
6961 1 to return when input is available, or
6962 -1 means caller will actually read the input, so don't throw to
6963 the quit handler.
6965 see full version for other parameters. We know that wait_proc will
6966 always be NULL, since `subprocesses' isn't defined.
6968 DO_DISPLAY means redisplay should be done to show subprocess
6969 output that arrives.
6971 Return positive if we received input from WAIT_PROC (or from any
6972 process if WAIT_PROC is null), zero if we attempted to receive
6973 input but got none, and negative if we didn't even try. */
6976 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6977 bool do_display,
6978 Lisp_Object wait_for_cell,
6979 struct Lisp_Process *wait_proc, int just_wait_proc)
6981 register int nfds;
6982 struct timespec end_time, timeout;
6984 if (time_limit < 0)
6986 time_limit = 0;
6987 nsecs = -1;
6989 else if (TYPE_MAXIMUM (time_t) < time_limit)
6990 time_limit = TYPE_MAXIMUM (time_t);
6992 /* What does time_limit really mean? */
6993 if (time_limit || nsecs > 0)
6995 timeout = make_timespec (time_limit, nsecs);
6996 end_time = timespec_add (current_timespec (), timeout);
6999 /* Turn off periodic alarms (in case they are in use)
7000 and then turn off any other atimers,
7001 because the select emulator uses alarms. */
7002 stop_polling ();
7003 turn_on_atimers (0);
7005 while (1)
7007 bool timeout_reduced_for_timers = false;
7008 fd_set waitchannels;
7009 int xerrno;
7011 /* If calling from keyboard input, do not quit
7012 since we want to return C-g as an input character.
7013 Otherwise, do pending quit if requested. */
7014 if (read_kbd >= 0)
7015 QUIT;
7017 /* Exit now if the cell we're waiting for became non-nil. */
7018 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7019 break;
7021 /* Compute time from now till when time limit is up. */
7022 /* Exit if already run out. */
7023 if (nsecs < 0)
7025 /* A negative timeout means
7026 gobble output available now
7027 but don't wait at all. */
7029 timeout = make_timespec (0, 0);
7031 else if (time_limit || nsecs > 0)
7033 struct timespec now = current_timespec ();
7034 if (timespec_cmp (end_time, now) <= 0)
7035 break;
7036 timeout = timespec_sub (end_time, now);
7038 else
7040 timeout = make_timespec (100000, 0);
7043 /* If our caller will not immediately handle keyboard events,
7044 run timer events directly.
7045 (Callers that will immediately read keyboard events
7046 call timer_delay on their own.) */
7047 if (NILP (wait_for_cell))
7049 struct timespec timer_delay;
7053 unsigned old_timers_run = timers_run;
7054 timer_delay = timer_check ();
7055 if (timers_run != old_timers_run && do_display)
7056 /* We must retry, since a timer may have requeued itself
7057 and that could alter the time delay. */
7058 redisplay_preserve_echo_area (14);
7059 else
7060 break;
7062 while (!detect_input_pending ());
7064 /* If there is unread keyboard input, also return. */
7065 if (read_kbd != 0
7066 && requeued_events_pending_p ())
7067 break;
7069 if (timespec_valid_p (timer_delay) && nsecs >= 0)
7071 if (timespec_cmp (timer_delay, timeout) < 0)
7073 timeout = timer_delay;
7074 timeout_reduced_for_timers = true;
7079 /* Cause C-g and alarm signals to take immediate action,
7080 and cause input available signals to zero out timeout. */
7081 if (read_kbd < 0)
7082 set_waiting_for_input (&timeout);
7084 /* If a frame has been newly mapped and needs updating,
7085 reprocess its display stuff. */
7086 if (frame_garbaged && do_display)
7088 clear_waiting_for_input ();
7089 redisplay_preserve_echo_area (15);
7090 if (read_kbd < 0)
7091 set_waiting_for_input (&timeout);
7094 /* Wait till there is something to do. */
7095 FD_ZERO (&waitchannels);
7096 if (read_kbd && detect_input_pending ())
7097 nfds = 0;
7098 else
7100 if (read_kbd || !NILP (wait_for_cell))
7101 FD_SET (0, &waitchannels);
7102 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7105 xerrno = errno;
7107 /* Make C-g and alarm signals set flags again. */
7108 clear_waiting_for_input ();
7110 /* If we woke up due to SIGWINCH, actually change size now. */
7111 do_pending_window_change (0);
7113 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
7114 /* We waited the full specified time, so return now. */
7115 break;
7117 if (nfds == -1)
7119 /* If the system call was interrupted, then go around the
7120 loop again. */
7121 if (xerrno == EINTR)
7122 FD_ZERO (&waitchannels);
7123 else
7124 report_file_errno ("Failed select", Qnil, xerrno);
7127 /* Check for keyboard input. */
7129 if (read_kbd
7130 && detect_input_pending_run_timers (do_display))
7132 swallow_events (do_display);
7133 if (detect_input_pending_run_timers (do_display))
7134 break;
7137 /* If there is unread keyboard input, also return. */
7138 if (read_kbd
7139 && requeued_events_pending_p ())
7140 break;
7142 /* If wait_for_cell. check for keyboard input
7143 but don't run any timers.
7144 ??? (It seems wrong to me to check for keyboard
7145 input at all when wait_for_cell, but the code
7146 has been this way since July 1994.
7147 Try changing this after version 19.31.) */
7148 if (! NILP (wait_for_cell)
7149 && detect_input_pending ())
7151 swallow_events (do_display);
7152 if (detect_input_pending ())
7153 break;
7156 /* Exit now if the cell we're waiting for became non-nil. */
7157 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7158 break;
7161 start_polling ();
7163 return -1;
7166 #endif /* not subprocesses */
7168 /* The following functions are needed even if async subprocesses are
7169 not supported. Some of them are no-op stubs in that case. */
7171 #ifdef HAVE_TIMERFD
7173 /* Add FD, which is a descriptor returned by timerfd_create,
7174 to the set of non-keyboard input descriptors. */
7176 void
7177 add_timer_wait_descriptor (int fd)
7179 FD_SET (fd, &input_wait_mask);
7180 FD_SET (fd, &non_keyboard_wait_mask);
7181 FD_SET (fd, &non_process_wait_mask);
7182 fd_callback_info[fd].func = timerfd_callback;
7183 fd_callback_info[fd].data = NULL;
7184 fd_callback_info[fd].condition |= FOR_READ;
7185 if (fd > max_input_desc)
7186 max_input_desc = fd;
7189 #endif /* HAVE_TIMERFD */
7191 /* Add DESC to the set of keyboard input descriptors. */
7193 void
7194 add_keyboard_wait_descriptor (int desc)
7196 #ifdef subprocesses /* Actually means "not MSDOS". */
7197 FD_SET (desc, &input_wait_mask);
7198 FD_SET (desc, &non_process_wait_mask);
7199 if (desc > max_input_desc)
7200 max_input_desc = desc;
7201 #endif
7204 /* From now on, do not expect DESC to give keyboard input. */
7206 void
7207 delete_keyboard_wait_descriptor (int desc)
7209 #ifdef subprocesses
7210 FD_CLR (desc, &input_wait_mask);
7211 FD_CLR (desc, &non_process_wait_mask);
7212 delete_input_desc (desc);
7213 #endif
7216 /* Setup coding systems of PROCESS. */
7218 void
7219 setup_process_coding_systems (Lisp_Object process)
7221 #ifdef subprocesses
7222 struct Lisp_Process *p = XPROCESS (process);
7223 int inch = p->infd;
7224 int outch = p->outfd;
7225 Lisp_Object coding_system;
7227 if (inch < 0 || outch < 0)
7228 return;
7230 if (!proc_decode_coding_system[inch])
7231 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7232 coding_system = p->decode_coding_system;
7233 if (EQ (p->filter, Qinternal_default_process_filter)
7234 && BUFFERP (p->buffer))
7236 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7237 coding_system = raw_text_coding_system (coding_system);
7239 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7241 if (!proc_encode_coding_system[outch])
7242 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7243 setup_coding_system (p->encode_coding_system,
7244 proc_encode_coding_system[outch]);
7245 #endif
7248 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7249 doc: /* Return the (or a) process associated with BUFFER.
7250 BUFFER may be a buffer or the name of one. */)
7251 (register Lisp_Object buffer)
7253 #ifdef subprocesses
7254 register Lisp_Object buf, tail, proc;
7256 if (NILP (buffer)) return Qnil;
7257 buf = Fget_buffer (buffer);
7258 if (NILP (buf)) return Qnil;
7260 FOR_EACH_PROCESS (tail, proc)
7261 if (EQ (XPROCESS (proc)->buffer, buf))
7262 return proc;
7263 #endif /* subprocesses */
7264 return Qnil;
7267 DEFUN ("process-inherit-coding-system-flag",
7268 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7269 1, 1, 0,
7270 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7271 If this flag is t, `buffer-file-coding-system' of the buffer
7272 associated with PROCESS will inherit the coding system used to decode
7273 the process output. */)
7274 (register Lisp_Object process)
7276 #ifdef subprocesses
7277 CHECK_PROCESS (process);
7278 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7279 #else
7280 /* Ignore the argument and return the value of
7281 inherit-process-coding-system. */
7282 return inherit_process_coding_system ? Qt : Qnil;
7283 #endif
7286 /* Kill all processes associated with `buffer'.
7287 If `buffer' is nil, kill all processes. */
7289 void
7290 kill_buffer_processes (Lisp_Object buffer)
7292 #ifdef subprocesses
7293 Lisp_Object tail, proc;
7295 FOR_EACH_PROCESS (tail, proc)
7296 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7298 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7299 Fdelete_process (proc);
7300 else if (XPROCESS (proc)->infd >= 0)
7301 process_send_signal (proc, SIGHUP, Qnil, 1);
7303 #else /* subprocesses */
7304 /* Since we have no subprocesses, this does nothing. */
7305 #endif /* subprocesses */
7308 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7309 Swaiting_for_user_input_p, 0, 0, 0,
7310 doc: /* Return non-nil if Emacs is waiting for input from the user.
7311 This is intended for use by asynchronous process output filters and sentinels. */)
7312 (void)
7314 #ifdef subprocesses
7315 return (waiting_for_user_input_p ? Qt : Qnil);
7316 #else
7317 return Qnil;
7318 #endif
7321 /* Stop reading input from keyboard sources. */
7323 void
7324 hold_keyboard_input (void)
7326 kbd_is_on_hold = 1;
7329 /* Resume reading input from keyboard sources. */
7331 void
7332 unhold_keyboard_input (void)
7334 kbd_is_on_hold = 0;
7337 /* Return true if keyboard input is on hold, zero otherwise. */
7339 bool
7340 kbd_on_hold_p (void)
7342 return kbd_is_on_hold;
7346 /* Enumeration of and access to system processes a-la ps(1). */
7348 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7349 0, 0, 0,
7350 doc: /* Return a list of numerical process IDs of all running processes.
7351 If this functionality is unsupported, return nil.
7353 See `process-attributes' for getting attributes of a process given its ID. */)
7354 (void)
7356 return list_system_processes ();
7359 DEFUN ("process-attributes", Fprocess_attributes,
7360 Sprocess_attributes, 1, 1, 0,
7361 doc: /* Return attributes of the process given by its PID, a number.
7363 Value is an alist where each element is a cons cell of the form
7365 \(KEY . VALUE)
7367 If this functionality is unsupported, the value is nil.
7369 See `list-system-processes' for getting a list of all process IDs.
7371 The KEYs of the attributes that this function may return are listed
7372 below, together with the type of the associated VALUE (in parentheses).
7373 Not all platforms support all of these attributes; unsupported
7374 attributes will not appear in the returned alist.
7375 Unless explicitly indicated otherwise, numbers can have either
7376 integer or floating point values.
7378 euid -- Effective user User ID of the process (number)
7379 user -- User name corresponding to euid (string)
7380 egid -- Effective user Group ID of the process (number)
7381 group -- Group name corresponding to egid (string)
7382 comm -- Command name (executable name only) (string)
7383 state -- Process state code, such as "S", "R", or "T" (string)
7384 ppid -- Parent process ID (number)
7385 pgrp -- Process group ID (number)
7386 sess -- Session ID, i.e. process ID of session leader (number)
7387 ttname -- Controlling tty name (string)
7388 tpgid -- ID of foreground process group on the process's tty (number)
7389 minflt -- number of minor page faults (number)
7390 majflt -- number of major page faults (number)
7391 cminflt -- cumulative number of minor page faults (number)
7392 cmajflt -- cumulative number of major page faults (number)
7393 utime -- user time used by the process, in (current-time) format,
7394 which is a list of integers (HIGH LOW USEC PSEC)
7395 stime -- system time used by the process (current-time)
7396 time -- sum of utime and stime (current-time)
7397 cutime -- user time used by the process and its children (current-time)
7398 cstime -- system time used by the process and its children (current-time)
7399 ctime -- sum of cutime and cstime (current-time)
7400 pri -- priority of the process (number)
7401 nice -- nice value of the process (number)
7402 thcount -- process thread count (number)
7403 start -- time the process started (current-time)
7404 vsize -- virtual memory size of the process in KB's (number)
7405 rss -- resident set size of the process in KB's (number)
7406 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7407 pcpu -- percents of CPU time used by the process (floating-point number)
7408 pmem -- percents of total physical memory used by process's resident set
7409 (floating-point number)
7410 args -- command line which invoked the process (string). */)
7411 ( Lisp_Object pid)
7413 return system_process_attributes (pid);
7416 #ifdef subprocesses
7417 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7418 Invoke this after init_process_emacs, and after glib and/or GNUstep
7419 futz with the SIGCHLD handler, but before Emacs forks any children.
7420 This function's caller should block SIGCHLD. */
7422 void
7423 catch_child_signal (void)
7425 struct sigaction action, old_action;
7426 sigset_t oldset;
7427 emacs_sigaction_init (&action, deliver_child_signal);
7428 block_child_signal (&oldset);
7429 sigaction (SIGCHLD, &action, &old_action);
7430 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7431 || ! (old_action.sa_flags & SA_SIGINFO));
7433 if (old_action.sa_handler != deliver_child_signal)
7434 lib_child_handler
7435 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7436 ? dummy_handler
7437 : old_action.sa_handler);
7438 unblock_child_signal (&oldset);
7440 #endif /* subprocesses */
7443 /* This is not called "init_process" because that is the name of a
7444 Mach system call, so it would cause problems on Darwin systems. */
7445 void
7446 init_process_emacs (void)
7448 #ifdef subprocesses
7449 register int i;
7451 inhibit_sentinels = 0;
7453 #ifndef CANNOT_DUMP
7454 if (! noninteractive || initialized)
7455 #endif
7457 #if defined HAVE_GLIB && !defined WINDOWSNT
7458 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7459 this should always fail, but is enough to initialize glib's
7460 private SIGCHLD handler, allowing catch_child_signal to copy
7461 it into lib_child_handler. */
7462 g_source_unref (g_child_watch_source_new (getpid ()));
7463 #endif
7464 catch_child_signal ();
7467 FD_ZERO (&input_wait_mask);
7468 FD_ZERO (&non_keyboard_wait_mask);
7469 FD_ZERO (&non_process_wait_mask);
7470 FD_ZERO (&write_mask);
7471 max_process_desc = max_input_desc = -1;
7472 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7474 #ifdef NON_BLOCKING_CONNECT
7475 FD_ZERO (&connect_wait_mask);
7476 num_pending_connects = 0;
7477 #endif
7479 #ifdef ADAPTIVE_READ_BUFFERING
7480 process_output_delay_count = 0;
7481 process_output_skip = 0;
7482 #endif
7484 /* Don't do this, it caused infinite select loops. The display
7485 method should call add_keyboard_wait_descriptor on stdin if it
7486 needs that. */
7487 #if 0
7488 FD_SET (0, &input_wait_mask);
7489 #endif
7491 Vprocess_alist = Qnil;
7492 deleted_pid_list = Qnil;
7493 for (i = 0; i < FD_SETSIZE; i++)
7495 chan_process[i] = Qnil;
7496 proc_buffered_char[i] = -1;
7498 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7499 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7500 #ifdef DATAGRAM_SOCKETS
7501 memset (datagram_address, 0, sizeof datagram_address);
7502 #endif
7504 #if defined (DARWIN_OS)
7505 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7506 processes. As such, we only change the default value. */
7507 if (initialized)
7509 char const *release = (STRINGP (Voperating_system_release)
7510 ? SSDATA (Voperating_system_release)
7511 : 0);
7512 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7513 Vprocess_connection_type = Qnil;
7516 #endif
7517 #endif /* subprocesses */
7518 kbd_is_on_hold = 0;
7521 void
7522 syms_of_process (void)
7524 #ifdef subprocesses
7526 DEFSYM (Qprocessp, "processp");
7527 DEFSYM (Qrun, "run");
7528 DEFSYM (Qstop, "stop");
7529 DEFSYM (Qsignal, "signal");
7531 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7532 here again. */
7534 DEFSYM (Qopen, "open");
7535 DEFSYM (Qclosed, "closed");
7536 DEFSYM (Qconnect, "connect");
7537 DEFSYM (Qfailed, "failed");
7538 DEFSYM (Qlisten, "listen");
7539 DEFSYM (Qlocal, "local");
7540 DEFSYM (Qipv4, "ipv4");
7541 #ifdef AF_INET6
7542 DEFSYM (Qipv6, "ipv6");
7543 #endif
7544 DEFSYM (Qdatagram, "datagram");
7545 DEFSYM (Qseqpacket, "seqpacket");
7547 DEFSYM (QCport, ":port");
7548 DEFSYM (QCspeed, ":speed");
7549 DEFSYM (QCprocess, ":process");
7551 DEFSYM (QCbytesize, ":bytesize");
7552 DEFSYM (QCstopbits, ":stopbits");
7553 DEFSYM (QCparity, ":parity");
7554 DEFSYM (Qodd, "odd");
7555 DEFSYM (Qeven, "even");
7556 DEFSYM (QCflowcontrol, ":flowcontrol");
7557 DEFSYM (Qhw, "hw");
7558 DEFSYM (Qsw, "sw");
7559 DEFSYM (QCsummary, ":summary");
7561 DEFSYM (Qreal, "real");
7562 DEFSYM (Qnetwork, "network");
7563 DEFSYM (Qserial, "serial");
7564 DEFSYM (Qpipe, "pipe");
7565 DEFSYM (QCbuffer, ":buffer");
7566 DEFSYM (QChost, ":host");
7567 DEFSYM (QCservice, ":service");
7568 DEFSYM (QClocal, ":local");
7569 DEFSYM (QCremote, ":remote");
7570 DEFSYM (QCcoding, ":coding");
7571 DEFSYM (QCserver, ":server");
7572 DEFSYM (QCnowait, ":nowait");
7573 DEFSYM (QCsentinel, ":sentinel");
7574 DEFSYM (QClog, ":log");
7575 DEFSYM (QCnoquery, ":noquery");
7576 DEFSYM (QCstop, ":stop");
7577 DEFSYM (QCplist, ":plist");
7578 DEFSYM (QCcommand, ":command");
7579 DEFSYM (QCconnection_type, ":connection-type");
7580 DEFSYM (QCstderr, ":stderr");
7581 DEFSYM (Qpty, "pty");
7582 DEFSYM (Qpipe, "pipe");
7584 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7586 staticpro (&Vprocess_alist);
7587 staticpro (&deleted_pid_list);
7589 #endif /* subprocesses */
7591 DEFSYM (QCname, ":name");
7592 DEFSYM (QCtype, ":type");
7594 DEFSYM (Qeuid, "euid");
7595 DEFSYM (Qegid, "egid");
7596 DEFSYM (Quser, "user");
7597 DEFSYM (Qgroup, "group");
7598 DEFSYM (Qcomm, "comm");
7599 DEFSYM (Qstate, "state");
7600 DEFSYM (Qppid, "ppid");
7601 DEFSYM (Qpgrp, "pgrp");
7602 DEFSYM (Qsess, "sess");
7603 DEFSYM (Qttname, "ttname");
7604 DEFSYM (Qtpgid, "tpgid");
7605 DEFSYM (Qminflt, "minflt");
7606 DEFSYM (Qmajflt, "majflt");
7607 DEFSYM (Qcminflt, "cminflt");
7608 DEFSYM (Qcmajflt, "cmajflt");
7609 DEFSYM (Qutime, "utime");
7610 DEFSYM (Qstime, "stime");
7611 DEFSYM (Qtime, "time");
7612 DEFSYM (Qcutime, "cutime");
7613 DEFSYM (Qcstime, "cstime");
7614 DEFSYM (Qctime, "ctime");
7615 #ifdef subprocesses
7616 DEFSYM (Qinternal_default_process_sentinel,
7617 "internal-default-process-sentinel");
7618 DEFSYM (Qinternal_default_process_filter,
7619 "internal-default-process-filter");
7620 #endif
7621 DEFSYM (Qpri, "pri");
7622 DEFSYM (Qnice, "nice");
7623 DEFSYM (Qthcount, "thcount");
7624 DEFSYM (Qstart, "start");
7625 DEFSYM (Qvsize, "vsize");
7626 DEFSYM (Qrss, "rss");
7627 DEFSYM (Qetime, "etime");
7628 DEFSYM (Qpcpu, "pcpu");
7629 DEFSYM (Qpmem, "pmem");
7630 DEFSYM (Qargs, "args");
7632 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7633 doc: /* Non-nil means delete processes immediately when they exit.
7634 A value of nil means don't delete them until `list-processes' is run. */);
7636 delete_exited_processes = 1;
7638 #ifdef subprocesses
7639 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7640 doc: /* Control type of device used to communicate with subprocesses.
7641 Values are nil to use a pipe, or t or `pty' to use a pty.
7642 The value has no effect if the system has no ptys or if all ptys are busy:
7643 then a pipe is used in any case.
7644 The value takes effect when `start-process' is called. */);
7645 Vprocess_connection_type = Qt;
7647 #ifdef ADAPTIVE_READ_BUFFERING
7648 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7649 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7650 On some systems, when Emacs reads the output from a subprocess, the output data
7651 is read in very small blocks, potentially resulting in very poor performance.
7652 This behavior can be remedied to some extent by setting this variable to a
7653 non-nil value, as it will automatically delay reading from such processes, to
7654 allow them to produce more output before Emacs tries to read it.
7655 If the value is t, the delay is reset after each write to the process; any other
7656 non-nil value means that the delay is not reset on write.
7657 The variable takes effect when `start-process' is called. */);
7658 Vprocess_adaptive_read_buffering = Qt;
7659 #endif
7661 defsubr (&Sprocessp);
7662 defsubr (&Sget_process);
7663 defsubr (&Sdelete_process);
7664 defsubr (&Sprocess_status);
7665 defsubr (&Sprocess_exit_status);
7666 defsubr (&Sprocess_id);
7667 defsubr (&Sprocess_name);
7668 defsubr (&Sprocess_tty_name);
7669 defsubr (&Sprocess_command);
7670 defsubr (&Sset_process_buffer);
7671 defsubr (&Sprocess_buffer);
7672 defsubr (&Sprocess_mark);
7673 defsubr (&Sset_process_filter);
7674 defsubr (&Sprocess_filter);
7675 defsubr (&Sset_process_sentinel);
7676 defsubr (&Sprocess_sentinel);
7677 defsubr (&Sset_process_window_size);
7678 defsubr (&Sset_process_inherit_coding_system_flag);
7679 defsubr (&Sset_process_query_on_exit_flag);
7680 defsubr (&Sprocess_query_on_exit_flag);
7681 defsubr (&Sprocess_contact);
7682 defsubr (&Sprocess_plist);
7683 defsubr (&Sset_process_plist);
7684 defsubr (&Sprocess_list);
7685 defsubr (&Smake_process);
7686 defsubr (&Smake_pipe_process);
7687 defsubr (&Sserial_process_configure);
7688 defsubr (&Smake_serial_process);
7689 defsubr (&Sset_network_process_option);
7690 defsubr (&Smake_network_process);
7691 defsubr (&Sformat_network_address);
7692 defsubr (&Snetwork_interface_list);
7693 defsubr (&Snetwork_interface_info);
7694 #ifdef DATAGRAM_SOCKETS
7695 defsubr (&Sprocess_datagram_address);
7696 defsubr (&Sset_process_datagram_address);
7697 #endif
7698 defsubr (&Saccept_process_output);
7699 defsubr (&Sprocess_send_region);
7700 defsubr (&Sprocess_send_string);
7701 defsubr (&Sinterrupt_process);
7702 defsubr (&Skill_process);
7703 defsubr (&Squit_process);
7704 defsubr (&Sstop_process);
7705 defsubr (&Scontinue_process);
7706 defsubr (&Sprocess_running_child_p);
7707 defsubr (&Sprocess_send_eof);
7708 defsubr (&Ssignal_process);
7709 defsubr (&Swaiting_for_user_input_p);
7710 defsubr (&Sprocess_type);
7711 defsubr (&Sinternal_default_process_sentinel);
7712 defsubr (&Sinternal_default_process_filter);
7713 defsubr (&Sset_process_coding_system);
7714 defsubr (&Sprocess_coding_system);
7715 defsubr (&Sset_process_filter_multibyte);
7716 defsubr (&Sprocess_filter_multibyte_p);
7718 #endif /* subprocesses */
7720 defsubr (&Sget_buffer_process);
7721 defsubr (&Sprocess_inherit_coding_system_flag);
7722 defsubr (&Slist_system_processes);
7723 defsubr (&Sprocess_attributes);
7726 Lisp_Object subfeatures = Qnil;
7727 const struct socket_options *sopt;
7729 #define ADD_SUBFEATURE(key, val) \
7730 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7732 #ifdef NON_BLOCKING_CONNECT
7733 ADD_SUBFEATURE (QCnowait, Qt);
7734 #endif
7735 #ifdef DATAGRAM_SOCKETS
7736 ADD_SUBFEATURE (QCtype, Qdatagram);
7737 #endif
7738 #ifdef HAVE_SEQPACKET
7739 ADD_SUBFEATURE (QCtype, Qseqpacket);
7740 #endif
7741 #ifdef HAVE_LOCAL_SOCKETS
7742 ADD_SUBFEATURE (QCfamily, Qlocal);
7743 #endif
7744 ADD_SUBFEATURE (QCfamily, Qipv4);
7745 #ifdef AF_INET6
7746 ADD_SUBFEATURE (QCfamily, Qipv6);
7747 #endif
7748 #ifdef HAVE_GETSOCKNAME
7749 ADD_SUBFEATURE (QCservice, Qt);
7750 #endif
7751 ADD_SUBFEATURE (QCserver, Qt);
7753 for (sopt = socket_options; sopt->name; sopt++)
7754 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7756 Fprovide (intern_c_string ("make-network-process"), subfeatures);