Bind grep-highlight-matches around the rgrep call
[emacs.git] / src / process.c
blob3132f19d636708dc87dabe792579c55abc7f3b0b
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_TTY_NAME_SPRINTF
662 PTY_TTY_NAME_SPRINTF
663 #else
664 sprintf (pty_name, "/dev/tty%c%x", c, i);
665 #endif /* no PTY_TTY_NAME_SPRINTF */
667 /* Set FD's close-on-exec flag. This is needed even if
668 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
669 doesn't require support for that combination.
670 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
671 doesn't work if the close-on-exec flag is set (Bug#20555).
672 Multithreaded platforms where posix_openpt ignores
673 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
674 have a race condition between the PTY_OPEN and here. */
675 fcntl (fd, F_SETFD, FD_CLOEXEC);
677 /* Check to make certain that both sides are available.
678 This avoids a nasty yet stupid bug in rlogins. */
679 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
681 emacs_close (fd);
682 # ifndef __sgi
683 continue;
684 # else
685 return -1;
686 # endif /* __sgi */
688 setup_pty (fd);
689 return fd;
692 #endif /* HAVE_PTYS */
693 return -1;
696 /* Allocate basically initialized process. */
698 static struct Lisp_Process *
699 allocate_process (void)
701 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
704 static Lisp_Object
705 make_process (Lisp_Object name)
707 register Lisp_Object val, tem, name1;
708 register struct Lisp_Process *p;
709 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
710 printmax_t i;
712 p = allocate_process ();
713 /* Initialize Lisp data. Note that allocate_process initializes all
714 Lisp data to nil, so do it only for slots which should not be nil. */
715 pset_status (p, Qrun);
716 pset_mark (p, Fmake_marker ());
718 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
719 non-Lisp data, so do it only for slots which should not be zero. */
720 p->infd = -1;
721 p->outfd = -1;
722 for (i = 0; i < PROCESS_OPEN_FDS; i++)
723 p->open_fd[i] = -1;
725 #ifdef HAVE_GNUTLS
726 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
727 #endif
729 /* If name is already in use, modify it until it is unused. */
731 name1 = name;
732 for (i = 1; ; i++)
734 tem = Fget_process (name1);
735 if (NILP (tem)) break;
736 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
738 name = name1;
739 pset_name (p, name);
740 pset_sentinel (p, Qinternal_default_process_sentinel);
741 pset_filter (p, Qinternal_default_process_filter);
742 XSETPROCESS (val, p);
743 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
744 return val;
747 static void
748 remove_process (register Lisp_Object proc)
750 register Lisp_Object pair;
752 pair = Frassq (proc, Vprocess_alist);
753 Vprocess_alist = Fdelq (pair, Vprocess_alist);
755 deactivate_process (proc);
759 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
760 doc: /* Return t if OBJECT is a process. */)
761 (Lisp_Object object)
763 return PROCESSP (object) ? Qt : Qnil;
766 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
767 doc: /* Return the process named NAME, or nil if there is none. */)
768 (register Lisp_Object name)
770 if (PROCESSP (name))
771 return name;
772 CHECK_STRING (name);
773 return Fcdr (Fassoc (name, Vprocess_alist));
776 /* This is how commands for the user decode process arguments. It
777 accepts a process, a process name, a buffer, a buffer name, or nil.
778 Buffers denote the first process in the buffer, and nil denotes the
779 current buffer. */
781 static Lisp_Object
782 get_process (register Lisp_Object name)
784 register Lisp_Object proc, obj;
785 if (STRINGP (name))
787 obj = Fget_process (name);
788 if (NILP (obj))
789 obj = Fget_buffer (name);
790 if (NILP (obj))
791 error ("Process %s does not exist", SDATA (name));
793 else if (NILP (name))
794 obj = Fcurrent_buffer ();
795 else
796 obj = name;
798 /* Now obj should be either a buffer object or a process object. */
799 if (BUFFERP (obj))
801 if (NILP (BVAR (XBUFFER (obj), name)))
802 error ("Attempt to get process for a dead buffer");
803 proc = Fget_buffer_process (obj);
804 if (NILP (proc))
805 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
807 else
809 CHECK_PROCESS (obj);
810 proc = obj;
812 return proc;
816 /* Fdelete_process promises to immediately forget about the process, but in
817 reality, Emacs needs to remember those processes until they have been
818 treated by the SIGCHLD handler and waitpid has been invoked on them;
819 otherwise they might fill up the kernel's process table.
821 Some processes created by call-process are also put onto this list.
823 Members of this list are (process-ID . filename) pairs. The
824 process-ID is a number; the filename, if a string, is a file that
825 needs to be removed after the process exits. */
826 static Lisp_Object deleted_pid_list;
828 void
829 record_deleted_pid (pid_t pid, Lisp_Object filename)
831 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
832 /* GC treated elements set to nil. */
833 Fdelq (Qnil, deleted_pid_list));
837 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
838 doc: /* Delete PROCESS: kill it and forget about it immediately.
839 PROCESS may be a process, a buffer, the name of a process or buffer, or
840 nil, indicating the current buffer's process. */)
841 (register Lisp_Object process)
843 register struct Lisp_Process *p;
845 process = get_process (process);
846 p = XPROCESS (process);
848 p->raw_status_new = 0;
849 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
851 pset_status (p, list2 (Qexit, make_number (0)));
852 p->tick = ++process_tick;
853 status_notify (p, NULL);
854 redisplay_preserve_echo_area (13);
856 else
858 if (p->alive)
859 record_kill_process (p, Qnil);
861 if (p->infd >= 0)
863 /* Update P's status, since record_kill_process will make the
864 SIGCHLD handler update deleted_pid_list, not *P. */
865 Lisp_Object symbol;
866 if (p->raw_status_new)
867 update_status (p);
868 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
869 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
870 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
872 p->tick = ++process_tick;
873 status_notify (p, NULL);
874 redisplay_preserve_echo_area (13);
877 remove_process (process);
878 return Qnil;
881 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
882 doc: /* Return the status of PROCESS.
883 The returned value is one of the following symbols:
884 run -- for a process that is running.
885 stop -- for a process stopped but continuable.
886 exit -- for a process that has exited.
887 signal -- for a process that has got a fatal signal.
888 open -- for a network stream connection that is open.
889 listen -- for a network stream server that is listening.
890 closed -- for a network stream connection that is closed.
891 connect -- when waiting for a non-blocking connection to complete.
892 failed -- when a non-blocking connection has failed.
893 nil -- if arg is a process name and no such process exists.
894 PROCESS may be a process, a buffer, the name of a process, or
895 nil, indicating the current buffer's process. */)
896 (register Lisp_Object process)
898 register struct Lisp_Process *p;
899 register Lisp_Object status;
901 if (STRINGP (process))
902 process = Fget_process (process);
903 else
904 process = get_process (process);
906 if (NILP (process))
907 return process;
909 p = XPROCESS (process);
910 if (p->raw_status_new)
911 update_status (p);
912 status = p->status;
913 if (CONSP (status))
914 status = XCAR (status);
915 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
917 if (EQ (status, Qexit))
918 status = Qclosed;
919 else if (EQ (p->command, Qt))
920 status = Qstop;
921 else if (EQ (status, Qrun))
922 status = Qopen;
924 return status;
927 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
928 1, 1, 0,
929 doc: /* Return the exit status of PROCESS or the signal number that killed it.
930 If PROCESS has not yet exited or died, return 0. */)
931 (register Lisp_Object process)
933 CHECK_PROCESS (process);
934 if (XPROCESS (process)->raw_status_new)
935 update_status (XPROCESS (process));
936 if (CONSP (XPROCESS (process)->status))
937 return XCAR (XCDR (XPROCESS (process)->status));
938 return make_number (0);
941 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
942 doc: /* Return the process id of PROCESS.
943 This is the pid of the external process which PROCESS uses or talks to.
944 For a network connection, this value is nil. */)
945 (register Lisp_Object process)
947 pid_t pid;
949 CHECK_PROCESS (process);
950 pid = XPROCESS (process)->pid;
951 return (pid ? make_fixnum_or_float (pid) : Qnil);
954 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
955 doc: /* Return the name of PROCESS, as a string.
956 This is the name of the program invoked in PROCESS,
957 possibly modified to make it unique among process names. */)
958 (register Lisp_Object process)
960 CHECK_PROCESS (process);
961 return XPROCESS (process)->name;
964 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
965 doc: /* Return the command that was executed to start PROCESS.
966 This is a list of strings, the first string being the program executed
967 and the rest of the strings being the arguments given to it.
968 For a network or serial process, this is nil (process is running) or t
969 \(process is stopped). */)
970 (register Lisp_Object process)
972 CHECK_PROCESS (process);
973 return XPROCESS (process)->command;
976 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
977 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
978 This is the terminal that the process itself reads and writes on,
979 not the name of the pty that Emacs uses to talk with that terminal. */)
980 (register Lisp_Object process)
982 CHECK_PROCESS (process);
983 return XPROCESS (process)->tty_name;
986 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
987 2, 2, 0,
988 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
989 Return BUFFER. */)
990 (register Lisp_Object process, Lisp_Object buffer)
992 struct Lisp_Process *p;
994 CHECK_PROCESS (process);
995 if (!NILP (buffer))
996 CHECK_BUFFER (buffer);
997 p = XPROCESS (process);
998 pset_buffer (p, buffer);
999 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1000 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1001 setup_process_coding_systems (process);
1002 return buffer;
1005 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1006 1, 1, 0,
1007 doc: /* Return the buffer PROCESS is associated with.
1008 The default process filter inserts output from PROCESS into this buffer. */)
1009 (register Lisp_Object process)
1011 CHECK_PROCESS (process);
1012 return XPROCESS (process)->buffer;
1015 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1016 1, 1, 0,
1017 doc: /* Return the marker for the end of the last output from PROCESS. */)
1018 (register Lisp_Object process)
1020 CHECK_PROCESS (process);
1021 return XPROCESS (process)->mark;
1024 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1025 2, 2, 0,
1026 doc: /* Give PROCESS the filter function FILTER; nil means default.
1027 A value of t means stop accepting output from the process.
1029 When a process has a non-default filter, its buffer is not used for output.
1030 Instead, each time it does output, the entire string of output is
1031 passed to the filter.
1033 The filter gets two arguments: the process and the string of output.
1034 The string argument is normally a multibyte string, except:
1035 - if the process's input coding system is no-conversion or raw-text,
1036 it is a unibyte string (the non-converted input), or else
1037 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1038 string (the result of converting the decoded input multibyte
1039 string to unibyte with `string-make-unibyte'). */)
1040 (register Lisp_Object process, Lisp_Object filter)
1042 struct Lisp_Process *p;
1044 CHECK_PROCESS (process);
1045 p = XPROCESS (process);
1047 /* Don't signal an error if the process's input file descriptor
1048 is closed. This could make debugging Lisp more difficult,
1049 for example when doing something like
1051 (setq process (start-process ...))
1052 (debug)
1053 (set-process-filter process ...) */
1055 if (NILP (filter))
1056 filter = Qinternal_default_process_filter;
1058 if (p->infd >= 0)
1060 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1062 FD_CLR (p->infd, &input_wait_mask);
1063 FD_CLR (p->infd, &non_keyboard_wait_mask);
1065 else if (EQ (p->filter, Qt)
1066 /* Network or serial process not stopped: */
1067 && !EQ (p->command, Qt))
1069 FD_SET (p->infd, &input_wait_mask);
1070 FD_SET (p->infd, &non_keyboard_wait_mask);
1074 pset_filter (p, filter);
1075 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1076 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1077 setup_process_coding_systems (process);
1078 return filter;
1081 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1082 1, 1, 0,
1083 doc: /* Return the filter function of PROCESS.
1084 See `set-process-filter' for more info on filter functions. */)
1085 (register Lisp_Object process)
1087 CHECK_PROCESS (process);
1088 return XPROCESS (process)->filter;
1091 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1092 2, 2, 0,
1093 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1094 The sentinel is called as a function when the process changes state.
1095 It gets two arguments: the process, and a string describing the change. */)
1096 (register Lisp_Object process, Lisp_Object sentinel)
1098 struct Lisp_Process *p;
1100 CHECK_PROCESS (process);
1101 p = XPROCESS (process);
1103 if (NILP (sentinel))
1104 sentinel = Qinternal_default_process_sentinel;
1106 pset_sentinel (p, sentinel);
1107 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1108 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1109 return sentinel;
1112 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1113 1, 1, 0,
1114 doc: /* Return the sentinel of PROCESS.
1115 See `set-process-sentinel' for more info on sentinels. */)
1116 (register Lisp_Object process)
1118 CHECK_PROCESS (process);
1119 return XPROCESS (process)->sentinel;
1122 DEFUN ("set-process-window-size", Fset_process_window_size,
1123 Sset_process_window_size, 3, 3, 0,
1124 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1125 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1127 CHECK_PROCESS (process);
1129 /* All known platforms store window sizes as 'unsigned short'. */
1130 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1131 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1133 if (XPROCESS (process)->infd < 0
1134 || (set_window_size (XPROCESS (process)->infd,
1135 XINT (height), XINT (width))
1136 < 0))
1137 return Qnil;
1138 else
1139 return Qt;
1142 DEFUN ("set-process-inherit-coding-system-flag",
1143 Fset_process_inherit_coding_system_flag,
1144 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1145 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1146 If the second argument FLAG is non-nil, then the variable
1147 `buffer-file-coding-system' of the buffer associated with PROCESS
1148 will be bound to the value of the coding system used to decode
1149 the process output.
1151 This is useful when the coding system specified for the process buffer
1152 leaves either the character code conversion or the end-of-line conversion
1153 unspecified, or if the coding system used to decode the process output
1154 is more appropriate for saving the process buffer.
1156 Binding the variable `inherit-process-coding-system' to non-nil before
1157 starting the process is an alternative way of setting the inherit flag
1158 for the process which will run.
1160 This function returns FLAG. */)
1161 (register Lisp_Object process, Lisp_Object flag)
1163 CHECK_PROCESS (process);
1164 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1165 return flag;
1168 DEFUN ("set-process-query-on-exit-flag",
1169 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1170 2, 2, 0,
1171 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1172 If the second argument FLAG is non-nil, Emacs will query the user before
1173 exiting or killing a buffer if PROCESS is running. This function
1174 returns FLAG. */)
1175 (register Lisp_Object process, Lisp_Object flag)
1177 CHECK_PROCESS (process);
1178 XPROCESS (process)->kill_without_query = NILP (flag);
1179 return flag;
1182 DEFUN ("process-query-on-exit-flag",
1183 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1184 1, 1, 0,
1185 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1186 (register Lisp_Object process)
1188 CHECK_PROCESS (process);
1189 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1192 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1193 1, 2, 0,
1194 doc: /* Return the contact info of PROCESS; t for a real child.
1195 For a network or serial connection, the value depends on the optional
1196 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1197 SERVICE) for a network connection or (PORT SPEED) for a serial
1198 connection. If KEY is t, the complete contact information for the
1199 connection is returned, else the specific value for the keyword KEY is
1200 returned. See `make-network-process' or `make-serial-process' for a
1201 list of keywords. */)
1202 (register Lisp_Object process, Lisp_Object key)
1204 Lisp_Object contact;
1206 CHECK_PROCESS (process);
1207 contact = XPROCESS (process)->childp;
1209 #ifdef DATAGRAM_SOCKETS
1210 if (DATAGRAM_CONN_P (process)
1211 && (EQ (key, Qt) || EQ (key, QCremote)))
1212 contact = Fplist_put (contact, QCremote,
1213 Fprocess_datagram_address (process));
1214 #endif
1216 if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1217 || EQ (key, Qt))
1218 return contact;
1219 if (NILP (key) && NETCONN_P (process))
1220 return list2 (Fplist_get (contact, QChost),
1221 Fplist_get (contact, QCservice));
1222 if (NILP (key) && SERIALCONN_P (process))
1223 return list2 (Fplist_get (contact, QCport),
1224 Fplist_get (contact, QCspeed));
1225 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1226 if the pipe process is useful for purposes other than receiving
1227 stderr. */
1228 if (NILP (key) && PIPECONN_P (process))
1229 return Qt;
1230 return Fplist_get (contact, key);
1233 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1234 1, 1, 0,
1235 doc: /* Return the plist of PROCESS. */)
1236 (register Lisp_Object process)
1238 CHECK_PROCESS (process);
1239 return XPROCESS (process)->plist;
1242 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1243 2, 2, 0,
1244 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1245 (register Lisp_Object process, Lisp_Object plist)
1247 CHECK_PROCESS (process);
1248 CHECK_LIST (plist);
1250 pset_plist (XPROCESS (process), plist);
1251 return plist;
1254 #if 0 /* Turned off because we don't currently record this info
1255 in the process. Perhaps add it. */
1256 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1257 doc: /* Return the connection type of PROCESS.
1258 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1259 a socket connection. */)
1260 (Lisp_Object process)
1262 return XPROCESS (process)->type;
1264 #endif
1266 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1267 doc: /* Return the connection type of PROCESS.
1268 The value is either the symbol `real', `network', or `serial'.
1269 PROCESS may be a process, a buffer, the name of a process or buffer, or
1270 nil, indicating the current buffer's process. */)
1271 (Lisp_Object process)
1273 Lisp_Object proc;
1274 proc = get_process (process);
1275 return XPROCESS (proc)->type;
1278 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1279 1, 2, 0,
1280 doc: /* Convert network ADDRESS from internal format to a string.
1281 A 4 or 5 element vector represents an IPv4 address (with port number).
1282 An 8 or 9 element vector represents an IPv6 address (with port number).
1283 If optional second argument OMIT-PORT is non-nil, don't include a port
1284 number in the string, even when present in ADDRESS.
1285 Returns nil if format of ADDRESS is invalid. */)
1286 (Lisp_Object address, Lisp_Object omit_port)
1288 if (NILP (address))
1289 return Qnil;
1291 if (STRINGP (address)) /* AF_LOCAL */
1292 return address;
1294 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1296 register struct Lisp_Vector *p = XVECTOR (address);
1297 ptrdiff_t size = p->header.size;
1298 Lisp_Object args[10];
1299 int nargs, i;
1300 char const *format;
1302 if (size == 4 || (size == 5 && !NILP (omit_port)))
1304 format = "%d.%d.%d.%d";
1305 nargs = 4;
1307 else if (size == 5)
1309 format = "%d.%d.%d.%d:%d";
1310 nargs = 5;
1312 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1314 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1315 nargs = 8;
1317 else if (size == 9)
1319 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1320 nargs = 9;
1322 else
1323 return Qnil;
1325 AUTO_STRING (format_obj, format);
1326 args[0] = format_obj;
1328 for (i = 0; i < nargs; i++)
1330 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1331 return Qnil;
1333 if (nargs <= 5 /* IPv4 */
1334 && i < 4 /* host, not port */
1335 && XINT (p->contents[i]) > 255)
1336 return Qnil;
1338 args[i + 1] = p->contents[i];
1341 return Fformat (nargs + 1, args);
1344 if (CONSP (address))
1346 AUTO_STRING (format, "<Family %d>");
1347 return CALLN (Fformat, format, Fcar (address));
1350 return Qnil;
1353 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1354 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1355 (void)
1357 return Fmapcar (Qcdr, Vprocess_alist);
1360 /* Starting asynchronous inferior processes. */
1362 static void start_process_unwind (Lisp_Object proc);
1364 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1365 doc: /* Start a program in a subprocess. Return the process object for it.
1367 This is similar to `start-process', but arguments are specified as
1368 keyword/argument pairs. The following arguments are defined:
1370 :name NAME -- NAME is name for process. It is modified if necessary
1371 to make it unique.
1373 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1374 with the process. Process output goes at end of that buffer, unless
1375 you specify an output stream or filter function to handle the output.
1376 BUFFER may be also nil, meaning that this process is not associated
1377 with any buffer.
1379 :command COMMAND -- COMMAND is a list starting with the program file
1380 name, followed by strings to give to the program as arguments.
1382 :coding CODING -- If CODING is a symbol, it specifies the coding
1383 system used for both reading and writing for this process. If CODING
1384 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1385 ENCODING is used for writing.
1387 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1388 the process is running. If BOOL is not given, query before exiting.
1390 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1391 In the stopped state, a process does not accept incoming data, but you
1392 can send outgoing data. The stopped state is cleared by
1393 `continue-process' and set by `stop-process'.
1395 :connection-type TYPE -- TYPE is control type of device used to
1396 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1397 to use a pty, or nil to use the default specified through
1398 `process-connection-type'.
1400 :filter FILTER -- Install FILTER as the process filter.
1402 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1404 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1405 to the standard error of subprocess. Specifying this implies
1406 `:connection-type' is set to `pipe'.
1408 usage: (make-process &rest ARGS) */)
1409 (ptrdiff_t nargs, Lisp_Object *args)
1411 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1412 Lisp_Object xstderr, stderrproc;
1413 ptrdiff_t count = SPECPDL_INDEX ();
1414 struct gcpro gcpro1;
1415 USE_SAFE_ALLOCA;
1417 if (nargs == 0)
1418 return Qnil;
1420 /* Save arguments for process-contact and clone-process. */
1421 contact = Flist (nargs, args);
1422 GCPRO1 (contact);
1424 buffer = Fplist_get (contact, QCbuffer);
1425 if (!NILP (buffer))
1426 buffer = Fget_buffer_create (buffer);
1428 /* Make sure that the child will be able to chdir to the current
1429 buffer's current directory, or its unhandled equivalent. We
1430 can't just have the child check for an error when it does the
1431 chdir, since it's in a vfork.
1433 We have to GCPRO around this because Fexpand_file_name and
1434 Funhandled_file_name_directory might call a file name handling
1435 function. The argument list is protected by the caller, so all
1436 we really have to worry about is buffer. */
1438 struct gcpro gcpro1;
1439 GCPRO1 (buffer);
1440 current_dir = encode_current_directory ();
1441 UNGCPRO;
1444 name = Fplist_get (contact, QCname);
1445 CHECK_STRING (name);
1447 command = Fplist_get (contact, QCcommand);
1448 if (CONSP (command))
1449 program = XCAR (command);
1450 else
1451 program = Qnil;
1453 if (!NILP (program))
1454 CHECK_STRING (program);
1456 stderrproc = Qnil;
1457 xstderr = Fplist_get (contact, QCstderr);
1458 if (PROCESSP (xstderr))
1460 if (!PIPECONN_P (xstderr))
1461 error ("Process is not a pipe process");
1462 stderrproc = xstderr;
1464 else if (!NILP (xstderr))
1466 struct gcpro gcpro1, gcpro2;
1467 CHECK_STRING (program);
1468 GCPRO2 (buffer, current_dir);
1469 stderrproc = CALLN (Fmake_pipe_process,
1470 QCname,
1471 concat2 (name, build_string (" stderr")),
1472 QCbuffer,
1473 Fget_buffer_create (xstderr));
1474 UNGCPRO;
1477 proc = make_process (name);
1478 /* If an error occurs and we can't start the process, we want to
1479 remove it from the process list. This means that each error
1480 check in create_process doesn't need to call remove_process
1481 itself; it's all taken care of here. */
1482 record_unwind_protect (start_process_unwind, proc);
1484 pset_childp (XPROCESS (proc), Qt);
1485 pset_plist (XPROCESS (proc), Qnil);
1486 pset_type (XPROCESS (proc), Qreal);
1487 pset_buffer (XPROCESS (proc), buffer);
1488 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1489 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1490 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1492 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
1493 XPROCESS (proc)->kill_without_query = 1;
1494 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1495 pset_command (XPROCESS (proc), Qt);
1497 tem = Fplist_get (contact, QCconnection_type);
1498 if (EQ (tem, Qpty))
1499 XPROCESS (proc)->pty_flag = true;
1500 else if (EQ (tem, Qpipe))
1501 XPROCESS (proc)->pty_flag = false;
1502 else if (NILP (tem))
1503 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1504 else
1505 report_file_error ("Unknown connection type", tem);
1507 if (!NILP (stderrproc))
1509 pset_stderrproc (XPROCESS (proc), stderrproc);
1511 XPROCESS (proc)->pty_flag = false;
1514 #ifdef HAVE_GNUTLS
1515 /* AKA GNUTLS_INITSTAGE(proc). */
1516 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1517 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1518 #endif
1520 #ifdef ADAPTIVE_READ_BUFFERING
1521 XPROCESS (proc)->adaptive_read_buffering
1522 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1523 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1524 #endif
1526 /* Make the process marker point into the process buffer (if any). */
1527 if (BUFFERP (buffer))
1528 set_marker_both (XPROCESS (proc)->mark, buffer,
1529 BUF_ZV (XBUFFER (buffer)),
1530 BUF_ZV_BYTE (XBUFFER (buffer)));
1533 /* Decide coding systems for communicating with the process. Here
1534 we don't setup the structure coding_system nor pay attention to
1535 unibyte mode. They are done in create_process. */
1537 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1538 Lisp_Object coding_systems = Qt;
1539 Lisp_Object val, *args2;
1540 struct gcpro gcpro1, gcpro2;
1542 tem = Fplist_get (contact, QCcoding);
1543 if (!NILP (tem))
1545 val = tem;
1546 if (CONSP (val))
1547 val = XCAR (val);
1549 else
1550 val = Vcoding_system_for_read;
1551 if (NILP (val))
1553 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1554 Lisp_Object tem2;
1555 SAFE_ALLOCA_LISP (args2, nargs2);
1556 ptrdiff_t i = 0;
1557 args2[i++] = Qstart_process;
1558 args2[i++] = name;
1559 args2[i++] = buffer;
1560 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1561 args2[i++] = XCAR (tem2);
1562 GCPRO2 (proc, current_dir);
1563 if (!NILP (program))
1564 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1565 UNGCPRO;
1566 if (CONSP (coding_systems))
1567 val = XCAR (coding_systems);
1568 else if (CONSP (Vdefault_process_coding_system))
1569 val = XCAR (Vdefault_process_coding_system);
1571 pset_decode_coding_system (XPROCESS (proc), val);
1573 if (!NILP (tem))
1575 val = tem;
1576 if (CONSP (val))
1577 val = XCDR (val);
1579 else
1580 val = Vcoding_system_for_write;
1581 if (NILP (val))
1583 if (EQ (coding_systems, Qt))
1585 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1586 Lisp_Object tem2;
1587 SAFE_ALLOCA_LISP (args2, nargs2);
1588 ptrdiff_t i = 0;
1589 args2[i++] = Qstart_process;
1590 args2[i++] = name;
1591 args2[i++] = buffer;
1592 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1593 args2[i++] = XCAR (tem2);
1594 GCPRO2 (proc, current_dir);
1595 if (!NILP (program))
1596 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1597 UNGCPRO;
1599 if (CONSP (coding_systems))
1600 val = XCDR (coding_systems);
1601 else if (CONSP (Vdefault_process_coding_system))
1602 val = XCDR (Vdefault_process_coding_system);
1604 pset_encode_coding_system (XPROCESS (proc), val);
1605 /* Note: At this moment, the above coding system may leave
1606 text-conversion or eol-conversion unspecified. They will be
1607 decided after we read output from the process and decode it by
1608 some coding system, or just before we actually send a text to
1609 the process. */
1613 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1614 XPROCESS (proc)->decoding_carryover = 0;
1615 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1617 XPROCESS (proc)->inherit_coding_system_flag
1618 = !(NILP (buffer) || !inherit_process_coding_system);
1620 if (!NILP (program))
1622 Lisp_Object program_args = XCDR (command);
1624 /* If program file name is not absolute, search our path for it.
1625 Put the name we will really use in TEM. */
1626 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1627 && !(SCHARS (program) > 1
1628 && IS_DEVICE_SEP (SREF (program, 1))))
1630 struct gcpro gcpro1, gcpro2;
1632 tem = Qnil;
1633 GCPRO2 (buffer, current_dir);
1634 openp (Vexec_path, program, Vexec_suffixes, &tem,
1635 make_number (X_OK), false);
1636 UNGCPRO;
1637 if (NILP (tem))
1638 report_file_error ("Searching for program", program);
1639 tem = Fexpand_file_name (tem, Qnil);
1641 else
1643 if (!NILP (Ffile_directory_p (program)))
1644 error ("Specified program for new process is a directory");
1645 tem = program;
1648 /* Remove "/:" from TEM. */
1649 tem = remove_slash_colon (tem);
1651 Lisp_Object arg_encoding = Qnil;
1652 struct gcpro gcpro1;
1653 GCPRO1 (tem);
1655 /* Encode the file name and put it in NEW_ARGV.
1656 That's where the child will use it to execute the program. */
1657 tem = list1 (ENCODE_FILE (tem));
1658 ptrdiff_t new_argc = 1;
1660 /* Here we encode arguments by the coding system used for sending
1661 data to the process. We don't support using different coding
1662 systems for encoding arguments and for encoding data sent to the
1663 process. */
1665 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1667 Lisp_Object arg = XCAR (tem2);
1668 CHECK_STRING (arg);
1669 if (STRING_MULTIBYTE (arg))
1671 if (NILP (arg_encoding))
1672 arg_encoding = (complement_process_encoding_system
1673 (XPROCESS (proc)->encode_coding_system));
1674 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1676 tem = Fcons (arg, tem);
1677 new_argc++;
1680 UNGCPRO;
1682 /* Now that everything is encoded we can collect the strings into
1683 NEW_ARGV. */
1684 char **new_argv;
1685 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1686 new_argv[new_argc] = 0;
1688 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1690 new_argv[i] = SSDATA (XCAR (tem));
1691 tem = XCDR (tem);
1694 create_process (proc, new_argv, current_dir);
1696 else
1697 create_pty (proc);
1699 UNGCPRO;
1700 SAFE_FREE ();
1701 return unbind_to (count, proc);
1704 /* This function is the unwind_protect form for Fstart_process. If
1705 PROC doesn't have its pid set, then we know someone has signaled
1706 an error and the process wasn't started successfully, so we should
1707 remove it from the process list. */
1708 static void
1709 start_process_unwind (Lisp_Object proc)
1711 if (!PROCESSP (proc))
1712 emacs_abort ();
1714 /* Was PROC started successfully?
1715 -2 is used for a pty with no process, eg for gdb. */
1716 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1717 remove_process (proc);
1720 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1722 static void
1723 close_process_fd (int *fd_addr)
1725 int fd = *fd_addr;
1726 if (0 <= fd)
1728 *fd_addr = -1;
1729 emacs_close (fd);
1733 /* Indexes of file descriptors in open_fds. */
1734 enum
1736 /* The pipe from Emacs to its subprocess. */
1737 SUBPROCESS_STDIN,
1738 WRITE_TO_SUBPROCESS,
1740 /* The main pipe from the subprocess to Emacs. */
1741 READ_FROM_SUBPROCESS,
1742 SUBPROCESS_STDOUT,
1744 /* The pipe from the subprocess to Emacs that is closed when the
1745 subprocess execs. */
1746 READ_FROM_EXEC_MONITOR,
1747 EXEC_MONITOR_OUTPUT
1750 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1752 static void
1753 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1755 struct Lisp_Process *p = XPROCESS (process);
1756 int inchannel, outchannel;
1757 pid_t pid;
1758 int vfork_errno;
1759 int forkin, forkout, forkerr = -1;
1760 bool pty_flag = 0;
1761 char pty_name[PTY_NAME_SIZE];
1762 Lisp_Object lisp_pty_name = Qnil;
1763 sigset_t oldset;
1765 inchannel = outchannel = -1;
1767 if (p->pty_flag)
1768 outchannel = inchannel = allocate_pty (pty_name);
1770 if (inchannel >= 0)
1772 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1773 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1774 /* On most USG systems it does not work to open the pty's tty here,
1775 then close it and reopen it in the child. */
1776 /* Don't let this terminal become our controlling terminal
1777 (in case we don't have one). */
1778 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1779 if (forkin < 0)
1780 report_file_error ("Opening pty", Qnil);
1781 p->open_fd[SUBPROCESS_STDIN] = forkin;
1782 #else
1783 forkin = forkout = -1;
1784 #endif /* not USG, or USG_SUBTTY_WORKS */
1785 pty_flag = 1;
1786 lisp_pty_name = build_string (pty_name);
1788 else
1790 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1791 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1792 report_file_error ("Creating pipe", Qnil);
1793 forkin = p->open_fd[SUBPROCESS_STDIN];
1794 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1795 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1796 forkout = p->open_fd[SUBPROCESS_STDOUT];
1798 if (!NILP (p->stderrproc))
1800 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
1802 forkerr = pp->open_fd[SUBPROCESS_STDOUT];
1804 /* Close unnecessary file descriptors. */
1805 close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
1806 close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
1810 #ifndef WINDOWSNT
1811 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1812 report_file_error ("Creating pipe", Qnil);
1813 #endif
1815 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1816 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1818 /* Record this as an active process, with its channels. */
1819 chan_process[inchannel] = process;
1820 p->infd = inchannel;
1821 p->outfd = outchannel;
1823 /* Previously we recorded the tty descriptor used in the subprocess.
1824 It was only used for getting the foreground tty process, so now
1825 we just reopen the device (see emacs_get_tty_pgrp) as this is
1826 more portable (see USG_SUBTTY_WORKS above). */
1828 p->pty_flag = pty_flag;
1829 pset_status (p, Qrun);
1831 if (!EQ (p->command, Qt))
1833 FD_SET (inchannel, &input_wait_mask);
1834 FD_SET (inchannel, &non_keyboard_wait_mask);
1837 if (inchannel > max_process_desc)
1838 max_process_desc = inchannel;
1840 /* This may signal an error. */
1841 setup_process_coding_systems (process);
1843 block_input ();
1844 block_child_signal (&oldset);
1846 #ifndef WINDOWSNT
1847 /* vfork, and prevent local vars from being clobbered by the vfork. */
1848 Lisp_Object volatile current_dir_volatile = current_dir;
1849 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1850 char **volatile new_argv_volatile = new_argv;
1851 int volatile forkin_volatile = forkin;
1852 int volatile forkout_volatile = forkout;
1853 int volatile forkerr_volatile = forkerr;
1854 struct Lisp_Process *p_volatile = p;
1856 pid = vfork ();
1858 current_dir = current_dir_volatile;
1859 lisp_pty_name = lisp_pty_name_volatile;
1860 new_argv = new_argv_volatile;
1861 forkin = forkin_volatile;
1862 forkout = forkout_volatile;
1863 forkerr = forkerr_volatile;
1864 p = p_volatile;
1866 pty_flag = p->pty_flag;
1868 if (pid == 0)
1869 #endif /* not WINDOWSNT */
1871 /* Make the pty be the controlling terminal of the process. */
1872 #ifdef HAVE_PTYS
1873 /* First, disconnect its current controlling terminal. */
1874 /* We tried doing setsid only if pty_flag, but it caused
1875 process_set_signal to fail on SGI when using a pipe. */
1876 setsid ();
1877 /* Make the pty's terminal the controlling terminal. */
1878 if (pty_flag && forkin >= 0)
1880 #ifdef TIOCSCTTY
1881 /* We ignore the return value
1882 because faith@cs.unc.edu says that is necessary on Linux. */
1883 ioctl (forkin, TIOCSCTTY, 0);
1884 #endif
1886 #if defined (LDISC1)
1887 if (pty_flag && forkin >= 0)
1889 struct termios t;
1890 tcgetattr (forkin, &t);
1891 t.c_lflag = LDISC1;
1892 if (tcsetattr (forkin, TCSANOW, &t) < 0)
1893 emacs_perror ("create_process/tcsetattr LDISC1");
1895 #else
1896 #if defined (NTTYDISC) && defined (TIOCSETD)
1897 if (pty_flag && forkin >= 0)
1899 /* Use new line discipline. */
1900 int ldisc = NTTYDISC;
1901 ioctl (forkin, TIOCSETD, &ldisc);
1903 #endif
1904 #endif
1905 #ifdef TIOCNOTTY
1906 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1907 can do TIOCSPGRP only to the process's controlling tty. */
1908 if (pty_flag)
1910 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1911 I can't test it since I don't have 4.3. */
1912 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1913 if (j >= 0)
1915 ioctl (j, TIOCNOTTY, 0);
1916 emacs_close (j);
1919 #endif /* TIOCNOTTY */
1921 #if !defined (DONT_REOPEN_PTY)
1922 /*** There is a suggestion that this ought to be a
1923 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1924 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1925 that system does seem to need this code, even though
1926 both TIOCSCTTY is defined. */
1927 /* Now close the pty (if we had it open) and reopen it.
1928 This makes the pty the controlling terminal of the subprocess. */
1929 if (pty_flag)
1932 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1933 would work? */
1934 if (forkin >= 0)
1935 emacs_close (forkin);
1936 forkout = forkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1938 if (forkin < 0)
1940 emacs_perror (SSDATA (lisp_pty_name));
1941 _exit (EXIT_CANCELED);
1945 #endif /* not DONT_REOPEN_PTY */
1947 #ifdef SETUP_SLAVE_PTY
1948 if (pty_flag)
1950 SETUP_SLAVE_PTY;
1952 #endif /* SETUP_SLAVE_PTY */
1953 #endif /* HAVE_PTYS */
1955 signal (SIGINT, SIG_DFL);
1956 signal (SIGQUIT, SIG_DFL);
1957 #ifdef SIGPROF
1958 signal (SIGPROF, SIG_DFL);
1959 #endif
1961 /* Emacs ignores SIGPIPE, but the child should not. */
1962 signal (SIGPIPE, SIG_DFL);
1964 /* Stop blocking SIGCHLD in the child. */
1965 unblock_child_signal (&oldset);
1967 if (pty_flag)
1968 child_setup_tty (forkout);
1970 if (forkerr < 0)
1971 forkerr = forkout;
1972 #ifdef WINDOWSNT
1973 pid = child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1974 #else /* not WINDOWSNT */
1975 child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1976 #endif /* not WINDOWSNT */
1979 /* Back in the parent process. */
1981 vfork_errno = errno;
1982 p->pid = pid;
1983 if (pid >= 0)
1984 p->alive = 1;
1986 /* Stop blocking in the parent. */
1987 unblock_child_signal (&oldset);
1988 unblock_input ();
1990 if (pid < 0)
1991 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1992 else
1994 /* vfork succeeded. */
1996 /* Close the pipe ends that the child uses, or the child's pty. */
1997 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
1998 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
2000 #ifdef WINDOWSNT
2001 register_child (pid, inchannel);
2002 #endif /* WINDOWSNT */
2004 pset_tty_name (p, lisp_pty_name);
2006 #ifndef WINDOWSNT
2007 /* Wait for child_setup to complete in case that vfork is
2008 actually defined as fork. The descriptor
2009 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2010 of a pipe is closed at the child side either by close-on-exec
2011 on successful execve or the _exit call in child_setup. */
2013 char dummy;
2015 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
2016 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
2017 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
2019 #endif
2020 if (!NILP (p->stderrproc))
2022 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2023 close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
2028 static void
2029 create_pty (Lisp_Object process)
2031 struct Lisp_Process *p = XPROCESS (process);
2032 char pty_name[PTY_NAME_SIZE];
2033 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
2035 if (pty_fd >= 0)
2037 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
2038 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2039 /* On most USG systems it does not work to open the pty's tty here,
2040 then close it and reopen it in the child. */
2041 /* Don't let this terminal become our controlling terminal
2042 (in case we don't have one). */
2043 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2044 if (forkout < 0)
2045 report_file_error ("Opening pty", Qnil);
2046 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2047 #if defined (DONT_REOPEN_PTY)
2048 /* In the case that vfork is defined as fork, the parent process
2049 (Emacs) may send some data before the child process completes
2050 tty options setup. So we setup tty before forking. */
2051 child_setup_tty (forkout);
2052 #endif /* DONT_REOPEN_PTY */
2053 #endif /* not USG, or USG_SUBTTY_WORKS */
2055 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2057 /* Record this as an active process, with its channels.
2058 As a result, child_setup will close Emacs's side of the pipes. */
2059 chan_process[pty_fd] = process;
2060 p->infd = pty_fd;
2061 p->outfd = pty_fd;
2063 /* Previously we recorded the tty descriptor used in the subprocess.
2064 It was only used for getting the foreground tty process, so now
2065 we just reopen the device (see emacs_get_tty_pgrp) as this is
2066 more portable (see USG_SUBTTY_WORKS above). */
2068 p->pty_flag = 1;
2069 pset_status (p, Qrun);
2070 setup_process_coding_systems (process);
2072 FD_SET (pty_fd, &input_wait_mask);
2073 FD_SET (pty_fd, &non_keyboard_wait_mask);
2074 if (pty_fd > max_process_desc)
2075 max_process_desc = pty_fd;
2077 pset_tty_name (p, build_string (pty_name));
2080 p->pid = -2;
2083 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2084 0, MANY, 0,
2085 doc: /* Create and return a bidirectional pipe process.
2087 In Emacs, pipes are represented by process objects, so input and
2088 output work as for subprocesses, and `delete-process' closes a pipe.
2089 However, a pipe process has no process id, it cannot be signaled,
2090 and the status codes are different from normal processes.
2092 Arguments are specified as keyword/argument pairs. The following
2093 arguments are defined:
2095 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2097 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2098 with the process. Process output goes at the end of that buffer,
2099 unless you specify an output stream or filter function to handle the
2100 output. If BUFFER is not given, the value of NAME is used.
2102 :coding CODING -- If CODING is a symbol, it specifies the coding
2103 system used for both reading and writing for this process. If CODING
2104 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2105 ENCODING is used for writing.
2107 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2108 the process is running. If BOOL is not given, query before exiting.
2110 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2111 In the stopped state, a pipe process does not accept incoming data,
2112 but you can send outgoing data. The stopped state is cleared by
2113 `continue-process' and set by `stop-process'.
2115 :filter FILTER -- Install FILTER as the process filter.
2117 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2119 usage: (make-pipe-process &rest ARGS) */)
2120 (ptrdiff_t nargs, Lisp_Object *args)
2122 Lisp_Object proc, contact;
2123 struct Lisp_Process *p;
2124 struct gcpro gcpro1;
2125 Lisp_Object name, buffer;
2126 Lisp_Object tem;
2127 ptrdiff_t specpdl_count;
2128 int inchannel, outchannel;
2130 if (nargs == 0)
2131 return Qnil;
2133 contact = Flist (nargs, args);
2134 GCPRO1 (contact);
2136 name = Fplist_get (contact, QCname);
2137 CHECK_STRING (name);
2138 proc = make_process (name);
2139 specpdl_count = SPECPDL_INDEX ();
2140 record_unwind_protect (remove_process, proc);
2141 p = XPROCESS (proc);
2143 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2144 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2145 report_file_error ("Creating pipe", Qnil);
2146 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2147 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2149 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2150 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2152 #ifdef WINDOWSNT
2153 register_aux_fd (inchannel);
2154 #endif
2156 /* Record this as an active process, with its channels. */
2157 chan_process[inchannel] = proc;
2158 p->infd = inchannel;
2159 p->outfd = outchannel;
2161 if (inchannel > max_process_desc)
2162 max_process_desc = inchannel;
2164 buffer = Fplist_get (contact, QCbuffer);
2165 if (NILP (buffer))
2166 buffer = name;
2167 buffer = Fget_buffer_create (buffer);
2168 pset_buffer (p, buffer);
2170 pset_childp (p, contact);
2171 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2172 pset_type (p, Qpipe);
2173 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2174 pset_filter (p, Fplist_get (contact, QCfilter));
2175 pset_log (p, Qnil);
2176 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2177 p->kill_without_query = 1;
2178 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2179 pset_command (p, Qt);
2180 eassert (! p->pty_flag);
2182 if (!EQ (p->command, Qt))
2184 FD_SET (inchannel, &input_wait_mask);
2185 FD_SET (inchannel, &non_keyboard_wait_mask);
2187 #ifdef ADAPTIVE_READ_BUFFERING
2188 p->adaptive_read_buffering
2189 = (NILP (Vprocess_adaptive_read_buffering) ? 0
2190 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2191 #endif
2193 /* Make the process marker point into the process buffer (if any). */
2194 if (BUFFERP (buffer))
2195 set_marker_both (p->mark, buffer,
2196 BUF_ZV (XBUFFER (buffer)),
2197 BUF_ZV_BYTE (XBUFFER (buffer)));
2200 /* Setup coding systems for communicating with the network stream. */
2202 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2203 Lisp_Object coding_systems = Qt;
2204 Lisp_Object val;
2206 tem = Fplist_get (contact, QCcoding);
2207 val = Qnil;
2208 if (!NILP (tem))
2210 val = tem;
2211 if (CONSP (val))
2212 val = XCAR (val);
2214 else if (!NILP (Vcoding_system_for_read))
2215 val = Vcoding_system_for_read;
2216 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2217 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2218 /* We dare not decode end-of-line format by setting VAL to
2219 Qraw_text, because the existing Emacs Lisp libraries
2220 assume that they receive bare code including a sequence of
2221 CR LF. */
2222 val = Qnil;
2223 else
2225 if (CONSP (coding_systems))
2226 val = XCAR (coding_systems);
2227 else if (CONSP (Vdefault_process_coding_system))
2228 val = XCAR (Vdefault_process_coding_system);
2229 else
2230 val = Qnil;
2232 pset_decode_coding_system (p, val);
2234 if (!NILP (tem))
2236 val = tem;
2237 if (CONSP (val))
2238 val = XCDR (val);
2240 else if (!NILP (Vcoding_system_for_write))
2241 val = Vcoding_system_for_write;
2242 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2243 val = Qnil;
2244 else
2246 if (CONSP (coding_systems))
2247 val = XCDR (coding_systems);
2248 else if (CONSP (Vdefault_process_coding_system))
2249 val = XCDR (Vdefault_process_coding_system);
2250 else
2251 val = Qnil;
2253 pset_encode_coding_system (p, val);
2255 /* This may signal an error. */
2256 setup_process_coding_systems (proc);
2258 specpdl_ptr = specpdl + specpdl_count;
2260 UNGCPRO;
2261 return proc;
2265 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2266 The address family of sa is not included in the result. */
2268 Lisp_Object
2269 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2271 Lisp_Object address;
2272 int i;
2273 unsigned char *cp;
2274 register struct Lisp_Vector *p;
2276 /* Workaround for a bug in getsockname on BSD: Names bound to
2277 sockets in the UNIX domain are inaccessible; getsockname returns
2278 a zero length name. */
2279 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2280 return empty_unibyte_string;
2282 switch (sa->sa_family)
2284 case AF_INET:
2286 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2287 len = sizeof (sin->sin_addr) + 1;
2288 address = Fmake_vector (make_number (len), Qnil);
2289 p = XVECTOR (address);
2290 p->contents[--len] = make_number (ntohs (sin->sin_port));
2291 cp = (unsigned char *) &sin->sin_addr;
2292 break;
2294 #ifdef AF_INET6
2295 case AF_INET6:
2297 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2298 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2299 len = sizeof (sin6->sin6_addr) / 2 + 1;
2300 address = Fmake_vector (make_number (len), Qnil);
2301 p = XVECTOR (address);
2302 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2303 for (i = 0; i < len; i++)
2304 p->contents[i] = make_number (ntohs (ip6[i]));
2305 return address;
2307 #endif
2308 #ifdef HAVE_LOCAL_SOCKETS
2309 case AF_LOCAL:
2311 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2312 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2313 /* If the first byte is NUL, the name is a Linux abstract
2314 socket name, and the name can contain embedded NULs. If
2315 it's not, we have a NUL-terminated string. Be careful not
2316 to walk past the end of the object looking for the name
2317 terminator, however. */
2318 if (name_length > 0 && sockun->sun_path[0] != '\0')
2320 const char *terminator
2321 = memchr (sockun->sun_path, '\0', name_length);
2323 if (terminator)
2324 name_length = terminator - (const char *) sockun->sun_path;
2327 return make_unibyte_string (sockun->sun_path, name_length);
2329 #endif
2330 default:
2331 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2332 address = Fcons (make_number (sa->sa_family),
2333 Fmake_vector (make_number (len), Qnil));
2334 p = XVECTOR (XCDR (address));
2335 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2336 break;
2339 i = 0;
2340 while (i < len)
2341 p->contents[i++] = make_number (*cp++);
2343 return address;
2347 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2349 static int
2350 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2352 register struct Lisp_Vector *p;
2354 if (VECTORP (address))
2356 p = XVECTOR (address);
2357 if (p->header.size == 5)
2359 *familyp = AF_INET;
2360 return sizeof (struct sockaddr_in);
2362 #ifdef AF_INET6
2363 else if (p->header.size == 9)
2365 *familyp = AF_INET6;
2366 return sizeof (struct sockaddr_in6);
2368 #endif
2370 #ifdef HAVE_LOCAL_SOCKETS
2371 else if (STRINGP (address))
2373 *familyp = AF_LOCAL;
2374 return sizeof (struct sockaddr_un);
2376 #endif
2377 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2378 && VECTORP (XCDR (address)))
2380 struct sockaddr *sa;
2381 p = XVECTOR (XCDR (address));
2382 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2383 return 0;
2384 *familyp = XINT (XCAR (address));
2385 return p->header.size + sizeof (sa->sa_family);
2387 return 0;
2390 /* Convert an address object (vector or string) to an internal sockaddr.
2392 The address format has been basically validated by
2393 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2394 it could have come from user data. So if FAMILY is not valid,
2395 we return after zeroing *SA. */
2397 static void
2398 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2400 register struct Lisp_Vector *p;
2401 register unsigned char *cp = NULL;
2402 register int i;
2403 EMACS_INT hostport;
2405 memset (sa, 0, len);
2407 if (VECTORP (address))
2409 p = XVECTOR (address);
2410 if (family == AF_INET)
2412 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2413 len = sizeof (sin->sin_addr) + 1;
2414 hostport = XINT (p->contents[--len]);
2415 sin->sin_port = htons (hostport);
2416 cp = (unsigned char *)&sin->sin_addr;
2417 sa->sa_family = family;
2419 #ifdef AF_INET6
2420 else if (family == AF_INET6)
2422 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2423 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2424 len = sizeof (sin6->sin6_addr) + 1;
2425 hostport = XINT (p->contents[--len]);
2426 sin6->sin6_port = htons (hostport);
2427 for (i = 0; i < len; i++)
2428 if (INTEGERP (p->contents[i]))
2430 int j = XFASTINT (p->contents[i]) & 0xffff;
2431 ip6[i] = ntohs (j);
2433 sa->sa_family = family;
2434 return;
2436 #endif
2437 else
2438 return;
2440 else if (STRINGP (address))
2442 #ifdef HAVE_LOCAL_SOCKETS
2443 if (family == AF_LOCAL)
2445 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2446 cp = SDATA (address);
2447 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2448 sockun->sun_path[i] = *cp++;
2449 sa->sa_family = family;
2451 #endif
2452 return;
2454 else
2456 p = XVECTOR (XCDR (address));
2457 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2460 for (i = 0; i < len; i++)
2461 if (INTEGERP (p->contents[i]))
2462 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2465 #ifdef DATAGRAM_SOCKETS
2466 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2467 1, 1, 0,
2468 doc: /* Get the current datagram address associated with PROCESS. */)
2469 (Lisp_Object process)
2471 int channel;
2473 CHECK_PROCESS (process);
2475 if (!DATAGRAM_CONN_P (process))
2476 return Qnil;
2478 channel = XPROCESS (process)->infd;
2479 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2480 datagram_address[channel].len);
2483 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2484 2, 2, 0,
2485 doc: /* Set the datagram address for PROCESS to ADDRESS.
2486 Returns nil upon error setting address, ADDRESS otherwise. */)
2487 (Lisp_Object process, Lisp_Object address)
2489 int channel;
2490 int family, len;
2492 CHECK_PROCESS (process);
2494 if (!DATAGRAM_CONN_P (process))
2495 return Qnil;
2497 channel = XPROCESS (process)->infd;
2499 len = get_lisp_to_sockaddr_size (address, &family);
2500 if (len == 0 || datagram_address[channel].len != len)
2501 return Qnil;
2502 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2503 return address;
2505 #endif
2508 static const struct socket_options {
2509 /* The name of this option. Should be lowercase version of option
2510 name without SO_ prefix. */
2511 const char *name;
2512 /* Option level SOL_... */
2513 int optlevel;
2514 /* Option number SO_... */
2515 int optnum;
2516 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2517 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2518 } socket_options[] =
2520 #ifdef SO_BINDTODEVICE
2521 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2522 #endif
2523 #ifdef SO_BROADCAST
2524 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2525 #endif
2526 #ifdef SO_DONTROUTE
2527 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2528 #endif
2529 #ifdef SO_KEEPALIVE
2530 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2531 #endif
2532 #ifdef SO_LINGER
2533 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2534 #endif
2535 #ifdef SO_OOBINLINE
2536 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2537 #endif
2538 #ifdef SO_PRIORITY
2539 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2540 #endif
2541 #ifdef SO_REUSEADDR
2542 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2543 #endif
2544 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2547 /* Set option OPT to value VAL on socket S.
2549 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2550 Signals an error if setting a known option fails.
2553 static int
2554 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2556 char *name;
2557 const struct socket_options *sopt;
2558 int ret = 0;
2560 CHECK_SYMBOL (opt);
2562 name = SSDATA (SYMBOL_NAME (opt));
2563 for (sopt = socket_options; sopt->name; sopt++)
2564 if (strcmp (name, sopt->name) == 0)
2565 break;
2567 switch (sopt->opttype)
2569 case SOPT_BOOL:
2571 int optval;
2572 optval = NILP (val) ? 0 : 1;
2573 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2574 &optval, sizeof (optval));
2575 break;
2578 case SOPT_INT:
2580 int optval;
2581 if (TYPE_RANGED_INTEGERP (int, val))
2582 optval = XINT (val);
2583 else
2584 error ("Bad option value for %s", name);
2585 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2586 &optval, sizeof (optval));
2587 break;
2590 #ifdef SO_BINDTODEVICE
2591 case SOPT_IFNAME:
2593 char devname[IFNAMSIZ + 1];
2595 /* This is broken, at least in the Linux 2.4 kernel.
2596 To unbind, the arg must be a zero integer, not the empty string.
2597 This should work on all systems. KFS. 2003-09-23. */
2598 memset (devname, 0, sizeof devname);
2599 if (STRINGP (val))
2601 char *arg = SSDATA (val);
2602 int len = min (strlen (arg), IFNAMSIZ);
2603 memcpy (devname, arg, len);
2605 else if (!NILP (val))
2606 error ("Bad option value for %s", name);
2607 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2608 devname, IFNAMSIZ);
2609 break;
2611 #endif
2613 #ifdef SO_LINGER
2614 case SOPT_LINGER:
2616 struct linger linger;
2618 linger.l_onoff = 1;
2619 linger.l_linger = 0;
2620 if (TYPE_RANGED_INTEGERP (int, val))
2621 linger.l_linger = XINT (val);
2622 else
2623 linger.l_onoff = NILP (val) ? 0 : 1;
2624 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2625 &linger, sizeof (linger));
2626 break;
2628 #endif
2630 default:
2631 return 0;
2634 if (ret < 0)
2636 int setsockopt_errno = errno;
2637 report_file_errno ("Cannot set network option", list2 (opt, val),
2638 setsockopt_errno);
2641 return (1 << sopt->optbit);
2645 DEFUN ("set-network-process-option",
2646 Fset_network_process_option, Sset_network_process_option,
2647 3, 4, 0,
2648 doc: /* For network process PROCESS set option OPTION to value VALUE.
2649 See `make-network-process' for a list of options and values.
2650 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2651 OPTION is not a supported option, return nil instead; otherwise return t. */)
2652 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2654 int s;
2655 struct Lisp_Process *p;
2657 CHECK_PROCESS (process);
2658 p = XPROCESS (process);
2659 if (!NETCONN1_P (p))
2660 error ("Process is not a network process");
2662 s = p->infd;
2663 if (s < 0)
2664 error ("Process is not running");
2666 if (set_socket_option (s, option, value))
2668 pset_childp (p, Fplist_put (p->childp, option, value));
2669 return Qt;
2672 if (NILP (no_error))
2673 error ("Unknown or unsupported option");
2675 return Qnil;
2679 DEFUN ("serial-process-configure",
2680 Fserial_process_configure,
2681 Sserial_process_configure,
2682 0, MANY, 0,
2683 doc: /* Configure speed, bytesize, etc. of a serial process.
2685 Arguments are specified as keyword/argument pairs. Attributes that
2686 are not given are re-initialized from the process's current
2687 configuration (available via the function `process-contact') or set to
2688 reasonable default values. The following arguments are defined:
2690 :process PROCESS
2691 :name NAME
2692 :buffer BUFFER
2693 :port PORT
2694 -- Any of these arguments can be given to identify the process that is
2695 to be configured. If none of these arguments is given, the current
2696 buffer's process is used.
2698 :speed SPEED -- SPEED is the speed of the serial port in bits per
2699 second, also called baud rate. Any value can be given for SPEED, but
2700 most serial ports work only at a few defined values between 1200 and
2701 115200, with 9600 being the most common value. If SPEED is nil, the
2702 serial port is not configured any further, i.e., all other arguments
2703 are ignored. This may be useful for special serial ports such as
2704 Bluetooth-to-serial converters which can only be configured through AT
2705 commands. A value of nil for SPEED can be used only when passed
2706 through `make-serial-process' or `serial-term'.
2708 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2709 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2711 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2712 `odd' (use odd parity), or the symbol `even' (use even parity). If
2713 PARITY is not given, no parity is used.
2715 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2716 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2717 is not given or nil, 1 stopbit is used.
2719 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2720 flowcontrol to be used, which is either nil (don't use flowcontrol),
2721 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2722 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2723 flowcontrol is used.
2725 `serial-process-configure' is called by `make-serial-process' for the
2726 initial configuration of the serial port.
2728 Examples:
2730 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2732 \(serial-process-configure
2733 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2735 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2737 usage: (serial-process-configure &rest ARGS) */)
2738 (ptrdiff_t nargs, Lisp_Object *args)
2740 struct Lisp_Process *p;
2741 Lisp_Object contact = Qnil;
2742 Lisp_Object proc = Qnil;
2743 struct gcpro gcpro1;
2745 contact = Flist (nargs, args);
2746 GCPRO1 (contact);
2748 proc = Fplist_get (contact, QCprocess);
2749 if (NILP (proc))
2750 proc = Fplist_get (contact, QCname);
2751 if (NILP (proc))
2752 proc = Fplist_get (contact, QCbuffer);
2753 if (NILP (proc))
2754 proc = Fplist_get (contact, QCport);
2755 proc = get_process (proc);
2756 p = XPROCESS (proc);
2757 if (!EQ (p->type, Qserial))
2758 error ("Not a serial process");
2760 if (NILP (Fplist_get (p->childp, QCspeed)))
2762 UNGCPRO;
2763 return Qnil;
2766 serial_configure (p, contact);
2768 UNGCPRO;
2769 return Qnil;
2772 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2773 0, MANY, 0,
2774 doc: /* Create and return a serial port process.
2776 In Emacs, serial port connections are represented by process objects,
2777 so input and output work as for subprocesses, and `delete-process'
2778 closes a serial port connection. However, a serial process has no
2779 process id, it cannot be signaled, and the status codes are different
2780 from normal processes.
2782 `make-serial-process' creates a process and a buffer, on which you
2783 probably want to use `process-send-string'. Try \\[serial-term] for
2784 an interactive terminal. See below for examples.
2786 Arguments are specified as keyword/argument pairs. The following
2787 arguments are defined:
2789 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2790 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2791 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2792 the backslashes in strings).
2794 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2795 which this function calls.
2797 :name NAME -- NAME is the name of the process. If NAME is not given,
2798 the value of PORT is used.
2800 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2801 with the process. Process output goes at the end of that buffer,
2802 unless you specify an output stream or filter function to handle the
2803 output. If BUFFER is not given, the value of NAME is used.
2805 :coding CODING -- If CODING is a symbol, it specifies the coding
2806 system used for both reading and writing for this process. If CODING
2807 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2808 ENCODING is used for writing.
2810 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2811 the process is running. If BOOL is not given, query before exiting.
2813 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2814 In the stopped state, a serial process does not accept incoming data,
2815 but you can send outgoing data. The stopped state is cleared by
2816 `continue-process' and set by `stop-process'.
2818 :filter FILTER -- Install FILTER as the process filter.
2820 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2822 :plist PLIST -- Install PLIST as the initial plist of the process.
2824 :bytesize
2825 :parity
2826 :stopbits
2827 :flowcontrol
2828 -- This function calls `serial-process-configure' to handle these
2829 arguments.
2831 The original argument list, possibly modified by later configuration,
2832 is available via the function `process-contact'.
2834 Examples:
2836 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2838 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2840 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2842 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2844 usage: (make-serial-process &rest ARGS) */)
2845 (ptrdiff_t nargs, Lisp_Object *args)
2847 int fd = -1;
2848 Lisp_Object proc, contact, port;
2849 struct Lisp_Process *p;
2850 struct gcpro gcpro1;
2851 Lisp_Object name, buffer;
2852 Lisp_Object tem, val;
2853 ptrdiff_t specpdl_count;
2855 if (nargs == 0)
2856 return Qnil;
2858 contact = Flist (nargs, args);
2859 GCPRO1 (contact);
2861 port = Fplist_get (contact, QCport);
2862 if (NILP (port))
2863 error ("No port specified");
2864 CHECK_STRING (port);
2866 if (NILP (Fplist_member (contact, QCspeed)))
2867 error (":speed not specified");
2868 if (!NILP (Fplist_get (contact, QCspeed)))
2869 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2871 name = Fplist_get (contact, QCname);
2872 if (NILP (name))
2873 name = port;
2874 CHECK_STRING (name);
2875 proc = make_process (name);
2876 specpdl_count = SPECPDL_INDEX ();
2877 record_unwind_protect (remove_process, proc);
2878 p = XPROCESS (proc);
2880 fd = serial_open (port);
2881 p->open_fd[SUBPROCESS_STDIN] = fd;
2882 p->infd = fd;
2883 p->outfd = fd;
2884 if (fd > max_process_desc)
2885 max_process_desc = fd;
2886 chan_process[fd] = proc;
2888 buffer = Fplist_get (contact, QCbuffer);
2889 if (NILP (buffer))
2890 buffer = name;
2891 buffer = Fget_buffer_create (buffer);
2892 pset_buffer (p, buffer);
2894 pset_childp (p, contact);
2895 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2896 pset_type (p, Qserial);
2897 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2898 pset_filter (p, Fplist_get (contact, QCfilter));
2899 pset_log (p, Qnil);
2900 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2901 p->kill_without_query = 1;
2902 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2903 pset_command (p, Qt);
2904 eassert (! p->pty_flag);
2906 if (!EQ (p->command, Qt))
2908 FD_SET (fd, &input_wait_mask);
2909 FD_SET (fd, &non_keyboard_wait_mask);
2912 if (BUFFERP (buffer))
2914 set_marker_both (p->mark, buffer,
2915 BUF_ZV (XBUFFER (buffer)),
2916 BUF_ZV_BYTE (XBUFFER (buffer)));
2919 tem = Fplist_member (contact, QCcoding);
2920 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2921 tem = Qnil;
2923 val = Qnil;
2924 if (!NILP (tem))
2926 val = XCAR (XCDR (tem));
2927 if (CONSP (val))
2928 val = XCAR (val);
2930 else if (!NILP (Vcoding_system_for_read))
2931 val = Vcoding_system_for_read;
2932 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2933 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2934 val = Qnil;
2935 pset_decode_coding_system (p, val);
2937 val = Qnil;
2938 if (!NILP (tem))
2940 val = XCAR (XCDR (tem));
2941 if (CONSP (val))
2942 val = XCDR (val);
2944 else if (!NILP (Vcoding_system_for_write))
2945 val = Vcoding_system_for_write;
2946 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2947 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2948 val = Qnil;
2949 pset_encode_coding_system (p, val);
2951 setup_process_coding_systems (proc);
2952 pset_decoding_buf (p, empty_unibyte_string);
2953 p->decoding_carryover = 0;
2954 pset_encoding_buf (p, empty_unibyte_string);
2955 p->inherit_coding_system_flag
2956 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2958 Fserial_process_configure (nargs, args);
2960 specpdl_ptr = specpdl + specpdl_count;
2962 UNGCPRO;
2963 return proc;
2966 /* Create a network stream/datagram client/server process. Treated
2967 exactly like a normal process when reading and writing. Primary
2968 differences are in status display and process deletion. A network
2969 connection has no PID; you cannot signal it. All you can do is
2970 stop/continue it and deactivate/close it via delete-process. */
2972 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2973 0, MANY, 0,
2974 doc: /* Create and return a network server or client process.
2976 In Emacs, network connections are represented by process objects, so
2977 input and output work as for subprocesses and `delete-process' closes
2978 a network connection. However, a network process has no process id,
2979 it cannot be signaled, and the status codes are different from normal
2980 processes.
2982 Arguments are specified as keyword/argument pairs. The following
2983 arguments are defined:
2985 :name NAME -- NAME is name for process. It is modified if necessary
2986 to make it unique.
2988 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2989 with the process. Process output goes at end of that buffer, unless
2990 you specify an output stream or filter function to handle the output.
2991 BUFFER may be also nil, meaning that this process is not associated
2992 with any buffer.
2994 :host HOST -- HOST is name of the host to connect to, or its IP
2995 address. The symbol `local' specifies the local host. If specified
2996 for a server process, it must be a valid name or address for the local
2997 host, and only clients connecting to that address will be accepted.
2999 :service SERVICE -- SERVICE is name of the service desired, or an
3000 integer specifying a port number to connect to. If SERVICE is t,
3001 a random port number is selected for the server. (If Emacs was
3002 compiled with getaddrinfo, a port number can also be specified as a
3003 string, e.g. "80", as well as an integer. This is not portable.)
3005 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3006 stream type connection, `datagram' creates a datagram type connection,
3007 `seqpacket' creates a reliable datagram connection.
3009 :family FAMILY -- FAMILY is the address (and protocol) family for the
3010 service specified by HOST and SERVICE. The default (nil) is to use
3011 whatever address family (IPv4 or IPv6) that is defined for the host
3012 and port number specified by HOST and SERVICE. Other address families
3013 supported are:
3014 local -- for a local (i.e. UNIX) address specified by SERVICE.
3015 ipv4 -- use IPv4 address family only.
3016 ipv6 -- use IPv6 address family only.
3018 :local ADDRESS -- ADDRESS is the local address used for the connection.
3019 This parameter is ignored when opening a client process. When specified
3020 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3022 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3023 connection. This parameter is ignored when opening a stream server
3024 process. For a datagram server process, it specifies the initial
3025 setting of the remote datagram address. When specified for a client
3026 process, the FAMILY, HOST, and SERVICE args are ignored.
3028 The format of ADDRESS depends on the address family:
3029 - An IPv4 address is represented as an vector of integers [A B C D P]
3030 corresponding to numeric IP address A.B.C.D and port number P.
3031 - A local address is represented as a string with the address in the
3032 local address space.
3033 - An "unsupported family" address is represented by a cons (F . AV)
3034 where F is the family number and AV is a vector containing the socket
3035 address data with one element per address data byte. Do not rely on
3036 this format in portable code, as it may depend on implementation
3037 defined constants, data sizes, and data structure alignment.
3039 :coding CODING -- If CODING is a symbol, it specifies the coding
3040 system used for both reading and writing for this process. If CODING
3041 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3042 ENCODING is used for writing.
3044 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3045 return without waiting for the connection to complete; instead, the
3046 sentinel function will be called with second arg matching "open" (if
3047 successful) or "failed" when the connect completes. Default is to use
3048 a blocking connect (i.e. wait) for stream type connections.
3050 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3051 running when Emacs is exited.
3053 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3054 In the stopped state, a server process does not accept new
3055 connections, and a client process does not handle incoming traffic.
3056 The stopped state is cleared by `continue-process' and set by
3057 `stop-process'.
3059 :filter FILTER -- Install FILTER as the process filter.
3061 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3062 process filter are multibyte, otherwise they are unibyte.
3063 If this keyword is not specified, the strings are multibyte if
3064 the default value of `enable-multibyte-characters' is non-nil.
3066 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3068 :log LOG -- Install LOG as the server process log function. This
3069 function is called when the server accepts a network connection from a
3070 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3071 is the server process, CLIENT is the new process for the connection,
3072 and MESSAGE is a string.
3074 :plist PLIST -- Install PLIST as the new process's initial plist.
3076 :server QLEN -- if QLEN is non-nil, create a server process for the
3077 specified FAMILY, SERVICE, and connection type (stream or datagram).
3078 If QLEN is an integer, it is used as the max. length of the server's
3079 pending connection queue (also known as the backlog); the default
3080 queue length is 5. Default is to create a client process.
3082 The following network options can be specified for this connection:
3084 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3085 :dontroute BOOL -- Only send to directly connected hosts.
3086 :keepalive BOOL -- Send keep-alive messages on network stream.
3087 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3088 :oobinline BOOL -- Place out-of-band data in receive data stream.
3089 :priority INT -- Set protocol defined priority for sent packets.
3090 :reuseaddr BOOL -- Allow reusing a recently used local address
3091 (this is allowed by default for a server process).
3092 :bindtodevice NAME -- bind to interface NAME. Using this may require
3093 special privileges on some systems.
3095 Consult the relevant system programmer's manual pages for more
3096 information on using these options.
3099 A server process will listen for and accept connections from clients.
3100 When a client connection is accepted, a new network process is created
3101 for the connection with the following parameters:
3103 - The client's process name is constructed by concatenating the server
3104 process's NAME and a client identification string.
3105 - If the FILTER argument is non-nil, the client process will not get a
3106 separate process buffer; otherwise, the client's process buffer is a newly
3107 created buffer named after the server process's BUFFER name or process
3108 NAME concatenated with the client identification string.
3109 - The connection type and the process filter and sentinel parameters are
3110 inherited from the server process's TYPE, FILTER and SENTINEL.
3111 - The client process's contact info is set according to the client's
3112 addressing information (typically an IP address and a port number).
3113 - The client process's plist is initialized from the server's plist.
3115 Notice that the FILTER and SENTINEL args are never used directly by
3116 the server process. Also, the BUFFER argument is not used directly by
3117 the server process, but via the optional :log function, accepted (and
3118 failed) connections may be logged in the server process's buffer.
3120 The original argument list, modified with the actual connection
3121 information, is available via the `process-contact' function.
3123 usage: (make-network-process &rest ARGS) */)
3124 (ptrdiff_t nargs, Lisp_Object *args)
3126 Lisp_Object proc;
3127 Lisp_Object contact;
3128 struct Lisp_Process *p;
3129 #ifdef HAVE_GETADDRINFO
3130 struct addrinfo ai, *res, *lres;
3131 struct addrinfo hints;
3132 const char *portstring;
3133 char portbuf[128];
3134 #else /* HAVE_GETADDRINFO */
3135 struct _emacs_addrinfo
3137 int ai_family;
3138 int ai_socktype;
3139 int ai_protocol;
3140 int ai_addrlen;
3141 struct sockaddr *ai_addr;
3142 struct _emacs_addrinfo *ai_next;
3143 } ai, *res, *lres;
3144 #endif /* HAVE_GETADDRINFO */
3145 struct sockaddr_in address_in;
3146 #ifdef HAVE_LOCAL_SOCKETS
3147 struct sockaddr_un address_un;
3148 #endif
3149 int port;
3150 int ret = 0;
3151 int xerrno = 0;
3152 int s = -1, outch, inch;
3153 struct gcpro gcpro1;
3154 ptrdiff_t count = SPECPDL_INDEX ();
3155 ptrdiff_t count1;
3156 Lisp_Object colon_address; /* Either QClocal or QCremote. */
3157 Lisp_Object tem;
3158 Lisp_Object name, buffer, host, service, address;
3159 Lisp_Object filter, sentinel;
3160 bool is_non_blocking_client = 0;
3161 bool is_server = 0;
3162 int backlog = 5;
3163 int socktype;
3164 int family = -1;
3166 if (nargs == 0)
3167 return Qnil;
3169 /* Save arguments for process-contact and clone-process. */
3170 contact = Flist (nargs, args);
3171 GCPRO1 (contact);
3173 #ifdef WINDOWSNT
3174 /* Ensure socket support is loaded if available. */
3175 init_winsock (TRUE);
3176 #endif
3178 /* :type TYPE (nil: stream, datagram */
3179 tem = Fplist_get (contact, QCtype);
3180 if (NILP (tem))
3181 socktype = SOCK_STREAM;
3182 #ifdef DATAGRAM_SOCKETS
3183 else if (EQ (tem, Qdatagram))
3184 socktype = SOCK_DGRAM;
3185 #endif
3186 #ifdef HAVE_SEQPACKET
3187 else if (EQ (tem, Qseqpacket))
3188 socktype = SOCK_SEQPACKET;
3189 #endif
3190 else
3191 error ("Unsupported connection type");
3193 /* :server BOOL */
3194 tem = Fplist_get (contact, QCserver);
3195 if (!NILP (tem))
3197 /* Don't support network sockets when non-blocking mode is
3198 not available, since a blocked Emacs is not useful. */
3199 is_server = 1;
3200 if (TYPE_RANGED_INTEGERP (int, tem))
3201 backlog = XINT (tem);
3204 /* Make colon_address an alias for :local (server) or :remote (client). */
3205 colon_address = is_server ? QClocal : QCremote;
3207 /* :nowait BOOL */
3208 if (!is_server && socktype != SOCK_DGRAM
3209 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3211 #ifndef NON_BLOCKING_CONNECT
3212 error ("Non-blocking connect not supported");
3213 #else
3214 is_non_blocking_client = 1;
3215 #endif
3218 name = Fplist_get (contact, QCname);
3219 buffer = Fplist_get (contact, QCbuffer);
3220 filter = Fplist_get (contact, QCfilter);
3221 sentinel = Fplist_get (contact, QCsentinel);
3223 CHECK_STRING (name);
3225 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3226 ai.ai_socktype = socktype;
3227 ai.ai_protocol = 0;
3228 ai.ai_next = NULL;
3229 res = &ai;
3231 /* :local ADDRESS or :remote ADDRESS */
3232 address = Fplist_get (contact, colon_address);
3233 if (!NILP (address))
3235 host = service = Qnil;
3237 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3238 error ("Malformed :address");
3239 ai.ai_family = family;
3240 ai.ai_addr = alloca (ai.ai_addrlen);
3241 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3242 goto open_socket;
3245 /* :family FAMILY -- nil (for Inet), local, or integer. */
3246 tem = Fplist_get (contact, QCfamily);
3247 if (NILP (tem))
3249 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3250 family = AF_UNSPEC;
3251 #else
3252 family = AF_INET;
3253 #endif
3255 #ifdef HAVE_LOCAL_SOCKETS
3256 else if (EQ (tem, Qlocal))
3257 family = AF_LOCAL;
3258 #endif
3259 #ifdef AF_INET6
3260 else if (EQ (tem, Qipv6))
3261 family = AF_INET6;
3262 #endif
3263 else if (EQ (tem, Qipv4))
3264 family = AF_INET;
3265 else if (TYPE_RANGED_INTEGERP (int, tem))
3266 family = XINT (tem);
3267 else
3268 error ("Unknown address family");
3270 ai.ai_family = family;
3272 /* :service SERVICE -- string, integer (port number), or t (random port). */
3273 service = Fplist_get (contact, QCservice);
3275 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3276 host = Fplist_get (contact, QChost);
3277 if (!NILP (host))
3279 if (EQ (host, Qlocal))
3280 /* Depending on setup, "localhost" may map to different IPv4 and/or
3281 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3282 host = build_string ("127.0.0.1");
3283 CHECK_STRING (host);
3286 #ifdef HAVE_LOCAL_SOCKETS
3287 if (family == AF_LOCAL)
3289 if (!NILP (host))
3291 message (":family local ignores the :host property");
3292 contact = Fplist_put (contact, QChost, Qnil);
3293 host = Qnil;
3295 CHECK_STRING (service);
3296 memset (&address_un, 0, sizeof address_un);
3297 address_un.sun_family = AF_LOCAL;
3298 if (sizeof address_un.sun_path <= SBYTES (service))
3299 error ("Service name too long");
3300 lispstpcpy (address_un.sun_path, service);
3301 ai.ai_addr = (struct sockaddr *) &address_un;
3302 ai.ai_addrlen = sizeof address_un;
3303 goto open_socket;
3305 #endif
3307 /* Slow down polling to every ten seconds.
3308 Some kernels have a bug which causes retrying connect to fail
3309 after a connect. Polling can interfere with gethostbyname too. */
3310 #ifdef POLL_FOR_INPUT
3311 if (socktype != SOCK_DGRAM)
3313 record_unwind_protect_void (run_all_atimers);
3314 bind_polling_period (10);
3316 #endif
3318 #ifdef HAVE_GETADDRINFO
3319 /* If we have a host, use getaddrinfo to resolve both host and service.
3320 Otherwise, use getservbyname to lookup the service. */
3321 if (!NILP (host))
3324 /* SERVICE can either be a string or int.
3325 Convert to a C string for later use by getaddrinfo. */
3326 if (EQ (service, Qt))
3327 portstring = "0";
3328 else if (INTEGERP (service))
3330 sprintf (portbuf, "%"pI"d", XINT (service));
3331 portstring = portbuf;
3333 else
3335 CHECK_STRING (service);
3336 portstring = SSDATA (service);
3339 immediate_quit = 1;
3340 QUIT;
3341 memset (&hints, 0, sizeof (hints));
3342 hints.ai_flags = 0;
3343 hints.ai_family = family;
3344 hints.ai_socktype = socktype;
3345 hints.ai_protocol = 0;
3347 #ifdef HAVE_RES_INIT
3348 res_init ();
3349 #endif
3351 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3352 if (ret)
3353 #ifdef HAVE_GAI_STRERROR
3354 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3355 #else
3356 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3357 #endif
3358 immediate_quit = 0;
3360 goto open_socket;
3362 #endif /* HAVE_GETADDRINFO */
3364 /* We end up here if getaddrinfo is not defined, or in case no hostname
3365 has been specified (e.g. for a local server process). */
3367 if (EQ (service, Qt))
3368 port = 0;
3369 else if (INTEGERP (service))
3370 port = htons ((unsigned short) XINT (service));
3371 else
3373 struct servent *svc_info;
3374 CHECK_STRING (service);
3375 svc_info = getservbyname (SSDATA (service),
3376 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3377 if (svc_info == 0)
3378 error ("Unknown service: %s", SDATA (service));
3379 port = svc_info->s_port;
3382 memset (&address_in, 0, sizeof address_in);
3383 address_in.sin_family = family;
3384 address_in.sin_addr.s_addr = INADDR_ANY;
3385 address_in.sin_port = port;
3387 #ifndef HAVE_GETADDRINFO
3388 if (!NILP (host))
3390 struct hostent *host_info_ptr;
3392 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3393 as it may `hang' Emacs for a very long time. */
3394 immediate_quit = 1;
3395 QUIT;
3397 #ifdef HAVE_RES_INIT
3398 res_init ();
3399 #endif
3401 host_info_ptr = gethostbyname (SDATA (host));
3402 immediate_quit = 0;
3404 if (host_info_ptr)
3406 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3407 host_info_ptr->h_length);
3408 family = host_info_ptr->h_addrtype;
3409 address_in.sin_family = family;
3411 else
3412 /* Attempt to interpret host as numeric inet address. */
3414 unsigned long numeric_addr;
3415 numeric_addr = inet_addr (SSDATA (host));
3416 if (numeric_addr == -1)
3417 error ("Unknown host \"%s\"", SDATA (host));
3419 memcpy (&address_in.sin_addr, &numeric_addr,
3420 sizeof (address_in.sin_addr));
3424 #endif /* not HAVE_GETADDRINFO */
3426 ai.ai_family = family;
3427 ai.ai_addr = (struct sockaddr *) &address_in;
3428 ai.ai_addrlen = sizeof address_in;
3430 open_socket:
3432 /* Do this in case we never enter the for-loop below. */
3433 count1 = SPECPDL_INDEX ();
3434 s = -1;
3436 for (lres = res; lres; lres = lres->ai_next)
3438 ptrdiff_t optn;
3439 int optbits;
3441 #ifdef WINDOWSNT
3442 retry_connect:
3443 #endif
3445 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3446 lres->ai_protocol);
3447 if (s < 0)
3449 xerrno = errno;
3450 continue;
3453 #ifdef DATAGRAM_SOCKETS
3454 if (!is_server && socktype == SOCK_DGRAM)
3455 break;
3456 #endif /* DATAGRAM_SOCKETS */
3458 #ifdef NON_BLOCKING_CONNECT
3459 if (is_non_blocking_client)
3461 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3462 if (ret < 0)
3464 xerrno = errno;
3465 emacs_close (s);
3466 s = -1;
3467 continue;
3470 #endif
3472 /* Make us close S if quit. */
3473 record_unwind_protect_int (close_file_unwind, s);
3475 /* Parse network options in the arg list.
3476 We simply ignore anything which isn't a known option (including other keywords).
3477 An error is signaled if setting a known option fails. */
3478 for (optn = optbits = 0; optn < nargs - 1; optn += 2)
3479 optbits |= set_socket_option (s, args[optn], args[optn + 1]);
3481 if (is_server)
3483 /* Configure as a server socket. */
3485 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3486 explicit :reuseaddr key to override this. */
3487 #ifdef HAVE_LOCAL_SOCKETS
3488 if (family != AF_LOCAL)
3489 #endif
3490 if (!(optbits & (1 << OPIX_REUSEADDR)))
3492 int optval = 1;
3493 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3494 report_file_error ("Cannot set reuse option on server socket", Qnil);
3497 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3498 report_file_error ("Cannot bind server socket", Qnil);
3500 #ifdef HAVE_GETSOCKNAME
3501 if (EQ (service, Qt))
3503 struct sockaddr_in sa1;
3504 socklen_t len1 = sizeof (sa1);
3505 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3507 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3508 service = make_number (ntohs (sa1.sin_port));
3509 contact = Fplist_put (contact, QCservice, service);
3512 #endif
3514 if (socktype != SOCK_DGRAM && listen (s, backlog))
3515 report_file_error ("Cannot listen on server socket", Qnil);
3517 break;
3520 immediate_quit = 1;
3521 QUIT;
3523 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3524 xerrno = errno;
3526 if (ret == 0 || xerrno == EISCONN)
3528 /* The unwind-protect will be discarded afterwards.
3529 Likewise for immediate_quit. */
3530 break;
3533 #ifdef NON_BLOCKING_CONNECT
3534 #ifdef EINPROGRESS
3535 if (is_non_blocking_client && xerrno == EINPROGRESS)
3536 break;
3537 #else
3538 #ifdef EWOULDBLOCK
3539 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3540 break;
3541 #endif
3542 #endif
3543 #endif
3545 #ifndef WINDOWSNT
3546 if (xerrno == EINTR)
3548 /* Unlike most other syscalls connect() cannot be called
3549 again. (That would return EALREADY.) The proper way to
3550 wait for completion is pselect(). */
3551 int sc;
3552 socklen_t len;
3553 fd_set fdset;
3554 retry_select:
3555 FD_ZERO (&fdset);
3556 FD_SET (s, &fdset);
3557 QUIT;
3558 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3559 if (sc == -1)
3561 if (errno == EINTR)
3562 goto retry_select;
3563 else
3564 report_file_error ("Failed select", Qnil);
3566 eassert (sc > 0);
3568 len = sizeof xerrno;
3569 eassert (FD_ISSET (s, &fdset));
3570 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3571 report_file_error ("Failed getsockopt", Qnil);
3572 if (xerrno)
3573 report_file_errno ("Failed connect", Qnil, xerrno);
3574 break;
3576 #endif /* !WINDOWSNT */
3578 immediate_quit = 0;
3580 /* Discard the unwind protect closing S. */
3581 specpdl_ptr = specpdl + count1;
3582 emacs_close (s);
3583 s = -1;
3585 #ifdef WINDOWSNT
3586 if (xerrno == EINTR)
3587 goto retry_connect;
3588 #endif
3591 if (s >= 0)
3593 #ifdef DATAGRAM_SOCKETS
3594 if (socktype == SOCK_DGRAM)
3596 if (datagram_address[s].sa)
3597 emacs_abort ();
3598 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3599 datagram_address[s].len = lres->ai_addrlen;
3600 if (is_server)
3602 Lisp_Object remote;
3603 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3604 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3606 int rfamily, rlen;
3607 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3608 if (rlen != 0 && rfamily == lres->ai_family
3609 && rlen == lres->ai_addrlen)
3610 conv_lisp_to_sockaddr (rfamily, remote,
3611 datagram_address[s].sa, rlen);
3614 else
3615 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3617 #endif
3618 contact = Fplist_put (contact, colon_address,
3619 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3620 #ifdef HAVE_GETSOCKNAME
3621 if (!is_server)
3623 struct sockaddr_in sa1;
3624 socklen_t len1 = sizeof (sa1);
3625 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3626 contact = Fplist_put (contact, QClocal,
3627 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3629 #endif
3632 immediate_quit = 0;
3634 #ifdef HAVE_GETADDRINFO
3635 if (res != &ai)
3637 block_input ();
3638 freeaddrinfo (res);
3639 unblock_input ();
3641 #endif
3643 if (s < 0)
3645 /* If non-blocking got this far - and failed - assume non-blocking is
3646 not supported after all. This is probably a wrong assumption, but
3647 the normal blocking calls to open-network-stream handles this error
3648 better. */
3649 if (is_non_blocking_client)
3650 return Qnil;
3652 report_file_errno ((is_server
3653 ? "make server process failed"
3654 : "make client process failed"),
3655 contact, xerrno);
3658 inch = s;
3659 outch = s;
3661 if (!NILP (buffer))
3662 buffer = Fget_buffer_create (buffer);
3663 proc = make_process (name);
3665 chan_process[inch] = proc;
3667 fcntl (inch, F_SETFL, O_NONBLOCK);
3669 p = XPROCESS (proc);
3671 pset_childp (p, contact);
3672 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3673 pset_type (p, Qnetwork);
3675 pset_buffer (p, buffer);
3676 pset_sentinel (p, sentinel);
3677 pset_filter (p, filter);
3678 pset_log (p, Fplist_get (contact, QClog));
3679 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3680 p->kill_without_query = 1;
3681 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3682 pset_command (p, Qt);
3683 p->pid = 0;
3685 p->open_fd[SUBPROCESS_STDIN] = inch;
3686 p->infd = inch;
3687 p->outfd = outch;
3689 /* Discard the unwind protect for closing S, if any. */
3690 specpdl_ptr = specpdl + count1;
3692 /* Unwind bind_polling_period and request_sigio. */
3693 unbind_to (count, Qnil);
3695 if (is_server && socktype != SOCK_DGRAM)
3696 pset_status (p, Qlisten);
3698 /* Make the process marker point into the process buffer (if any). */
3699 if (BUFFERP (buffer))
3700 set_marker_both (p->mark, buffer,
3701 BUF_ZV (XBUFFER (buffer)),
3702 BUF_ZV_BYTE (XBUFFER (buffer)));
3704 #ifdef NON_BLOCKING_CONNECT
3705 if (is_non_blocking_client)
3707 /* We may get here if connect did succeed immediately. However,
3708 in that case, we still need to signal this like a non-blocking
3709 connection. */
3710 pset_status (p, Qconnect);
3711 if (!FD_ISSET (inch, &connect_wait_mask))
3713 FD_SET (inch, &connect_wait_mask);
3714 FD_SET (inch, &write_mask);
3715 num_pending_connects++;
3718 else
3719 #endif
3720 /* A server may have a client filter setting of Qt, but it must
3721 still listen for incoming connects unless it is stopped. */
3722 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3723 || (EQ (p->status, Qlisten) && NILP (p->command)))
3725 FD_SET (inch, &input_wait_mask);
3726 FD_SET (inch, &non_keyboard_wait_mask);
3729 if (inch > max_process_desc)
3730 max_process_desc = inch;
3732 tem = Fplist_member (contact, QCcoding);
3733 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3734 tem = Qnil; /* No error message (too late!). */
3737 /* Setup coding systems for communicating with the network stream. */
3738 struct gcpro gcpro1;
3739 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3740 Lisp_Object coding_systems = Qt;
3741 Lisp_Object val;
3743 if (!NILP (tem))
3745 val = XCAR (XCDR (tem));
3746 if (CONSP (val))
3747 val = XCAR (val);
3749 else if (!NILP (Vcoding_system_for_read))
3750 val = Vcoding_system_for_read;
3751 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3752 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3753 /* We dare not decode end-of-line format by setting VAL to
3754 Qraw_text, because the existing Emacs Lisp libraries
3755 assume that they receive bare code including a sequence of
3756 CR LF. */
3757 val = Qnil;
3758 else
3760 if (NILP (host) || NILP (service))
3761 coding_systems = Qnil;
3762 else
3764 GCPRO1 (proc);
3765 coding_systems = CALLN (Ffind_operation_coding_system,
3766 Qopen_network_stream, name, buffer,
3767 host, service);
3768 UNGCPRO;
3770 if (CONSP (coding_systems))
3771 val = XCAR (coding_systems);
3772 else if (CONSP (Vdefault_process_coding_system))
3773 val = XCAR (Vdefault_process_coding_system);
3774 else
3775 val = Qnil;
3777 pset_decode_coding_system (p, val);
3779 if (!NILP (tem))
3781 val = XCAR (XCDR (tem));
3782 if (CONSP (val))
3783 val = XCDR (val);
3785 else if (!NILP (Vcoding_system_for_write))
3786 val = Vcoding_system_for_write;
3787 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3788 val = Qnil;
3789 else
3791 if (EQ (coding_systems, Qt))
3793 if (NILP (host) || NILP (service))
3794 coding_systems = Qnil;
3795 else
3797 GCPRO1 (proc);
3798 coding_systems = CALLN (Ffind_operation_coding_system,
3799 Qopen_network_stream, name, buffer,
3800 host, service);
3801 UNGCPRO;
3804 if (CONSP (coding_systems))
3805 val = XCDR (coding_systems);
3806 else if (CONSP (Vdefault_process_coding_system))
3807 val = XCDR (Vdefault_process_coding_system);
3808 else
3809 val = Qnil;
3811 pset_encode_coding_system (p, val);
3813 setup_process_coding_systems (proc);
3815 pset_decoding_buf (p, empty_unibyte_string);
3816 p->decoding_carryover = 0;
3817 pset_encoding_buf (p, empty_unibyte_string);
3819 p->inherit_coding_system_flag
3820 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3822 UNGCPRO;
3823 return proc;
3827 #ifdef HAVE_NET_IF_H
3829 #ifdef SIOCGIFCONF
3830 static Lisp_Object
3831 network_interface_list (void)
3833 struct ifconf ifconf;
3834 struct ifreq *ifreq;
3835 void *buf = NULL;
3836 ptrdiff_t buf_size = 512;
3837 int s;
3838 Lisp_Object res;
3839 ptrdiff_t count;
3841 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3842 if (s < 0)
3843 return Qnil;
3844 count = SPECPDL_INDEX ();
3845 record_unwind_protect_int (close_file_unwind, s);
3849 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3850 ifconf.ifc_buf = buf;
3851 ifconf.ifc_len = buf_size;
3852 if (ioctl (s, SIOCGIFCONF, &ifconf))
3854 emacs_close (s);
3855 xfree (buf);
3856 return Qnil;
3859 while (ifconf.ifc_len == buf_size);
3861 res = unbind_to (count, Qnil);
3862 ifreq = ifconf.ifc_req;
3863 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3865 struct ifreq *ifq = ifreq;
3866 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3867 #define SIZEOF_IFREQ(sif) \
3868 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3869 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3871 int len = SIZEOF_IFREQ (ifq);
3872 #else
3873 int len = sizeof (*ifreq);
3874 #endif
3875 char namebuf[sizeof (ifq->ifr_name) + 1];
3876 ifreq = (struct ifreq *) ((char *) ifreq + len);
3878 if (ifq->ifr_addr.sa_family != AF_INET)
3879 continue;
3881 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3882 namebuf[sizeof (ifq->ifr_name)] = 0;
3883 res = Fcons (Fcons (build_string (namebuf),
3884 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3885 sizeof (struct sockaddr))),
3886 res);
3889 xfree (buf);
3890 return res;
3892 #endif /* SIOCGIFCONF */
3894 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3896 struct ifflag_def {
3897 int flag_bit;
3898 const char *flag_sym;
3901 static const struct ifflag_def ifflag_table[] = {
3902 #ifdef IFF_UP
3903 { IFF_UP, "up" },
3904 #endif
3905 #ifdef IFF_BROADCAST
3906 { IFF_BROADCAST, "broadcast" },
3907 #endif
3908 #ifdef IFF_DEBUG
3909 { IFF_DEBUG, "debug" },
3910 #endif
3911 #ifdef IFF_LOOPBACK
3912 { IFF_LOOPBACK, "loopback" },
3913 #endif
3914 #ifdef IFF_POINTOPOINT
3915 { IFF_POINTOPOINT, "pointopoint" },
3916 #endif
3917 #ifdef IFF_RUNNING
3918 { IFF_RUNNING, "running" },
3919 #endif
3920 #ifdef IFF_NOARP
3921 { IFF_NOARP, "noarp" },
3922 #endif
3923 #ifdef IFF_PROMISC
3924 { IFF_PROMISC, "promisc" },
3925 #endif
3926 #ifdef IFF_NOTRAILERS
3927 #ifdef NS_IMPL_COCOA
3928 /* Really means smart, notrailers is obsolete. */
3929 { IFF_NOTRAILERS, "smart" },
3930 #else
3931 { IFF_NOTRAILERS, "notrailers" },
3932 #endif
3933 #endif
3934 #ifdef IFF_ALLMULTI
3935 { IFF_ALLMULTI, "allmulti" },
3936 #endif
3937 #ifdef IFF_MASTER
3938 { IFF_MASTER, "master" },
3939 #endif
3940 #ifdef IFF_SLAVE
3941 { IFF_SLAVE, "slave" },
3942 #endif
3943 #ifdef IFF_MULTICAST
3944 { IFF_MULTICAST, "multicast" },
3945 #endif
3946 #ifdef IFF_PORTSEL
3947 { IFF_PORTSEL, "portsel" },
3948 #endif
3949 #ifdef IFF_AUTOMEDIA
3950 { IFF_AUTOMEDIA, "automedia" },
3951 #endif
3952 #ifdef IFF_DYNAMIC
3953 { IFF_DYNAMIC, "dynamic" },
3954 #endif
3955 #ifdef IFF_OACTIVE
3956 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
3957 #endif
3958 #ifdef IFF_SIMPLEX
3959 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
3960 #endif
3961 #ifdef IFF_LINK0
3962 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
3963 #endif
3964 #ifdef IFF_LINK1
3965 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
3966 #endif
3967 #ifdef IFF_LINK2
3968 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
3969 #endif
3970 { 0, 0 }
3973 static Lisp_Object
3974 network_interface_info (Lisp_Object ifname)
3976 struct ifreq rq;
3977 Lisp_Object res = Qnil;
3978 Lisp_Object elt;
3979 int s;
3980 bool any = 0;
3981 ptrdiff_t count;
3982 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3983 && defined HAVE_GETIFADDRS && defined LLADDR)
3984 struct ifaddrs *ifap;
3985 #endif
3987 CHECK_STRING (ifname);
3989 if (sizeof rq.ifr_name <= SBYTES (ifname))
3990 error ("interface name too long");
3991 lispstpcpy (rq.ifr_name, ifname);
3993 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3994 if (s < 0)
3995 return Qnil;
3996 count = SPECPDL_INDEX ();
3997 record_unwind_protect_int (close_file_unwind, s);
3999 elt = Qnil;
4000 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4001 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4003 int flags = rq.ifr_flags;
4004 const struct ifflag_def *fp;
4005 int fnum;
4007 /* If flags is smaller than int (i.e. short) it may have the high bit set
4008 due to IFF_MULTICAST. In that case, sign extending it into
4009 an int is wrong. */
4010 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
4011 flags = (unsigned short) rq.ifr_flags;
4013 any = 1;
4014 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4016 if (flags & fp->flag_bit)
4018 elt = Fcons (intern (fp->flag_sym), elt);
4019 flags -= fp->flag_bit;
4022 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
4024 if (flags & 1)
4026 elt = Fcons (make_number (fnum), elt);
4030 #endif
4031 res = Fcons (elt, res);
4033 elt = Qnil;
4034 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4035 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4037 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4038 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4039 int n;
4041 any = 1;
4042 for (n = 0; n < 6; n++)
4043 p->contents[n] = make_number (((unsigned char *)
4044 &rq.ifr_hwaddr.sa_data[0])
4045 [n]);
4046 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4048 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4049 if (getifaddrs (&ifap) != -1)
4051 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4052 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4053 struct ifaddrs *it;
4055 for (it = ifap; it != NULL; it = it->ifa_next)
4057 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
4058 unsigned char linkaddr[6];
4059 int n;
4061 if (it->ifa_addr->sa_family != AF_LINK
4062 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4063 || sdl->sdl_alen != 6)
4064 continue;
4066 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4067 for (n = 0; n < 6; n++)
4068 p->contents[n] = make_number (linkaddr[n]);
4070 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4071 break;
4074 #ifdef HAVE_FREEIFADDRS
4075 freeifaddrs (ifap);
4076 #endif
4078 #endif /* HAVE_GETIFADDRS && LLADDR */
4080 res = Fcons (elt, res);
4082 elt = Qnil;
4083 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4084 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4086 any = 1;
4087 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4088 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4089 #else
4090 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4091 #endif
4093 #endif
4094 res = Fcons (elt, res);
4096 elt = Qnil;
4097 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4098 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4100 any = 1;
4101 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4103 #endif
4104 res = Fcons (elt, res);
4106 elt = Qnil;
4107 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4108 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4110 any = 1;
4111 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4113 #endif
4114 res = Fcons (elt, res);
4116 return unbind_to (count, any ? res : Qnil);
4118 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4119 #endif /* defined (HAVE_NET_IF_H) */
4121 DEFUN ("network-interface-list", Fnetwork_interface_list,
4122 Snetwork_interface_list, 0, 0, 0,
4123 doc: /* Return an alist of all network interfaces and their network address.
4124 Each element is a cons, the car of which is a string containing the
4125 interface name, and the cdr is the network address in internal
4126 format; see the description of ADDRESS in `make-network-process'.
4128 If the information is not available, return nil. */)
4129 (void)
4131 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4132 return network_interface_list ();
4133 #else
4134 return Qnil;
4135 #endif
4138 DEFUN ("network-interface-info", Fnetwork_interface_info,
4139 Snetwork_interface_info, 1, 1, 0,
4140 doc: /* Return information about network interface named IFNAME.
4141 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4142 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4143 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4144 FLAGS is the current flags of the interface.
4146 Data that is unavailable is returned as nil. */)
4147 (Lisp_Object ifname)
4149 #if ((defined HAVE_NET_IF_H \
4150 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4151 || defined SIOCGIFFLAGS)) \
4152 || defined WINDOWSNT)
4153 return network_interface_info (ifname);
4154 #else
4155 return Qnil;
4156 #endif
4159 /* If program file NAME starts with /: for quoting a magic
4160 name, remove that, preserving the multibyteness of NAME. */
4162 Lisp_Object
4163 remove_slash_colon (Lisp_Object name)
4165 return
4166 ((SBYTES (name) > 2 && SREF (name, 0) == '/' && SREF (name, 1) == ':')
4167 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
4168 SBYTES (name) - 2, STRING_MULTIBYTE (name))
4169 : name);
4172 /* Turn off input and output for process PROC. */
4174 static void
4175 deactivate_process (Lisp_Object proc)
4177 int inchannel;
4178 struct Lisp_Process *p = XPROCESS (proc);
4179 int i;
4181 #ifdef HAVE_GNUTLS
4182 /* Delete GnuTLS structures in PROC, if any. */
4183 emacs_gnutls_deinit (proc);
4184 #endif /* HAVE_GNUTLS */
4186 #ifdef ADAPTIVE_READ_BUFFERING
4187 if (p->read_output_delay > 0)
4189 if (--process_output_delay_count < 0)
4190 process_output_delay_count = 0;
4191 p->read_output_delay = 0;
4192 p->read_output_skip = 0;
4194 #endif
4196 /* Beware SIGCHLD hereabouts. */
4198 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4199 close_process_fd (&p->open_fd[i]);
4201 inchannel = p->infd;
4202 if (inchannel >= 0)
4204 p->infd = -1;
4205 p->outfd = -1;
4206 #ifdef DATAGRAM_SOCKETS
4207 if (DATAGRAM_CHAN_P (inchannel))
4209 xfree (datagram_address[inchannel].sa);
4210 datagram_address[inchannel].sa = 0;
4211 datagram_address[inchannel].len = 0;
4213 #endif
4214 chan_process[inchannel] = Qnil;
4215 FD_CLR (inchannel, &input_wait_mask);
4216 FD_CLR (inchannel, &non_keyboard_wait_mask);
4217 #ifdef NON_BLOCKING_CONNECT
4218 if (FD_ISSET (inchannel, &connect_wait_mask))
4220 FD_CLR (inchannel, &connect_wait_mask);
4221 FD_CLR (inchannel, &write_mask);
4222 if (--num_pending_connects < 0)
4223 emacs_abort ();
4225 #endif
4226 if (inchannel == max_process_desc)
4228 /* We just closed the highest-numbered process input descriptor,
4229 so recompute the highest-numbered one now. */
4230 int i = inchannel;
4232 i--;
4233 while (0 <= i && NILP (chan_process[i]));
4235 max_process_desc = i;
4241 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4242 0, 4, 0,
4243 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4244 It is given to their filter functions.
4245 Optional argument PROCESS means do not return until output has been
4246 received from PROCESS.
4248 Optional second argument SECONDS and third argument MILLISEC
4249 specify a timeout; return after that much time even if there is
4250 no subprocess output. If SECONDS is a floating point number,
4251 it specifies a fractional number of seconds to wait.
4252 The MILLISEC argument is obsolete and should be avoided.
4254 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4255 from PROCESS only, suspending reading output from other processes.
4256 If JUST-THIS-ONE is an integer, don't run any timers either.
4257 Return non-nil if we received any output from PROCESS (or, if PROCESS
4258 is nil, from any process) before the timeout expired. */)
4259 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4261 intmax_t secs;
4262 int nsecs;
4264 if (! NILP (process))
4265 CHECK_PROCESS (process);
4266 else
4267 just_this_one = Qnil;
4269 if (!NILP (millisec))
4270 { /* Obsolete calling convention using integers rather than floats. */
4271 CHECK_NUMBER (millisec);
4272 if (NILP (seconds))
4273 seconds = make_float (XINT (millisec) / 1000.0);
4274 else
4276 CHECK_NUMBER (seconds);
4277 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4281 secs = 0;
4282 nsecs = -1;
4284 if (!NILP (seconds))
4286 if (INTEGERP (seconds))
4288 if (XINT (seconds) > 0)
4290 secs = XINT (seconds);
4291 nsecs = 0;
4294 else if (FLOATP (seconds))
4296 if (XFLOAT_DATA (seconds) > 0)
4298 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4299 secs = min (t.tv_sec, WAIT_READING_MAX);
4300 nsecs = t.tv_nsec;
4303 else
4304 wrong_type_argument (Qnumberp, seconds);
4306 else if (! NILP (process))
4307 nsecs = 0;
4309 return
4310 ((wait_reading_process_output (secs, nsecs, 0, 0,
4311 Qnil,
4312 !NILP (process) ? XPROCESS (process) : NULL,
4313 (NILP (just_this_one) ? 0
4314 : !INTEGERP (just_this_one) ? 1 : -1))
4315 <= 0)
4316 ? Qnil : Qt);
4319 /* Accept a connection for server process SERVER on CHANNEL. */
4321 static EMACS_INT connect_counter = 0;
4323 static void
4324 server_accept_connection (Lisp_Object server, int channel)
4326 Lisp_Object proc, caller, name, buffer;
4327 Lisp_Object contact, host, service;
4328 struct Lisp_Process *ps = XPROCESS (server);
4329 struct Lisp_Process *p;
4330 int s;
4331 union u_sockaddr {
4332 struct sockaddr sa;
4333 struct sockaddr_in in;
4334 #ifdef AF_INET6
4335 struct sockaddr_in6 in6;
4336 #endif
4337 #ifdef HAVE_LOCAL_SOCKETS
4338 struct sockaddr_un un;
4339 #endif
4340 } saddr;
4341 socklen_t len = sizeof saddr;
4342 ptrdiff_t count;
4344 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4346 if (s < 0)
4348 int code = errno;
4350 if (code == EAGAIN)
4351 return;
4352 #ifdef EWOULDBLOCK
4353 if (code == EWOULDBLOCK)
4354 return;
4355 #endif
4357 if (!NILP (ps->log))
4358 call3 (ps->log, server, Qnil,
4359 concat3 (build_string ("accept failed with code"),
4360 Fnumber_to_string (make_number (code)),
4361 build_string ("\n")));
4362 return;
4365 count = SPECPDL_INDEX ();
4366 record_unwind_protect_int (close_file_unwind, s);
4368 connect_counter++;
4370 /* Setup a new process to handle the connection. */
4372 /* Generate a unique identification of the caller, and build contact
4373 information for this process. */
4374 host = Qt;
4375 service = Qnil;
4376 switch (saddr.sa.sa_family)
4378 case AF_INET:
4380 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4382 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4383 host = CALLN (Fformat, ipv4_format,
4384 make_number (ip[0]), make_number (ip[1]),
4385 make_number (ip[2]), make_number (ip[3]));
4386 service = make_number (ntohs (saddr.in.sin_port));
4387 AUTO_STRING (caller_format, " <%s:%d>");
4388 caller = CALLN (Fformat, caller_format, host, service);
4390 break;
4392 #ifdef AF_INET6
4393 case AF_INET6:
4395 Lisp_Object args[9];
4396 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4397 int i;
4399 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4400 args[0] = ipv6_format;
4401 for (i = 0; i < 8; i++)
4402 args[i + 1] = make_number (ntohs (ip6[i]));
4403 host = CALLMANY (Fformat, args);
4404 service = make_number (ntohs (saddr.in.sin_port));
4405 AUTO_STRING (caller_format, " <[%s]:%d>");
4406 caller = CALLN (Fformat, caller_format, host, service);
4408 break;
4409 #endif
4411 #ifdef HAVE_LOCAL_SOCKETS
4412 case AF_LOCAL:
4413 #endif
4414 default:
4415 caller = Fnumber_to_string (make_number (connect_counter));
4416 AUTO_STRING (space_less_than, " <");
4417 AUTO_STRING (greater_than, ">");
4418 caller = concat3 (space_less_than, caller, greater_than);
4419 break;
4422 /* Create a new buffer name for this process if it doesn't have a
4423 filter. The new buffer name is based on the buffer name or
4424 process name of the server process concatenated with the caller
4425 identification. */
4427 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4428 || EQ (ps->filter, Qt)))
4429 buffer = Qnil;
4430 else
4432 buffer = ps->buffer;
4433 if (!NILP (buffer))
4434 buffer = Fbuffer_name (buffer);
4435 else
4436 buffer = ps->name;
4437 if (!NILP (buffer))
4439 buffer = concat2 (buffer, caller);
4440 buffer = Fget_buffer_create (buffer);
4444 /* Generate a unique name for the new server process. Combine the
4445 server process name with the caller identification. */
4447 name = concat2 (ps->name, caller);
4448 proc = make_process (name);
4450 chan_process[s] = proc;
4452 fcntl (s, F_SETFL, O_NONBLOCK);
4454 p = XPROCESS (proc);
4456 /* Build new contact information for this setup. */
4457 contact = Fcopy_sequence (ps->childp);
4458 contact = Fplist_put (contact, QCserver, Qnil);
4459 contact = Fplist_put (contact, QChost, host);
4460 if (!NILP (service))
4461 contact = Fplist_put (contact, QCservice, service);
4462 contact = Fplist_put (contact, QCremote,
4463 conv_sockaddr_to_lisp (&saddr.sa, len));
4464 #ifdef HAVE_GETSOCKNAME
4465 len = sizeof saddr;
4466 if (getsockname (s, &saddr.sa, &len) == 0)
4467 contact = Fplist_put (contact, QClocal,
4468 conv_sockaddr_to_lisp (&saddr.sa, len));
4469 #endif
4471 pset_childp (p, contact);
4472 pset_plist (p, Fcopy_sequence (ps->plist));
4473 pset_type (p, Qnetwork);
4475 pset_buffer (p, buffer);
4476 pset_sentinel (p, ps->sentinel);
4477 pset_filter (p, ps->filter);
4478 pset_command (p, Qnil);
4479 p->pid = 0;
4481 /* Discard the unwind protect for closing S. */
4482 specpdl_ptr = specpdl + count;
4484 p->open_fd[SUBPROCESS_STDIN] = s;
4485 p->infd = s;
4486 p->outfd = s;
4487 pset_status (p, Qrun);
4489 /* Client processes for accepted connections are not stopped initially. */
4490 if (!EQ (p->filter, Qt))
4492 FD_SET (s, &input_wait_mask);
4493 FD_SET (s, &non_keyboard_wait_mask);
4496 if (s > max_process_desc)
4497 max_process_desc = s;
4499 /* Setup coding system for new process based on server process.
4500 This seems to be the proper thing to do, as the coding system
4501 of the new process should reflect the settings at the time the
4502 server socket was opened; not the current settings. */
4504 pset_decode_coding_system (p, ps->decode_coding_system);
4505 pset_encode_coding_system (p, ps->encode_coding_system);
4506 setup_process_coding_systems (proc);
4508 pset_decoding_buf (p, empty_unibyte_string);
4509 p->decoding_carryover = 0;
4510 pset_encoding_buf (p, empty_unibyte_string);
4512 p->inherit_coding_system_flag
4513 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4515 AUTO_STRING (dash, "-");
4516 AUTO_STRING (nl, "\n");
4517 Lisp_Object host_string = STRINGP (host) ? host : dash;
4519 if (!NILP (ps->log))
4521 AUTO_STRING (accept_from, "accept from ");
4522 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4525 AUTO_STRING (open_from, "open from ");
4526 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4529 /* This variable is different from waiting_for_input in keyboard.c.
4530 It is used to communicate to a lisp process-filter/sentinel (via the
4531 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4532 for user-input when that process-filter was called.
4533 waiting_for_input cannot be used as that is by definition 0 when
4534 lisp code is being evalled.
4535 This is also used in record_asynch_buffer_change.
4536 For that purpose, this must be 0
4537 when not inside wait_reading_process_output. */
4538 static int waiting_for_user_input_p;
4540 static void
4541 wait_reading_process_output_unwind (int data)
4543 waiting_for_user_input_p = data;
4546 /* This is here so breakpoints can be put on it. */
4547 static void
4548 wait_reading_process_output_1 (void)
4552 /* Read and dispose of subprocess output while waiting for timeout to
4553 elapse and/or keyboard input to be available.
4555 TIME_LIMIT is:
4556 timeout in seconds
4557 If negative, gobble data immediately available but don't wait for any.
4559 NSECS is:
4560 an additional duration to wait, measured in nanoseconds
4561 If TIME_LIMIT is zero, then:
4562 If NSECS == 0, there is no limit.
4563 If NSECS > 0, the timeout consists of NSECS only.
4564 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4566 READ_KBD is:
4567 0 to ignore keyboard input, or
4568 1 to return when input is available, or
4569 -1 meaning caller will actually read the input, so don't throw to
4570 the quit handler, or
4572 DO_DISPLAY means redisplay should be done to show subprocess
4573 output that arrives.
4575 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4576 (and gobble terminal input into the buffer if any arrives).
4578 If WAIT_PROC is specified, wait until something arrives from that
4579 process.
4581 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4582 (suspending output from other processes). A negative value
4583 means don't run any timers either.
4585 Return positive if we received input from WAIT_PROC (or from any
4586 process if WAIT_PROC is null), zero if we attempted to receive
4587 input but got none, and negative if we didn't even try. */
4590 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4591 bool do_display,
4592 Lisp_Object wait_for_cell,
4593 struct Lisp_Process *wait_proc, int just_wait_proc)
4595 int channel, nfds;
4596 fd_set Available;
4597 fd_set Writeok;
4598 bool check_write;
4599 int check_delay;
4600 bool no_avail;
4601 int xerrno;
4602 Lisp_Object proc;
4603 struct timespec timeout, end_time;
4604 int got_some_input = -1;
4605 ptrdiff_t count = SPECPDL_INDEX ();
4607 FD_ZERO (&Available);
4608 FD_ZERO (&Writeok);
4610 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4611 && !(CONSP (wait_proc->status)
4612 && EQ (XCAR (wait_proc->status), Qexit)))
4613 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4615 record_unwind_protect_int (wait_reading_process_output_unwind,
4616 waiting_for_user_input_p);
4617 waiting_for_user_input_p = read_kbd;
4619 if (time_limit < 0)
4621 time_limit = 0;
4622 nsecs = -1;
4624 else if (TYPE_MAXIMUM (time_t) < time_limit)
4625 time_limit = TYPE_MAXIMUM (time_t);
4627 /* Since we may need to wait several times,
4628 compute the absolute time to return at. */
4629 if (time_limit || nsecs > 0)
4631 timeout = make_timespec (time_limit, nsecs);
4632 end_time = timespec_add (current_timespec (), timeout);
4635 while (1)
4637 bool timeout_reduced_for_timers = false;
4639 /* If calling from keyboard input, do not quit
4640 since we want to return C-g as an input character.
4641 Otherwise, do pending quit if requested. */
4642 if (read_kbd >= 0)
4643 QUIT;
4644 else if (pending_signals)
4645 process_pending_signals ();
4647 /* Exit now if the cell we're waiting for became non-nil. */
4648 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4649 break;
4651 /* After reading input, vacuum up any leftovers without waiting. */
4652 if (0 <= got_some_input)
4653 nsecs = -1;
4655 /* Compute time from now till when time limit is up. */
4656 /* Exit if already run out. */
4657 if (nsecs < 0)
4659 /* A negative timeout means
4660 gobble output available now
4661 but don't wait at all. */
4663 timeout = make_timespec (0, 0);
4665 else if (time_limit || nsecs > 0)
4667 struct timespec now = current_timespec ();
4668 if (timespec_cmp (end_time, now) <= 0)
4669 break;
4670 timeout = timespec_sub (end_time, now);
4672 else
4674 timeout = make_timespec (100000, 0);
4677 /* Normally we run timers here.
4678 But not if wait_for_cell; in those cases,
4679 the wait is supposed to be short,
4680 and those callers cannot handle running arbitrary Lisp code here. */
4681 if (NILP (wait_for_cell)
4682 && just_wait_proc >= 0)
4684 struct timespec timer_delay;
4688 unsigned old_timers_run = timers_run;
4689 struct buffer *old_buffer = current_buffer;
4690 Lisp_Object old_window = selected_window;
4692 timer_delay = timer_check ();
4694 /* If a timer has run, this might have changed buffers
4695 an alike. Make read_key_sequence aware of that. */
4696 if (timers_run != old_timers_run
4697 && (old_buffer != current_buffer
4698 || !EQ (old_window, selected_window))
4699 && waiting_for_user_input_p == -1)
4700 record_asynch_buffer_change ();
4702 if (timers_run != old_timers_run && do_display)
4703 /* We must retry, since a timer may have requeued itself
4704 and that could alter the time_delay. */
4705 redisplay_preserve_echo_area (9);
4706 else
4707 break;
4709 while (!detect_input_pending ());
4711 /* If there is unread keyboard input, also return. */
4712 if (read_kbd != 0
4713 && requeued_events_pending_p ())
4714 break;
4716 /* A negative timeout means do not wait at all. */
4717 if (nsecs >= 0)
4719 if (timespec_valid_p (timer_delay))
4721 if (timespec_cmp (timer_delay, timeout) < 0)
4723 timeout = timer_delay;
4724 timeout_reduced_for_timers = true;
4727 else
4729 /* This is so a breakpoint can be put here. */
4730 wait_reading_process_output_1 ();
4735 /* Cause C-g and alarm signals to take immediate action,
4736 and cause input available signals to zero out timeout.
4738 It is important that we do this before checking for process
4739 activity. If we get a SIGCHLD after the explicit checks for
4740 process activity, timeout is the only way we will know. */
4741 if (read_kbd < 0)
4742 set_waiting_for_input (&timeout);
4744 /* If status of something has changed, and no input is
4745 available, notify the user of the change right away. After
4746 this explicit check, we'll let the SIGCHLD handler zap
4747 timeout to get our attention. */
4748 if (update_tick != process_tick)
4750 fd_set Atemp;
4751 fd_set Ctemp;
4753 if (kbd_on_hold_p ())
4754 FD_ZERO (&Atemp);
4755 else
4756 Atemp = input_wait_mask;
4757 Ctemp = write_mask;
4759 timeout = make_timespec (0, 0);
4760 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4761 &Atemp,
4762 #ifdef NON_BLOCKING_CONNECT
4763 (num_pending_connects > 0 ? &Ctemp : NULL),
4764 #else
4765 NULL,
4766 #endif
4767 NULL, &timeout, NULL)
4768 <= 0))
4770 /* It's okay for us to do this and then continue with
4771 the loop, since timeout has already been zeroed out. */
4772 clear_waiting_for_input ();
4773 got_some_input = status_notify (NULL, wait_proc);
4774 if (do_display) redisplay_preserve_echo_area (13);
4778 /* Don't wait for output from a non-running process. Just
4779 read whatever data has already been received. */
4780 if (wait_proc && wait_proc->raw_status_new)
4781 update_status (wait_proc);
4782 if (wait_proc
4783 && ! EQ (wait_proc->status, Qrun)
4784 && ! EQ (wait_proc->status, Qconnect))
4786 bool read_some_bytes = false;
4788 clear_waiting_for_input ();
4790 /* If data can be read from the process, do so until exhausted. */
4791 if (wait_proc->infd >= 0)
4793 XSETPROCESS (proc, wait_proc);
4795 while (true)
4797 int nread = read_process_output (proc, wait_proc->infd);
4798 if (nread < 0)
4800 if (errno == EIO || errno == EAGAIN)
4801 break;
4802 #ifdef EWOULDBLOCK
4803 if (errno == EWOULDBLOCK)
4804 break;
4805 #endif
4807 else
4809 if (got_some_input < nread)
4810 got_some_input = nread;
4811 if (nread == 0)
4812 break;
4813 read_some_bytes = true;
4818 if (read_some_bytes && do_display)
4819 redisplay_preserve_echo_area (10);
4821 break;
4824 /* Wait till there is something to do. */
4826 if (wait_proc && just_wait_proc)
4828 if (wait_proc->infd < 0) /* Terminated. */
4829 break;
4830 FD_SET (wait_proc->infd, &Available);
4831 check_delay = 0;
4832 check_write = 0;
4834 else if (!NILP (wait_for_cell))
4836 Available = non_process_wait_mask;
4837 check_delay = 0;
4838 check_write = 0;
4840 else
4842 if (! read_kbd)
4843 Available = non_keyboard_wait_mask;
4844 else
4845 Available = input_wait_mask;
4846 Writeok = write_mask;
4847 check_delay = wait_proc ? 0 : process_output_delay_count;
4848 check_write = true;
4851 /* If frame size has changed or the window is newly mapped,
4852 redisplay now, before we start to wait. There is a race
4853 condition here; if a SIGIO arrives between now and the select
4854 and indicates that a frame is trashed, the select may block
4855 displaying a trashed screen. */
4856 if (frame_garbaged && do_display)
4858 clear_waiting_for_input ();
4859 redisplay_preserve_echo_area (11);
4860 if (read_kbd < 0)
4861 set_waiting_for_input (&timeout);
4864 /* Skip the `select' call if input is available and we're
4865 waiting for keyboard input or a cell change (which can be
4866 triggered by processing X events). In the latter case, set
4867 nfds to 1 to avoid breaking the loop. */
4868 no_avail = 0;
4869 if ((read_kbd || !NILP (wait_for_cell))
4870 && detect_input_pending ())
4872 nfds = read_kbd ? 0 : 1;
4873 no_avail = 1;
4874 FD_ZERO (&Available);
4877 if (!no_avail)
4880 #ifdef ADAPTIVE_READ_BUFFERING
4881 /* Set the timeout for adaptive read buffering if any
4882 process has non-zero read_output_skip and non-zero
4883 read_output_delay, and we are not reading output for a
4884 specific process. It is not executed if
4885 Vprocess_adaptive_read_buffering is nil. */
4886 if (process_output_skip && check_delay > 0)
4888 int nsecs = timeout.tv_nsec;
4889 if (timeout.tv_sec > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4890 nsecs = READ_OUTPUT_DELAY_MAX;
4891 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4893 proc = chan_process[channel];
4894 if (NILP (proc))
4895 continue;
4896 /* Find minimum non-zero read_output_delay among the
4897 processes with non-zero read_output_skip. */
4898 if (XPROCESS (proc)->read_output_delay > 0)
4900 check_delay--;
4901 if (!XPROCESS (proc)->read_output_skip)
4902 continue;
4903 FD_CLR (channel, &Available);
4904 XPROCESS (proc)->read_output_skip = 0;
4905 if (XPROCESS (proc)->read_output_delay < nsecs)
4906 nsecs = XPROCESS (proc)->read_output_delay;
4909 timeout = make_timespec (0, nsecs);
4910 process_output_skip = 0;
4912 #endif
4914 #if defined (HAVE_NS)
4915 nfds = ns_select
4916 #elif defined (HAVE_GLIB)
4917 nfds = xg_select
4918 #else
4919 nfds = pselect
4920 #endif
4921 (max (max_process_desc, max_input_desc) + 1,
4922 &Available,
4923 (check_write ? &Writeok : 0),
4924 NULL, &timeout, NULL);
4926 #ifdef HAVE_GNUTLS
4927 /* GnuTLS buffers data internally. In lowat mode it leaves
4928 some data in the TCP buffers so that select works, but
4929 with custom pull/push functions we need to check if some
4930 data is available in the buffers manually. */
4931 if (nfds == 0)
4933 if (! wait_proc)
4935 /* We're not waiting on a specific process, so loop
4936 through all the channels and check for data.
4937 This is a workaround needed for some versions of
4938 the gnutls library -- 2.12.14 has been confirmed
4939 to need it. See
4940 http://comments.gmane.org/gmane.emacs.devel/145074 */
4941 for (channel = 0; channel < FD_SETSIZE; ++channel)
4942 if (! NILP (chan_process[channel]))
4944 struct Lisp_Process *p =
4945 XPROCESS (chan_process[channel]);
4946 if (p && p->gnutls_p && p->gnutls_state
4947 && ((emacs_gnutls_record_check_pending
4948 (p->gnutls_state))
4949 > 0))
4951 nfds++;
4952 eassert (p->infd == channel);
4953 FD_SET (p->infd, &Available);
4957 else
4959 /* Check this specific channel. */
4960 if (wait_proc->gnutls_p /* Check for valid process. */
4961 && wait_proc->gnutls_state
4962 /* Do we have pending data? */
4963 && ((emacs_gnutls_record_check_pending
4964 (wait_proc->gnutls_state))
4965 > 0))
4967 nfds = 1;
4968 eassert (0 <= wait_proc->infd);
4969 /* Set to Available. */
4970 FD_SET (wait_proc->infd, &Available);
4974 #endif
4977 xerrno = errno;
4979 /* Make C-g and alarm signals set flags again. */
4980 clear_waiting_for_input ();
4982 /* If we woke up due to SIGWINCH, actually change size now. */
4983 do_pending_window_change (0);
4985 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4986 /* We waited the full specified time, so return now. */
4987 break;
4988 if (nfds < 0)
4990 if (xerrno == EINTR)
4991 no_avail = 1;
4992 else if (xerrno == EBADF)
4993 emacs_abort ();
4994 else
4995 report_file_errno ("Failed select", Qnil, xerrno);
4998 /* Check for keyboard input. */
4999 /* If there is any, return immediately
5000 to give it higher priority than subprocesses. */
5002 if (read_kbd != 0)
5004 unsigned old_timers_run = timers_run;
5005 struct buffer *old_buffer = current_buffer;
5006 Lisp_Object old_window = selected_window;
5007 bool leave = false;
5009 if (detect_input_pending_run_timers (do_display))
5011 swallow_events (do_display);
5012 if (detect_input_pending_run_timers (do_display))
5013 leave = true;
5016 /* If a timer has run, this might have changed buffers
5017 an alike. Make read_key_sequence aware of that. */
5018 if (timers_run != old_timers_run
5019 && waiting_for_user_input_p == -1
5020 && (old_buffer != current_buffer
5021 || !EQ (old_window, selected_window)))
5022 record_asynch_buffer_change ();
5024 if (leave)
5025 break;
5028 /* If there is unread keyboard input, also return. */
5029 if (read_kbd != 0
5030 && requeued_events_pending_p ())
5031 break;
5033 /* If we are not checking for keyboard input now,
5034 do process events (but don't run any timers).
5035 This is so that X events will be processed.
5036 Otherwise they may have to wait until polling takes place.
5037 That would causes delays in pasting selections, for example.
5039 (We used to do this only if wait_for_cell.) */
5040 if (read_kbd == 0 && detect_input_pending ())
5042 swallow_events (do_display);
5043 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5044 if (detect_input_pending ())
5045 break;
5046 #endif
5049 /* Exit now if the cell we're waiting for became non-nil. */
5050 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5051 break;
5053 #ifdef USABLE_SIGIO
5054 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5055 go read it. This can happen with X on BSD after logging out.
5056 In that case, there really is no input and no SIGIO,
5057 but select says there is input. */
5059 if (read_kbd && interrupt_input
5060 && keyboard_bit_set (&Available) && ! noninteractive)
5061 handle_input_available_signal (SIGIO);
5062 #endif
5064 /* If checking input just got us a size-change event from X,
5065 obey it now if we should. */
5066 if (read_kbd || ! NILP (wait_for_cell))
5067 do_pending_window_change (0);
5069 /* Check for data from a process. */
5070 if (no_avail || nfds == 0)
5071 continue;
5073 for (channel = 0; channel <= max_input_desc; ++channel)
5075 struct fd_callback_data *d = &fd_callback_info[channel];
5076 if (d->func
5077 && ((d->condition & FOR_READ
5078 && FD_ISSET (channel, &Available))
5079 || (d->condition & FOR_WRITE
5080 && FD_ISSET (channel, &write_mask))))
5081 d->func (channel, d->data);
5084 for (channel = 0; channel <= max_process_desc; channel++)
5086 if (FD_ISSET (channel, &Available)
5087 && FD_ISSET (channel, &non_keyboard_wait_mask)
5088 && !FD_ISSET (channel, &non_process_wait_mask))
5090 int nread;
5092 /* If waiting for this channel, arrange to return as
5093 soon as no more input to be processed. No more
5094 waiting. */
5095 proc = chan_process[channel];
5096 if (NILP (proc))
5097 continue;
5099 /* If this is a server stream socket, accept connection. */
5100 if (EQ (XPROCESS (proc)->status, Qlisten))
5102 server_accept_connection (proc, channel);
5103 continue;
5106 /* Read data from the process, starting with our
5107 buffered-ahead character if we have one. */
5109 nread = read_process_output (proc, channel);
5110 if ((!wait_proc || wait_proc == XPROCESS (proc)) && got_some_input < nread)
5111 got_some_input = nread;
5112 if (nread > 0)
5114 /* Since read_process_output can run a filter,
5115 which can call accept-process-output,
5116 don't try to read from any other processes
5117 before doing the select again. */
5118 FD_ZERO (&Available);
5120 if (do_display)
5121 redisplay_preserve_echo_area (12);
5123 #ifdef EWOULDBLOCK
5124 else if (nread == -1 && errno == EWOULDBLOCK)
5126 #endif
5127 else if (nread == -1 && errno == EAGAIN)
5129 #ifdef WINDOWSNT
5130 /* FIXME: Is this special case still needed? */
5131 /* Note that we cannot distinguish between no input
5132 available now and a closed pipe.
5133 With luck, a closed pipe will be accompanied by
5134 subprocess termination and SIGCHLD. */
5135 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5136 && !PIPECONN_P (proc))
5138 #endif
5139 #ifdef HAVE_PTYS
5140 /* On some OSs with ptys, when the process on one end of
5141 a pty exits, the other end gets an error reading with
5142 errno = EIO instead of getting an EOF (0 bytes read).
5143 Therefore, if we get an error reading and errno =
5144 EIO, just continue, because the child process has
5145 exited and should clean itself up soon (e.g. when we
5146 get a SIGCHLD). */
5147 else if (nread == -1 && errno == EIO)
5149 struct Lisp_Process *p = XPROCESS (proc);
5151 /* Clear the descriptor now, so we only raise the
5152 signal once. */
5153 FD_CLR (channel, &input_wait_mask);
5154 FD_CLR (channel, &non_keyboard_wait_mask);
5156 if (p->pid == -2)
5158 /* If the EIO occurs on a pty, the SIGCHLD handler's
5159 waitpid call will not find the process object to
5160 delete. Do it here. */
5161 p->tick = ++process_tick;
5162 pset_status (p, Qfailed);
5165 #endif /* HAVE_PTYS */
5166 /* If we can detect process termination, don't consider the
5167 process gone just because its pipe is closed. */
5168 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5169 && !PIPECONN_P (proc))
5171 else if (nread == 0 && PIPECONN_P (proc))
5173 /* Preserve status of processes already terminated. */
5174 XPROCESS (proc)->tick = ++process_tick;
5175 deactivate_process (proc);
5176 if (EQ (XPROCESS (proc)->status, Qrun))
5177 pset_status (XPROCESS (proc),
5178 list2 (Qexit, make_number (0)));
5180 else
5182 /* Preserve status of processes already terminated. */
5183 XPROCESS (proc)->tick = ++process_tick;
5184 deactivate_process (proc);
5185 if (XPROCESS (proc)->raw_status_new)
5186 update_status (XPROCESS (proc));
5187 if (EQ (XPROCESS (proc)->status, Qrun))
5188 pset_status (XPROCESS (proc),
5189 list2 (Qexit, make_number (256)));
5192 #ifdef NON_BLOCKING_CONNECT
5193 if (FD_ISSET (channel, &Writeok)
5194 && FD_ISSET (channel, &connect_wait_mask))
5196 struct Lisp_Process *p;
5198 FD_CLR (channel, &connect_wait_mask);
5199 FD_CLR (channel, &write_mask);
5200 if (--num_pending_connects < 0)
5201 emacs_abort ();
5203 proc = chan_process[channel];
5204 if (NILP (proc))
5205 continue;
5207 p = XPROCESS (proc);
5209 #ifdef GNU_LINUX
5210 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5211 So only use it on systems where it is known to work. */
5213 socklen_t xlen = sizeof (xerrno);
5214 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5215 xerrno = errno;
5217 #else
5219 struct sockaddr pname;
5220 socklen_t pnamelen = sizeof (pname);
5222 /* If connection failed, getpeername will fail. */
5223 xerrno = 0;
5224 if (getpeername (channel, &pname, &pnamelen) < 0)
5226 /* Obtain connect failure code through error slippage. */
5227 char dummy;
5228 xerrno = errno;
5229 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5230 xerrno = errno;
5233 #endif
5234 if (xerrno)
5236 p->tick = ++process_tick;
5237 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5238 deactivate_process (proc);
5240 else
5242 pset_status (p, Qrun);
5243 /* Execute the sentinel here. If we had relied on
5244 status_notify to do it later, it will read input
5245 from the process before calling the sentinel. */
5246 exec_sentinel (proc, build_string ("open\n"));
5247 if (0 <= p->infd && !EQ (p->filter, Qt)
5248 && !EQ (p->command, Qt))
5250 FD_SET (p->infd, &input_wait_mask);
5251 FD_SET (p->infd, &non_keyboard_wait_mask);
5255 #endif /* NON_BLOCKING_CONNECT */
5256 } /* End for each file descriptor. */
5257 } /* End while exit conditions not met. */
5259 unbind_to (count, Qnil);
5261 /* If calling from keyboard input, do not quit
5262 since we want to return C-g as an input character.
5263 Otherwise, do pending quit if requested. */
5264 if (read_kbd >= 0)
5266 /* Prevent input_pending from remaining set if we quit. */
5267 clear_input_pending ();
5268 QUIT;
5271 return got_some_input;
5274 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5276 static Lisp_Object
5277 read_process_output_call (Lisp_Object fun_and_args)
5279 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5282 static Lisp_Object
5283 read_process_output_error_handler (Lisp_Object error_val)
5285 cmd_error_internal (error_val, "error in process filter: ");
5286 Vinhibit_quit = Qt;
5287 update_echo_area ();
5288 Fsleep_for (make_number (2), Qnil);
5289 return Qt;
5292 static void
5293 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5294 ssize_t nbytes,
5295 struct coding_system *coding);
5297 /* Read pending output from the process channel,
5298 starting with our buffered-ahead character if we have one.
5299 Yield number of decoded characters read.
5301 This function reads at most 4096 characters.
5302 If you want to read all available subprocess output,
5303 you must call it repeatedly until it returns zero.
5305 The characters read are decoded according to PROC's coding-system
5306 for decoding. */
5308 static int
5309 read_process_output (Lisp_Object proc, int channel)
5311 ssize_t nbytes;
5312 struct Lisp_Process *p = XPROCESS (proc);
5313 struct coding_system *coding = proc_decode_coding_system[channel];
5314 int carryover = p->decoding_carryover;
5315 enum { readmax = 4096 };
5316 ptrdiff_t count = SPECPDL_INDEX ();
5317 Lisp_Object odeactivate;
5318 char chars[sizeof coding->carryover + readmax];
5320 if (carryover)
5321 /* See the comment above. */
5322 memcpy (chars, SDATA (p->decoding_buf), carryover);
5324 #ifdef DATAGRAM_SOCKETS
5325 /* We have a working select, so proc_buffered_char is always -1. */
5326 if (DATAGRAM_CHAN_P (channel))
5328 socklen_t len = datagram_address[channel].len;
5329 nbytes = recvfrom (channel, chars + carryover, readmax,
5330 0, datagram_address[channel].sa, &len);
5332 else
5333 #endif
5335 bool buffered = proc_buffered_char[channel] >= 0;
5336 if (buffered)
5338 chars[carryover] = proc_buffered_char[channel];
5339 proc_buffered_char[channel] = -1;
5341 #ifdef HAVE_GNUTLS
5342 if (p->gnutls_p && p->gnutls_state)
5343 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5344 readmax - buffered);
5345 else
5346 #endif
5347 nbytes = emacs_read (channel, chars + carryover + buffered,
5348 readmax - buffered);
5349 #ifdef ADAPTIVE_READ_BUFFERING
5350 if (nbytes > 0 && p->adaptive_read_buffering)
5352 int delay = p->read_output_delay;
5353 if (nbytes < 256)
5355 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5357 if (delay == 0)
5358 process_output_delay_count++;
5359 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5362 else if (delay > 0 && nbytes == readmax - buffered)
5364 delay -= READ_OUTPUT_DELAY_INCREMENT;
5365 if (delay == 0)
5366 process_output_delay_count--;
5368 p->read_output_delay = delay;
5369 if (delay)
5371 p->read_output_skip = 1;
5372 process_output_skip = 1;
5375 #endif
5376 nbytes += buffered;
5377 nbytes += buffered && nbytes <= 0;
5380 p->decoding_carryover = 0;
5382 /* At this point, NBYTES holds number of bytes just received
5383 (including the one in proc_buffered_char[channel]). */
5384 if (nbytes <= 0)
5386 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5387 return nbytes;
5388 coding->mode |= CODING_MODE_LAST_BLOCK;
5391 /* Now set NBYTES how many bytes we must decode. */
5392 nbytes += carryover;
5394 odeactivate = Vdeactivate_mark;
5395 /* There's no good reason to let process filters change the current
5396 buffer, and many callers of accept-process-output, sit-for, and
5397 friends don't expect current-buffer to be changed from under them. */
5398 record_unwind_current_buffer ();
5400 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5402 /* Handling the process output should not deactivate the mark. */
5403 Vdeactivate_mark = odeactivate;
5405 unbind_to (count, Qnil);
5406 return nbytes;
5409 static void
5410 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5411 ssize_t nbytes,
5412 struct coding_system *coding)
5414 Lisp_Object outstream = p->filter;
5415 Lisp_Object text;
5416 bool outer_running_asynch_code = running_asynch_code;
5417 int waiting = waiting_for_user_input_p;
5419 /* No need to gcpro these, because all we do with them later
5420 is test them for EQness, and none of them should be a string. */
5421 #if 0
5422 Lisp_Object obuffer, okeymap;
5423 XSETBUFFER (obuffer, current_buffer);
5424 okeymap = BVAR (current_buffer, keymap);
5425 #endif
5427 /* We inhibit quit here instead of just catching it so that
5428 hitting ^G when a filter happens to be running won't screw
5429 it up. */
5430 specbind (Qinhibit_quit, Qt);
5431 specbind (Qlast_nonmenu_event, Qt);
5433 /* In case we get recursively called,
5434 and we already saved the match data nonrecursively,
5435 save the same match data in safely recursive fashion. */
5436 if (outer_running_asynch_code)
5438 Lisp_Object tem;
5439 /* Don't clobber the CURRENT match data, either! */
5440 tem = Fmatch_data (Qnil, Qnil, Qnil);
5441 restore_search_regs ();
5442 record_unwind_save_match_data ();
5443 Fset_match_data (tem, Qt);
5446 /* For speed, if a search happens within this code,
5447 save the match data in a special nonrecursive fashion. */
5448 running_asynch_code = 1;
5450 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5451 text = coding->dst_object;
5452 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5453 /* A new coding system might be found. */
5454 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5456 pset_decode_coding_system (p, Vlast_coding_system_used);
5458 /* Don't call setup_coding_system for
5459 proc_decode_coding_system[channel] here. It is done in
5460 detect_coding called via decode_coding above. */
5462 /* If a coding system for encoding is not yet decided, we set
5463 it as the same as coding-system for decoding.
5465 But, before doing that we must check if
5466 proc_encode_coding_system[p->outfd] surely points to a
5467 valid memory because p->outfd will be changed once EOF is
5468 sent to the process. */
5469 if (NILP (p->encode_coding_system) && p->outfd >= 0
5470 && proc_encode_coding_system[p->outfd])
5472 pset_encode_coding_system
5473 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5474 setup_coding_system (p->encode_coding_system,
5475 proc_encode_coding_system[p->outfd]);
5479 if (coding->carryover_bytes > 0)
5481 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5482 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5483 memcpy (SDATA (p->decoding_buf), coding->carryover,
5484 coding->carryover_bytes);
5485 p->decoding_carryover = coding->carryover_bytes;
5487 if (SBYTES (text) > 0)
5488 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5489 sometimes it's simply wrong to wrap (e.g. when called from
5490 accept-process-output). */
5491 internal_condition_case_1 (read_process_output_call,
5492 list3 (outstream, make_lisp_proc (p), text),
5493 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5494 read_process_output_error_handler);
5496 /* If we saved the match data nonrecursively, restore it now. */
5497 restore_search_regs ();
5498 running_asynch_code = outer_running_asynch_code;
5500 /* Restore waiting_for_user_input_p as it was
5501 when we were called, in case the filter clobbered it. */
5502 waiting_for_user_input_p = waiting;
5504 #if 0 /* Call record_asynch_buffer_change unconditionally,
5505 because we might have changed minor modes or other things
5506 that affect key bindings. */
5507 if (! EQ (Fcurrent_buffer (), obuffer)
5508 || ! EQ (current_buffer->keymap, okeymap))
5509 #endif
5510 /* But do it only if the caller is actually going to read events.
5511 Otherwise there's no need to make him wake up, and it could
5512 cause trouble (for example it would make sit_for return). */
5513 if (waiting_for_user_input_p == -1)
5514 record_asynch_buffer_change ();
5517 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5518 Sinternal_default_process_filter, 2, 2, 0,
5519 doc: /* Function used as default process filter.
5520 This inserts the process's output into its buffer, if there is one.
5521 Otherwise it discards the output. */)
5522 (Lisp_Object proc, Lisp_Object text)
5524 struct Lisp_Process *p;
5525 ptrdiff_t opoint;
5527 CHECK_PROCESS (proc);
5528 p = XPROCESS (proc);
5529 CHECK_STRING (text);
5531 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5533 Lisp_Object old_read_only;
5534 ptrdiff_t old_begv, old_zv;
5535 ptrdiff_t old_begv_byte, old_zv_byte;
5536 ptrdiff_t before, before_byte;
5537 ptrdiff_t opoint_byte;
5538 struct buffer *b;
5540 Fset_buffer (p->buffer);
5541 opoint = PT;
5542 opoint_byte = PT_BYTE;
5543 old_read_only = BVAR (current_buffer, read_only);
5544 old_begv = BEGV;
5545 old_zv = ZV;
5546 old_begv_byte = BEGV_BYTE;
5547 old_zv_byte = ZV_BYTE;
5549 bset_read_only (current_buffer, Qnil);
5551 /* Insert new output into buffer at the current end-of-output
5552 marker, thus preserving logical ordering of input and output. */
5553 if (XMARKER (p->mark)->buffer)
5554 set_point_from_marker (p->mark);
5555 else
5556 SET_PT_BOTH (ZV, ZV_BYTE);
5557 before = PT;
5558 before_byte = PT_BYTE;
5560 /* If the output marker is outside of the visible region, save
5561 the restriction and widen. */
5562 if (! (BEGV <= PT && PT <= ZV))
5563 Fwiden ();
5565 /* Adjust the multibyteness of TEXT to that of the buffer. */
5566 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5567 != ! STRING_MULTIBYTE (text))
5568 text = (STRING_MULTIBYTE (text)
5569 ? Fstring_as_unibyte (text)
5570 : Fstring_to_multibyte (text));
5571 /* Insert before markers in case we are inserting where
5572 the buffer's mark is, and the user's next command is Meta-y. */
5573 insert_from_string_before_markers (text, 0, 0,
5574 SCHARS (text), SBYTES (text), 0);
5576 /* Make sure the process marker's position is valid when the
5577 process buffer is changed in the signal_after_change above.
5578 W3 is known to do that. */
5579 if (BUFFERP (p->buffer)
5580 && (b = XBUFFER (p->buffer), b != current_buffer))
5581 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5582 else
5583 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5585 update_mode_lines = 23;
5587 /* Make sure opoint and the old restrictions
5588 float ahead of any new text just as point would. */
5589 if (opoint >= before)
5591 opoint += PT - before;
5592 opoint_byte += PT_BYTE - before_byte;
5594 if (old_begv > before)
5596 old_begv += PT - before;
5597 old_begv_byte += PT_BYTE - before_byte;
5599 if (old_zv >= before)
5601 old_zv += PT - before;
5602 old_zv_byte += PT_BYTE - before_byte;
5605 /* If the restriction isn't what it should be, set it. */
5606 if (old_begv != BEGV || old_zv != ZV)
5607 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5609 bset_read_only (current_buffer, old_read_only);
5610 SET_PT_BOTH (opoint, opoint_byte);
5612 return Qnil;
5615 /* Sending data to subprocess. */
5617 /* In send_process, when a write fails temporarily,
5618 wait_reading_process_output is called. It may execute user code,
5619 e.g. timers, that attempts to write new data to the same process.
5620 We must ensure that data is sent in the right order, and not
5621 interspersed half-completed with other writes (Bug#10815). This is
5622 handled by the write_queue element of struct process. It is a list
5623 with each entry having the form
5625 (string . (offset . length))
5627 where STRING is a lisp string, OFFSET is the offset into the
5628 string's byte sequence from which we should begin to send, and
5629 LENGTH is the number of bytes left to send. */
5631 /* Create a new entry in write_queue.
5632 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5633 BUF is a pointer to the string sequence of the input_obj or a C
5634 string in case of Qt or Qnil. */
5636 static void
5637 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5638 const char *buf, ptrdiff_t len, bool front)
5640 ptrdiff_t offset;
5641 Lisp_Object entry, obj;
5643 if (STRINGP (input_obj))
5645 offset = buf - SSDATA (input_obj);
5646 obj = input_obj;
5648 else
5650 offset = 0;
5651 obj = make_unibyte_string (buf, len);
5654 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5656 if (front)
5657 pset_write_queue (p, Fcons (entry, p->write_queue));
5658 else
5659 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5662 /* Remove the first element in the write_queue of process P, put its
5663 contents in OBJ, BUF and LEN, and return true. If the
5664 write_queue is empty, return false. */
5666 static bool
5667 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5668 const char **buf, ptrdiff_t *len)
5670 Lisp_Object entry, offset_length;
5671 ptrdiff_t offset;
5673 if (NILP (p->write_queue))
5674 return 0;
5676 entry = XCAR (p->write_queue);
5677 pset_write_queue (p, XCDR (p->write_queue));
5679 *obj = XCAR (entry);
5680 offset_length = XCDR (entry);
5682 *len = XINT (XCDR (offset_length));
5683 offset = XINT (XCAR (offset_length));
5684 *buf = SSDATA (*obj) + offset;
5686 return 1;
5689 /* Send some data to process PROC.
5690 BUF is the beginning of the data; LEN is the number of characters.
5691 OBJECT is the Lisp object that the data comes from. If OBJECT is
5692 nil or t, it means that the data comes from C string.
5694 If OBJECT is not nil, the data is encoded by PROC's coding-system
5695 for encoding before it is sent.
5697 This function can evaluate Lisp code and can garbage collect. */
5699 static void
5700 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5701 Lisp_Object object)
5703 struct Lisp_Process *p = XPROCESS (proc);
5704 ssize_t rv;
5705 struct coding_system *coding;
5707 if (p->raw_status_new)
5708 update_status (p);
5709 if (! EQ (p->status, Qrun))
5710 error ("Process %s not running", SDATA (p->name));
5711 if (p->outfd < 0)
5712 error ("Output file descriptor of %s is closed", SDATA (p->name));
5714 coding = proc_encode_coding_system[p->outfd];
5715 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5717 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5718 || (BUFFERP (object)
5719 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5720 || EQ (object, Qt))
5722 pset_encode_coding_system
5723 (p, complement_process_encoding_system (p->encode_coding_system));
5724 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5726 /* The coding system for encoding was changed to raw-text
5727 because we sent a unibyte text previously. Now we are
5728 sending a multibyte text, thus we must encode it by the
5729 original coding system specified for the current process.
5731 Another reason we come here is that the coding system
5732 was just complemented and a new one was returned by
5733 complement_process_encoding_system. */
5734 setup_coding_system (p->encode_coding_system, coding);
5735 Vlast_coding_system_used = p->encode_coding_system;
5737 coding->src_multibyte = 1;
5739 else
5741 coding->src_multibyte = 0;
5742 /* For sending a unibyte text, character code conversion should
5743 not take place but EOL conversion should. So, setup raw-text
5744 or one of the subsidiary if we have not yet done it. */
5745 if (CODING_REQUIRE_ENCODING (coding))
5747 if (CODING_REQUIRE_FLUSHING (coding))
5749 /* But, before changing the coding, we must flush out data. */
5750 coding->mode |= CODING_MODE_LAST_BLOCK;
5751 send_process (proc, "", 0, Qt);
5752 coding->mode &= CODING_MODE_LAST_BLOCK;
5754 setup_coding_system (raw_text_coding_system
5755 (Vlast_coding_system_used),
5756 coding);
5757 coding->src_multibyte = 0;
5760 coding->dst_multibyte = 0;
5762 if (CODING_REQUIRE_ENCODING (coding))
5764 coding->dst_object = Qt;
5765 if (BUFFERP (object))
5767 ptrdiff_t from_byte, from, to;
5768 ptrdiff_t save_pt, save_pt_byte;
5769 struct buffer *cur = current_buffer;
5771 set_buffer_internal (XBUFFER (object));
5772 save_pt = PT, save_pt_byte = PT_BYTE;
5774 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5775 from = BYTE_TO_CHAR (from_byte);
5776 to = BYTE_TO_CHAR (from_byte + len);
5777 TEMP_SET_PT_BOTH (from, from_byte);
5778 encode_coding_object (coding, object, from, from_byte,
5779 to, from_byte + len, Qt);
5780 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5781 set_buffer_internal (cur);
5783 else if (STRINGP (object))
5785 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5786 SBYTES (object), Qt);
5788 else
5790 coding->dst_object = make_unibyte_string (buf, len);
5791 coding->produced = len;
5794 len = coding->produced;
5795 object = coding->dst_object;
5796 buf = SSDATA (object);
5799 /* If there is already data in the write_queue, put the new data
5800 in the back of queue. Otherwise, ignore it. */
5801 if (!NILP (p->write_queue))
5802 write_queue_push (p, object, buf, len, 0);
5804 do /* while !NILP (p->write_queue) */
5806 ptrdiff_t cur_len = -1;
5807 const char *cur_buf;
5808 Lisp_Object cur_object;
5810 /* If write_queue is empty, ignore it. */
5811 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5813 cur_len = len;
5814 cur_buf = buf;
5815 cur_object = object;
5818 while (cur_len > 0)
5820 /* Send this batch, using one or more write calls. */
5821 ptrdiff_t written = 0;
5822 int outfd = p->outfd;
5823 #ifdef DATAGRAM_SOCKETS
5824 if (DATAGRAM_CHAN_P (outfd))
5826 rv = sendto (outfd, cur_buf, cur_len,
5827 0, datagram_address[outfd].sa,
5828 datagram_address[outfd].len);
5829 if (rv >= 0)
5830 written = rv;
5831 else if (errno == EMSGSIZE)
5832 report_file_error ("Sending datagram", proc);
5834 else
5835 #endif
5837 #ifdef HAVE_GNUTLS
5838 if (p->gnutls_p && p->gnutls_state)
5839 written = emacs_gnutls_write (p, cur_buf, cur_len);
5840 else
5841 #endif
5842 written = emacs_write_sig (outfd, cur_buf, cur_len);
5843 rv = (written ? 0 : -1);
5844 #ifdef ADAPTIVE_READ_BUFFERING
5845 if (p->read_output_delay > 0
5846 && p->adaptive_read_buffering == 1)
5848 p->read_output_delay = 0;
5849 process_output_delay_count--;
5850 p->read_output_skip = 0;
5852 #endif
5855 if (rv < 0)
5857 if (errno == EAGAIN
5858 #ifdef EWOULDBLOCK
5859 || errno == EWOULDBLOCK
5860 #endif
5862 /* Buffer is full. Wait, accepting input;
5863 that may allow the program
5864 to finish doing output and read more. */
5866 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5867 /* A gross hack to work around a bug in FreeBSD.
5868 In the following sequence, read(2) returns
5869 bogus data:
5871 write(2) 1022 bytes
5872 write(2) 954 bytes, get EAGAIN
5873 read(2) 1024 bytes in process_read_output
5874 read(2) 11 bytes in process_read_output
5876 That is, read(2) returns more bytes than have
5877 ever been written successfully. The 1033 bytes
5878 read are the 1022 bytes written successfully
5879 after processing (for example with CRs added if
5880 the terminal is set up that way which it is
5881 here). The same bytes will be seen again in a
5882 later read(2), without the CRs. */
5884 if (errno == EAGAIN)
5886 int flags = FWRITE;
5887 ioctl (p->outfd, TIOCFLUSH, &flags);
5889 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5891 /* Put what we should have written in wait_queue. */
5892 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5893 wait_reading_process_output (0, 20 * 1000 * 1000,
5894 0, 0, Qnil, NULL, 0);
5895 /* Reread queue, to see what is left. */
5896 break;
5898 else if (errno == EPIPE)
5900 p->raw_status_new = 0;
5901 pset_status (p, list2 (Qexit, make_number (256)));
5902 p->tick = ++process_tick;
5903 deactivate_process (proc);
5904 error ("process %s no longer connected to pipe; closed it",
5905 SDATA (p->name));
5907 else
5908 /* This is a real error. */
5909 report_file_error ("Writing to process", proc);
5911 cur_buf += written;
5912 cur_len -= written;
5915 while (!NILP (p->write_queue));
5918 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5919 3, 3, 0,
5920 doc: /* Send current contents of region as input to PROCESS.
5921 PROCESS may be a process, a buffer, the name of a process or buffer, or
5922 nil, indicating the current buffer's process.
5923 Called from program, takes three arguments, PROCESS, START and END.
5924 If the region is more than 500 characters long,
5925 it is sent in several bunches. This may happen even for shorter regions.
5926 Output from processes can arrive in between bunches. */)
5927 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5929 Lisp_Object proc = get_process (process);
5930 ptrdiff_t start_byte, end_byte;
5932 validate_region (&start, &end);
5934 start_byte = CHAR_TO_BYTE (XINT (start));
5935 end_byte = CHAR_TO_BYTE (XINT (end));
5937 if (XINT (start) < GPT && XINT (end) > GPT)
5938 move_gap_both (XINT (start), start_byte);
5940 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5941 end_byte - start_byte, Fcurrent_buffer ());
5943 return Qnil;
5946 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5947 2, 2, 0,
5948 doc: /* Send PROCESS the contents of STRING as input.
5949 PROCESS may be a process, a buffer, the name of a process or buffer, or
5950 nil, indicating the current buffer's process.
5951 If STRING is more than 500 characters long,
5952 it is sent in several bunches. This may happen even for shorter strings.
5953 Output from processes can arrive in between bunches. */)
5954 (Lisp_Object process, Lisp_Object string)
5956 Lisp_Object proc;
5957 CHECK_STRING (string);
5958 proc = get_process (process);
5959 send_process (proc, SSDATA (string),
5960 SBYTES (string), string);
5961 return Qnil;
5964 /* Return the foreground process group for the tty/pty that
5965 the process P uses. */
5966 static pid_t
5967 emacs_get_tty_pgrp (struct Lisp_Process *p)
5969 pid_t gid = -1;
5971 #ifdef TIOCGPGRP
5972 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5974 int fd;
5975 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5976 master side. Try the slave side. */
5977 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5979 if (fd != -1)
5981 ioctl (fd, TIOCGPGRP, &gid);
5982 emacs_close (fd);
5985 #endif /* defined (TIOCGPGRP ) */
5987 return gid;
5990 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5991 Sprocess_running_child_p, 0, 1, 0,
5992 doc: /* Return non-nil if PROCESS has given the terminal to a
5993 child. If the operating system does not make it possible to find out,
5994 return t. If we can find out, return the numeric ID of the foreground
5995 process group. */)
5996 (Lisp_Object process)
5998 /* Initialize in case ioctl doesn't exist or gives an error,
5999 in a way that will cause returning t. */
6000 pid_t gid;
6001 Lisp_Object proc;
6002 struct Lisp_Process *p;
6004 proc = get_process (process);
6005 p = XPROCESS (proc);
6007 if (!EQ (p->type, Qreal))
6008 error ("Process %s is not a subprocess",
6009 SDATA (p->name));
6010 if (p->infd < 0)
6011 error ("Process %s is not active",
6012 SDATA (p->name));
6014 gid = emacs_get_tty_pgrp (p);
6016 if (gid == p->pid)
6017 return Qnil;
6018 if (gid != -1)
6019 return make_number (gid);
6020 return Qt;
6023 /* Send a signal number SIGNO to PROCESS.
6024 If CURRENT_GROUP is t, that means send to the process group
6025 that currently owns the terminal being used to communicate with PROCESS.
6026 This is used for various commands in shell mode.
6027 If CURRENT_GROUP is lambda, that means send to the process group
6028 that currently owns the terminal, but only if it is NOT the shell itself.
6030 If NOMSG is false, insert signal-announcements into process's buffers
6031 right away.
6033 If we can, we try to signal PROCESS by sending control characters
6034 down the pty. This allows us to signal inferiors who have changed
6035 their uid, for which kill would return an EPERM error. */
6037 static void
6038 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
6039 bool nomsg)
6041 Lisp_Object proc;
6042 struct Lisp_Process *p;
6043 pid_t gid;
6044 bool no_pgrp = 0;
6046 proc = get_process (process);
6047 p = XPROCESS (proc);
6049 if (!EQ (p->type, Qreal))
6050 error ("Process %s is not a subprocess",
6051 SDATA (p->name));
6052 if (p->infd < 0)
6053 error ("Process %s is not active",
6054 SDATA (p->name));
6056 if (!p->pty_flag)
6057 current_group = Qnil;
6059 /* If we are using pgrps, get a pgrp number and make it negative. */
6060 if (NILP (current_group))
6061 /* Send the signal to the shell's process group. */
6062 gid = p->pid;
6063 else
6065 #ifdef SIGNALS_VIA_CHARACTERS
6066 /* If possible, send signals to the entire pgrp
6067 by sending an input character to it. */
6069 struct termios t;
6070 cc_t *sig_char = NULL;
6072 tcgetattr (p->infd, &t);
6074 switch (signo)
6076 case SIGINT:
6077 sig_char = &t.c_cc[VINTR];
6078 break;
6080 case SIGQUIT:
6081 sig_char = &t.c_cc[VQUIT];
6082 break;
6084 case SIGTSTP:
6085 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6086 sig_char = &t.c_cc[VSWTCH];
6087 #else
6088 sig_char = &t.c_cc[VSUSP];
6089 #endif
6090 break;
6093 if (sig_char && *sig_char != CDISABLE)
6095 send_process (proc, (char *) sig_char, 1, Qnil);
6096 return;
6098 /* If we can't send the signal with a character,
6099 fall through and send it another way. */
6101 /* The code above may fall through if it can't
6102 handle the signal. */
6103 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6105 #ifdef TIOCGPGRP
6106 /* Get the current pgrp using the tty itself, if we have that.
6107 Otherwise, use the pty to get the pgrp.
6108 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6109 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6110 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6111 His patch indicates that if TIOCGPGRP returns an error, then
6112 we should just assume that p->pid is also the process group id. */
6114 gid = emacs_get_tty_pgrp (p);
6116 if (gid == -1)
6117 /* If we can't get the information, assume
6118 the shell owns the tty. */
6119 gid = p->pid;
6121 /* It is not clear whether anything really can set GID to -1.
6122 Perhaps on some system one of those ioctls can or could do so.
6123 Or perhaps this is vestigial. */
6124 if (gid == -1)
6125 no_pgrp = 1;
6126 #else /* ! defined (TIOCGPGRP) */
6127 /* Can't select pgrps on this system, so we know that
6128 the child itself heads the pgrp. */
6129 gid = p->pid;
6130 #endif /* ! defined (TIOCGPGRP) */
6132 /* If current_group is lambda, and the shell owns the terminal,
6133 don't send any signal. */
6134 if (EQ (current_group, Qlambda) && gid == p->pid)
6135 return;
6138 #ifdef SIGCONT
6139 if (signo == SIGCONT)
6141 p->raw_status_new = 0;
6142 pset_status (p, Qrun);
6143 p->tick = ++process_tick;
6144 if (!nomsg)
6146 status_notify (NULL, NULL);
6147 redisplay_preserve_echo_area (13);
6150 #endif
6152 #ifdef TIOCSIGSEND
6153 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6154 We don't know whether the bug is fixed in later HP-UX versions. */
6155 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6156 return;
6157 #endif
6159 /* If we don't have process groups, send the signal to the immediate
6160 subprocess. That isn't really right, but it's better than any
6161 obvious alternative. */
6162 pid_t pid = no_pgrp ? gid : - gid;
6164 /* Do not kill an already-reaped process, as that could kill an
6165 innocent bystander that happens to have the same process ID. */
6166 sigset_t oldset;
6167 block_child_signal (&oldset);
6168 if (p->alive)
6169 kill (pid, signo);
6170 unblock_child_signal (&oldset);
6173 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6174 doc: /* Interrupt process PROCESS.
6175 PROCESS may be a process, a buffer, or the name of a process or buffer.
6176 No arg or nil means current buffer's process.
6177 Second arg CURRENT-GROUP non-nil means send signal to
6178 the current process-group of the process's controlling terminal
6179 rather than to the process's own process group.
6180 If the process is a shell, this means interrupt current subjob
6181 rather than the shell.
6183 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6184 don't send the signal. */)
6185 (Lisp_Object process, Lisp_Object current_group)
6187 process_send_signal (process, SIGINT, current_group, 0);
6188 return process;
6191 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6192 doc: /* Kill process PROCESS. May be process or name of one.
6193 See function `interrupt-process' for more details on usage. */)
6194 (Lisp_Object process, Lisp_Object current_group)
6196 process_send_signal (process, SIGKILL, current_group, 0);
6197 return process;
6200 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6201 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6202 See function `interrupt-process' for more details on usage. */)
6203 (Lisp_Object process, Lisp_Object current_group)
6205 process_send_signal (process, SIGQUIT, current_group, 0);
6206 return process;
6209 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6210 doc: /* Stop process PROCESS. May be process or name of one.
6211 See function `interrupt-process' for more details on usage.
6212 If PROCESS is a network or serial process, inhibit handling of incoming
6213 traffic. */)
6214 (Lisp_Object process, Lisp_Object current_group)
6216 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6217 || PIPECONN_P (process)))
6219 struct Lisp_Process *p;
6221 p = XPROCESS (process);
6222 if (NILP (p->command)
6223 && p->infd >= 0)
6225 FD_CLR (p->infd, &input_wait_mask);
6226 FD_CLR (p->infd, &non_keyboard_wait_mask);
6228 pset_command (p, Qt);
6229 return process;
6231 #ifndef SIGTSTP
6232 error ("No SIGTSTP support");
6233 #else
6234 process_send_signal (process, SIGTSTP, current_group, 0);
6235 #endif
6236 return process;
6239 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6240 doc: /* Continue process PROCESS. May be process or name of one.
6241 See function `interrupt-process' for more details on usage.
6242 If PROCESS is a network or serial process, resume handling of incoming
6243 traffic. */)
6244 (Lisp_Object process, Lisp_Object current_group)
6246 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6247 || PIPECONN_P (process)))
6249 struct Lisp_Process *p;
6251 p = XPROCESS (process);
6252 if (EQ (p->command, Qt)
6253 && p->infd >= 0
6254 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6256 FD_SET (p->infd, &input_wait_mask);
6257 FD_SET (p->infd, &non_keyboard_wait_mask);
6258 #ifdef WINDOWSNT
6259 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6260 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6261 #else /* not WINDOWSNT */
6262 tcflush (p->infd, TCIFLUSH);
6263 #endif /* not WINDOWSNT */
6265 pset_command (p, Qnil);
6266 return process;
6268 #ifdef SIGCONT
6269 process_send_signal (process, SIGCONT, current_group, 0);
6270 #else
6271 error ("No SIGCONT support");
6272 #endif
6273 return process;
6276 /* Return the integer value of the signal whose abbreviation is ABBR,
6277 or a negative number if there is no such signal. */
6278 static int
6279 abbr_to_signal (char const *name)
6281 int i, signo;
6282 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6284 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6285 name += 3;
6287 for (i = 0; i < sizeof sigbuf; i++)
6289 sigbuf[i] = c_toupper (name[i]);
6290 if (! sigbuf[i])
6291 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6294 return -1;
6297 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6298 2, 2, "sProcess (name or number): \nnSignal code: ",
6299 doc: /* Send PROCESS the signal with code SIGCODE.
6300 PROCESS may also be a number specifying the process id of the
6301 process to signal; in this case, the process need not be a child of
6302 this Emacs.
6303 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6304 (Lisp_Object process, Lisp_Object sigcode)
6306 pid_t pid;
6307 int signo;
6309 if (STRINGP (process))
6311 Lisp_Object tem = Fget_process (process);
6312 if (NILP (tem))
6314 Lisp_Object process_number
6315 = string_to_number (SSDATA (process), 10, 1);
6316 if (INTEGERP (process_number) || FLOATP (process_number))
6317 tem = process_number;
6319 process = tem;
6321 else if (!NUMBERP (process))
6322 process = get_process (process);
6324 if (NILP (process))
6325 return process;
6327 if (NUMBERP (process))
6328 CONS_TO_INTEGER (process, pid_t, pid);
6329 else
6331 CHECK_PROCESS (process);
6332 pid = XPROCESS (process)->pid;
6333 if (pid <= 0)
6334 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6337 if (INTEGERP (sigcode))
6339 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6340 signo = XINT (sigcode);
6342 else
6344 char *name;
6346 CHECK_SYMBOL (sigcode);
6347 name = SSDATA (SYMBOL_NAME (sigcode));
6349 signo = abbr_to_signal (name);
6350 if (signo < 0)
6351 error ("Undefined signal name %s", name);
6354 return make_number (kill (pid, signo));
6357 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6358 doc: /* Make PROCESS see end-of-file in its input.
6359 EOF comes after any text already sent to it.
6360 PROCESS may be a process, a buffer, the name of a process or buffer, or
6361 nil, indicating the current buffer's process.
6362 If PROCESS is a network connection, or is a process communicating
6363 through a pipe (as opposed to a pty), then you cannot send any more
6364 text to PROCESS after you call this function.
6365 If PROCESS is a serial process, wait until all output written to the
6366 process has been transmitted to the serial port. */)
6367 (Lisp_Object process)
6369 Lisp_Object proc;
6370 struct coding_system *coding = NULL;
6371 int outfd;
6373 if (DATAGRAM_CONN_P (process))
6374 return process;
6376 proc = get_process (process);
6377 outfd = XPROCESS (proc)->outfd;
6378 if (outfd >= 0)
6379 coding = proc_encode_coding_system[outfd];
6381 /* Make sure the process is really alive. */
6382 if (XPROCESS (proc)->raw_status_new)
6383 update_status (XPROCESS (proc));
6384 if (! EQ (XPROCESS (proc)->status, Qrun))
6385 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6387 if (coding && CODING_REQUIRE_FLUSHING (coding))
6389 coding->mode |= CODING_MODE_LAST_BLOCK;
6390 send_process (proc, "", 0, Qnil);
6393 if (XPROCESS (proc)->pty_flag)
6394 send_process (proc, "\004", 1, Qnil);
6395 else if (EQ (XPROCESS (proc)->type, Qserial))
6397 #ifndef WINDOWSNT
6398 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6399 report_file_error ("Failed tcdrain", Qnil);
6400 #endif /* not WINDOWSNT */
6401 /* Do nothing on Windows because writes are blocking. */
6403 else
6405 struct Lisp_Process *p = XPROCESS (proc);
6406 int old_outfd = p->outfd;
6407 int new_outfd;
6409 #ifdef HAVE_SHUTDOWN
6410 /* If this is a network connection, or socketpair is used
6411 for communication with the subprocess, call shutdown to cause EOF.
6412 (In some old system, shutdown to socketpair doesn't work.
6413 Then we just can't win.) */
6414 if (0 <= old_outfd
6415 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6416 shutdown (old_outfd, 1);
6417 #endif
6418 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6419 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6420 if (new_outfd < 0)
6421 report_file_error ("Opening null device", Qnil);
6422 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6423 p->outfd = new_outfd;
6425 if (!proc_encode_coding_system[new_outfd])
6426 proc_encode_coding_system[new_outfd]
6427 = xmalloc (sizeof (struct coding_system));
6428 if (old_outfd >= 0)
6430 *proc_encode_coding_system[new_outfd]
6431 = *proc_encode_coding_system[old_outfd];
6432 memset (proc_encode_coding_system[old_outfd], 0,
6433 sizeof (struct coding_system));
6435 else
6436 setup_coding_system (p->encode_coding_system,
6437 proc_encode_coding_system[new_outfd]);
6439 return process;
6442 /* The main Emacs thread records child processes in three places:
6444 - Vprocess_alist, for asynchronous subprocesses, which are child
6445 processes visible to Lisp.
6447 - deleted_pid_list, for child processes invisible to Lisp,
6448 typically because of delete-process. These are recorded so that
6449 the processes can be reaped when they exit, so that the operating
6450 system's process table is not cluttered by zombies.
6452 - the local variable PID in Fcall_process, call_process_cleanup and
6453 call_process_kill, for synchronous subprocesses.
6454 record_unwind_protect is used to make sure this process is not
6455 forgotten: if the user interrupts call-process and the child
6456 process refuses to exit immediately even with two C-g's,
6457 call_process_kill adds PID's contents to deleted_pid_list before
6458 returning.
6460 The main Emacs thread invokes waitpid only on child processes that
6461 it creates and that have not been reaped. This avoid races on
6462 platforms such as GTK, where other threads create their own
6463 subprocesses which the main thread should not reap. For example,
6464 if the main thread attempted to reap an already-reaped child, it
6465 might inadvertently reap a GTK-created process that happened to
6466 have the same process ID. */
6468 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6469 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6470 keep track of its own children. GNUstep is similar. */
6472 static void dummy_handler (int sig) {}
6473 static signal_handler_t volatile lib_child_handler;
6475 /* Handle a SIGCHLD signal by looking for known child processes of
6476 Emacs whose status have changed. For each one found, record its
6477 new status.
6479 All we do is change the status; we do not run sentinels or print
6480 notifications. That is saved for the next time keyboard input is
6481 done, in order to avoid timing errors.
6483 ** WARNING: this can be called during garbage collection.
6484 Therefore, it must not be fooled by the presence of mark bits in
6485 Lisp objects.
6487 ** USG WARNING: Although it is not obvious from the documentation
6488 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6489 signal() before executing at least one wait(), otherwise the
6490 handler will be called again, resulting in an infinite loop. The
6491 relevant portion of the documentation reads "SIGCLD signals will be
6492 queued and the signal-catching function will be continually
6493 reentered until the queue is empty". Invoking signal() causes the
6494 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6495 Inc.
6497 ** Malloc WARNING: This should never call malloc either directly or
6498 indirectly; if it does, that is a bug. */
6500 static void
6501 handle_child_signal (int sig)
6503 Lisp_Object tail, proc;
6505 /* Find the process that signaled us, and record its status. */
6507 /* The process can have been deleted by Fdelete_process, or have
6508 been started asynchronously by Fcall_process. */
6509 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6511 bool all_pids_are_fixnums
6512 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6513 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6514 Lisp_Object head = XCAR (tail);
6515 Lisp_Object xpid;
6516 if (! CONSP (head))
6517 continue;
6518 xpid = XCAR (head);
6519 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6521 pid_t deleted_pid;
6522 if (INTEGERP (xpid))
6523 deleted_pid = XINT (xpid);
6524 else
6525 deleted_pid = XFLOAT_DATA (xpid);
6526 if (child_status_changed (deleted_pid, 0, 0))
6528 if (STRINGP (XCDR (head)))
6529 unlink (SSDATA (XCDR (head)));
6530 XSETCAR (tail, Qnil);
6535 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6536 FOR_EACH_PROCESS (tail, proc)
6538 struct Lisp_Process *p = XPROCESS (proc);
6539 int status;
6541 if (p->alive
6542 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6544 /* Change the status of the process that was found. */
6545 p->tick = ++process_tick;
6546 p->raw_status = status;
6547 p->raw_status_new = 1;
6549 /* If process has terminated, stop waiting for its output. */
6550 if (WIFSIGNALED (status) || WIFEXITED (status))
6552 bool clear_desc_flag = 0;
6553 p->alive = 0;
6554 if (p->infd >= 0)
6555 clear_desc_flag = 1;
6557 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6558 if (clear_desc_flag)
6560 FD_CLR (p->infd, &input_wait_mask);
6561 FD_CLR (p->infd, &non_keyboard_wait_mask);
6567 lib_child_handler (sig);
6568 #ifdef NS_IMPL_GNUSTEP
6569 /* NSTask in GNUstep sets its child handler each time it is called.
6570 So we must re-set ours. */
6571 catch_child_signal ();
6572 #endif
6575 static void
6576 deliver_child_signal (int sig)
6578 deliver_process_signal (sig, handle_child_signal);
6582 static Lisp_Object
6583 exec_sentinel_error_handler (Lisp_Object error_val)
6585 cmd_error_internal (error_val, "error in process sentinel: ");
6586 Vinhibit_quit = Qt;
6587 update_echo_area ();
6588 Fsleep_for (make_number (2), Qnil);
6589 return Qt;
6592 static void
6593 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6595 Lisp_Object sentinel, odeactivate;
6596 struct Lisp_Process *p = XPROCESS (proc);
6597 ptrdiff_t count = SPECPDL_INDEX ();
6598 bool outer_running_asynch_code = running_asynch_code;
6599 int waiting = waiting_for_user_input_p;
6601 if (inhibit_sentinels)
6602 return;
6604 /* No need to gcpro these, because all we do with them later
6605 is test them for EQness, and none of them should be a string. */
6606 odeactivate = Vdeactivate_mark;
6607 #if 0
6608 Lisp_Object obuffer, okeymap;
6609 XSETBUFFER (obuffer, current_buffer);
6610 okeymap = BVAR (current_buffer, keymap);
6611 #endif
6613 /* There's no good reason to let sentinels change the current
6614 buffer, and many callers of accept-process-output, sit-for, and
6615 friends don't expect current-buffer to be changed from under them. */
6616 record_unwind_current_buffer ();
6618 sentinel = p->sentinel;
6620 /* Inhibit quit so that random quits don't screw up a running filter. */
6621 specbind (Qinhibit_quit, Qt);
6622 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6624 /* In case we get recursively called,
6625 and we already saved the match data nonrecursively,
6626 save the same match data in safely recursive fashion. */
6627 if (outer_running_asynch_code)
6629 Lisp_Object tem;
6630 tem = Fmatch_data (Qnil, Qnil, Qnil);
6631 restore_search_regs ();
6632 record_unwind_save_match_data ();
6633 Fset_match_data (tem, Qt);
6636 /* For speed, if a search happens within this code,
6637 save the match data in a special nonrecursive fashion. */
6638 running_asynch_code = 1;
6640 internal_condition_case_1 (read_process_output_call,
6641 list3 (sentinel, proc, reason),
6642 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6643 exec_sentinel_error_handler);
6645 /* If we saved the match data nonrecursively, restore it now. */
6646 restore_search_regs ();
6647 running_asynch_code = outer_running_asynch_code;
6649 Vdeactivate_mark = odeactivate;
6651 /* Restore waiting_for_user_input_p as it was
6652 when we were called, in case the filter clobbered it. */
6653 waiting_for_user_input_p = waiting;
6655 #if 0
6656 if (! EQ (Fcurrent_buffer (), obuffer)
6657 || ! EQ (current_buffer->keymap, okeymap))
6658 #endif
6659 /* But do it only if the caller is actually going to read events.
6660 Otherwise there's no need to make him wake up, and it could
6661 cause trouble (for example it would make sit_for return). */
6662 if (waiting_for_user_input_p == -1)
6663 record_asynch_buffer_change ();
6665 unbind_to (count, Qnil);
6668 /* Report all recent events of a change in process status
6669 (either run the sentinel or output a message).
6670 This is usually done while Emacs is waiting for keyboard input
6671 but can be done at other times.
6673 Return positive if any input was received from WAIT_PROC (or from
6674 any process if WAIT_PROC is null), zero if input was attempted but
6675 none received, and negative if we didn't even try. */
6677 static int
6678 status_notify (struct Lisp_Process *deleting_process,
6679 struct Lisp_Process *wait_proc)
6681 Lisp_Object proc;
6682 Lisp_Object tail, msg;
6683 struct gcpro gcpro1, gcpro2;
6684 int got_some_input = -1;
6686 tail = Qnil;
6687 msg = Qnil;
6688 /* We need to gcpro tail; if read_process_output calls a filter
6689 which deletes a process and removes the cons to which tail points
6690 from Vprocess_alist, and then causes a GC, tail is an unprotected
6691 reference. */
6692 GCPRO2 (tail, msg);
6694 /* Set this now, so that if new processes are created by sentinels
6695 that we run, we get called again to handle their status changes. */
6696 update_tick = process_tick;
6698 FOR_EACH_PROCESS (tail, proc)
6700 Lisp_Object symbol;
6701 register struct Lisp_Process *p = XPROCESS (proc);
6703 if (p->tick != p->update_tick)
6705 p->update_tick = p->tick;
6707 /* If process is still active, read any output that remains. */
6708 while (! EQ (p->filter, Qt)
6709 && ! EQ (p->status, Qconnect)
6710 && ! EQ (p->status, Qlisten)
6711 /* Network or serial process not stopped: */
6712 && ! EQ (p->command, Qt)
6713 && p->infd >= 0
6714 && p != deleting_process)
6716 int nread = read_process_output (proc, p->infd);
6717 if (got_some_input < nread)
6718 got_some_input = nread;
6719 if (nread <= 0)
6720 break;
6723 /* Get the text to use for the message. */
6724 if (p->raw_status_new)
6725 update_status (p);
6726 msg = status_message (p);
6728 /* If process is terminated, deactivate it or delete it. */
6729 symbol = p->status;
6730 if (CONSP (p->status))
6731 symbol = XCAR (p->status);
6733 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6734 || EQ (symbol, Qclosed))
6736 if (delete_exited_processes)
6737 remove_process (proc);
6738 else
6739 deactivate_process (proc);
6742 /* The actions above may have further incremented p->tick.
6743 So set p->update_tick again so that an error in the sentinel will
6744 not cause this code to be run again. */
6745 p->update_tick = p->tick;
6746 /* Now output the message suitably. */
6747 exec_sentinel (proc, msg);
6749 } /* end for */
6751 update_mode_lines = 24; /* In case buffers use %s in mode-line-format. */
6752 UNGCPRO;
6753 return got_some_input;
6756 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6757 Sinternal_default_process_sentinel, 2, 2, 0,
6758 doc: /* Function used as default sentinel for processes.
6759 This inserts a status message into the process's buffer, if there is one. */)
6760 (Lisp_Object proc, Lisp_Object msg)
6762 Lisp_Object buffer, symbol;
6763 struct Lisp_Process *p;
6764 CHECK_PROCESS (proc);
6765 p = XPROCESS (proc);
6766 buffer = p->buffer;
6767 symbol = p->status;
6768 if (CONSP (symbol))
6769 symbol = XCAR (symbol);
6771 if (!EQ (symbol, Qrun) && !NILP (buffer))
6773 Lisp_Object tem;
6774 struct buffer *old = current_buffer;
6775 ptrdiff_t opoint, opoint_byte;
6776 ptrdiff_t before, before_byte;
6778 /* Avoid error if buffer is deleted
6779 (probably that's why the process is dead, too). */
6780 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6781 return Qnil;
6782 Fset_buffer (buffer);
6784 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6785 msg = (code_convert_string_norecord
6786 (msg, Vlocale_coding_system, 1));
6788 opoint = PT;
6789 opoint_byte = PT_BYTE;
6790 /* Insert new output into buffer
6791 at the current end-of-output marker,
6792 thus preserving logical ordering of input and output. */
6793 if (XMARKER (p->mark)->buffer)
6794 Fgoto_char (p->mark);
6795 else
6796 SET_PT_BOTH (ZV, ZV_BYTE);
6798 before = PT;
6799 before_byte = PT_BYTE;
6801 tem = BVAR (current_buffer, read_only);
6802 bset_read_only (current_buffer, Qnil);
6803 insert_string ("\nProcess ");
6804 { /* FIXME: temporary kludge. */
6805 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6806 insert_string (" ");
6807 Finsert (1, &msg);
6808 bset_read_only (current_buffer, tem);
6809 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6811 if (opoint >= before)
6812 SET_PT_BOTH (opoint + (PT - before),
6813 opoint_byte + (PT_BYTE - before_byte));
6814 else
6815 SET_PT_BOTH (opoint, opoint_byte);
6817 set_buffer_internal (old);
6819 return Qnil;
6823 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6824 Sset_process_coding_system, 1, 3, 0,
6825 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6826 DECODING will be used to decode subprocess output and ENCODING to
6827 encode subprocess input. */)
6828 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6830 register struct Lisp_Process *p;
6832 CHECK_PROCESS (process);
6833 p = XPROCESS (process);
6834 if (p->infd < 0)
6835 error ("Input file descriptor of %s closed", SDATA (p->name));
6836 if (p->outfd < 0)
6837 error ("Output file descriptor of %s closed", SDATA (p->name));
6838 Fcheck_coding_system (decoding);
6839 Fcheck_coding_system (encoding);
6840 encoding = coding_inherit_eol_type (encoding, Qnil);
6841 pset_decode_coding_system (p, decoding);
6842 pset_encode_coding_system (p, encoding);
6843 setup_process_coding_systems (process);
6845 return Qnil;
6848 DEFUN ("process-coding-system",
6849 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6850 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6851 (register Lisp_Object process)
6853 CHECK_PROCESS (process);
6854 return Fcons (XPROCESS (process)->decode_coding_system,
6855 XPROCESS (process)->encode_coding_system);
6858 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6859 Sset_process_filter_multibyte, 2, 2, 0,
6860 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6861 If FLAG is non-nil, the filter is given multibyte strings.
6862 If FLAG is nil, the filter is given unibyte strings. In this case,
6863 all character code conversion except for end-of-line conversion is
6864 suppressed. */)
6865 (Lisp_Object process, Lisp_Object flag)
6867 register struct Lisp_Process *p;
6869 CHECK_PROCESS (process);
6870 p = XPROCESS (process);
6871 if (NILP (flag))
6872 pset_decode_coding_system
6873 (p, raw_text_coding_system (p->decode_coding_system));
6874 setup_process_coding_systems (process);
6876 return Qnil;
6879 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6880 Sprocess_filter_multibyte_p, 1, 1, 0,
6881 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6882 (Lisp_Object process)
6884 register struct Lisp_Process *p;
6885 struct coding_system *coding;
6887 CHECK_PROCESS (process);
6888 p = XPROCESS (process);
6889 if (p->infd < 0)
6890 return Qnil;
6891 coding = proc_decode_coding_system[p->infd];
6892 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6898 # ifdef HAVE_GPM
6900 void
6901 add_gpm_wait_descriptor (int desc)
6903 add_keyboard_wait_descriptor (desc);
6906 void
6907 delete_gpm_wait_descriptor (int desc)
6909 delete_keyboard_wait_descriptor (desc);
6912 # endif
6914 # ifdef USABLE_SIGIO
6916 /* Return true if *MASK has a bit set
6917 that corresponds to one of the keyboard input descriptors. */
6919 static bool
6920 keyboard_bit_set (fd_set *mask)
6922 int fd;
6924 for (fd = 0; fd <= max_input_desc; fd++)
6925 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6926 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6927 return 1;
6929 return 0;
6931 # endif
6933 #else /* not subprocesses */
6935 /* Defined in msdos.c. */
6936 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6937 struct timespec *, void *);
6939 /* Implementation of wait_reading_process_output, assuming that there
6940 are no subprocesses. Used only by the MS-DOS build.
6942 Wait for timeout to elapse and/or keyboard input to be available.
6944 TIME_LIMIT is:
6945 timeout in seconds
6946 If negative, gobble data immediately available but don't wait for any.
6948 NSECS is:
6949 an additional duration to wait, measured in nanoseconds
6950 If TIME_LIMIT is zero, then:
6951 If NSECS == 0, there is no limit.
6952 If NSECS > 0, the timeout consists of NSECS only.
6953 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6955 READ_KBD is:
6956 0 to ignore keyboard input, or
6957 1 to return when input is available, or
6958 -1 means caller will actually read the input, so don't throw to
6959 the quit handler.
6961 see full version for other parameters. We know that wait_proc will
6962 always be NULL, since `subprocesses' isn't defined.
6964 DO_DISPLAY means redisplay should be done to show subprocess
6965 output that arrives.
6967 Return positive if we received input from WAIT_PROC (or from any
6968 process if WAIT_PROC is null), zero if we attempted to receive
6969 input but got none, and negative if we didn't even try. */
6972 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6973 bool do_display,
6974 Lisp_Object wait_for_cell,
6975 struct Lisp_Process *wait_proc, int just_wait_proc)
6977 register int nfds;
6978 struct timespec end_time, timeout;
6980 if (time_limit < 0)
6982 time_limit = 0;
6983 nsecs = -1;
6985 else if (TYPE_MAXIMUM (time_t) < time_limit)
6986 time_limit = TYPE_MAXIMUM (time_t);
6988 /* What does time_limit really mean? */
6989 if (time_limit || nsecs > 0)
6991 timeout = make_timespec (time_limit, nsecs);
6992 end_time = timespec_add (current_timespec (), timeout);
6995 /* Turn off periodic alarms (in case they are in use)
6996 and then turn off any other atimers,
6997 because the select emulator uses alarms. */
6998 stop_polling ();
6999 turn_on_atimers (0);
7001 while (1)
7003 bool timeout_reduced_for_timers = false;
7004 fd_set waitchannels;
7005 int xerrno;
7007 /* If calling from keyboard input, do not quit
7008 since we want to return C-g as an input character.
7009 Otherwise, do pending quit if requested. */
7010 if (read_kbd >= 0)
7011 QUIT;
7013 /* Exit now if the cell we're waiting for became non-nil. */
7014 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7015 break;
7017 /* Compute time from now till when time limit is up. */
7018 /* Exit if already run out. */
7019 if (nsecs < 0)
7021 /* A negative timeout means
7022 gobble output available now
7023 but don't wait at all. */
7025 timeout = make_timespec (0, 0);
7027 else if (time_limit || nsecs > 0)
7029 struct timespec now = current_timespec ();
7030 if (timespec_cmp (end_time, now) <= 0)
7031 break;
7032 timeout = timespec_sub (end_time, now);
7034 else
7036 timeout = make_timespec (100000, 0);
7039 /* If our caller will not immediately handle keyboard events,
7040 run timer events directly.
7041 (Callers that will immediately read keyboard events
7042 call timer_delay on their own.) */
7043 if (NILP (wait_for_cell))
7045 struct timespec timer_delay;
7049 unsigned old_timers_run = timers_run;
7050 timer_delay = timer_check ();
7051 if (timers_run != old_timers_run && do_display)
7052 /* We must retry, since a timer may have requeued itself
7053 and that could alter the time delay. */
7054 redisplay_preserve_echo_area (14);
7055 else
7056 break;
7058 while (!detect_input_pending ());
7060 /* If there is unread keyboard input, also return. */
7061 if (read_kbd != 0
7062 && requeued_events_pending_p ())
7063 break;
7065 if (timespec_valid_p (timer_delay) && nsecs >= 0)
7067 if (timespec_cmp (timer_delay, timeout) < 0)
7069 timeout = timer_delay;
7070 timeout_reduced_for_timers = true;
7075 /* Cause C-g and alarm signals to take immediate action,
7076 and cause input available signals to zero out timeout. */
7077 if (read_kbd < 0)
7078 set_waiting_for_input (&timeout);
7080 /* If a frame has been newly mapped and needs updating,
7081 reprocess its display stuff. */
7082 if (frame_garbaged && do_display)
7084 clear_waiting_for_input ();
7085 redisplay_preserve_echo_area (15);
7086 if (read_kbd < 0)
7087 set_waiting_for_input (&timeout);
7090 /* Wait till there is something to do. */
7091 FD_ZERO (&waitchannels);
7092 if (read_kbd && detect_input_pending ())
7093 nfds = 0;
7094 else
7096 if (read_kbd || !NILP (wait_for_cell))
7097 FD_SET (0, &waitchannels);
7098 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7101 xerrno = errno;
7103 /* Make C-g and alarm signals set flags again. */
7104 clear_waiting_for_input ();
7106 /* If we woke up due to SIGWINCH, actually change size now. */
7107 do_pending_window_change (0);
7109 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
7110 /* We waited the full specified time, so return now. */
7111 break;
7113 if (nfds == -1)
7115 /* If the system call was interrupted, then go around the
7116 loop again. */
7117 if (xerrno == EINTR)
7118 FD_ZERO (&waitchannels);
7119 else
7120 report_file_errno ("Failed select", Qnil, xerrno);
7123 /* Check for keyboard input. */
7125 if (read_kbd
7126 && detect_input_pending_run_timers (do_display))
7128 swallow_events (do_display);
7129 if (detect_input_pending_run_timers (do_display))
7130 break;
7133 /* If there is unread keyboard input, also return. */
7134 if (read_kbd
7135 && requeued_events_pending_p ())
7136 break;
7138 /* If wait_for_cell. check for keyboard input
7139 but don't run any timers.
7140 ??? (It seems wrong to me to check for keyboard
7141 input at all when wait_for_cell, but the code
7142 has been this way since July 1994.
7143 Try changing this after version 19.31.) */
7144 if (! NILP (wait_for_cell)
7145 && detect_input_pending ())
7147 swallow_events (do_display);
7148 if (detect_input_pending ())
7149 break;
7152 /* Exit now if the cell we're waiting for became non-nil. */
7153 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7154 break;
7157 start_polling ();
7159 return -1;
7162 #endif /* not subprocesses */
7164 /* The following functions are needed even if async subprocesses are
7165 not supported. Some of them are no-op stubs in that case. */
7167 #ifdef HAVE_TIMERFD
7169 /* Add FD, which is a descriptor returned by timerfd_create,
7170 to the set of non-keyboard input descriptors. */
7172 void
7173 add_timer_wait_descriptor (int fd)
7175 FD_SET (fd, &input_wait_mask);
7176 FD_SET (fd, &non_keyboard_wait_mask);
7177 FD_SET (fd, &non_process_wait_mask);
7178 fd_callback_info[fd].func = timerfd_callback;
7179 fd_callback_info[fd].data = NULL;
7180 fd_callback_info[fd].condition |= FOR_READ;
7181 if (fd > max_input_desc)
7182 max_input_desc = fd;
7185 #endif /* HAVE_TIMERFD */
7187 /* Add DESC to the set of keyboard input descriptors. */
7189 void
7190 add_keyboard_wait_descriptor (int desc)
7192 #ifdef subprocesses /* Actually means "not MSDOS". */
7193 FD_SET (desc, &input_wait_mask);
7194 FD_SET (desc, &non_process_wait_mask);
7195 if (desc > max_input_desc)
7196 max_input_desc = desc;
7197 #endif
7200 /* From now on, do not expect DESC to give keyboard input. */
7202 void
7203 delete_keyboard_wait_descriptor (int desc)
7205 #ifdef subprocesses
7206 FD_CLR (desc, &input_wait_mask);
7207 FD_CLR (desc, &non_process_wait_mask);
7208 delete_input_desc (desc);
7209 #endif
7212 /* Setup coding systems of PROCESS. */
7214 void
7215 setup_process_coding_systems (Lisp_Object process)
7217 #ifdef subprocesses
7218 struct Lisp_Process *p = XPROCESS (process);
7219 int inch = p->infd;
7220 int outch = p->outfd;
7221 Lisp_Object coding_system;
7223 if (inch < 0 || outch < 0)
7224 return;
7226 if (!proc_decode_coding_system[inch])
7227 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7228 coding_system = p->decode_coding_system;
7229 if (EQ (p->filter, Qinternal_default_process_filter)
7230 && BUFFERP (p->buffer))
7232 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7233 coding_system = raw_text_coding_system (coding_system);
7235 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7237 if (!proc_encode_coding_system[outch])
7238 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7239 setup_coding_system (p->encode_coding_system,
7240 proc_encode_coding_system[outch]);
7241 #endif
7244 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7245 doc: /* Return the (or a) process associated with BUFFER.
7246 BUFFER may be a buffer or the name of one. */)
7247 (register Lisp_Object buffer)
7249 #ifdef subprocesses
7250 register Lisp_Object buf, tail, proc;
7252 if (NILP (buffer)) return Qnil;
7253 buf = Fget_buffer (buffer);
7254 if (NILP (buf)) return Qnil;
7256 FOR_EACH_PROCESS (tail, proc)
7257 if (EQ (XPROCESS (proc)->buffer, buf))
7258 return proc;
7259 #endif /* subprocesses */
7260 return Qnil;
7263 DEFUN ("process-inherit-coding-system-flag",
7264 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7265 1, 1, 0,
7266 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7267 If this flag is t, `buffer-file-coding-system' of the buffer
7268 associated with PROCESS will inherit the coding system used to decode
7269 the process output. */)
7270 (register Lisp_Object process)
7272 #ifdef subprocesses
7273 CHECK_PROCESS (process);
7274 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7275 #else
7276 /* Ignore the argument and return the value of
7277 inherit-process-coding-system. */
7278 return inherit_process_coding_system ? Qt : Qnil;
7279 #endif
7282 /* Kill all processes associated with `buffer'.
7283 If `buffer' is nil, kill all processes. */
7285 void
7286 kill_buffer_processes (Lisp_Object buffer)
7288 #ifdef subprocesses
7289 Lisp_Object tail, proc;
7291 FOR_EACH_PROCESS (tail, proc)
7292 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7294 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7295 Fdelete_process (proc);
7296 else if (XPROCESS (proc)->infd >= 0)
7297 process_send_signal (proc, SIGHUP, Qnil, 1);
7299 #else /* subprocesses */
7300 /* Since we have no subprocesses, this does nothing. */
7301 #endif /* subprocesses */
7304 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7305 Swaiting_for_user_input_p, 0, 0, 0,
7306 doc: /* Return non-nil if Emacs is waiting for input from the user.
7307 This is intended for use by asynchronous process output filters and sentinels. */)
7308 (void)
7310 #ifdef subprocesses
7311 return (waiting_for_user_input_p ? Qt : Qnil);
7312 #else
7313 return Qnil;
7314 #endif
7317 /* Stop reading input from keyboard sources. */
7319 void
7320 hold_keyboard_input (void)
7322 kbd_is_on_hold = 1;
7325 /* Resume reading input from keyboard sources. */
7327 void
7328 unhold_keyboard_input (void)
7330 kbd_is_on_hold = 0;
7333 /* Return true if keyboard input is on hold, zero otherwise. */
7335 bool
7336 kbd_on_hold_p (void)
7338 return kbd_is_on_hold;
7342 /* Enumeration of and access to system processes a-la ps(1). */
7344 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7345 0, 0, 0,
7346 doc: /* Return a list of numerical process IDs of all running processes.
7347 If this functionality is unsupported, return nil.
7349 See `process-attributes' for getting attributes of a process given its ID. */)
7350 (void)
7352 return list_system_processes ();
7355 DEFUN ("process-attributes", Fprocess_attributes,
7356 Sprocess_attributes, 1, 1, 0,
7357 doc: /* Return attributes of the process given by its PID, a number.
7359 Value is an alist where each element is a cons cell of the form
7361 \(KEY . VALUE)
7363 If this functionality is unsupported, the value is nil.
7365 See `list-system-processes' for getting a list of all process IDs.
7367 The KEYs of the attributes that this function may return are listed
7368 below, together with the type of the associated VALUE (in parentheses).
7369 Not all platforms support all of these attributes; unsupported
7370 attributes will not appear in the returned alist.
7371 Unless explicitly indicated otherwise, numbers can have either
7372 integer or floating point values.
7374 euid -- Effective user User ID of the process (number)
7375 user -- User name corresponding to euid (string)
7376 egid -- Effective user Group ID of the process (number)
7377 group -- Group name corresponding to egid (string)
7378 comm -- Command name (executable name only) (string)
7379 state -- Process state code, such as "S", "R", or "T" (string)
7380 ppid -- Parent process ID (number)
7381 pgrp -- Process group ID (number)
7382 sess -- Session ID, i.e. process ID of session leader (number)
7383 ttname -- Controlling tty name (string)
7384 tpgid -- ID of foreground process group on the process's tty (number)
7385 minflt -- number of minor page faults (number)
7386 majflt -- number of major page faults (number)
7387 cminflt -- cumulative number of minor page faults (number)
7388 cmajflt -- cumulative number of major page faults (number)
7389 utime -- user time used by the process, in (current-time) format,
7390 which is a list of integers (HIGH LOW USEC PSEC)
7391 stime -- system time used by the process (current-time)
7392 time -- sum of utime and stime (current-time)
7393 cutime -- user time used by the process and its children (current-time)
7394 cstime -- system time used by the process and its children (current-time)
7395 ctime -- sum of cutime and cstime (current-time)
7396 pri -- priority of the process (number)
7397 nice -- nice value of the process (number)
7398 thcount -- process thread count (number)
7399 start -- time the process started (current-time)
7400 vsize -- virtual memory size of the process in KB's (number)
7401 rss -- resident set size of the process in KB's (number)
7402 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7403 pcpu -- percents of CPU time used by the process (floating-point number)
7404 pmem -- percents of total physical memory used by process's resident set
7405 (floating-point number)
7406 args -- command line which invoked the process (string). */)
7407 ( Lisp_Object pid)
7409 return system_process_attributes (pid);
7412 #ifdef subprocesses
7413 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7414 Invoke this after init_process_emacs, and after glib and/or GNUstep
7415 futz with the SIGCHLD handler, but before Emacs forks any children.
7416 This function's caller should block SIGCHLD. */
7418 void
7419 catch_child_signal (void)
7421 struct sigaction action, old_action;
7422 sigset_t oldset;
7423 emacs_sigaction_init (&action, deliver_child_signal);
7424 block_child_signal (&oldset);
7425 sigaction (SIGCHLD, &action, &old_action);
7426 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7427 || ! (old_action.sa_flags & SA_SIGINFO));
7429 if (old_action.sa_handler != deliver_child_signal)
7430 lib_child_handler
7431 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7432 ? dummy_handler
7433 : old_action.sa_handler);
7434 unblock_child_signal (&oldset);
7436 #endif /* subprocesses */
7439 /* This is not called "init_process" because that is the name of a
7440 Mach system call, so it would cause problems on Darwin systems. */
7441 void
7442 init_process_emacs (void)
7444 #ifdef subprocesses
7445 register int i;
7447 inhibit_sentinels = 0;
7449 #ifndef CANNOT_DUMP
7450 if (! noninteractive || initialized)
7451 #endif
7453 #if defined HAVE_GLIB && !defined WINDOWSNT
7454 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7455 this should always fail, but is enough to initialize glib's
7456 private SIGCHLD handler, allowing catch_child_signal to copy
7457 it into lib_child_handler. */
7458 g_source_unref (g_child_watch_source_new (getpid ()));
7459 #endif
7460 catch_child_signal ();
7463 FD_ZERO (&input_wait_mask);
7464 FD_ZERO (&non_keyboard_wait_mask);
7465 FD_ZERO (&non_process_wait_mask);
7466 FD_ZERO (&write_mask);
7467 max_process_desc = max_input_desc = -1;
7468 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7470 #ifdef NON_BLOCKING_CONNECT
7471 FD_ZERO (&connect_wait_mask);
7472 num_pending_connects = 0;
7473 #endif
7475 #ifdef ADAPTIVE_READ_BUFFERING
7476 process_output_delay_count = 0;
7477 process_output_skip = 0;
7478 #endif
7480 /* Don't do this, it caused infinite select loops. The display
7481 method should call add_keyboard_wait_descriptor on stdin if it
7482 needs that. */
7483 #if 0
7484 FD_SET (0, &input_wait_mask);
7485 #endif
7487 Vprocess_alist = Qnil;
7488 deleted_pid_list = Qnil;
7489 for (i = 0; i < FD_SETSIZE; i++)
7491 chan_process[i] = Qnil;
7492 proc_buffered_char[i] = -1;
7494 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7495 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7496 #ifdef DATAGRAM_SOCKETS
7497 memset (datagram_address, 0, sizeof datagram_address);
7498 #endif
7500 #if defined (DARWIN_OS)
7501 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7502 processes. As such, we only change the default value. */
7503 if (initialized)
7505 char const *release = (STRINGP (Voperating_system_release)
7506 ? SSDATA (Voperating_system_release)
7507 : 0);
7508 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7509 Vprocess_connection_type = Qnil;
7512 #endif
7513 #endif /* subprocesses */
7514 kbd_is_on_hold = 0;
7517 void
7518 syms_of_process (void)
7520 #ifdef subprocesses
7522 DEFSYM (Qprocessp, "processp");
7523 DEFSYM (Qrun, "run");
7524 DEFSYM (Qstop, "stop");
7525 DEFSYM (Qsignal, "signal");
7527 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7528 here again. */
7530 DEFSYM (Qopen, "open");
7531 DEFSYM (Qclosed, "closed");
7532 DEFSYM (Qconnect, "connect");
7533 DEFSYM (Qfailed, "failed");
7534 DEFSYM (Qlisten, "listen");
7535 DEFSYM (Qlocal, "local");
7536 DEFSYM (Qipv4, "ipv4");
7537 #ifdef AF_INET6
7538 DEFSYM (Qipv6, "ipv6");
7539 #endif
7540 DEFSYM (Qdatagram, "datagram");
7541 DEFSYM (Qseqpacket, "seqpacket");
7543 DEFSYM (QCport, ":port");
7544 DEFSYM (QCspeed, ":speed");
7545 DEFSYM (QCprocess, ":process");
7547 DEFSYM (QCbytesize, ":bytesize");
7548 DEFSYM (QCstopbits, ":stopbits");
7549 DEFSYM (QCparity, ":parity");
7550 DEFSYM (Qodd, "odd");
7551 DEFSYM (Qeven, "even");
7552 DEFSYM (QCflowcontrol, ":flowcontrol");
7553 DEFSYM (Qhw, "hw");
7554 DEFSYM (Qsw, "sw");
7555 DEFSYM (QCsummary, ":summary");
7557 DEFSYM (Qreal, "real");
7558 DEFSYM (Qnetwork, "network");
7559 DEFSYM (Qserial, "serial");
7560 DEFSYM (Qpipe, "pipe");
7561 DEFSYM (QCbuffer, ":buffer");
7562 DEFSYM (QChost, ":host");
7563 DEFSYM (QCservice, ":service");
7564 DEFSYM (QClocal, ":local");
7565 DEFSYM (QCremote, ":remote");
7566 DEFSYM (QCcoding, ":coding");
7567 DEFSYM (QCserver, ":server");
7568 DEFSYM (QCnowait, ":nowait");
7569 DEFSYM (QCsentinel, ":sentinel");
7570 DEFSYM (QClog, ":log");
7571 DEFSYM (QCnoquery, ":noquery");
7572 DEFSYM (QCstop, ":stop");
7573 DEFSYM (QCplist, ":plist");
7574 DEFSYM (QCcommand, ":command");
7575 DEFSYM (QCconnection_type, ":connection-type");
7576 DEFSYM (QCstderr, ":stderr");
7577 DEFSYM (Qpty, "pty");
7578 DEFSYM (Qpipe, "pipe");
7580 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7582 staticpro (&Vprocess_alist);
7583 staticpro (&deleted_pid_list);
7585 #endif /* subprocesses */
7587 DEFSYM (QCname, ":name");
7588 DEFSYM (QCtype, ":type");
7590 DEFSYM (Qeuid, "euid");
7591 DEFSYM (Qegid, "egid");
7592 DEFSYM (Quser, "user");
7593 DEFSYM (Qgroup, "group");
7594 DEFSYM (Qcomm, "comm");
7595 DEFSYM (Qstate, "state");
7596 DEFSYM (Qppid, "ppid");
7597 DEFSYM (Qpgrp, "pgrp");
7598 DEFSYM (Qsess, "sess");
7599 DEFSYM (Qttname, "ttname");
7600 DEFSYM (Qtpgid, "tpgid");
7601 DEFSYM (Qminflt, "minflt");
7602 DEFSYM (Qmajflt, "majflt");
7603 DEFSYM (Qcminflt, "cminflt");
7604 DEFSYM (Qcmajflt, "cmajflt");
7605 DEFSYM (Qutime, "utime");
7606 DEFSYM (Qstime, "stime");
7607 DEFSYM (Qtime, "time");
7608 DEFSYM (Qcutime, "cutime");
7609 DEFSYM (Qcstime, "cstime");
7610 DEFSYM (Qctime, "ctime");
7611 #ifdef subprocesses
7612 DEFSYM (Qinternal_default_process_sentinel,
7613 "internal-default-process-sentinel");
7614 DEFSYM (Qinternal_default_process_filter,
7615 "internal-default-process-filter");
7616 #endif
7617 DEFSYM (Qpri, "pri");
7618 DEFSYM (Qnice, "nice");
7619 DEFSYM (Qthcount, "thcount");
7620 DEFSYM (Qstart, "start");
7621 DEFSYM (Qvsize, "vsize");
7622 DEFSYM (Qrss, "rss");
7623 DEFSYM (Qetime, "etime");
7624 DEFSYM (Qpcpu, "pcpu");
7625 DEFSYM (Qpmem, "pmem");
7626 DEFSYM (Qargs, "args");
7628 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7629 doc: /* Non-nil means delete processes immediately when they exit.
7630 A value of nil means don't delete them until `list-processes' is run. */);
7632 delete_exited_processes = 1;
7634 #ifdef subprocesses
7635 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7636 doc: /* Control type of device used to communicate with subprocesses.
7637 Values are nil to use a pipe, or t or `pty' to use a pty.
7638 The value has no effect if the system has no ptys or if all ptys are busy:
7639 then a pipe is used in any case.
7640 The value takes effect when `start-process' is called. */);
7641 Vprocess_connection_type = Qt;
7643 #ifdef ADAPTIVE_READ_BUFFERING
7644 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7645 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7646 On some systems, when Emacs reads the output from a subprocess, the output data
7647 is read in very small blocks, potentially resulting in very poor performance.
7648 This behavior can be remedied to some extent by setting this variable to a
7649 non-nil value, as it will automatically delay reading from such processes, to
7650 allow them to produce more output before Emacs tries to read it.
7651 If the value is t, the delay is reset after each write to the process; any other
7652 non-nil value means that the delay is not reset on write.
7653 The variable takes effect when `start-process' is called. */);
7654 Vprocess_adaptive_read_buffering = Qt;
7655 #endif
7657 defsubr (&Sprocessp);
7658 defsubr (&Sget_process);
7659 defsubr (&Sdelete_process);
7660 defsubr (&Sprocess_status);
7661 defsubr (&Sprocess_exit_status);
7662 defsubr (&Sprocess_id);
7663 defsubr (&Sprocess_name);
7664 defsubr (&Sprocess_tty_name);
7665 defsubr (&Sprocess_command);
7666 defsubr (&Sset_process_buffer);
7667 defsubr (&Sprocess_buffer);
7668 defsubr (&Sprocess_mark);
7669 defsubr (&Sset_process_filter);
7670 defsubr (&Sprocess_filter);
7671 defsubr (&Sset_process_sentinel);
7672 defsubr (&Sprocess_sentinel);
7673 defsubr (&Sset_process_window_size);
7674 defsubr (&Sset_process_inherit_coding_system_flag);
7675 defsubr (&Sset_process_query_on_exit_flag);
7676 defsubr (&Sprocess_query_on_exit_flag);
7677 defsubr (&Sprocess_contact);
7678 defsubr (&Sprocess_plist);
7679 defsubr (&Sset_process_plist);
7680 defsubr (&Sprocess_list);
7681 defsubr (&Smake_process);
7682 defsubr (&Smake_pipe_process);
7683 defsubr (&Sserial_process_configure);
7684 defsubr (&Smake_serial_process);
7685 defsubr (&Sset_network_process_option);
7686 defsubr (&Smake_network_process);
7687 defsubr (&Sformat_network_address);
7688 defsubr (&Snetwork_interface_list);
7689 defsubr (&Snetwork_interface_info);
7690 #ifdef DATAGRAM_SOCKETS
7691 defsubr (&Sprocess_datagram_address);
7692 defsubr (&Sset_process_datagram_address);
7693 #endif
7694 defsubr (&Saccept_process_output);
7695 defsubr (&Sprocess_send_region);
7696 defsubr (&Sprocess_send_string);
7697 defsubr (&Sinterrupt_process);
7698 defsubr (&Skill_process);
7699 defsubr (&Squit_process);
7700 defsubr (&Sstop_process);
7701 defsubr (&Scontinue_process);
7702 defsubr (&Sprocess_running_child_p);
7703 defsubr (&Sprocess_send_eof);
7704 defsubr (&Ssignal_process);
7705 defsubr (&Swaiting_for_user_input_p);
7706 defsubr (&Sprocess_type);
7707 defsubr (&Sinternal_default_process_sentinel);
7708 defsubr (&Sinternal_default_process_filter);
7709 defsubr (&Sset_process_coding_system);
7710 defsubr (&Sprocess_coding_system);
7711 defsubr (&Sset_process_filter_multibyte);
7712 defsubr (&Sprocess_filter_multibyte_p);
7714 #endif /* subprocesses */
7716 defsubr (&Sget_buffer_process);
7717 defsubr (&Sprocess_inherit_coding_system_flag);
7718 defsubr (&Slist_system_processes);
7719 defsubr (&Sprocess_attributes);
7722 Lisp_Object subfeatures = Qnil;
7723 const struct socket_options *sopt;
7725 #define ADD_SUBFEATURE(key, val) \
7726 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7728 #ifdef NON_BLOCKING_CONNECT
7729 ADD_SUBFEATURE (QCnowait, Qt);
7730 #endif
7731 #ifdef DATAGRAM_SOCKETS
7732 ADD_SUBFEATURE (QCtype, Qdatagram);
7733 #endif
7734 #ifdef HAVE_SEQPACKET
7735 ADD_SUBFEATURE (QCtype, Qseqpacket);
7736 #endif
7737 #ifdef HAVE_LOCAL_SOCKETS
7738 ADD_SUBFEATURE (QCfamily, Qlocal);
7739 #endif
7740 ADD_SUBFEATURE (QCfamily, Qipv4);
7741 #ifdef AF_INET6
7742 ADD_SUBFEATURE (QCfamily, Qipv6);
7743 #endif
7744 #ifdef HAVE_GETSOCKNAME
7745 ADD_SUBFEATURE (QCservice, Qt);
7746 #endif
7747 ADD_SUBFEATURE (QCserver, Qt);
7749 for (sopt = socket_options; sopt->name; sopt++)
7750 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7752 Fprovide (intern_c_string ("make-network-process"), subfeatures);