* test/automated/vc-tests.el: Try enabling tests on hydra.nixos.org.
[emacs.git] / src / process.c
blobce78d818e2984f11a941edb7c999966713ed426f
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2015 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
27 #include <sys/file.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30 #include <fcntl.h>
32 #include "lisp.h"
34 /* Only MS-DOS does not define `subprocesses'. */
35 #ifdef subprocesses
37 #include <sys/socket.h>
38 #include <netdb.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
42 /* Are local (unix) sockets supported? */
43 #if defined (HAVE_SYS_UN_H)
44 #if !defined (AF_LOCAL) && defined (AF_UNIX)
45 #define AF_LOCAL AF_UNIX
46 #endif
47 #ifdef AF_LOCAL
48 #define HAVE_LOCAL_SOCKETS
49 #include <sys/un.h>
50 #endif
51 #endif
53 #include <sys/ioctl.h>
54 #if defined (HAVE_NET_IF_H)
55 #include <net/if.h>
56 #endif /* HAVE_NET_IF_H */
58 #if defined (HAVE_IFADDRS_H)
59 /* Must be after net/if.h */
60 #include <ifaddrs.h>
62 /* We only use structs from this header when we use getifaddrs. */
63 #if defined (HAVE_NET_IF_DL_H)
64 #include <net/if_dl.h>
65 #endif
67 #endif
69 #ifdef NEED_BSDTTY
70 #include <bsdtty.h>
71 #endif
73 #ifdef USG5_4
74 # include <sys/stream.h>
75 # include <sys/stropts.h>
76 #endif
78 #ifdef HAVE_RES_INIT
79 #include <arpa/nameser.h>
80 #include <resolv.h>
81 #endif
83 #ifdef HAVE_UTIL_H
84 #include <util.h>
85 #endif
87 #ifdef HAVE_PTY_H
88 #include <pty.h>
89 #endif
91 #include <c-ctype.h>
92 #include <sig2str.h>
93 #include <verify.h>
95 #endif /* subprocesses */
97 #include "systime.h"
98 #include "systty.h"
100 #include "window.h"
101 #include "character.h"
102 #include "buffer.h"
103 #include "coding.h"
104 #include "process.h"
105 #include "frame.h"
106 #include "termhooks.h"
107 #include "termopts.h"
108 #include "commands.h"
109 #include "keyboard.h"
110 #include "blockinput.h"
111 #include "dispextern.h"
112 #include "composite.h"
113 #include "atimer.h"
114 #include "sysselect.h"
115 #include "syssignal.h"
116 #include "syswait.h"
117 #ifdef HAVE_GNUTLS
118 #include "gnutls.h"
119 #endif
121 #ifdef HAVE_WINDOW_SYSTEM
122 #include TERM_HEADER
123 #endif /* HAVE_WINDOW_SYSTEM */
125 #ifdef HAVE_GLIB
126 #include "xgselect.h"
127 #ifndef WINDOWSNT
128 #include <glib.h>
129 #endif
130 #endif
132 #ifdef WINDOWSNT
133 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
134 struct timespec *, void *);
135 #endif
137 /* Work around GCC 4.7.0 bug with strict overflow checking; see
138 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
139 This bug appears to be fixed in GCC 5.1, so don't work around it there. */
140 #if __GNUC__ == 4 && __GNUC_MINOR__ >= 3
141 # pragma GCC diagnostic ignored "-Wstrict-overflow"
142 #endif
144 /* True if keyboard input is on hold, zero otherwise. */
146 static bool kbd_is_on_hold;
148 /* Nonzero means don't run process sentinels. This is used
149 when exiting. */
150 bool inhibit_sentinels;
152 #ifdef subprocesses
154 #ifndef SOCK_CLOEXEC
155 # define SOCK_CLOEXEC 0
156 #endif
158 #ifndef HAVE_ACCEPT4
160 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
162 static int
163 close_on_exec (int fd)
165 if (0 <= fd)
166 fcntl (fd, F_SETFD, FD_CLOEXEC);
167 return fd;
170 # undef accept4
171 # define accept4(sockfd, addr, addrlen, flags) \
172 process_accept4 (sockfd, addr, addrlen, flags)
173 static int
174 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
176 return close_on_exec (accept (sockfd, addr, addrlen));
179 static int
180 process_socket (int domain, int type, int protocol)
182 return close_on_exec (socket (domain, type, protocol));
184 # undef socket
185 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
186 #endif
188 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
189 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
190 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
191 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
192 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
193 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
195 /* Number of events of change of status of a process. */
196 static EMACS_INT process_tick;
197 /* Number of events for which the user or sentinel has been notified. */
198 static EMACS_INT update_tick;
200 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects.
201 The code can be simplified by assuming NON_BLOCKING_CONNECT once
202 Emacs starts assuming POSIX 1003.1-2001 or later. */
204 #if (defined HAVE_SELECT \
205 && (defined GNU_LINUX || defined HAVE_GETPEERNAME) \
206 && (defined EWOULDBLOCK || defined EINPROGRESS))
207 # define NON_BLOCKING_CONNECT
208 #endif
210 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
211 this system. We need to read full packets, so we need a
212 "non-destructive" select. So we require either native select,
213 or emulation of select using FIONREAD. */
215 #ifndef BROKEN_DATAGRAM_SOCKETS
216 # if defined HAVE_SELECT || defined USABLE_FIONREAD
217 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
218 # define DATAGRAM_SOCKETS
219 # endif
220 # endif
221 #endif
223 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
224 # define HAVE_SEQPACKET
225 #endif
227 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
228 #define ADAPTIVE_READ_BUFFERING
229 #endif
231 #ifdef ADAPTIVE_READ_BUFFERING
232 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
233 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
234 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
236 /* Number of processes which have a non-zero read_output_delay,
237 and therefore might be delayed for adaptive read buffering. */
239 static int process_output_delay_count;
241 /* True if any process has non-nil read_output_skip. */
243 static bool process_output_skip;
245 #else
246 #define process_output_delay_count 0
247 #endif
249 static void create_process (Lisp_Object, char **, Lisp_Object);
250 #ifdef USABLE_SIGIO
251 static bool keyboard_bit_set (fd_set *);
252 #endif
253 static void deactivate_process (Lisp_Object);
254 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
255 static int read_process_output (Lisp_Object, int);
256 static void handle_child_signal (int);
257 static void create_pty (Lisp_Object);
259 static Lisp_Object get_process (register Lisp_Object name);
260 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
262 /* Mask of bits indicating the descriptors that we wait for input on. */
264 static fd_set input_wait_mask;
266 /* Mask that excludes keyboard input descriptor(s). */
268 static fd_set non_keyboard_wait_mask;
270 /* Mask that excludes process input descriptor(s). */
272 static fd_set non_process_wait_mask;
274 /* Mask for selecting for write. */
276 static fd_set write_mask;
278 #ifdef NON_BLOCKING_CONNECT
279 /* Mask of bits indicating the descriptors that we wait for connect to
280 complete on. Once they complete, they are removed from this mask
281 and added to the input_wait_mask and non_keyboard_wait_mask. */
283 static fd_set connect_wait_mask;
285 /* Number of bits set in connect_wait_mask. */
286 static int num_pending_connects;
287 #endif /* NON_BLOCKING_CONNECT */
289 /* The largest descriptor currently in use for a process object; -1 if none. */
290 static int max_process_desc;
292 /* The largest descriptor currently in use for input; -1 if none. */
293 static int max_input_desc;
295 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
296 static Lisp_Object chan_process[FD_SETSIZE];
298 /* Alist of elements (NAME . PROCESS). */
299 static Lisp_Object Vprocess_alist;
301 /* Buffered-ahead input char from process, indexed by channel.
302 -1 means empty (no char is buffered).
303 Used on sys V where the only way to tell if there is any
304 output from the process is to read at least one char.
305 Always -1 on systems that support FIONREAD. */
307 static int proc_buffered_char[FD_SETSIZE];
309 /* Table of `struct coding-system' for each process. */
310 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
311 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
313 #ifdef DATAGRAM_SOCKETS
314 /* Table of `partner address' for datagram sockets. */
315 static struct sockaddr_and_len {
316 struct sockaddr *sa;
317 int len;
318 } datagram_address[FD_SETSIZE];
319 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
320 #define DATAGRAM_CONN_P(proc) \
321 (PROCESSP (proc) && \
322 XPROCESS (proc)->infd >= 0 && \
323 datagram_address[XPROCESS (proc)->infd].sa != 0)
324 #else
325 #define DATAGRAM_CHAN_P(chan) (0)
326 #define DATAGRAM_CONN_P(proc) (0)
327 #endif
329 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
330 a `for' loop which iterates over processes from Vprocess_alist. */
332 #define FOR_EACH_PROCESS(list_var, proc_var) \
333 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
335 /* These setters are used only in this file, so they can be private. */
336 static void
337 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
339 p->buffer = val;
341 static void
342 pset_command (struct Lisp_Process *p, Lisp_Object val)
344 p->command = val;
346 static void
347 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
349 p->decode_coding_system = val;
351 static void
352 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
354 p->decoding_buf = val;
356 static void
357 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
359 p->encode_coding_system = val;
361 static void
362 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
364 p->encoding_buf = val;
366 static void
367 pset_filter (struct Lisp_Process *p, Lisp_Object val)
369 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
371 static void
372 pset_log (struct Lisp_Process *p, Lisp_Object val)
374 p->log = val;
376 static void
377 pset_mark (struct Lisp_Process *p, Lisp_Object val)
379 p->mark = val;
381 static void
382 pset_name (struct Lisp_Process *p, Lisp_Object val)
384 p->name = val;
386 static void
387 pset_plist (struct Lisp_Process *p, Lisp_Object val)
389 p->plist = val;
391 static void
392 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
394 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
396 static void
397 pset_status (struct Lisp_Process *p, Lisp_Object val)
399 p->status = val;
401 static void
402 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
404 p->tty_name = val;
406 static void
407 pset_type (struct Lisp_Process *p, Lisp_Object val)
409 p->type = val;
411 static void
412 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
414 p->write_queue = val;
416 static void
417 pset_stderrproc (struct Lisp_Process *p, Lisp_Object val)
419 p->stderrproc = val;
423 static Lisp_Object
424 make_lisp_proc (struct Lisp_Process *p)
426 return make_lisp_ptr (p, Lisp_Vectorlike);
429 static struct fd_callback_data
431 fd_callback func;
432 void *data;
433 #define FOR_READ 1
434 #define FOR_WRITE 2
435 int condition; /* Mask of the defines above. */
436 } fd_callback_info[FD_SETSIZE];
439 /* Add a file descriptor FD to be monitored for when read is possible.
440 When read is possible, call FUNC with argument DATA. */
442 void
443 add_read_fd (int fd, fd_callback func, void *data)
445 add_keyboard_wait_descriptor (fd);
447 fd_callback_info[fd].func = func;
448 fd_callback_info[fd].data = data;
449 fd_callback_info[fd].condition |= FOR_READ;
452 /* Stop monitoring file descriptor FD for when read is possible. */
454 void
455 delete_read_fd (int fd)
457 delete_keyboard_wait_descriptor (fd);
459 fd_callback_info[fd].condition &= ~FOR_READ;
460 if (fd_callback_info[fd].condition == 0)
462 fd_callback_info[fd].func = 0;
463 fd_callback_info[fd].data = 0;
467 /* Add a file descriptor FD to be monitored for when write is possible.
468 When write is possible, call FUNC with argument DATA. */
470 void
471 add_write_fd (int fd, fd_callback func, void *data)
473 FD_SET (fd, &write_mask);
474 if (fd > max_input_desc)
475 max_input_desc = fd;
477 fd_callback_info[fd].func = func;
478 fd_callback_info[fd].data = data;
479 fd_callback_info[fd].condition |= FOR_WRITE;
482 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
484 static void
485 delete_input_desc (int fd)
487 if (fd == max_input_desc)
490 fd--;
491 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
492 || FD_ISSET (fd, &write_mask)));
494 max_input_desc = fd;
498 /* Stop monitoring file descriptor FD for when write is possible. */
500 void
501 delete_write_fd (int fd)
503 FD_CLR (fd, &write_mask);
504 fd_callback_info[fd].condition &= ~FOR_WRITE;
505 if (fd_callback_info[fd].condition == 0)
507 fd_callback_info[fd].func = 0;
508 fd_callback_info[fd].data = 0;
509 delete_input_desc (fd);
514 /* Compute the Lisp form of the process status, p->status, from
515 the numeric status that was returned by `wait'. */
517 static Lisp_Object status_convert (int);
519 static void
520 update_status (struct Lisp_Process *p)
522 eassert (p->raw_status_new);
523 pset_status (p, status_convert (p->raw_status));
524 p->raw_status_new = 0;
527 /* Convert a process status word in Unix format to
528 the list that we use internally. */
530 static Lisp_Object
531 status_convert (int w)
533 if (WIFSTOPPED (w))
534 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
535 else if (WIFEXITED (w))
536 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
537 WCOREDUMP (w) ? Qt : Qnil));
538 else if (WIFSIGNALED (w))
539 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
540 WCOREDUMP (w) ? Qt : Qnil));
541 else
542 return Qrun;
545 /* Given a status-list, extract the three pieces of information
546 and store them individually through the three pointers. */
548 static void
549 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
551 Lisp_Object tem;
553 if (SYMBOLP (l))
555 *symbol = l;
556 *code = 0;
557 *coredump = 0;
559 else
561 *symbol = XCAR (l);
562 tem = XCDR (l);
563 *code = XFASTINT (XCAR (tem));
564 tem = XCDR (tem);
565 *coredump = !NILP (tem);
569 /* Return a string describing a process status list. */
571 static Lisp_Object
572 status_message (struct Lisp_Process *p)
574 Lisp_Object status = p->status;
575 Lisp_Object symbol;
576 int code;
577 bool coredump;
578 Lisp_Object string;
580 decode_status (status, &symbol, &code, &coredump);
582 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
584 char const *signame;
585 synchronize_system_messages_locale ();
586 signame = strsignal (code);
587 if (signame == 0)
588 string = build_string ("unknown");
589 else
591 int c1, c2;
593 string = build_unibyte_string (signame);
594 if (! NILP (Vlocale_coding_system))
595 string = (code_convert_string_norecord
596 (string, Vlocale_coding_system, 0));
597 c1 = STRING_CHAR (SDATA (string));
598 c2 = downcase (c1);
599 if (c1 != c2)
600 Faset (string, make_number (0), make_number (c2));
602 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
603 return concat2 (string, suffix);
605 else if (EQ (symbol, Qexit))
607 if (NETCONN1_P (p))
608 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
609 if (code == 0)
610 return build_string ("finished\n");
611 AUTO_STRING (prefix, "exited abnormally with code ");
612 string = Fnumber_to_string (make_number (code));
613 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
614 return concat3 (prefix, string, suffix);
616 else if (EQ (symbol, Qfailed))
618 AUTO_STRING (prefix, "failed with code ");
619 string = Fnumber_to_string (make_number (code));
620 AUTO_STRING (suffix, "\n");
621 return concat3 (prefix, string, suffix);
623 else
624 return Fcopy_sequence (Fsymbol_name (symbol));
627 enum { PTY_NAME_SIZE = 24 };
629 /* Open an available pty, returning a file descriptor.
630 Store into PTY_NAME the file name of the terminal corresponding to the pty.
631 Return -1 on failure. */
633 static int
634 allocate_pty (char pty_name[PTY_NAME_SIZE])
636 #ifdef HAVE_PTYS
637 int fd;
639 #ifdef PTY_ITERATION
640 PTY_ITERATION
641 #else
642 register int c, i;
643 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
644 for (i = 0; i < 16; i++)
645 #endif
647 #ifdef PTY_NAME_SPRINTF
648 PTY_NAME_SPRINTF
649 #else
650 sprintf (pty_name, "/dev/pty%c%x", c, i);
651 #endif /* no PTY_NAME_SPRINTF */
653 #ifdef PTY_OPEN
654 PTY_OPEN;
655 #else /* no PTY_OPEN */
656 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
657 #endif /* no PTY_OPEN */
659 if (fd >= 0)
661 #ifdef PTY_OPEN
662 /* Set FD's close-on-exec flag. This is needed even if
663 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
664 doesn't require support for that combination.
665 Multithreaded platforms where posix_openpt ignores
666 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
667 have a race condition between the PTY_OPEN and here. */
668 fcntl (fd, F_SETFD, FD_CLOEXEC);
669 #endif
670 /* Check to make certain that both sides are available
671 this avoids a nasty yet stupid bug in rlogins. */
672 #ifdef PTY_TTY_NAME_SPRINTF
673 PTY_TTY_NAME_SPRINTF
674 #else
675 sprintf (pty_name, "/dev/tty%c%x", c, i);
676 #endif /* no PTY_TTY_NAME_SPRINTF */
677 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
679 emacs_close (fd);
680 # ifndef __sgi
681 continue;
682 # else
683 return -1;
684 # endif /* __sgi */
686 setup_pty (fd);
687 return fd;
690 #endif /* HAVE_PTYS */
691 return -1;
694 /* Allocate basically initialized process. */
696 static struct Lisp_Process *
697 allocate_process (void)
699 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
702 static Lisp_Object
703 make_process (Lisp_Object name)
705 register Lisp_Object val, tem, name1;
706 register struct Lisp_Process *p;
707 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
708 printmax_t i;
710 p = allocate_process ();
711 /* Initialize Lisp data. Note that allocate_process initializes all
712 Lisp data to nil, so do it only for slots which should not be nil. */
713 pset_status (p, Qrun);
714 pset_mark (p, Fmake_marker ());
716 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
717 non-Lisp data, so do it only for slots which should not be zero. */
718 p->infd = -1;
719 p->outfd = -1;
720 for (i = 0; i < PROCESS_OPEN_FDS; i++)
721 p->open_fd[i] = -1;
723 #ifdef HAVE_GNUTLS
724 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
725 #endif
727 /* If name is already in use, modify it until it is unused. */
729 name1 = name;
730 for (i = 1; ; i++)
732 tem = Fget_process (name1);
733 if (NILP (tem)) break;
734 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
736 name = name1;
737 pset_name (p, name);
738 pset_sentinel (p, Qinternal_default_process_sentinel);
739 pset_filter (p, Qinternal_default_process_filter);
740 XSETPROCESS (val, p);
741 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
742 return val;
745 static void
746 remove_process (register Lisp_Object proc)
748 register Lisp_Object pair;
750 pair = Frassq (proc, Vprocess_alist);
751 Vprocess_alist = Fdelq (pair, Vprocess_alist);
753 deactivate_process (proc);
757 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
758 doc: /* Return t if OBJECT is a process. */)
759 (Lisp_Object object)
761 return PROCESSP (object) ? Qt : Qnil;
764 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
765 doc: /* Return the process named NAME, or nil if there is none. */)
766 (register Lisp_Object name)
768 if (PROCESSP (name))
769 return name;
770 CHECK_STRING (name);
771 return Fcdr (Fassoc (name, Vprocess_alist));
774 /* This is how commands for the user decode process arguments. It
775 accepts a process, a process name, a buffer, a buffer name, or nil.
776 Buffers denote the first process in the buffer, and nil denotes the
777 current buffer. */
779 static Lisp_Object
780 get_process (register Lisp_Object name)
782 register Lisp_Object proc, obj;
783 if (STRINGP (name))
785 obj = Fget_process (name);
786 if (NILP (obj))
787 obj = Fget_buffer (name);
788 if (NILP (obj))
789 error ("Process %s does not exist", SDATA (name));
791 else if (NILP (name))
792 obj = Fcurrent_buffer ();
793 else
794 obj = name;
796 /* Now obj should be either a buffer object or a process object. */
797 if (BUFFERP (obj))
799 if (NILP (BVAR (XBUFFER (obj), name)))
800 error ("Attempt to get process for a dead buffer");
801 proc = Fget_buffer_process (obj);
802 if (NILP (proc))
803 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
805 else
807 CHECK_PROCESS (obj);
808 proc = obj;
810 return proc;
814 /* Fdelete_process promises to immediately forget about the process, but in
815 reality, Emacs needs to remember those processes until they have been
816 treated by the SIGCHLD handler and waitpid has been invoked on them;
817 otherwise they might fill up the kernel's process table.
819 Some processes created by call-process are also put onto this list.
821 Members of this list are (process-ID . filename) pairs. The
822 process-ID is a number; the filename, if a string, is a file that
823 needs to be removed after the process exits. */
824 static Lisp_Object deleted_pid_list;
826 void
827 record_deleted_pid (pid_t pid, Lisp_Object filename)
829 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
830 /* GC treated elements set to nil. */
831 Fdelq (Qnil, deleted_pid_list));
835 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
836 doc: /* Delete PROCESS: kill it and forget about it immediately.
837 PROCESS may be a process, a buffer, the name of a process or buffer, or
838 nil, indicating the current buffer's process. */)
839 (register Lisp_Object process)
841 register struct Lisp_Process *p;
843 process = get_process (process);
844 p = XPROCESS (process);
846 p->raw_status_new = 0;
847 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
849 pset_status (p, list2 (Qexit, make_number (0)));
850 p->tick = ++process_tick;
851 status_notify (p, NULL);
852 redisplay_preserve_echo_area (13);
854 else
856 if (p->alive)
857 record_kill_process (p, Qnil);
859 if (p->infd >= 0)
861 /* Update P's status, since record_kill_process will make the
862 SIGCHLD handler update deleted_pid_list, not *P. */
863 Lisp_Object symbol;
864 if (p->raw_status_new)
865 update_status (p);
866 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
867 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
868 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
870 p->tick = ++process_tick;
871 status_notify (p, NULL);
872 redisplay_preserve_echo_area (13);
875 remove_process (process);
876 return Qnil;
879 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
880 doc: /* Return the status of PROCESS.
881 The returned value is one of the following symbols:
882 run -- for a process that is running.
883 stop -- for a process stopped but continuable.
884 exit -- for a process that has exited.
885 signal -- for a process that has got a fatal signal.
886 open -- for a network stream connection that is open.
887 listen -- for a network stream server that is listening.
888 closed -- for a network stream connection that is closed.
889 connect -- when waiting for a non-blocking connection to complete.
890 failed -- when a non-blocking connection has failed.
891 nil -- if arg is a process name and no such process exists.
892 PROCESS may be a process, a buffer, the name of a process, or
893 nil, indicating the current buffer's process. */)
894 (register Lisp_Object process)
896 register struct Lisp_Process *p;
897 register Lisp_Object status;
899 if (STRINGP (process))
900 process = Fget_process (process);
901 else
902 process = get_process (process);
904 if (NILP (process))
905 return process;
907 p = XPROCESS (process);
908 if (p->raw_status_new)
909 update_status (p);
910 status = p->status;
911 if (CONSP (status))
912 status = XCAR (status);
913 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
915 if (EQ (status, Qexit))
916 status = Qclosed;
917 else if (EQ (p->command, Qt))
918 status = Qstop;
919 else if (EQ (status, Qrun))
920 status = Qopen;
922 return status;
925 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
926 1, 1, 0,
927 doc: /* Return the exit status of PROCESS or the signal number that killed it.
928 If PROCESS has not yet exited or died, return 0. */)
929 (register Lisp_Object process)
931 CHECK_PROCESS (process);
932 if (XPROCESS (process)->raw_status_new)
933 update_status (XPROCESS (process));
934 if (CONSP (XPROCESS (process)->status))
935 return XCAR (XCDR (XPROCESS (process)->status));
936 return make_number (0);
939 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
940 doc: /* Return the process id of PROCESS.
941 This is the pid of the external process which PROCESS uses or talks to.
942 For a network connection, this value is nil. */)
943 (register Lisp_Object process)
945 pid_t pid;
947 CHECK_PROCESS (process);
948 pid = XPROCESS (process)->pid;
949 return (pid ? make_fixnum_or_float (pid) : Qnil);
952 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
953 doc: /* Return the name of PROCESS, as a string.
954 This is the name of the program invoked in PROCESS,
955 possibly modified to make it unique among process names. */)
956 (register Lisp_Object process)
958 CHECK_PROCESS (process);
959 return XPROCESS (process)->name;
962 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
963 doc: /* Return the command that was executed to start PROCESS.
964 This is a list of strings, the first string being the program executed
965 and the rest of the strings being the arguments given to it.
966 For a network or serial process, this is nil (process is running) or t
967 \(process is stopped). */)
968 (register Lisp_Object process)
970 CHECK_PROCESS (process);
971 return XPROCESS (process)->command;
974 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
975 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
976 This is the terminal that the process itself reads and writes on,
977 not the name of the pty that Emacs uses to talk with that terminal. */)
978 (register Lisp_Object process)
980 CHECK_PROCESS (process);
981 return XPROCESS (process)->tty_name;
984 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
985 2, 2, 0,
986 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
987 Return BUFFER. */)
988 (register Lisp_Object process, Lisp_Object buffer)
990 struct Lisp_Process *p;
992 CHECK_PROCESS (process);
993 if (!NILP (buffer))
994 CHECK_BUFFER (buffer);
995 p = XPROCESS (process);
996 pset_buffer (p, buffer);
997 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
998 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
999 setup_process_coding_systems (process);
1000 return buffer;
1003 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1004 1, 1, 0,
1005 doc: /* Return the buffer PROCESS is associated with.
1006 The default process filter inserts output from PROCESS into this buffer. */)
1007 (register Lisp_Object process)
1009 CHECK_PROCESS (process);
1010 return XPROCESS (process)->buffer;
1013 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1014 1, 1, 0,
1015 doc: /* Return the marker for the end of the last output from PROCESS. */)
1016 (register Lisp_Object process)
1018 CHECK_PROCESS (process);
1019 return XPROCESS (process)->mark;
1022 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1023 2, 2, 0,
1024 doc: /* Give PROCESS the filter function FILTER; nil means default.
1025 A value of t means stop accepting output from the process.
1027 When a process has a non-default filter, its buffer is not used for output.
1028 Instead, each time it does output, the entire string of output is
1029 passed to the filter.
1031 The filter gets two arguments: the process and the string of output.
1032 The string argument is normally a multibyte string, except:
1033 - if the process's input coding system is no-conversion or raw-text,
1034 it is a unibyte string (the non-converted input), or else
1035 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1036 string (the result of converting the decoded input multibyte
1037 string to unibyte with `string-make-unibyte'). */)
1038 (register Lisp_Object process, Lisp_Object filter)
1040 struct Lisp_Process *p;
1042 CHECK_PROCESS (process);
1043 p = XPROCESS (process);
1045 /* Don't signal an error if the process's input file descriptor
1046 is closed. This could make debugging Lisp more difficult,
1047 for example when doing something like
1049 (setq process (start-process ...))
1050 (debug)
1051 (set-process-filter process ...) */
1053 if (NILP (filter))
1054 filter = Qinternal_default_process_filter;
1056 if (p->infd >= 0)
1058 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1060 FD_CLR (p->infd, &input_wait_mask);
1061 FD_CLR (p->infd, &non_keyboard_wait_mask);
1063 else if (EQ (p->filter, Qt)
1064 /* Network or serial process not stopped: */
1065 && !EQ (p->command, Qt))
1067 FD_SET (p->infd, &input_wait_mask);
1068 FD_SET (p->infd, &non_keyboard_wait_mask);
1072 pset_filter (p, filter);
1073 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1074 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1075 setup_process_coding_systems (process);
1076 return filter;
1079 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1080 1, 1, 0,
1081 doc: /* Return the filter function of PROCESS.
1082 See `set-process-filter' for more info on filter functions. */)
1083 (register Lisp_Object process)
1085 CHECK_PROCESS (process);
1086 return XPROCESS (process)->filter;
1089 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1090 2, 2, 0,
1091 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1092 The sentinel is called as a function when the process changes state.
1093 It gets two arguments: the process, and a string describing the change. */)
1094 (register Lisp_Object process, Lisp_Object sentinel)
1096 struct Lisp_Process *p;
1098 CHECK_PROCESS (process);
1099 p = XPROCESS (process);
1101 if (NILP (sentinel))
1102 sentinel = Qinternal_default_process_sentinel;
1104 pset_sentinel (p, sentinel);
1105 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1106 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1107 return sentinel;
1110 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1111 1, 1, 0,
1112 doc: /* Return the sentinel of PROCESS.
1113 See `set-process-sentinel' for more info on sentinels. */)
1114 (register Lisp_Object process)
1116 CHECK_PROCESS (process);
1117 return XPROCESS (process)->sentinel;
1120 DEFUN ("set-process-window-size", Fset_process_window_size,
1121 Sset_process_window_size, 3, 3, 0,
1122 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1123 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1125 CHECK_PROCESS (process);
1127 /* All known platforms store window sizes as 'unsigned short'. */
1128 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1129 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1131 if (XPROCESS (process)->infd < 0
1132 || (set_window_size (XPROCESS (process)->infd,
1133 XINT (height), XINT (width))
1134 < 0))
1135 return Qnil;
1136 else
1137 return Qt;
1140 DEFUN ("set-process-inherit-coding-system-flag",
1141 Fset_process_inherit_coding_system_flag,
1142 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1143 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1144 If the second argument FLAG is non-nil, then the variable
1145 `buffer-file-coding-system' of the buffer associated with PROCESS
1146 will be bound to the value of the coding system used to decode
1147 the process output.
1149 This is useful when the coding system specified for the process buffer
1150 leaves either the character code conversion or the end-of-line conversion
1151 unspecified, or if the coding system used to decode the process output
1152 is more appropriate for saving the process buffer.
1154 Binding the variable `inherit-process-coding-system' to non-nil before
1155 starting the process is an alternative way of setting the inherit flag
1156 for the process which will run.
1158 This function returns FLAG. */)
1159 (register Lisp_Object process, Lisp_Object flag)
1161 CHECK_PROCESS (process);
1162 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1163 return flag;
1166 DEFUN ("set-process-query-on-exit-flag",
1167 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1168 2, 2, 0,
1169 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1170 If the second argument FLAG is non-nil, Emacs will query the user before
1171 exiting or killing a buffer if PROCESS is running. This function
1172 returns FLAG. */)
1173 (register Lisp_Object process, Lisp_Object flag)
1175 CHECK_PROCESS (process);
1176 XPROCESS (process)->kill_without_query = NILP (flag);
1177 return flag;
1180 DEFUN ("process-query-on-exit-flag",
1181 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1182 1, 1, 0,
1183 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1184 (register Lisp_Object process)
1186 CHECK_PROCESS (process);
1187 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1190 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1191 1, 2, 0,
1192 doc: /* Return the contact info of PROCESS; t for a real child.
1193 For a network or serial connection, the value depends on the optional
1194 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1195 SERVICE) for a network connection or (PORT SPEED) for a serial
1196 connection. If KEY is t, the complete contact information for the
1197 connection is returned, else the specific value for the keyword KEY is
1198 returned. See `make-network-process' or `make-serial-process' for a
1199 list of keywords. */)
1200 (register Lisp_Object process, Lisp_Object key)
1202 Lisp_Object contact;
1204 CHECK_PROCESS (process);
1205 contact = XPROCESS (process)->childp;
1207 #ifdef DATAGRAM_SOCKETS
1208 if (DATAGRAM_CONN_P (process)
1209 && (EQ (key, Qt) || EQ (key, QCremote)))
1210 contact = Fplist_put (contact, QCremote,
1211 Fprocess_datagram_address (process));
1212 #endif
1214 if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1215 || EQ (key, Qt))
1216 return contact;
1217 if (NILP (key) && NETCONN_P (process))
1218 return list2 (Fplist_get (contact, QChost),
1219 Fplist_get (contact, QCservice));
1220 if (NILP (key) && SERIALCONN_P (process))
1221 return list2 (Fplist_get (contact, QCport),
1222 Fplist_get (contact, QCspeed));
1223 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1224 if the pipe process is useful for purposes other than receiving
1225 stderr. */
1226 if (NILP (key) && PIPECONN_P (process))
1227 return Qt;
1228 return Fplist_get (contact, key);
1231 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1232 1, 1, 0,
1233 doc: /* Return the plist of PROCESS. */)
1234 (register Lisp_Object process)
1236 CHECK_PROCESS (process);
1237 return XPROCESS (process)->plist;
1240 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1241 2, 2, 0,
1242 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1243 (register Lisp_Object process, Lisp_Object plist)
1245 CHECK_PROCESS (process);
1246 CHECK_LIST (plist);
1248 pset_plist (XPROCESS (process), plist);
1249 return plist;
1252 #if 0 /* Turned off because we don't currently record this info
1253 in the process. Perhaps add it. */
1254 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1255 doc: /* Return the connection type of PROCESS.
1256 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1257 a socket connection. */)
1258 (Lisp_Object process)
1260 return XPROCESS (process)->type;
1262 #endif
1264 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1265 doc: /* Return the connection type of PROCESS.
1266 The value is either the symbol `real', `network', or `serial'.
1267 PROCESS may be a process, a buffer, the name of a process or buffer, or
1268 nil, indicating the current buffer's process. */)
1269 (Lisp_Object process)
1271 Lisp_Object proc;
1272 proc = get_process (process);
1273 return XPROCESS (proc)->type;
1276 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1277 1, 2, 0,
1278 doc: /* Convert network ADDRESS from internal format to a string.
1279 A 4 or 5 element vector represents an IPv4 address (with port number).
1280 An 8 or 9 element vector represents an IPv6 address (with port number).
1281 If optional second argument OMIT-PORT is non-nil, don't include a port
1282 number in the string, even when present in ADDRESS.
1283 Returns nil if format of ADDRESS is invalid. */)
1284 (Lisp_Object address, Lisp_Object omit_port)
1286 if (NILP (address))
1287 return Qnil;
1289 if (STRINGP (address)) /* AF_LOCAL */
1290 return address;
1292 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1294 register struct Lisp_Vector *p = XVECTOR (address);
1295 ptrdiff_t size = p->header.size;
1296 Lisp_Object args[10];
1297 int nargs, i;
1298 char const *format;
1300 if (size == 4 || (size == 5 && !NILP (omit_port)))
1302 format = "%d.%d.%d.%d";
1303 nargs = 4;
1305 else if (size == 5)
1307 format = "%d.%d.%d.%d:%d";
1308 nargs = 5;
1310 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1312 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1313 nargs = 8;
1315 else if (size == 9)
1317 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1318 nargs = 9;
1320 else
1321 return Qnil;
1323 AUTO_STRING (format_obj, format);
1324 args[0] = format_obj;
1326 for (i = 0; i < nargs; i++)
1328 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1329 return Qnil;
1331 if (nargs <= 5 /* IPv4 */
1332 && i < 4 /* host, not port */
1333 && XINT (p->contents[i]) > 255)
1334 return Qnil;
1336 args[i + 1] = p->contents[i];
1339 return Fformat (nargs + 1, args);
1342 if (CONSP (address))
1344 AUTO_STRING (format, "<Family %d>");
1345 return CALLN (Fformat, format, Fcar (address));
1348 return Qnil;
1351 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1352 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1353 (void)
1355 return Fmapcar (Qcdr, Vprocess_alist);
1358 /* Starting asynchronous inferior processes. */
1360 static void start_process_unwind (Lisp_Object proc);
1362 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1363 doc: /* Start a program in a subprocess. Return the process object for it.
1365 This is similar to `start-process', but arguments are specified as
1366 keyword/argument pairs. The following arguments are defined:
1368 :name NAME -- NAME is name for process. It is modified if necessary
1369 to make it unique.
1371 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1372 with the process. Process output goes at end of that buffer, unless
1373 you specify an output stream or filter function to handle the output.
1374 BUFFER may be also nil, meaning that this process is not associated
1375 with any buffer.
1377 :command COMMAND -- COMMAND is a list starting with the program file
1378 name, followed by strings to give to the program as arguments.
1380 :coding CODING -- If CODING is a symbol, it specifies the coding
1381 system used for both reading and writing for this process. If CODING
1382 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1383 ENCODING is used for writing.
1385 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1386 the process is running. If BOOL is not given, query before exiting.
1388 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1389 In the stopped state, a process does not accept incoming data, but you
1390 can send outgoing data. The stopped state is cleared by
1391 `continue-process' and set by `stop-process'.
1393 :connection-type TYPE -- TYPE is control type of device used to
1394 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1395 to use a pty, or nil to use the default specified through
1396 `process-connection-type'.
1398 :filter FILTER -- Install FILTER as the process filter.
1400 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1402 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1403 to the standard error of subprocess. Specifying this implies
1404 `:connection-type' is set to `pipe'.
1406 usage: (make-process &rest ARGS) */)
1407 (ptrdiff_t nargs, Lisp_Object *args)
1409 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1410 Lisp_Object xstderr, stderrproc;
1411 ptrdiff_t count = SPECPDL_INDEX ();
1412 struct gcpro gcpro1;
1413 USE_SAFE_ALLOCA;
1415 if (nargs == 0)
1416 return Qnil;
1418 /* Save arguments for process-contact and clone-process. */
1419 contact = Flist (nargs, args);
1420 GCPRO1 (contact);
1422 buffer = Fplist_get (contact, QCbuffer);
1423 if (!NILP (buffer))
1424 buffer = Fget_buffer_create (buffer);
1426 /* Make sure that the child will be able to chdir to the current
1427 buffer's current directory, or its unhandled equivalent. We
1428 can't just have the child check for an error when it does the
1429 chdir, since it's in a vfork.
1431 We have to GCPRO around this because Fexpand_file_name and
1432 Funhandled_file_name_directory might call a file name handling
1433 function. The argument list is protected by the caller, so all
1434 we really have to worry about is buffer. */
1436 struct gcpro gcpro1;
1437 GCPRO1 (buffer);
1438 current_dir = encode_current_directory ();
1439 UNGCPRO;
1442 name = Fplist_get (contact, QCname);
1443 CHECK_STRING (name);
1445 command = Fplist_get (contact, QCcommand);
1446 if (CONSP (command))
1447 program = XCAR (command);
1448 else
1449 program = Qnil;
1451 if (!NILP (program))
1452 CHECK_STRING (program);
1454 stderrproc = Qnil;
1455 xstderr = Fplist_get (contact, QCstderr);
1456 if (PROCESSP (xstderr))
1458 if (!PIPECONN_P (xstderr))
1459 error ("Process is not a pipe process");
1460 stderrproc = xstderr;
1462 else if (!NILP (xstderr))
1464 struct gcpro gcpro1, gcpro2;
1465 CHECK_STRING (program);
1466 GCPRO2 (buffer, current_dir);
1467 stderrproc = CALLN (Fmake_pipe_process,
1468 QCname,
1469 concat2 (name, build_string (" stderr")),
1470 QCbuffer,
1471 Fget_buffer_create (xstderr));
1472 UNGCPRO;
1475 proc = make_process (name);
1476 /* If an error occurs and we can't start the process, we want to
1477 remove it from the process list. This means that each error
1478 check in create_process doesn't need to call remove_process
1479 itself; it's all taken care of here. */
1480 record_unwind_protect (start_process_unwind, proc);
1482 pset_childp (XPROCESS (proc), Qt);
1483 pset_plist (XPROCESS (proc), Qnil);
1484 pset_type (XPROCESS (proc), Qreal);
1485 pset_buffer (XPROCESS (proc), buffer);
1486 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1487 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1488 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1490 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
1491 XPROCESS (proc)->kill_without_query = 1;
1492 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1493 pset_command (XPROCESS (proc), Qt);
1495 tem = Fplist_get (contact, QCconnection_type);
1496 if (EQ (tem, Qpty))
1497 XPROCESS (proc)->pty_flag = true;
1498 else if (EQ (tem, Qpipe))
1499 XPROCESS (proc)->pty_flag = false;
1500 else if (NILP (tem))
1501 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1502 else
1503 report_file_error ("Unknown connection type", tem);
1505 if (!NILP (stderrproc))
1507 pset_stderrproc (XPROCESS (proc), stderrproc);
1509 XPROCESS (proc)->pty_flag = false;
1512 #ifdef HAVE_GNUTLS
1513 /* AKA GNUTLS_INITSTAGE(proc). */
1514 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1515 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1516 #endif
1518 #ifdef ADAPTIVE_READ_BUFFERING
1519 XPROCESS (proc)->adaptive_read_buffering
1520 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1521 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1522 #endif
1524 /* Make the process marker point into the process buffer (if any). */
1525 if (BUFFERP (buffer))
1526 set_marker_both (XPROCESS (proc)->mark, buffer,
1527 BUF_ZV (XBUFFER (buffer)),
1528 BUF_ZV_BYTE (XBUFFER (buffer)));
1531 /* Decide coding systems for communicating with the process. Here
1532 we don't setup the structure coding_system nor pay attention to
1533 unibyte mode. They are done in create_process. */
1535 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1536 Lisp_Object coding_systems = Qt;
1537 Lisp_Object val, *args2;
1538 struct gcpro gcpro1, gcpro2;
1540 tem = Fplist_get (contact, QCcoding);
1541 if (!NILP (tem))
1543 val = tem;
1544 if (CONSP (val))
1545 val = XCAR (val);
1547 else
1548 val = Vcoding_system_for_read;
1549 if (NILP (val))
1551 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1552 Lisp_Object tem2;
1553 SAFE_ALLOCA_LISP (args2, nargs2);
1554 ptrdiff_t i = 0;
1555 args2[i++] = Qstart_process;
1556 args2[i++] = name;
1557 args2[i++] = buffer;
1558 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1559 args2[i++] = XCAR (tem2);
1560 GCPRO2 (proc, current_dir);
1561 if (!NILP (program))
1562 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1563 UNGCPRO;
1564 if (CONSP (coding_systems))
1565 val = XCAR (coding_systems);
1566 else if (CONSP (Vdefault_process_coding_system))
1567 val = XCAR (Vdefault_process_coding_system);
1569 pset_decode_coding_system (XPROCESS (proc), val);
1571 if (!NILP (tem))
1573 val = tem;
1574 if (CONSP (val))
1575 val = XCDR (val);
1577 else
1578 val = Vcoding_system_for_write;
1579 if (NILP (val))
1581 if (EQ (coding_systems, Qt))
1583 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1584 Lisp_Object tem2;
1585 SAFE_ALLOCA_LISP (args2, nargs2);
1586 ptrdiff_t i = 0;
1587 args2[i++] = Qstart_process;
1588 args2[i++] = name;
1589 args2[i++] = buffer;
1590 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1591 args2[i++] = XCAR (tem2);
1592 GCPRO2 (proc, current_dir);
1593 if (!NILP (program))
1594 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1595 UNGCPRO;
1597 if (CONSP (coding_systems))
1598 val = XCDR (coding_systems);
1599 else if (CONSP (Vdefault_process_coding_system))
1600 val = XCDR (Vdefault_process_coding_system);
1602 pset_encode_coding_system (XPROCESS (proc), val);
1603 /* Note: At this moment, the above coding system may leave
1604 text-conversion or eol-conversion unspecified. They will be
1605 decided after we read output from the process and decode it by
1606 some coding system, or just before we actually send a text to
1607 the process. */
1611 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1612 XPROCESS (proc)->decoding_carryover = 0;
1613 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1615 XPROCESS (proc)->inherit_coding_system_flag
1616 = !(NILP (buffer) || !inherit_process_coding_system);
1618 if (!NILP (program))
1620 Lisp_Object program_args = XCDR (command);
1622 /* If program file name is not absolute, search our path for it.
1623 Put the name we will really use in TEM. */
1624 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1625 && !(SCHARS (program) > 1
1626 && IS_DEVICE_SEP (SREF (program, 1))))
1628 struct gcpro gcpro1, gcpro2;
1630 tem = Qnil;
1631 GCPRO2 (buffer, current_dir);
1632 openp (Vexec_path, program, Vexec_suffixes, &tem,
1633 make_number (X_OK), false);
1634 UNGCPRO;
1635 if (NILP (tem))
1636 report_file_error ("Searching for program", program);
1637 tem = Fexpand_file_name (tem, Qnil);
1639 else
1641 if (!NILP (Ffile_directory_p (program)))
1642 error ("Specified program for new process is a directory");
1643 tem = program;
1646 /* Remove "/:" from TEM. */
1647 tem = remove_slash_colon (tem);
1649 Lisp_Object arg_encoding = Qnil;
1650 struct gcpro gcpro1;
1651 GCPRO1 (tem);
1653 /* Encode the file name and put it in NEW_ARGV.
1654 That's where the child will use it to execute the program. */
1655 tem = list1 (ENCODE_FILE (tem));
1656 ptrdiff_t new_argc = 1;
1658 /* Here we encode arguments by the coding system used for sending
1659 data to the process. We don't support using different coding
1660 systems for encoding arguments and for encoding data sent to the
1661 process. */
1663 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1665 Lisp_Object arg = XCAR (tem2);
1666 CHECK_STRING (arg);
1667 if (STRING_MULTIBYTE (arg))
1669 if (NILP (arg_encoding))
1670 arg_encoding = (complement_process_encoding_system
1671 (XPROCESS (proc)->encode_coding_system));
1672 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1674 tem = Fcons (arg, tem);
1675 new_argc++;
1678 UNGCPRO;
1680 /* Now that everything is encoded we can collect the strings into
1681 NEW_ARGV. */
1682 char **new_argv;
1683 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1684 new_argv[new_argc] = 0;
1686 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1688 new_argv[i] = SSDATA (XCAR (tem));
1689 tem = XCDR (tem);
1692 create_process (proc, new_argv, current_dir);
1694 else
1695 create_pty (proc);
1697 UNGCPRO;
1698 SAFE_FREE ();
1699 return unbind_to (count, proc);
1702 /* This function is the unwind_protect form for Fstart_process. If
1703 PROC doesn't have its pid set, then we know someone has signaled
1704 an error and the process wasn't started successfully, so we should
1705 remove it from the process list. */
1706 static void
1707 start_process_unwind (Lisp_Object proc)
1709 if (!PROCESSP (proc))
1710 emacs_abort ();
1712 /* Was PROC started successfully?
1713 -2 is used for a pty with no process, eg for gdb. */
1714 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1715 remove_process (proc);
1718 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1720 static void
1721 close_process_fd (int *fd_addr)
1723 int fd = *fd_addr;
1724 if (0 <= fd)
1726 *fd_addr = -1;
1727 emacs_close (fd);
1731 /* Indexes of file descriptors in open_fds. */
1732 enum
1734 /* The pipe from Emacs to its subprocess. */
1735 SUBPROCESS_STDIN,
1736 WRITE_TO_SUBPROCESS,
1738 /* The main pipe from the subprocess to Emacs. */
1739 READ_FROM_SUBPROCESS,
1740 SUBPROCESS_STDOUT,
1742 /* The pipe from the subprocess to Emacs that is closed when the
1743 subprocess execs. */
1744 READ_FROM_EXEC_MONITOR,
1745 EXEC_MONITOR_OUTPUT
1748 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1750 static void
1751 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1753 struct Lisp_Process *p = XPROCESS (process);
1754 int inchannel, outchannel;
1755 pid_t pid;
1756 int vfork_errno;
1757 int forkin, forkout, forkerr = -1;
1758 bool pty_flag = 0;
1759 char pty_name[PTY_NAME_SIZE];
1760 Lisp_Object lisp_pty_name = Qnil;
1761 sigset_t oldset;
1763 inchannel = outchannel = -1;
1765 if (p->pty_flag)
1766 outchannel = inchannel = allocate_pty (pty_name);
1768 if (inchannel >= 0)
1770 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1771 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1772 /* On most USG systems it does not work to open the pty's tty here,
1773 then close it and reopen it in the child. */
1774 /* Don't let this terminal become our controlling terminal
1775 (in case we don't have one). */
1776 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1777 if (forkin < 0)
1778 report_file_error ("Opening pty", Qnil);
1779 p->open_fd[SUBPROCESS_STDIN] = forkin;
1780 #else
1781 forkin = forkout = -1;
1782 #endif /* not USG, or USG_SUBTTY_WORKS */
1783 pty_flag = 1;
1784 lisp_pty_name = build_string (pty_name);
1786 else
1788 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1789 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1790 report_file_error ("Creating pipe", Qnil);
1791 forkin = p->open_fd[SUBPROCESS_STDIN];
1792 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1793 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1794 forkout = p->open_fd[SUBPROCESS_STDOUT];
1796 if (!NILP (p->stderrproc))
1798 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
1800 forkerr = pp->open_fd[SUBPROCESS_STDOUT];
1802 /* Close unnecessary file descriptors. */
1803 close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
1804 close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
1808 #ifndef WINDOWSNT
1809 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1810 report_file_error ("Creating pipe", Qnil);
1811 #endif
1813 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1814 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1816 /* Record this as an active process, with its channels. */
1817 chan_process[inchannel] = process;
1818 p->infd = inchannel;
1819 p->outfd = outchannel;
1821 /* Previously we recorded the tty descriptor used in the subprocess.
1822 It was only used for getting the foreground tty process, so now
1823 we just reopen the device (see emacs_get_tty_pgrp) as this is
1824 more portable (see USG_SUBTTY_WORKS above). */
1826 p->pty_flag = pty_flag;
1827 pset_status (p, Qrun);
1829 if (!EQ (p->command, Qt))
1831 FD_SET (inchannel, &input_wait_mask);
1832 FD_SET (inchannel, &non_keyboard_wait_mask);
1835 if (inchannel > max_process_desc)
1836 max_process_desc = inchannel;
1838 /* This may signal an error. */
1839 setup_process_coding_systems (process);
1841 block_input ();
1842 block_child_signal (&oldset);
1844 #ifndef WINDOWSNT
1845 /* vfork, and prevent local vars from being clobbered by the vfork. */
1847 Lisp_Object volatile current_dir_volatile = current_dir;
1848 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1849 char **volatile new_argv_volatile = new_argv;
1850 int volatile forkin_volatile = forkin;
1851 int volatile forkout_volatile = forkout;
1852 int volatile forkerr_volatile = forkerr;
1853 struct Lisp_Process *p_volatile = p;
1855 pid = vfork ();
1857 current_dir = current_dir_volatile;
1858 lisp_pty_name = lisp_pty_name_volatile;
1859 new_argv = new_argv_volatile;
1860 forkin = forkin_volatile;
1861 forkout = forkout_volatile;
1862 forkerr = forkerr_volatile;
1863 p = p_volatile;
1865 pty_flag = p->pty_flag;
1868 if (pid == 0)
1869 #endif /* not WINDOWSNT */
1871 int xforkin = forkin;
1872 int xforkout = forkout;
1873 int xforkerr = forkerr;
1875 /* Make the pty be the controlling terminal of the process. */
1876 #ifdef HAVE_PTYS
1877 /* First, disconnect its current controlling terminal. */
1878 /* We tried doing setsid only if pty_flag, but it caused
1879 process_set_signal to fail on SGI when using a pipe. */
1880 setsid ();
1881 /* Make the pty's terminal the controlling terminal. */
1882 if (pty_flag && xforkin >= 0)
1884 #ifdef TIOCSCTTY
1885 /* We ignore the return value
1886 because faith@cs.unc.edu says that is necessary on Linux. */
1887 ioctl (xforkin, TIOCSCTTY, 0);
1888 #endif
1890 #if defined (LDISC1)
1891 if (pty_flag && xforkin >= 0)
1893 struct termios t;
1894 tcgetattr (xforkin, &t);
1895 t.c_lflag = LDISC1;
1896 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1897 emacs_perror ("create_process/tcsetattr LDISC1");
1899 #else
1900 #if defined (NTTYDISC) && defined (TIOCSETD)
1901 if (pty_flag && xforkin >= 0)
1903 /* Use new line discipline. */
1904 int ldisc = NTTYDISC;
1905 ioctl (xforkin, TIOCSETD, &ldisc);
1907 #endif
1908 #endif
1909 #ifdef TIOCNOTTY
1910 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1911 can do TIOCSPGRP only to the process's controlling tty. */
1912 if (pty_flag)
1914 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1915 I can't test it since I don't have 4.3. */
1916 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1917 if (j >= 0)
1919 ioctl (j, TIOCNOTTY, 0);
1920 emacs_close (j);
1923 #endif /* TIOCNOTTY */
1925 #if !defined (DONT_REOPEN_PTY)
1926 /*** There is a suggestion that this ought to be a
1927 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1928 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1929 that system does seem to need this code, even though
1930 both TIOCSCTTY is defined. */
1931 /* Now close the pty (if we had it open) and reopen it.
1932 This makes the pty the controlling terminal of the subprocess. */
1933 if (pty_flag)
1936 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1937 would work? */
1938 if (xforkin >= 0)
1939 emacs_close (xforkin);
1940 xforkout = xforkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1942 if (xforkin < 0)
1944 emacs_perror (SSDATA (lisp_pty_name));
1945 _exit (EXIT_CANCELED);
1949 #endif /* not DONT_REOPEN_PTY */
1951 #ifdef SETUP_SLAVE_PTY
1952 if (pty_flag)
1954 SETUP_SLAVE_PTY;
1956 #endif /* SETUP_SLAVE_PTY */
1957 #endif /* HAVE_PTYS */
1959 signal (SIGINT, SIG_DFL);
1960 signal (SIGQUIT, SIG_DFL);
1961 #ifdef SIGPROF
1962 signal (SIGPROF, SIG_DFL);
1963 #endif
1965 /* Emacs ignores SIGPIPE, but the child should not. */
1966 signal (SIGPIPE, SIG_DFL);
1968 /* Stop blocking SIGCHLD in the child. */
1969 unblock_child_signal (&oldset);
1971 if (pty_flag)
1972 child_setup_tty (xforkout);
1974 if (xforkerr < 0)
1975 xforkerr = xforkout;
1976 #ifdef WINDOWSNT
1977 pid = child_setup (xforkin, xforkout, xforkerr, new_argv, 1, current_dir);
1978 #else /* not WINDOWSNT */
1979 child_setup (xforkin, xforkout, xforkerr, new_argv, 1, current_dir);
1980 #endif /* not WINDOWSNT */
1983 /* Back in the parent process. */
1985 vfork_errno = errno;
1986 p->pid = pid;
1987 if (pid >= 0)
1988 p->alive = 1;
1990 /* Stop blocking in the parent. */
1991 unblock_child_signal (&oldset);
1992 unblock_input ();
1994 if (pid < 0)
1995 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1996 else
1998 /* vfork succeeded. */
2000 /* Close the pipe ends that the child uses, or the child's pty. */
2001 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
2002 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
2004 #ifdef WINDOWSNT
2005 register_child (pid, inchannel);
2006 #endif /* WINDOWSNT */
2008 pset_tty_name (p, lisp_pty_name);
2010 #ifndef WINDOWSNT
2011 /* Wait for child_setup to complete in case that vfork is
2012 actually defined as fork. The descriptor
2013 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2014 of a pipe is closed at the child side either by close-on-exec
2015 on successful execve or the _exit call in child_setup. */
2017 char dummy;
2019 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
2020 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
2021 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
2023 #endif
2024 if (!NILP (p->stderrproc))
2026 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2027 close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
2032 static void
2033 create_pty (Lisp_Object process)
2035 struct Lisp_Process *p = XPROCESS (process);
2036 char pty_name[PTY_NAME_SIZE];
2037 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
2039 if (pty_fd >= 0)
2041 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
2042 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2043 /* On most USG systems it does not work to open the pty's tty here,
2044 then close it and reopen it in the child. */
2045 /* Don't let this terminal become our controlling terminal
2046 (in case we don't have one). */
2047 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2048 if (forkout < 0)
2049 report_file_error ("Opening pty", Qnil);
2050 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2051 #if defined (DONT_REOPEN_PTY)
2052 /* In the case that vfork is defined as fork, the parent process
2053 (Emacs) may send some data before the child process completes
2054 tty options setup. So we setup tty before forking. */
2055 child_setup_tty (forkout);
2056 #endif /* DONT_REOPEN_PTY */
2057 #endif /* not USG, or USG_SUBTTY_WORKS */
2059 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2061 /* Record this as an active process, with its channels.
2062 As a result, child_setup will close Emacs's side of the pipes. */
2063 chan_process[pty_fd] = process;
2064 p->infd = pty_fd;
2065 p->outfd = pty_fd;
2067 /* Previously we recorded the tty descriptor used in the subprocess.
2068 It was only used for getting the foreground tty process, so now
2069 we just reopen the device (see emacs_get_tty_pgrp) as this is
2070 more portable (see USG_SUBTTY_WORKS above). */
2072 p->pty_flag = 1;
2073 pset_status (p, Qrun);
2074 setup_process_coding_systems (process);
2076 FD_SET (pty_fd, &input_wait_mask);
2077 FD_SET (pty_fd, &non_keyboard_wait_mask);
2078 if (pty_fd > max_process_desc)
2079 max_process_desc = pty_fd;
2081 pset_tty_name (p, build_string (pty_name));
2084 p->pid = -2;
2087 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2088 0, MANY, 0,
2089 doc: /* Create and return a bidirectional pipe process.
2091 In Emacs, pipes are represented by process objects, so input and
2092 output work as for subprocesses, and `delete-process' closes a pipe.
2093 However, a pipe process has no process id, it cannot be signaled,
2094 and the status codes are different from normal processes.
2096 Arguments are specified as keyword/argument pairs. The following
2097 arguments are defined:
2099 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2101 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2102 with the process. Process output goes at the end of that buffer,
2103 unless you specify an output stream or filter function to handle the
2104 output. If BUFFER is not given, the value of NAME is used.
2106 :coding CODING -- If CODING is a symbol, it specifies the coding
2107 system used for both reading and writing for this process. If CODING
2108 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2109 ENCODING is used for writing.
2111 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2112 the process is running. If BOOL is not given, query before exiting.
2114 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2115 In the stopped state, a pipe process does not accept incoming data,
2116 but you can send outgoing data. The stopped state is cleared by
2117 `continue-process' and set by `stop-process'.
2119 :filter FILTER -- Install FILTER as the process filter.
2121 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2123 usage: (make-pipe-process &rest ARGS) */)
2124 (ptrdiff_t nargs, Lisp_Object *args)
2126 Lisp_Object proc, contact;
2127 struct Lisp_Process *p;
2128 struct gcpro gcpro1;
2129 Lisp_Object name, buffer;
2130 Lisp_Object tem;
2131 ptrdiff_t specpdl_count;
2132 int inchannel, outchannel;
2134 if (nargs == 0)
2135 return Qnil;
2137 contact = Flist (nargs, args);
2138 GCPRO1 (contact);
2140 name = Fplist_get (contact, QCname);
2141 CHECK_STRING (name);
2142 proc = make_process (name);
2143 specpdl_count = SPECPDL_INDEX ();
2144 record_unwind_protect (remove_process, proc);
2145 p = XPROCESS (proc);
2147 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2148 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2149 report_file_error ("Creating pipe", Qnil);
2150 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2151 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2153 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2154 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2156 #ifdef WINDOWSNT
2157 register_aux_fd (inchannel);
2158 #endif
2160 /* Record this as an active process, with its channels. */
2161 chan_process[inchannel] = proc;
2162 p->infd = inchannel;
2163 p->outfd = outchannel;
2165 if (inchannel > max_process_desc)
2166 max_process_desc = inchannel;
2168 buffer = Fplist_get (contact, QCbuffer);
2169 if (NILP (buffer))
2170 buffer = name;
2171 buffer = Fget_buffer_create (buffer);
2172 pset_buffer (p, buffer);
2174 pset_childp (p, contact);
2175 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2176 pset_type (p, Qpipe);
2177 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2178 pset_filter (p, Fplist_get (contact, QCfilter));
2179 pset_log (p, Qnil);
2180 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2181 p->kill_without_query = 1;
2182 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2183 pset_command (p, Qt);
2184 eassert (! p->pty_flag);
2186 if (!EQ (p->command, Qt))
2188 FD_SET (inchannel, &input_wait_mask);
2189 FD_SET (inchannel, &non_keyboard_wait_mask);
2191 #ifdef ADAPTIVE_READ_BUFFERING
2192 p->adaptive_read_buffering
2193 = (NILP (Vprocess_adaptive_read_buffering) ? 0
2194 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2195 #endif
2197 /* Make the process marker point into the process buffer (if any). */
2198 if (BUFFERP (buffer))
2199 set_marker_both (p->mark, buffer,
2200 BUF_ZV (XBUFFER (buffer)),
2201 BUF_ZV_BYTE (XBUFFER (buffer)));
2204 /* Setup coding systems for communicating with the network stream. */
2206 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2207 Lisp_Object coding_systems = Qt;
2208 Lisp_Object val;
2210 tem = Fplist_get (contact, QCcoding);
2211 val = Qnil;
2212 if (!NILP (tem))
2214 val = tem;
2215 if (CONSP (val))
2216 val = XCAR (val);
2218 else if (!NILP (Vcoding_system_for_read))
2219 val = Vcoding_system_for_read;
2220 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2221 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2222 /* We dare not decode end-of-line format by setting VAL to
2223 Qraw_text, because the existing Emacs Lisp libraries
2224 assume that they receive bare code including a sequence of
2225 CR LF. */
2226 val = Qnil;
2227 else
2229 if (CONSP (coding_systems))
2230 val = XCAR (coding_systems);
2231 else if (CONSP (Vdefault_process_coding_system))
2232 val = XCAR (Vdefault_process_coding_system);
2233 else
2234 val = Qnil;
2236 pset_decode_coding_system (p, val);
2238 if (!NILP (tem))
2240 val = tem;
2241 if (CONSP (val))
2242 val = XCDR (val);
2244 else if (!NILP (Vcoding_system_for_write))
2245 val = Vcoding_system_for_write;
2246 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2247 val = Qnil;
2248 else
2250 if (CONSP (coding_systems))
2251 val = XCDR (coding_systems);
2252 else if (CONSP (Vdefault_process_coding_system))
2253 val = XCDR (Vdefault_process_coding_system);
2254 else
2255 val = Qnil;
2257 pset_encode_coding_system (p, val);
2259 /* This may signal an error. */
2260 setup_process_coding_systems (proc);
2262 specpdl_ptr = specpdl + specpdl_count;
2264 UNGCPRO;
2265 return proc;
2269 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2270 The address family of sa is not included in the result. */
2272 Lisp_Object
2273 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2275 Lisp_Object address;
2276 int i;
2277 unsigned char *cp;
2278 register struct Lisp_Vector *p;
2280 /* Workaround for a bug in getsockname on BSD: Names bound to
2281 sockets in the UNIX domain are inaccessible; getsockname returns
2282 a zero length name. */
2283 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2284 return empty_unibyte_string;
2286 switch (sa->sa_family)
2288 case AF_INET:
2290 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2291 len = sizeof (sin->sin_addr) + 1;
2292 address = Fmake_vector (make_number (len), Qnil);
2293 p = XVECTOR (address);
2294 p->contents[--len] = make_number (ntohs (sin->sin_port));
2295 cp = (unsigned char *) &sin->sin_addr;
2296 break;
2298 #ifdef AF_INET6
2299 case AF_INET6:
2301 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2302 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2303 len = sizeof (sin6->sin6_addr) / 2 + 1;
2304 address = Fmake_vector (make_number (len), Qnil);
2305 p = XVECTOR (address);
2306 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2307 for (i = 0; i < len; i++)
2308 p->contents[i] = make_number (ntohs (ip6[i]));
2309 return address;
2311 #endif
2312 #ifdef HAVE_LOCAL_SOCKETS
2313 case AF_LOCAL:
2315 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2316 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2317 /* If the first byte is NUL, the name is a Linux abstract
2318 socket name, and the name can contain embedded NULs. If
2319 it's not, we have a NUL-terminated string. Be careful not
2320 to walk past the end of the object looking for the name
2321 terminator, however. */
2322 if (name_length > 0 && sockun->sun_path[0] != '\0')
2324 const char *terminator
2325 = memchr (sockun->sun_path, '\0', name_length);
2327 if (terminator)
2328 name_length = terminator - (const char *) sockun->sun_path;
2331 return make_unibyte_string (sockun->sun_path, name_length);
2333 #endif
2334 default:
2335 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2336 address = Fcons (make_number (sa->sa_family),
2337 Fmake_vector (make_number (len), Qnil));
2338 p = XVECTOR (XCDR (address));
2339 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2340 break;
2343 i = 0;
2344 while (i < len)
2345 p->contents[i++] = make_number (*cp++);
2347 return address;
2351 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2353 static int
2354 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2356 register struct Lisp_Vector *p;
2358 if (VECTORP (address))
2360 p = XVECTOR (address);
2361 if (p->header.size == 5)
2363 *familyp = AF_INET;
2364 return sizeof (struct sockaddr_in);
2366 #ifdef AF_INET6
2367 else if (p->header.size == 9)
2369 *familyp = AF_INET6;
2370 return sizeof (struct sockaddr_in6);
2372 #endif
2374 #ifdef HAVE_LOCAL_SOCKETS
2375 else if (STRINGP (address))
2377 *familyp = AF_LOCAL;
2378 return sizeof (struct sockaddr_un);
2380 #endif
2381 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2382 && VECTORP (XCDR (address)))
2384 struct sockaddr *sa;
2385 p = XVECTOR (XCDR (address));
2386 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2387 return 0;
2388 *familyp = XINT (XCAR (address));
2389 return p->header.size + sizeof (sa->sa_family);
2391 return 0;
2394 /* Convert an address object (vector or string) to an internal sockaddr.
2396 The address format has been basically validated by
2397 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2398 it could have come from user data. So if FAMILY is not valid,
2399 we return after zeroing *SA. */
2401 static void
2402 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2404 register struct Lisp_Vector *p;
2405 register unsigned char *cp = NULL;
2406 register int i;
2407 EMACS_INT hostport;
2409 memset (sa, 0, len);
2411 if (VECTORP (address))
2413 p = XVECTOR (address);
2414 if (family == AF_INET)
2416 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2417 len = sizeof (sin->sin_addr) + 1;
2418 hostport = XINT (p->contents[--len]);
2419 sin->sin_port = htons (hostport);
2420 cp = (unsigned char *)&sin->sin_addr;
2421 sa->sa_family = family;
2423 #ifdef AF_INET6
2424 else if (family == AF_INET6)
2426 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2427 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2428 len = sizeof (sin6->sin6_addr) + 1;
2429 hostport = XINT (p->contents[--len]);
2430 sin6->sin6_port = htons (hostport);
2431 for (i = 0; i < len; i++)
2432 if (INTEGERP (p->contents[i]))
2434 int j = XFASTINT (p->contents[i]) & 0xffff;
2435 ip6[i] = ntohs (j);
2437 sa->sa_family = family;
2438 return;
2440 #endif
2441 else
2442 return;
2444 else if (STRINGP (address))
2446 #ifdef HAVE_LOCAL_SOCKETS
2447 if (family == AF_LOCAL)
2449 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2450 cp = SDATA (address);
2451 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2452 sockun->sun_path[i] = *cp++;
2453 sa->sa_family = family;
2455 #endif
2456 return;
2458 else
2460 p = XVECTOR (XCDR (address));
2461 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2464 for (i = 0; i < len; i++)
2465 if (INTEGERP (p->contents[i]))
2466 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2469 #ifdef DATAGRAM_SOCKETS
2470 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2471 1, 1, 0,
2472 doc: /* Get the current datagram address associated with PROCESS. */)
2473 (Lisp_Object process)
2475 int channel;
2477 CHECK_PROCESS (process);
2479 if (!DATAGRAM_CONN_P (process))
2480 return Qnil;
2482 channel = XPROCESS (process)->infd;
2483 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2484 datagram_address[channel].len);
2487 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2488 2, 2, 0,
2489 doc: /* Set the datagram address for PROCESS to ADDRESS.
2490 Returns nil upon error setting address, ADDRESS otherwise. */)
2491 (Lisp_Object process, Lisp_Object address)
2493 int channel;
2494 int family, len;
2496 CHECK_PROCESS (process);
2498 if (!DATAGRAM_CONN_P (process))
2499 return Qnil;
2501 channel = XPROCESS (process)->infd;
2503 len = get_lisp_to_sockaddr_size (address, &family);
2504 if (len == 0 || datagram_address[channel].len != len)
2505 return Qnil;
2506 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2507 return address;
2509 #endif
2512 static const struct socket_options {
2513 /* The name of this option. Should be lowercase version of option
2514 name without SO_ prefix. */
2515 const char *name;
2516 /* Option level SOL_... */
2517 int optlevel;
2518 /* Option number SO_... */
2519 int optnum;
2520 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2521 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2522 } socket_options[] =
2524 #ifdef SO_BINDTODEVICE
2525 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2526 #endif
2527 #ifdef SO_BROADCAST
2528 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2529 #endif
2530 #ifdef SO_DONTROUTE
2531 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2532 #endif
2533 #ifdef SO_KEEPALIVE
2534 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2535 #endif
2536 #ifdef SO_LINGER
2537 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2538 #endif
2539 #ifdef SO_OOBINLINE
2540 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2541 #endif
2542 #ifdef SO_PRIORITY
2543 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2544 #endif
2545 #ifdef SO_REUSEADDR
2546 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2547 #endif
2548 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2551 /* Set option OPT to value VAL on socket S.
2553 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2554 Signals an error if setting a known option fails.
2557 static int
2558 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2560 char *name;
2561 const struct socket_options *sopt;
2562 int ret = 0;
2564 CHECK_SYMBOL (opt);
2566 name = SSDATA (SYMBOL_NAME (opt));
2567 for (sopt = socket_options; sopt->name; sopt++)
2568 if (strcmp (name, sopt->name) == 0)
2569 break;
2571 switch (sopt->opttype)
2573 case SOPT_BOOL:
2575 int optval;
2576 optval = NILP (val) ? 0 : 1;
2577 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2578 &optval, sizeof (optval));
2579 break;
2582 case SOPT_INT:
2584 int optval;
2585 if (TYPE_RANGED_INTEGERP (int, val))
2586 optval = XINT (val);
2587 else
2588 error ("Bad option value for %s", name);
2589 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2590 &optval, sizeof (optval));
2591 break;
2594 #ifdef SO_BINDTODEVICE
2595 case SOPT_IFNAME:
2597 char devname[IFNAMSIZ + 1];
2599 /* This is broken, at least in the Linux 2.4 kernel.
2600 To unbind, the arg must be a zero integer, not the empty string.
2601 This should work on all systems. KFS. 2003-09-23. */
2602 memset (devname, 0, sizeof devname);
2603 if (STRINGP (val))
2605 char *arg = SSDATA (val);
2606 int len = min (strlen (arg), IFNAMSIZ);
2607 memcpy (devname, arg, len);
2609 else if (!NILP (val))
2610 error ("Bad option value for %s", name);
2611 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2612 devname, IFNAMSIZ);
2613 break;
2615 #endif
2617 #ifdef SO_LINGER
2618 case SOPT_LINGER:
2620 struct linger linger;
2622 linger.l_onoff = 1;
2623 linger.l_linger = 0;
2624 if (TYPE_RANGED_INTEGERP (int, val))
2625 linger.l_linger = XINT (val);
2626 else
2627 linger.l_onoff = NILP (val) ? 0 : 1;
2628 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2629 &linger, sizeof (linger));
2630 break;
2632 #endif
2634 default:
2635 return 0;
2638 if (ret < 0)
2640 int setsockopt_errno = errno;
2641 report_file_errno ("Cannot set network option", list2 (opt, val),
2642 setsockopt_errno);
2645 return (1 << sopt->optbit);
2649 DEFUN ("set-network-process-option",
2650 Fset_network_process_option, Sset_network_process_option,
2651 3, 4, 0,
2652 doc: /* For network process PROCESS set option OPTION to value VALUE.
2653 See `make-network-process' for a list of options and values.
2654 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2655 OPTION is not a supported option, return nil instead; otherwise return t. */)
2656 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2658 int s;
2659 struct Lisp_Process *p;
2661 CHECK_PROCESS (process);
2662 p = XPROCESS (process);
2663 if (!NETCONN1_P (p))
2664 error ("Process is not a network process");
2666 s = p->infd;
2667 if (s < 0)
2668 error ("Process is not running");
2670 if (set_socket_option (s, option, value))
2672 pset_childp (p, Fplist_put (p->childp, option, value));
2673 return Qt;
2676 if (NILP (no_error))
2677 error ("Unknown or unsupported option");
2679 return Qnil;
2683 DEFUN ("serial-process-configure",
2684 Fserial_process_configure,
2685 Sserial_process_configure,
2686 0, MANY, 0,
2687 doc: /* Configure speed, bytesize, etc. of a serial process.
2689 Arguments are specified as keyword/argument pairs. Attributes that
2690 are not given are re-initialized from the process's current
2691 configuration (available via the function `process-contact') or set to
2692 reasonable default values. The following arguments are defined:
2694 :process PROCESS
2695 :name NAME
2696 :buffer BUFFER
2697 :port PORT
2698 -- Any of these arguments can be given to identify the process that is
2699 to be configured. If none of these arguments is given, the current
2700 buffer's process is used.
2702 :speed SPEED -- SPEED is the speed of the serial port in bits per
2703 second, also called baud rate. Any value can be given for SPEED, but
2704 most serial ports work only at a few defined values between 1200 and
2705 115200, with 9600 being the most common value. If SPEED is nil, the
2706 serial port is not configured any further, i.e., all other arguments
2707 are ignored. This may be useful for special serial ports such as
2708 Bluetooth-to-serial converters which can only be configured through AT
2709 commands. A value of nil for SPEED can be used only when passed
2710 through `make-serial-process' or `serial-term'.
2712 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2713 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2715 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2716 `odd' (use odd parity), or the symbol `even' (use even parity). If
2717 PARITY is not given, no parity is used.
2719 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2720 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2721 is not given or nil, 1 stopbit is used.
2723 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2724 flowcontrol to be used, which is either nil (don't use flowcontrol),
2725 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2726 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2727 flowcontrol is used.
2729 `serial-process-configure' is called by `make-serial-process' for the
2730 initial configuration of the serial port.
2732 Examples:
2734 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2736 \(serial-process-configure
2737 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2739 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2741 usage: (serial-process-configure &rest ARGS) */)
2742 (ptrdiff_t nargs, Lisp_Object *args)
2744 struct Lisp_Process *p;
2745 Lisp_Object contact = Qnil;
2746 Lisp_Object proc = Qnil;
2747 struct gcpro gcpro1;
2749 contact = Flist (nargs, args);
2750 GCPRO1 (contact);
2752 proc = Fplist_get (contact, QCprocess);
2753 if (NILP (proc))
2754 proc = Fplist_get (contact, QCname);
2755 if (NILP (proc))
2756 proc = Fplist_get (contact, QCbuffer);
2757 if (NILP (proc))
2758 proc = Fplist_get (contact, QCport);
2759 proc = get_process (proc);
2760 p = XPROCESS (proc);
2761 if (!EQ (p->type, Qserial))
2762 error ("Not a serial process");
2764 if (NILP (Fplist_get (p->childp, QCspeed)))
2766 UNGCPRO;
2767 return Qnil;
2770 serial_configure (p, contact);
2772 UNGCPRO;
2773 return Qnil;
2776 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2777 0, MANY, 0,
2778 doc: /* Create and return a serial port process.
2780 In Emacs, serial port connections are represented by process objects,
2781 so input and output work as for subprocesses, and `delete-process'
2782 closes a serial port connection. However, a serial process has no
2783 process id, it cannot be signaled, and the status codes are different
2784 from normal processes.
2786 `make-serial-process' creates a process and a buffer, on which you
2787 probably want to use `process-send-string'. Try \\[serial-term] for
2788 an interactive terminal. See below for examples.
2790 Arguments are specified as keyword/argument pairs. The following
2791 arguments are defined:
2793 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2794 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2795 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2796 the backslashes in strings).
2798 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2799 which this function calls.
2801 :name NAME -- NAME is the name of the process. If NAME is not given,
2802 the value of PORT is used.
2804 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2805 with the process. Process output goes at the end of that buffer,
2806 unless you specify an output stream or filter function to handle the
2807 output. If BUFFER is not given, the value of NAME is used.
2809 :coding CODING -- If CODING is a symbol, it specifies the coding
2810 system used for both reading and writing for this process. If CODING
2811 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2812 ENCODING is used for writing.
2814 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2815 the process is running. If BOOL is not given, query before exiting.
2817 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2818 In the stopped state, a serial process does not accept incoming data,
2819 but you can send outgoing data. The stopped state is cleared by
2820 `continue-process' and set by `stop-process'.
2822 :filter FILTER -- Install FILTER as the process filter.
2824 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2826 :plist PLIST -- Install PLIST as the initial plist of the process.
2828 :bytesize
2829 :parity
2830 :stopbits
2831 :flowcontrol
2832 -- This function calls `serial-process-configure' to handle these
2833 arguments.
2835 The original argument list, possibly modified by later configuration,
2836 is available via the function `process-contact'.
2838 Examples:
2840 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2842 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2844 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2846 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2848 usage: (make-serial-process &rest ARGS) */)
2849 (ptrdiff_t nargs, Lisp_Object *args)
2851 int fd = -1;
2852 Lisp_Object proc, contact, port;
2853 struct Lisp_Process *p;
2854 struct gcpro gcpro1;
2855 Lisp_Object name, buffer;
2856 Lisp_Object tem, val;
2857 ptrdiff_t specpdl_count;
2859 if (nargs == 0)
2860 return Qnil;
2862 contact = Flist (nargs, args);
2863 GCPRO1 (contact);
2865 port = Fplist_get (contact, QCport);
2866 if (NILP (port))
2867 error ("No port specified");
2868 CHECK_STRING (port);
2870 if (NILP (Fplist_member (contact, QCspeed)))
2871 error (":speed not specified");
2872 if (!NILP (Fplist_get (contact, QCspeed)))
2873 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2875 name = Fplist_get (contact, QCname);
2876 if (NILP (name))
2877 name = port;
2878 CHECK_STRING (name);
2879 proc = make_process (name);
2880 specpdl_count = SPECPDL_INDEX ();
2881 record_unwind_protect (remove_process, proc);
2882 p = XPROCESS (proc);
2884 fd = serial_open (port);
2885 p->open_fd[SUBPROCESS_STDIN] = fd;
2886 p->infd = fd;
2887 p->outfd = fd;
2888 if (fd > max_process_desc)
2889 max_process_desc = fd;
2890 chan_process[fd] = proc;
2892 buffer = Fplist_get (contact, QCbuffer);
2893 if (NILP (buffer))
2894 buffer = name;
2895 buffer = Fget_buffer_create (buffer);
2896 pset_buffer (p, buffer);
2898 pset_childp (p, contact);
2899 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2900 pset_type (p, Qserial);
2901 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2902 pset_filter (p, Fplist_get (contact, QCfilter));
2903 pset_log (p, Qnil);
2904 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2905 p->kill_without_query = 1;
2906 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2907 pset_command (p, Qt);
2908 eassert (! p->pty_flag);
2910 if (!EQ (p->command, Qt))
2912 FD_SET (fd, &input_wait_mask);
2913 FD_SET (fd, &non_keyboard_wait_mask);
2916 if (BUFFERP (buffer))
2918 set_marker_both (p->mark, buffer,
2919 BUF_ZV (XBUFFER (buffer)),
2920 BUF_ZV_BYTE (XBUFFER (buffer)));
2923 tem = Fplist_member (contact, QCcoding);
2924 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2925 tem = Qnil;
2927 val = Qnil;
2928 if (!NILP (tem))
2930 val = XCAR (XCDR (tem));
2931 if (CONSP (val))
2932 val = XCAR (val);
2934 else if (!NILP (Vcoding_system_for_read))
2935 val = Vcoding_system_for_read;
2936 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2937 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2938 val = Qnil;
2939 pset_decode_coding_system (p, val);
2941 val = Qnil;
2942 if (!NILP (tem))
2944 val = XCAR (XCDR (tem));
2945 if (CONSP (val))
2946 val = XCDR (val);
2948 else if (!NILP (Vcoding_system_for_write))
2949 val = Vcoding_system_for_write;
2950 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2951 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2952 val = Qnil;
2953 pset_encode_coding_system (p, val);
2955 setup_process_coding_systems (proc);
2956 pset_decoding_buf (p, empty_unibyte_string);
2957 p->decoding_carryover = 0;
2958 pset_encoding_buf (p, empty_unibyte_string);
2959 p->inherit_coding_system_flag
2960 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2962 Fserial_process_configure (nargs, args);
2964 specpdl_ptr = specpdl + specpdl_count;
2966 UNGCPRO;
2967 return proc;
2970 /* Create a network stream/datagram client/server process. Treated
2971 exactly like a normal process when reading and writing. Primary
2972 differences are in status display and process deletion. A network
2973 connection has no PID; you cannot signal it. All you can do is
2974 stop/continue it and deactivate/close it via delete-process. */
2976 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2977 0, MANY, 0,
2978 doc: /* Create and return a network server or client process.
2980 In Emacs, network connections are represented by process objects, so
2981 input and output work as for subprocesses and `delete-process' closes
2982 a network connection. However, a network process has no process id,
2983 it cannot be signaled, and the status codes are different from normal
2984 processes.
2986 Arguments are specified as keyword/argument pairs. The following
2987 arguments are defined:
2989 :name NAME -- NAME is name for process. It is modified if necessary
2990 to make it unique.
2992 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2993 with the process. Process output goes at end of that buffer, unless
2994 you specify an output stream or filter function to handle the output.
2995 BUFFER may be also nil, meaning that this process is not associated
2996 with any buffer.
2998 :host HOST -- HOST is name of the host to connect to, or its IP
2999 address. The symbol `local' specifies the local host. If specified
3000 for a server process, it must be a valid name or address for the local
3001 host, and only clients connecting to that address will be accepted.
3003 :service SERVICE -- SERVICE is name of the service desired, or an
3004 integer specifying a port number to connect to. If SERVICE is t,
3005 a random port number is selected for the server. (If Emacs was
3006 compiled with getaddrinfo, a port number can also be specified as a
3007 string, e.g. "80", as well as an integer. This is not portable.)
3009 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3010 stream type connection, `datagram' creates a datagram type connection,
3011 `seqpacket' creates a reliable datagram connection.
3013 :family FAMILY -- FAMILY is the address (and protocol) family for the
3014 service specified by HOST and SERVICE. The default (nil) is to use
3015 whatever address family (IPv4 or IPv6) that is defined for the host
3016 and port number specified by HOST and SERVICE. Other address families
3017 supported are:
3018 local -- for a local (i.e. UNIX) address specified by SERVICE.
3019 ipv4 -- use IPv4 address family only.
3020 ipv6 -- use IPv6 address family only.
3022 :local ADDRESS -- ADDRESS is the local address used for the connection.
3023 This parameter is ignored when opening a client process. When specified
3024 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3026 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3027 connection. This parameter is ignored when opening a stream server
3028 process. For a datagram server process, it specifies the initial
3029 setting of the remote datagram address. When specified for a client
3030 process, the FAMILY, HOST, and SERVICE args are ignored.
3032 The format of ADDRESS depends on the address family:
3033 - An IPv4 address is represented as an vector of integers [A B C D P]
3034 corresponding to numeric IP address A.B.C.D and port number P.
3035 - A local address is represented as a string with the address in the
3036 local address space.
3037 - An "unsupported family" address is represented by a cons (F . AV)
3038 where F is the family number and AV is a vector containing the socket
3039 address data with one element per address data byte. Do not rely on
3040 this format in portable code, as it may depend on implementation
3041 defined constants, data sizes, and data structure alignment.
3043 :coding CODING -- If CODING is a symbol, it specifies the coding
3044 system used for both reading and writing for this process. If CODING
3045 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3046 ENCODING is used for writing.
3048 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3049 return without waiting for the connection to complete; instead, the
3050 sentinel function will be called with second arg matching "open" (if
3051 successful) or "failed" when the connect completes. Default is to use
3052 a blocking connect (i.e. wait) for stream type connections.
3054 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3055 running when Emacs is exited.
3057 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3058 In the stopped state, a server process does not accept new
3059 connections, and a client process does not handle incoming traffic.
3060 The stopped state is cleared by `continue-process' and set by
3061 `stop-process'.
3063 :filter FILTER -- Install FILTER as the process filter.
3065 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3066 process filter are multibyte, otherwise they are unibyte.
3067 If this keyword is not specified, the strings are multibyte if
3068 the default value of `enable-multibyte-characters' is non-nil.
3070 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3072 :log LOG -- Install LOG as the server process log function. This
3073 function is called when the server accepts a network connection from a
3074 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3075 is the server process, CLIENT is the new process for the connection,
3076 and MESSAGE is a string.
3078 :plist PLIST -- Install PLIST as the new process's initial plist.
3080 :server QLEN -- if QLEN is non-nil, create a server process for the
3081 specified FAMILY, SERVICE, and connection type (stream or datagram).
3082 If QLEN is an integer, it is used as the max. length of the server's
3083 pending connection queue (also known as the backlog); the default
3084 queue length is 5. Default is to create a client process.
3086 The following network options can be specified for this connection:
3088 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3089 :dontroute BOOL -- Only send to directly connected hosts.
3090 :keepalive BOOL -- Send keep-alive messages on network stream.
3091 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3092 :oobinline BOOL -- Place out-of-band data in receive data stream.
3093 :priority INT -- Set protocol defined priority for sent packets.
3094 :reuseaddr BOOL -- Allow reusing a recently used local address
3095 (this is allowed by default for a server process).
3096 :bindtodevice NAME -- bind to interface NAME. Using this may require
3097 special privileges on some systems.
3099 Consult the relevant system programmer's manual pages for more
3100 information on using these options.
3103 A server process will listen for and accept connections from clients.
3104 When a client connection is accepted, a new network process is created
3105 for the connection with the following parameters:
3107 - The client's process name is constructed by concatenating the server
3108 process's NAME and a client identification string.
3109 - If the FILTER argument is non-nil, the client process will not get a
3110 separate process buffer; otherwise, the client's process buffer is a newly
3111 created buffer named after the server process's BUFFER name or process
3112 NAME concatenated with the client identification string.
3113 - The connection type and the process filter and sentinel parameters are
3114 inherited from the server process's TYPE, FILTER and SENTINEL.
3115 - The client process's contact info is set according to the client's
3116 addressing information (typically an IP address and a port number).
3117 - The client process's plist is initialized from the server's plist.
3119 Notice that the FILTER and SENTINEL args are never used directly by
3120 the server process. Also, the BUFFER argument is not used directly by
3121 the server process, but via the optional :log function, accepted (and
3122 failed) connections may be logged in the server process's buffer.
3124 The original argument list, modified with the actual connection
3125 information, is available via the `process-contact' function.
3127 usage: (make-network-process &rest ARGS) */)
3128 (ptrdiff_t nargs, Lisp_Object *args)
3130 Lisp_Object proc;
3131 Lisp_Object contact;
3132 struct Lisp_Process *p;
3133 #ifdef HAVE_GETADDRINFO
3134 struct addrinfo ai, *res, *lres;
3135 struct addrinfo hints;
3136 const char *portstring;
3137 char portbuf[128];
3138 #else /* HAVE_GETADDRINFO */
3139 struct _emacs_addrinfo
3141 int ai_family;
3142 int ai_socktype;
3143 int ai_protocol;
3144 int ai_addrlen;
3145 struct sockaddr *ai_addr;
3146 struct _emacs_addrinfo *ai_next;
3147 } ai, *res, *lres;
3148 #endif /* HAVE_GETADDRINFO */
3149 struct sockaddr_in address_in;
3150 #ifdef HAVE_LOCAL_SOCKETS
3151 struct sockaddr_un address_un;
3152 #endif
3153 int port;
3154 int ret = 0;
3155 int xerrno = 0;
3156 int s = -1, outch, inch;
3157 struct gcpro gcpro1;
3158 ptrdiff_t count = SPECPDL_INDEX ();
3159 ptrdiff_t count1;
3160 Lisp_Object colon_address; /* Either QClocal or QCremote. */
3161 Lisp_Object tem;
3162 Lisp_Object name, buffer, host, service, address;
3163 Lisp_Object filter, sentinel;
3164 bool is_non_blocking_client = 0;
3165 bool is_server = 0;
3166 int backlog = 5;
3167 int socktype;
3168 int family = -1;
3170 if (nargs == 0)
3171 return Qnil;
3173 /* Save arguments for process-contact and clone-process. */
3174 contact = Flist (nargs, args);
3175 GCPRO1 (contact);
3177 #ifdef WINDOWSNT
3178 /* Ensure socket support is loaded if available. */
3179 init_winsock (TRUE);
3180 #endif
3182 /* :type TYPE (nil: stream, datagram */
3183 tem = Fplist_get (contact, QCtype);
3184 if (NILP (tem))
3185 socktype = SOCK_STREAM;
3186 #ifdef DATAGRAM_SOCKETS
3187 else if (EQ (tem, Qdatagram))
3188 socktype = SOCK_DGRAM;
3189 #endif
3190 #ifdef HAVE_SEQPACKET
3191 else if (EQ (tem, Qseqpacket))
3192 socktype = SOCK_SEQPACKET;
3193 #endif
3194 else
3195 error ("Unsupported connection type");
3197 /* :server BOOL */
3198 tem = Fplist_get (contact, QCserver);
3199 if (!NILP (tem))
3201 /* Don't support network sockets when non-blocking mode is
3202 not available, since a blocked Emacs is not useful. */
3203 is_server = 1;
3204 if (TYPE_RANGED_INTEGERP (int, tem))
3205 backlog = XINT (tem);
3208 /* Make colon_address an alias for :local (server) or :remote (client). */
3209 colon_address = is_server ? QClocal : QCremote;
3211 /* :nowait BOOL */
3212 if (!is_server && socktype != SOCK_DGRAM
3213 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3215 #ifndef NON_BLOCKING_CONNECT
3216 error ("Non-blocking connect not supported");
3217 #else
3218 is_non_blocking_client = 1;
3219 #endif
3222 name = Fplist_get (contact, QCname);
3223 buffer = Fplist_get (contact, QCbuffer);
3224 filter = Fplist_get (contact, QCfilter);
3225 sentinel = Fplist_get (contact, QCsentinel);
3227 CHECK_STRING (name);
3229 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3230 ai.ai_socktype = socktype;
3231 ai.ai_protocol = 0;
3232 ai.ai_next = NULL;
3233 res = &ai;
3235 /* :local ADDRESS or :remote ADDRESS */
3236 address = Fplist_get (contact, colon_address);
3237 if (!NILP (address))
3239 host = service = Qnil;
3241 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3242 error ("Malformed :address");
3243 ai.ai_family = family;
3244 ai.ai_addr = alloca (ai.ai_addrlen);
3245 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3246 goto open_socket;
3249 /* :family FAMILY -- nil (for Inet), local, or integer. */
3250 tem = Fplist_get (contact, QCfamily);
3251 if (NILP (tem))
3253 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3254 family = AF_UNSPEC;
3255 #else
3256 family = AF_INET;
3257 #endif
3259 #ifdef HAVE_LOCAL_SOCKETS
3260 else if (EQ (tem, Qlocal))
3261 family = AF_LOCAL;
3262 #endif
3263 #ifdef AF_INET6
3264 else if (EQ (tem, Qipv6))
3265 family = AF_INET6;
3266 #endif
3267 else if (EQ (tem, Qipv4))
3268 family = AF_INET;
3269 else if (TYPE_RANGED_INTEGERP (int, tem))
3270 family = XINT (tem);
3271 else
3272 error ("Unknown address family");
3274 ai.ai_family = family;
3276 /* :service SERVICE -- string, integer (port number), or t (random port). */
3277 service = Fplist_get (contact, QCservice);
3279 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3280 host = Fplist_get (contact, QChost);
3281 if (!NILP (host))
3283 if (EQ (host, Qlocal))
3284 /* Depending on setup, "localhost" may map to different IPv4 and/or
3285 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3286 host = build_string ("127.0.0.1");
3287 CHECK_STRING (host);
3290 #ifdef HAVE_LOCAL_SOCKETS
3291 if (family == AF_LOCAL)
3293 if (!NILP (host))
3295 message (":family local ignores the :host \"%s\" property",
3296 SDATA (host));
3297 contact = Fplist_put (contact, QChost, Qnil);
3298 host = Qnil;
3300 CHECK_STRING (service);
3301 memset (&address_un, 0, sizeof address_un);
3302 address_un.sun_family = AF_LOCAL;
3303 if (sizeof address_un.sun_path <= SBYTES (service))
3304 error ("Service name too long");
3305 lispstpcpy (address_un.sun_path, service);
3306 ai.ai_addr = (struct sockaddr *) &address_un;
3307 ai.ai_addrlen = sizeof address_un;
3308 goto open_socket;
3310 #endif
3312 /* Slow down polling to every ten seconds.
3313 Some kernels have a bug which causes retrying connect to fail
3314 after a connect. Polling can interfere with gethostbyname too. */
3315 #ifdef POLL_FOR_INPUT
3316 if (socktype != SOCK_DGRAM)
3318 record_unwind_protect_void (run_all_atimers);
3319 bind_polling_period (10);
3321 #endif
3323 #ifdef HAVE_GETADDRINFO
3324 /* If we have a host, use getaddrinfo to resolve both host and service.
3325 Otherwise, use getservbyname to lookup the service. */
3326 if (!NILP (host))
3329 /* SERVICE can either be a string or int.
3330 Convert to a C string for later use by getaddrinfo. */
3331 if (EQ (service, Qt))
3332 portstring = "0";
3333 else if (INTEGERP (service))
3335 sprintf (portbuf, "%"pI"d", XINT (service));
3336 portstring = portbuf;
3338 else
3340 CHECK_STRING (service);
3341 portstring = SSDATA (service);
3344 immediate_quit = 1;
3345 QUIT;
3346 memset (&hints, 0, sizeof (hints));
3347 hints.ai_flags = 0;
3348 hints.ai_family = family;
3349 hints.ai_socktype = socktype;
3350 hints.ai_protocol = 0;
3352 #ifdef HAVE_RES_INIT
3353 res_init ();
3354 #endif
3356 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3357 if (ret)
3358 #ifdef HAVE_GAI_STRERROR
3359 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3360 #else
3361 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3362 #endif
3363 immediate_quit = 0;
3365 goto open_socket;
3367 #endif /* HAVE_GETADDRINFO */
3369 /* We end up here if getaddrinfo is not defined, or in case no hostname
3370 has been specified (e.g. for a local server process). */
3372 if (EQ (service, Qt))
3373 port = 0;
3374 else if (INTEGERP (service))
3375 port = htons ((unsigned short) XINT (service));
3376 else
3378 struct servent *svc_info;
3379 CHECK_STRING (service);
3380 svc_info = getservbyname (SSDATA (service),
3381 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3382 if (svc_info == 0)
3383 error ("Unknown service: %s", SDATA (service));
3384 port = svc_info->s_port;
3387 memset (&address_in, 0, sizeof address_in);
3388 address_in.sin_family = family;
3389 address_in.sin_addr.s_addr = INADDR_ANY;
3390 address_in.sin_port = port;
3392 #ifndef HAVE_GETADDRINFO
3393 if (!NILP (host))
3395 struct hostent *host_info_ptr;
3397 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3398 as it may `hang' Emacs for a very long time. */
3399 immediate_quit = 1;
3400 QUIT;
3402 #ifdef HAVE_RES_INIT
3403 res_init ();
3404 #endif
3406 host_info_ptr = gethostbyname (SDATA (host));
3407 immediate_quit = 0;
3409 if (host_info_ptr)
3411 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3412 host_info_ptr->h_length);
3413 family = host_info_ptr->h_addrtype;
3414 address_in.sin_family = family;
3416 else
3417 /* Attempt to interpret host as numeric inet address. */
3419 unsigned long numeric_addr;
3420 numeric_addr = inet_addr (SSDATA (host));
3421 if (numeric_addr == -1)
3422 error ("Unknown host \"%s\"", SDATA (host));
3424 memcpy (&address_in.sin_addr, &numeric_addr,
3425 sizeof (address_in.sin_addr));
3429 #endif /* not HAVE_GETADDRINFO */
3431 ai.ai_family = family;
3432 ai.ai_addr = (struct sockaddr *) &address_in;
3433 ai.ai_addrlen = sizeof address_in;
3435 open_socket:
3437 /* Do this in case we never enter the for-loop below. */
3438 count1 = SPECPDL_INDEX ();
3439 s = -1;
3441 for (lres = res; lres; lres = lres->ai_next)
3443 ptrdiff_t optn;
3444 int optbits;
3446 #ifdef WINDOWSNT
3447 retry_connect:
3448 #endif
3450 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3451 lres->ai_protocol);
3452 if (s < 0)
3454 xerrno = errno;
3455 continue;
3458 #ifdef DATAGRAM_SOCKETS
3459 if (!is_server && socktype == SOCK_DGRAM)
3460 break;
3461 #endif /* DATAGRAM_SOCKETS */
3463 #ifdef NON_BLOCKING_CONNECT
3464 if (is_non_blocking_client)
3466 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3467 if (ret < 0)
3469 xerrno = errno;
3470 emacs_close (s);
3471 s = -1;
3472 continue;
3475 #endif
3477 /* Make us close S if quit. */
3478 record_unwind_protect_int (close_file_unwind, s);
3480 /* Parse network options in the arg list.
3481 We simply ignore anything which isn't a known option (including other keywords).
3482 An error is signaled if setting a known option fails. */
3483 for (optn = optbits = 0; optn < nargs - 1; optn += 2)
3484 optbits |= set_socket_option (s, args[optn], args[optn + 1]);
3486 if (is_server)
3488 /* Configure as a server socket. */
3490 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3491 explicit :reuseaddr key to override this. */
3492 #ifdef HAVE_LOCAL_SOCKETS
3493 if (family != AF_LOCAL)
3494 #endif
3495 if (!(optbits & (1 << OPIX_REUSEADDR)))
3497 int optval = 1;
3498 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3499 report_file_error ("Cannot set reuse option on server socket", Qnil);
3502 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3503 report_file_error ("Cannot bind server socket", Qnil);
3505 #ifdef HAVE_GETSOCKNAME
3506 if (EQ (service, Qt))
3508 struct sockaddr_in sa1;
3509 socklen_t len1 = sizeof (sa1);
3510 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3512 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3513 service = make_number (ntohs (sa1.sin_port));
3514 contact = Fplist_put (contact, QCservice, service);
3517 #endif
3519 if (socktype != SOCK_DGRAM && listen (s, backlog))
3520 report_file_error ("Cannot listen on server socket", Qnil);
3522 break;
3525 immediate_quit = 1;
3526 QUIT;
3528 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3529 xerrno = errno;
3531 if (ret == 0 || xerrno == EISCONN)
3533 /* The unwind-protect will be discarded afterwards.
3534 Likewise for immediate_quit. */
3535 break;
3538 #ifdef NON_BLOCKING_CONNECT
3539 #ifdef EINPROGRESS
3540 if (is_non_blocking_client && xerrno == EINPROGRESS)
3541 break;
3542 #else
3543 #ifdef EWOULDBLOCK
3544 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3545 break;
3546 #endif
3547 #endif
3548 #endif
3550 #ifndef WINDOWSNT
3551 if (xerrno == EINTR)
3553 /* Unlike most other syscalls connect() cannot be called
3554 again. (That would return EALREADY.) The proper way to
3555 wait for completion is pselect(). */
3556 int sc;
3557 socklen_t len;
3558 fd_set fdset;
3559 retry_select:
3560 FD_ZERO (&fdset);
3561 FD_SET (s, &fdset);
3562 QUIT;
3563 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3564 if (sc == -1)
3566 if (errno == EINTR)
3567 goto retry_select;
3568 else
3569 report_file_error ("Failed select", Qnil);
3571 eassert (sc > 0);
3573 len = sizeof xerrno;
3574 eassert (FD_ISSET (s, &fdset));
3575 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3576 report_file_error ("Failed getsockopt", Qnil);
3577 if (xerrno)
3578 report_file_errno ("Failed connect", Qnil, xerrno);
3579 break;
3581 #endif /* !WINDOWSNT */
3583 immediate_quit = 0;
3585 /* Discard the unwind protect closing S. */
3586 specpdl_ptr = specpdl + count1;
3587 emacs_close (s);
3588 s = -1;
3590 #ifdef WINDOWSNT
3591 if (xerrno == EINTR)
3592 goto retry_connect;
3593 #endif
3596 if (s >= 0)
3598 #ifdef DATAGRAM_SOCKETS
3599 if (socktype == SOCK_DGRAM)
3601 if (datagram_address[s].sa)
3602 emacs_abort ();
3603 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3604 datagram_address[s].len = lres->ai_addrlen;
3605 if (is_server)
3607 Lisp_Object remote;
3608 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3609 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3611 int rfamily, rlen;
3612 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3613 if (rlen != 0 && rfamily == lres->ai_family
3614 && rlen == lres->ai_addrlen)
3615 conv_lisp_to_sockaddr (rfamily, remote,
3616 datagram_address[s].sa, rlen);
3619 else
3620 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3622 #endif
3623 contact = Fplist_put (contact, colon_address,
3624 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3625 #ifdef HAVE_GETSOCKNAME
3626 if (!is_server)
3628 struct sockaddr_in sa1;
3629 socklen_t len1 = sizeof (sa1);
3630 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3631 contact = Fplist_put (contact, QClocal,
3632 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3634 #endif
3637 immediate_quit = 0;
3639 #ifdef HAVE_GETADDRINFO
3640 if (res != &ai)
3642 block_input ();
3643 freeaddrinfo (res);
3644 unblock_input ();
3646 #endif
3648 if (s < 0)
3650 /* If non-blocking got this far - and failed - assume non-blocking is
3651 not supported after all. This is probably a wrong assumption, but
3652 the normal blocking calls to open-network-stream handles this error
3653 better. */
3654 if (is_non_blocking_client)
3655 return Qnil;
3657 report_file_errno ((is_server
3658 ? "make server process failed"
3659 : "make client process failed"),
3660 contact, xerrno);
3663 inch = s;
3664 outch = s;
3666 if (!NILP (buffer))
3667 buffer = Fget_buffer_create (buffer);
3668 proc = make_process (name);
3670 chan_process[inch] = proc;
3672 fcntl (inch, F_SETFL, O_NONBLOCK);
3674 p = XPROCESS (proc);
3676 pset_childp (p, contact);
3677 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3678 pset_type (p, Qnetwork);
3680 pset_buffer (p, buffer);
3681 pset_sentinel (p, sentinel);
3682 pset_filter (p, filter);
3683 pset_log (p, Fplist_get (contact, QClog));
3684 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3685 p->kill_without_query = 1;
3686 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3687 pset_command (p, Qt);
3688 p->pid = 0;
3690 p->open_fd[SUBPROCESS_STDIN] = inch;
3691 p->infd = inch;
3692 p->outfd = outch;
3694 /* Discard the unwind protect for closing S, if any. */
3695 specpdl_ptr = specpdl + count1;
3697 /* Unwind bind_polling_period and request_sigio. */
3698 unbind_to (count, Qnil);
3700 if (is_server && socktype != SOCK_DGRAM)
3701 pset_status (p, Qlisten);
3703 /* Make the process marker point into the process buffer (if any). */
3704 if (BUFFERP (buffer))
3705 set_marker_both (p->mark, buffer,
3706 BUF_ZV (XBUFFER (buffer)),
3707 BUF_ZV_BYTE (XBUFFER (buffer)));
3709 #ifdef NON_BLOCKING_CONNECT
3710 if (is_non_blocking_client)
3712 /* We may get here if connect did succeed immediately. However,
3713 in that case, we still need to signal this like a non-blocking
3714 connection. */
3715 pset_status (p, Qconnect);
3716 if (!FD_ISSET (inch, &connect_wait_mask))
3718 FD_SET (inch, &connect_wait_mask);
3719 FD_SET (inch, &write_mask);
3720 num_pending_connects++;
3723 else
3724 #endif
3725 /* A server may have a client filter setting of Qt, but it must
3726 still listen for incoming connects unless it is stopped. */
3727 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3728 || (EQ (p->status, Qlisten) && NILP (p->command)))
3730 FD_SET (inch, &input_wait_mask);
3731 FD_SET (inch, &non_keyboard_wait_mask);
3734 if (inch > max_process_desc)
3735 max_process_desc = inch;
3737 tem = Fplist_member (contact, QCcoding);
3738 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3739 tem = Qnil; /* No error message (too late!). */
3742 /* Setup coding systems for communicating with the network stream. */
3743 struct gcpro gcpro1;
3744 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3745 Lisp_Object coding_systems = Qt;
3746 Lisp_Object val;
3748 if (!NILP (tem))
3750 val = XCAR (XCDR (tem));
3751 if (CONSP (val))
3752 val = XCAR (val);
3754 else if (!NILP (Vcoding_system_for_read))
3755 val = Vcoding_system_for_read;
3756 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3757 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3758 /* We dare not decode end-of-line format by setting VAL to
3759 Qraw_text, because the existing Emacs Lisp libraries
3760 assume that they receive bare code including a sequence of
3761 CR LF. */
3762 val = Qnil;
3763 else
3765 if (NILP (host) || NILP (service))
3766 coding_systems = Qnil;
3767 else
3769 GCPRO1 (proc);
3770 coding_systems = CALLN (Ffind_operation_coding_system,
3771 Qopen_network_stream, name, buffer,
3772 host, service);
3773 UNGCPRO;
3775 if (CONSP (coding_systems))
3776 val = XCAR (coding_systems);
3777 else if (CONSP (Vdefault_process_coding_system))
3778 val = XCAR (Vdefault_process_coding_system);
3779 else
3780 val = Qnil;
3782 pset_decode_coding_system (p, val);
3784 if (!NILP (tem))
3786 val = XCAR (XCDR (tem));
3787 if (CONSP (val))
3788 val = XCDR (val);
3790 else if (!NILP (Vcoding_system_for_write))
3791 val = Vcoding_system_for_write;
3792 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3793 val = Qnil;
3794 else
3796 if (EQ (coding_systems, Qt))
3798 if (NILP (host) || NILP (service))
3799 coding_systems = Qnil;
3800 else
3802 GCPRO1 (proc);
3803 coding_systems = CALLN (Ffind_operation_coding_system,
3804 Qopen_network_stream, name, buffer,
3805 host, service);
3806 UNGCPRO;
3809 if (CONSP (coding_systems))
3810 val = XCDR (coding_systems);
3811 else if (CONSP (Vdefault_process_coding_system))
3812 val = XCDR (Vdefault_process_coding_system);
3813 else
3814 val = Qnil;
3816 pset_encode_coding_system (p, val);
3818 setup_process_coding_systems (proc);
3820 pset_decoding_buf (p, empty_unibyte_string);
3821 p->decoding_carryover = 0;
3822 pset_encoding_buf (p, empty_unibyte_string);
3824 p->inherit_coding_system_flag
3825 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3827 UNGCPRO;
3828 return proc;
3832 #ifdef HAVE_NET_IF_H
3834 #ifdef SIOCGIFCONF
3835 static Lisp_Object
3836 network_interface_list (void)
3838 struct ifconf ifconf;
3839 struct ifreq *ifreq;
3840 void *buf = NULL;
3841 ptrdiff_t buf_size = 512;
3842 int s;
3843 Lisp_Object res;
3844 ptrdiff_t count;
3846 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3847 if (s < 0)
3848 return Qnil;
3849 count = SPECPDL_INDEX ();
3850 record_unwind_protect_int (close_file_unwind, s);
3854 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3855 ifconf.ifc_buf = buf;
3856 ifconf.ifc_len = buf_size;
3857 if (ioctl (s, SIOCGIFCONF, &ifconf))
3859 emacs_close (s);
3860 xfree (buf);
3861 return Qnil;
3864 while (ifconf.ifc_len == buf_size);
3866 res = unbind_to (count, Qnil);
3867 ifreq = ifconf.ifc_req;
3868 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3870 struct ifreq *ifq = ifreq;
3871 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3872 #define SIZEOF_IFREQ(sif) \
3873 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3874 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3876 int len = SIZEOF_IFREQ (ifq);
3877 #else
3878 int len = sizeof (*ifreq);
3879 #endif
3880 char namebuf[sizeof (ifq->ifr_name) + 1];
3881 ifreq = (struct ifreq *) ((char *) ifreq + len);
3883 if (ifq->ifr_addr.sa_family != AF_INET)
3884 continue;
3886 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3887 namebuf[sizeof (ifq->ifr_name)] = 0;
3888 res = Fcons (Fcons (build_string (namebuf),
3889 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3890 sizeof (struct sockaddr))),
3891 res);
3894 xfree (buf);
3895 return res;
3897 #endif /* SIOCGIFCONF */
3899 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3901 struct ifflag_def {
3902 int flag_bit;
3903 const char *flag_sym;
3906 static const struct ifflag_def ifflag_table[] = {
3907 #ifdef IFF_UP
3908 { IFF_UP, "up" },
3909 #endif
3910 #ifdef IFF_BROADCAST
3911 { IFF_BROADCAST, "broadcast" },
3912 #endif
3913 #ifdef IFF_DEBUG
3914 { IFF_DEBUG, "debug" },
3915 #endif
3916 #ifdef IFF_LOOPBACK
3917 { IFF_LOOPBACK, "loopback" },
3918 #endif
3919 #ifdef IFF_POINTOPOINT
3920 { IFF_POINTOPOINT, "pointopoint" },
3921 #endif
3922 #ifdef IFF_RUNNING
3923 { IFF_RUNNING, "running" },
3924 #endif
3925 #ifdef IFF_NOARP
3926 { IFF_NOARP, "noarp" },
3927 #endif
3928 #ifdef IFF_PROMISC
3929 { IFF_PROMISC, "promisc" },
3930 #endif
3931 #ifdef IFF_NOTRAILERS
3932 #ifdef NS_IMPL_COCOA
3933 /* Really means smart, notrailers is obsolete. */
3934 { IFF_NOTRAILERS, "smart" },
3935 #else
3936 { IFF_NOTRAILERS, "notrailers" },
3937 #endif
3938 #endif
3939 #ifdef IFF_ALLMULTI
3940 { IFF_ALLMULTI, "allmulti" },
3941 #endif
3942 #ifdef IFF_MASTER
3943 { IFF_MASTER, "master" },
3944 #endif
3945 #ifdef IFF_SLAVE
3946 { IFF_SLAVE, "slave" },
3947 #endif
3948 #ifdef IFF_MULTICAST
3949 { IFF_MULTICAST, "multicast" },
3950 #endif
3951 #ifdef IFF_PORTSEL
3952 { IFF_PORTSEL, "portsel" },
3953 #endif
3954 #ifdef IFF_AUTOMEDIA
3955 { IFF_AUTOMEDIA, "automedia" },
3956 #endif
3957 #ifdef IFF_DYNAMIC
3958 { IFF_DYNAMIC, "dynamic" },
3959 #endif
3960 #ifdef IFF_OACTIVE
3961 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
3962 #endif
3963 #ifdef IFF_SIMPLEX
3964 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
3965 #endif
3966 #ifdef IFF_LINK0
3967 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
3968 #endif
3969 #ifdef IFF_LINK1
3970 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
3971 #endif
3972 #ifdef IFF_LINK2
3973 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
3974 #endif
3975 { 0, 0 }
3978 static Lisp_Object
3979 network_interface_info (Lisp_Object ifname)
3981 struct ifreq rq;
3982 Lisp_Object res = Qnil;
3983 Lisp_Object elt;
3984 int s;
3985 bool any = 0;
3986 ptrdiff_t count;
3987 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3988 && defined HAVE_GETIFADDRS && defined LLADDR)
3989 struct ifaddrs *ifap;
3990 #endif
3992 CHECK_STRING (ifname);
3994 if (sizeof rq.ifr_name <= SBYTES (ifname))
3995 error ("interface name too long");
3996 lispstpcpy (rq.ifr_name, ifname);
3998 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3999 if (s < 0)
4000 return Qnil;
4001 count = SPECPDL_INDEX ();
4002 record_unwind_protect_int (close_file_unwind, s);
4004 elt = Qnil;
4005 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4006 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4008 int flags = rq.ifr_flags;
4009 const struct ifflag_def *fp;
4010 int fnum;
4012 /* If flags is smaller than int (i.e. short) it may have the high bit set
4013 due to IFF_MULTICAST. In that case, sign extending it into
4014 an int is wrong. */
4015 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
4016 flags = (unsigned short) rq.ifr_flags;
4018 any = 1;
4019 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4021 if (flags & fp->flag_bit)
4023 elt = Fcons (intern (fp->flag_sym), elt);
4024 flags -= fp->flag_bit;
4027 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
4029 if (flags & 1)
4031 elt = Fcons (make_number (fnum), elt);
4035 #endif
4036 res = Fcons (elt, res);
4038 elt = Qnil;
4039 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4040 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4042 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4043 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4044 int n;
4046 any = 1;
4047 for (n = 0; n < 6; n++)
4048 p->contents[n] = make_number (((unsigned char *)
4049 &rq.ifr_hwaddr.sa_data[0])
4050 [n]);
4051 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4053 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4054 if (getifaddrs (&ifap) != -1)
4056 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4057 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4058 struct ifaddrs *it;
4060 for (it = ifap; it != NULL; it = it->ifa_next)
4062 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
4063 unsigned char linkaddr[6];
4064 int n;
4066 if (it->ifa_addr->sa_family != AF_LINK
4067 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4068 || sdl->sdl_alen != 6)
4069 continue;
4071 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4072 for (n = 0; n < 6; n++)
4073 p->contents[n] = make_number (linkaddr[n]);
4075 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4076 break;
4079 #ifdef HAVE_FREEIFADDRS
4080 freeifaddrs (ifap);
4081 #endif
4083 #endif /* HAVE_GETIFADDRS && LLADDR */
4085 res = Fcons (elt, res);
4087 elt = Qnil;
4088 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4089 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4091 any = 1;
4092 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4093 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4094 #else
4095 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4096 #endif
4098 #endif
4099 res = Fcons (elt, res);
4101 elt = Qnil;
4102 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4103 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4105 any = 1;
4106 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4108 #endif
4109 res = Fcons (elt, res);
4111 elt = Qnil;
4112 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4113 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4115 any = 1;
4116 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4118 #endif
4119 res = Fcons (elt, res);
4121 return unbind_to (count, any ? res : Qnil);
4123 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4124 #endif /* defined (HAVE_NET_IF_H) */
4126 DEFUN ("network-interface-list", Fnetwork_interface_list,
4127 Snetwork_interface_list, 0, 0, 0,
4128 doc: /* Return an alist of all network interfaces and their network address.
4129 Each element is a cons, the car of which is a string containing the
4130 interface name, and the cdr is the network address in internal
4131 format; see the description of ADDRESS in `make-network-process'.
4133 If the information is not available, return nil. */)
4134 (void)
4136 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4137 return network_interface_list ();
4138 #else
4139 return Qnil;
4140 #endif
4143 DEFUN ("network-interface-info", Fnetwork_interface_info,
4144 Snetwork_interface_info, 1, 1, 0,
4145 doc: /* Return information about network interface named IFNAME.
4146 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4147 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4148 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4149 FLAGS is the current flags of the interface.
4151 Data that is unavailable is returned as nil. */)
4152 (Lisp_Object ifname)
4154 #if ((defined HAVE_NET_IF_H \
4155 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4156 || defined SIOCGIFFLAGS)) \
4157 || defined WINDOWSNT)
4158 return network_interface_info (ifname);
4159 #else
4160 return Qnil;
4161 #endif
4164 /* If program file NAME starts with /: for quoting a magic
4165 name, remove that, preserving the multibyteness of NAME. */
4167 Lisp_Object
4168 remove_slash_colon (Lisp_Object name)
4170 return
4171 ((SBYTES (name) > 2 && SREF (name, 0) == '/' && SREF (name, 1) == ':')
4172 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
4173 SBYTES (name) - 2, STRING_MULTIBYTE (name))
4174 : name);
4177 /* Turn off input and output for process PROC. */
4179 static void
4180 deactivate_process (Lisp_Object proc)
4182 int inchannel;
4183 struct Lisp_Process *p = XPROCESS (proc);
4184 int i;
4186 #ifdef HAVE_GNUTLS
4187 /* Delete GnuTLS structures in PROC, if any. */
4188 emacs_gnutls_deinit (proc);
4189 #endif /* HAVE_GNUTLS */
4191 #ifdef ADAPTIVE_READ_BUFFERING
4192 if (p->read_output_delay > 0)
4194 if (--process_output_delay_count < 0)
4195 process_output_delay_count = 0;
4196 p->read_output_delay = 0;
4197 p->read_output_skip = 0;
4199 #endif
4201 /* Beware SIGCHLD hereabouts. */
4203 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4204 close_process_fd (&p->open_fd[i]);
4206 inchannel = p->infd;
4207 if (inchannel >= 0)
4209 p->infd = -1;
4210 p->outfd = -1;
4211 #ifdef DATAGRAM_SOCKETS
4212 if (DATAGRAM_CHAN_P (inchannel))
4214 xfree (datagram_address[inchannel].sa);
4215 datagram_address[inchannel].sa = 0;
4216 datagram_address[inchannel].len = 0;
4218 #endif
4219 chan_process[inchannel] = Qnil;
4220 FD_CLR (inchannel, &input_wait_mask);
4221 FD_CLR (inchannel, &non_keyboard_wait_mask);
4222 #ifdef NON_BLOCKING_CONNECT
4223 if (FD_ISSET (inchannel, &connect_wait_mask))
4225 FD_CLR (inchannel, &connect_wait_mask);
4226 FD_CLR (inchannel, &write_mask);
4227 if (--num_pending_connects < 0)
4228 emacs_abort ();
4230 #endif
4231 if (inchannel == max_process_desc)
4233 /* We just closed the highest-numbered process input descriptor,
4234 so recompute the highest-numbered one now. */
4235 int i = inchannel;
4237 i--;
4238 while (0 <= i && NILP (chan_process[i]));
4240 max_process_desc = i;
4246 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4247 0, 4, 0,
4248 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4249 It is given to their filter functions.
4250 Optional argument PROCESS means do not return until output has been
4251 received from PROCESS.
4253 Optional second argument SECONDS and third argument MILLISEC
4254 specify a timeout; return after that much time even if there is
4255 no subprocess output. If SECONDS is a floating point number,
4256 it specifies a fractional number of seconds to wait.
4257 The MILLISEC argument is obsolete and should be avoided.
4259 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4260 from PROCESS only, suspending reading output from other processes.
4261 If JUST-THIS-ONE is an integer, don't run any timers either.
4262 Return non-nil if we received any output from PROCESS (or, if PROCESS
4263 is nil, from any process) before the timeout expired. */)
4264 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4266 intmax_t secs;
4267 int nsecs;
4269 if (! NILP (process))
4270 CHECK_PROCESS (process);
4271 else
4272 just_this_one = Qnil;
4274 if (!NILP (millisec))
4275 { /* Obsolete calling convention using integers rather than floats. */
4276 CHECK_NUMBER (millisec);
4277 if (NILP (seconds))
4278 seconds = make_float (XINT (millisec) / 1000.0);
4279 else
4281 CHECK_NUMBER (seconds);
4282 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4286 secs = 0;
4287 nsecs = -1;
4289 if (!NILP (seconds))
4291 if (INTEGERP (seconds))
4293 if (XINT (seconds) > 0)
4295 secs = XINT (seconds);
4296 nsecs = 0;
4299 else if (FLOATP (seconds))
4301 if (XFLOAT_DATA (seconds) > 0)
4303 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4304 secs = min (t.tv_sec, WAIT_READING_MAX);
4305 nsecs = t.tv_nsec;
4308 else
4309 wrong_type_argument (Qnumberp, seconds);
4311 else if (! NILP (process))
4312 nsecs = 0;
4314 return
4315 ((wait_reading_process_output (secs, nsecs, 0, 0,
4316 Qnil,
4317 !NILP (process) ? XPROCESS (process) : NULL,
4318 (NILP (just_this_one) ? 0
4319 : !INTEGERP (just_this_one) ? 1 : -1))
4320 <= 0)
4321 ? Qnil : Qt);
4324 /* Accept a connection for server process SERVER on CHANNEL. */
4326 static EMACS_INT connect_counter = 0;
4328 static void
4329 server_accept_connection (Lisp_Object server, int channel)
4331 Lisp_Object proc, caller, name, buffer;
4332 Lisp_Object contact, host, service;
4333 struct Lisp_Process *ps = XPROCESS (server);
4334 struct Lisp_Process *p;
4335 int s;
4336 union u_sockaddr {
4337 struct sockaddr sa;
4338 struct sockaddr_in in;
4339 #ifdef AF_INET6
4340 struct sockaddr_in6 in6;
4341 #endif
4342 #ifdef HAVE_LOCAL_SOCKETS
4343 struct sockaddr_un un;
4344 #endif
4345 } saddr;
4346 socklen_t len = sizeof saddr;
4347 ptrdiff_t count;
4349 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4351 if (s < 0)
4353 int code = errno;
4355 if (code == EAGAIN)
4356 return;
4357 #ifdef EWOULDBLOCK
4358 if (code == EWOULDBLOCK)
4359 return;
4360 #endif
4362 if (!NILP (ps->log))
4363 call3 (ps->log, server, Qnil,
4364 concat3 (build_string ("accept failed with code"),
4365 Fnumber_to_string (make_number (code)),
4366 build_string ("\n")));
4367 return;
4370 count = SPECPDL_INDEX ();
4371 record_unwind_protect_int (close_file_unwind, s);
4373 connect_counter++;
4375 /* Setup a new process to handle the connection. */
4377 /* Generate a unique identification of the caller, and build contact
4378 information for this process. */
4379 host = Qt;
4380 service = Qnil;
4381 switch (saddr.sa.sa_family)
4383 case AF_INET:
4385 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4387 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4388 host = CALLN (Fformat, ipv4_format,
4389 make_number (ip[0]), make_number (ip[1]),
4390 make_number (ip[2]), make_number (ip[3]));
4391 service = make_number (ntohs (saddr.in.sin_port));
4392 AUTO_STRING (caller_format, " <%s:%d>");
4393 caller = CALLN (Fformat, caller_format, host, service);
4395 break;
4397 #ifdef AF_INET6
4398 case AF_INET6:
4400 Lisp_Object args[9];
4401 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4402 int i;
4404 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4405 args[0] = ipv6_format;
4406 for (i = 0; i < 8; i++)
4407 args[i + 1] = make_number (ntohs (ip6[i]));
4408 host = CALLMANY (Fformat, args);
4409 service = make_number (ntohs (saddr.in.sin_port));
4410 AUTO_STRING (caller_format, " <[%s]:%d>");
4411 caller = CALLN (Fformat, caller_format, host, service);
4413 break;
4414 #endif
4416 #ifdef HAVE_LOCAL_SOCKETS
4417 case AF_LOCAL:
4418 #endif
4419 default:
4420 caller = Fnumber_to_string (make_number (connect_counter));
4421 AUTO_STRING (space_less_than, " <");
4422 AUTO_STRING (greater_than, ">");
4423 caller = concat3 (space_less_than, caller, greater_than);
4424 break;
4427 /* Create a new buffer name for this process if it doesn't have a
4428 filter. The new buffer name is based on the buffer name or
4429 process name of the server process concatenated with the caller
4430 identification. */
4432 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4433 || EQ (ps->filter, Qt)))
4434 buffer = Qnil;
4435 else
4437 buffer = ps->buffer;
4438 if (!NILP (buffer))
4439 buffer = Fbuffer_name (buffer);
4440 else
4441 buffer = ps->name;
4442 if (!NILP (buffer))
4444 buffer = concat2 (buffer, caller);
4445 buffer = Fget_buffer_create (buffer);
4449 /* Generate a unique name for the new server process. Combine the
4450 server process name with the caller identification. */
4452 name = concat2 (ps->name, caller);
4453 proc = make_process (name);
4455 chan_process[s] = proc;
4457 fcntl (s, F_SETFL, O_NONBLOCK);
4459 p = XPROCESS (proc);
4461 /* Build new contact information for this setup. */
4462 contact = Fcopy_sequence (ps->childp);
4463 contact = Fplist_put (contact, QCserver, Qnil);
4464 contact = Fplist_put (contact, QChost, host);
4465 if (!NILP (service))
4466 contact = Fplist_put (contact, QCservice, service);
4467 contact = Fplist_put (contact, QCremote,
4468 conv_sockaddr_to_lisp (&saddr.sa, len));
4469 #ifdef HAVE_GETSOCKNAME
4470 len = sizeof saddr;
4471 if (getsockname (s, &saddr.sa, &len) == 0)
4472 contact = Fplist_put (contact, QClocal,
4473 conv_sockaddr_to_lisp (&saddr.sa, len));
4474 #endif
4476 pset_childp (p, contact);
4477 pset_plist (p, Fcopy_sequence (ps->plist));
4478 pset_type (p, Qnetwork);
4480 pset_buffer (p, buffer);
4481 pset_sentinel (p, ps->sentinel);
4482 pset_filter (p, ps->filter);
4483 pset_command (p, Qnil);
4484 p->pid = 0;
4486 /* Discard the unwind protect for closing S. */
4487 specpdl_ptr = specpdl + count;
4489 p->open_fd[SUBPROCESS_STDIN] = s;
4490 p->infd = s;
4491 p->outfd = s;
4492 pset_status (p, Qrun);
4494 /* Client processes for accepted connections are not stopped initially. */
4495 if (!EQ (p->filter, Qt))
4497 FD_SET (s, &input_wait_mask);
4498 FD_SET (s, &non_keyboard_wait_mask);
4501 if (s > max_process_desc)
4502 max_process_desc = s;
4504 /* Setup coding system for new process based on server process.
4505 This seems to be the proper thing to do, as the coding system
4506 of the new process should reflect the settings at the time the
4507 server socket was opened; not the current settings. */
4509 pset_decode_coding_system (p, ps->decode_coding_system);
4510 pset_encode_coding_system (p, ps->encode_coding_system);
4511 setup_process_coding_systems (proc);
4513 pset_decoding_buf (p, empty_unibyte_string);
4514 p->decoding_carryover = 0;
4515 pset_encoding_buf (p, empty_unibyte_string);
4517 p->inherit_coding_system_flag
4518 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4520 AUTO_STRING (dash, "-");
4521 AUTO_STRING (nl, "\n");
4522 Lisp_Object host_string = STRINGP (host) ? host : dash;
4524 if (!NILP (ps->log))
4526 AUTO_STRING (accept_from, "accept from ");
4527 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4530 AUTO_STRING (open_from, "open from ");
4531 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4534 /* This variable is different from waiting_for_input in keyboard.c.
4535 It is used to communicate to a lisp process-filter/sentinel (via the
4536 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4537 for user-input when that process-filter was called.
4538 waiting_for_input cannot be used as that is by definition 0 when
4539 lisp code is being evalled.
4540 This is also used in record_asynch_buffer_change.
4541 For that purpose, this must be 0
4542 when not inside wait_reading_process_output. */
4543 static int waiting_for_user_input_p;
4545 static void
4546 wait_reading_process_output_unwind (int data)
4548 waiting_for_user_input_p = data;
4551 /* This is here so breakpoints can be put on it. */
4552 static void
4553 wait_reading_process_output_1 (void)
4557 /* Read and dispose of subprocess output while waiting for timeout to
4558 elapse and/or keyboard input to be available.
4560 TIME_LIMIT is:
4561 timeout in seconds
4562 If negative, gobble data immediately available but don't wait for any.
4564 NSECS is:
4565 an additional duration to wait, measured in nanoseconds
4566 If TIME_LIMIT is zero, then:
4567 If NSECS == 0, there is no limit.
4568 If NSECS > 0, the timeout consists of NSECS only.
4569 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4571 READ_KBD is:
4572 0 to ignore keyboard input, or
4573 1 to return when input is available, or
4574 -1 meaning caller will actually read the input, so don't throw to
4575 the quit handler, or
4577 DO_DISPLAY means redisplay should be done to show subprocess
4578 output that arrives.
4580 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4581 (and gobble terminal input into the buffer if any arrives).
4583 If WAIT_PROC is specified, wait until something arrives from that
4584 process.
4586 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4587 (suspending output from other processes). A negative value
4588 means don't run any timers either.
4590 Return positive if we received input from WAIT_PROC (or from any
4591 process if WAIT_PROC is null), zero if we attempted to receive
4592 input but got none, and negative if we didn't even try. */
4595 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4596 bool do_display,
4597 Lisp_Object wait_for_cell,
4598 struct Lisp_Process *wait_proc, int just_wait_proc)
4600 int channel, nfds;
4601 fd_set Available;
4602 fd_set Writeok;
4603 bool check_write;
4604 int check_delay;
4605 bool no_avail;
4606 int xerrno;
4607 Lisp_Object proc;
4608 struct timespec timeout, end_time;
4609 int got_some_input = -1;
4610 ptrdiff_t count = SPECPDL_INDEX ();
4612 FD_ZERO (&Available);
4613 FD_ZERO (&Writeok);
4615 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4616 && !(CONSP (wait_proc->status)
4617 && EQ (XCAR (wait_proc->status), Qexit)))
4618 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4620 record_unwind_protect_int (wait_reading_process_output_unwind,
4621 waiting_for_user_input_p);
4622 waiting_for_user_input_p = read_kbd;
4624 if (time_limit < 0)
4626 time_limit = 0;
4627 nsecs = -1;
4629 else if (TYPE_MAXIMUM (time_t) < time_limit)
4630 time_limit = TYPE_MAXIMUM (time_t);
4632 /* Since we may need to wait several times,
4633 compute the absolute time to return at. */
4634 if (time_limit || nsecs > 0)
4636 timeout = make_timespec (time_limit, nsecs);
4637 end_time = timespec_add (current_timespec (), timeout);
4640 while (1)
4642 bool timeout_reduced_for_timers = false;
4644 /* If calling from keyboard input, do not quit
4645 since we want to return C-g as an input character.
4646 Otherwise, do pending quit if requested. */
4647 if (read_kbd >= 0)
4648 QUIT;
4649 else if (pending_signals)
4650 process_pending_signals ();
4652 /* Exit now if the cell we're waiting for became non-nil. */
4653 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4654 break;
4656 /* After reading input, vacuum up any leftovers without waiting. */
4657 if (0 <= got_some_input)
4658 nsecs = -1;
4660 /* Compute time from now till when time limit is up. */
4661 /* Exit if already run out. */
4662 if (nsecs < 0)
4664 /* A negative timeout means
4665 gobble output available now
4666 but don't wait at all. */
4668 timeout = make_timespec (0, 0);
4670 else if (time_limit || nsecs > 0)
4672 struct timespec now = current_timespec ();
4673 if (timespec_cmp (end_time, now) <= 0)
4674 break;
4675 timeout = timespec_sub (end_time, now);
4677 else
4679 timeout = make_timespec (100000, 0);
4682 /* Normally we run timers here.
4683 But not if wait_for_cell; in those cases,
4684 the wait is supposed to be short,
4685 and those callers cannot handle running arbitrary Lisp code here. */
4686 if (NILP (wait_for_cell)
4687 && just_wait_proc >= 0)
4689 struct timespec timer_delay;
4693 unsigned old_timers_run = timers_run;
4694 struct buffer *old_buffer = current_buffer;
4695 Lisp_Object old_window = selected_window;
4697 timer_delay = timer_check ();
4699 /* If a timer has run, this might have changed buffers
4700 an alike. Make read_key_sequence aware of that. */
4701 if (timers_run != old_timers_run
4702 && (old_buffer != current_buffer
4703 || !EQ (old_window, selected_window))
4704 && waiting_for_user_input_p == -1)
4705 record_asynch_buffer_change ();
4707 if (timers_run != old_timers_run && do_display)
4708 /* We must retry, since a timer may have requeued itself
4709 and that could alter the time_delay. */
4710 redisplay_preserve_echo_area (9);
4711 else
4712 break;
4714 while (!detect_input_pending ());
4716 /* If there is unread keyboard input, also return. */
4717 if (read_kbd != 0
4718 && requeued_events_pending_p ())
4719 break;
4721 /* A negative timeout means do not wait at all. */
4722 if (nsecs >= 0)
4724 if (timespec_valid_p (timer_delay))
4726 if (timespec_cmp (timer_delay, timeout) < 0)
4728 timeout = timer_delay;
4729 timeout_reduced_for_timers = true;
4732 else
4734 /* This is so a breakpoint can be put here. */
4735 wait_reading_process_output_1 ();
4740 /* Cause C-g and alarm signals to take immediate action,
4741 and cause input available signals to zero out timeout.
4743 It is important that we do this before checking for process
4744 activity. If we get a SIGCHLD after the explicit checks for
4745 process activity, timeout is the only way we will know. */
4746 if (read_kbd < 0)
4747 set_waiting_for_input (&timeout);
4749 /* If status of something has changed, and no input is
4750 available, notify the user of the change right away. After
4751 this explicit check, we'll let the SIGCHLD handler zap
4752 timeout to get our attention. */
4753 if (update_tick != process_tick)
4755 fd_set Atemp;
4756 fd_set Ctemp;
4758 if (kbd_on_hold_p ())
4759 FD_ZERO (&Atemp);
4760 else
4761 Atemp = input_wait_mask;
4762 Ctemp = write_mask;
4764 timeout = make_timespec (0, 0);
4765 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4766 &Atemp,
4767 #ifdef NON_BLOCKING_CONNECT
4768 (num_pending_connects > 0 ? &Ctemp : NULL),
4769 #else
4770 NULL,
4771 #endif
4772 NULL, &timeout, NULL)
4773 <= 0))
4775 /* It's okay for us to do this and then continue with
4776 the loop, since timeout has already been zeroed out. */
4777 clear_waiting_for_input ();
4778 got_some_input = status_notify (NULL, wait_proc);
4779 if (do_display) redisplay_preserve_echo_area (13);
4783 /* Don't wait for output from a non-running process. Just
4784 read whatever data has already been received. */
4785 if (wait_proc && wait_proc->raw_status_new)
4786 update_status (wait_proc);
4787 if (wait_proc
4788 && ! EQ (wait_proc->status, Qrun)
4789 && ! EQ (wait_proc->status, Qconnect))
4791 bool read_some_bytes = false;
4793 clear_waiting_for_input ();
4795 /* If data can be read from the process, do so until exhausted. */
4796 if (wait_proc->infd >= 0)
4798 XSETPROCESS (proc, wait_proc);
4800 while (true)
4802 int nread = read_process_output (proc, wait_proc->infd);
4803 if (nread < 0)
4805 if (errno == EIO || errno == EAGAIN)
4806 break;
4807 #ifdef EWOULDBLOCK
4808 if (errno == EWOULDBLOCK)
4809 break;
4810 #endif
4812 else
4814 if (got_some_input < nread)
4815 got_some_input = nread;
4816 if (nread == 0)
4817 break;
4818 read_some_bytes = true;
4823 if (read_some_bytes && do_display)
4824 redisplay_preserve_echo_area (10);
4826 break;
4829 /* Wait till there is something to do. */
4831 if (wait_proc && just_wait_proc)
4833 if (wait_proc->infd < 0) /* Terminated. */
4834 break;
4835 FD_SET (wait_proc->infd, &Available);
4836 check_delay = 0;
4837 check_write = 0;
4839 else if (!NILP (wait_for_cell))
4841 Available = non_process_wait_mask;
4842 check_delay = 0;
4843 check_write = 0;
4845 else
4847 if (! read_kbd)
4848 Available = non_keyboard_wait_mask;
4849 else
4850 Available = input_wait_mask;
4851 Writeok = write_mask;
4852 check_delay = wait_proc ? 0 : process_output_delay_count;
4853 check_write = true;
4856 /* If frame size has changed or the window is newly mapped,
4857 redisplay now, before we start to wait. There is a race
4858 condition here; if a SIGIO arrives between now and the select
4859 and indicates that a frame is trashed, the select may block
4860 displaying a trashed screen. */
4861 if (frame_garbaged && do_display)
4863 clear_waiting_for_input ();
4864 redisplay_preserve_echo_area (11);
4865 if (read_kbd < 0)
4866 set_waiting_for_input (&timeout);
4869 /* Skip the `select' call if input is available and we're
4870 waiting for keyboard input or a cell change (which can be
4871 triggered by processing X events). In the latter case, set
4872 nfds to 1 to avoid breaking the loop. */
4873 no_avail = 0;
4874 if ((read_kbd || !NILP (wait_for_cell))
4875 && detect_input_pending ())
4877 nfds = read_kbd ? 0 : 1;
4878 no_avail = 1;
4879 FD_ZERO (&Available);
4882 if (!no_avail)
4885 #ifdef ADAPTIVE_READ_BUFFERING
4886 /* Set the timeout for adaptive read buffering if any
4887 process has non-zero read_output_skip and non-zero
4888 read_output_delay, and we are not reading output for a
4889 specific process. It is not executed if
4890 Vprocess_adaptive_read_buffering is nil. */
4891 if (process_output_skip && check_delay > 0)
4893 int nsecs = timeout.tv_nsec;
4894 if (timeout.tv_sec > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4895 nsecs = READ_OUTPUT_DELAY_MAX;
4896 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4898 proc = chan_process[channel];
4899 if (NILP (proc))
4900 continue;
4901 /* Find minimum non-zero read_output_delay among the
4902 processes with non-zero read_output_skip. */
4903 if (XPROCESS (proc)->read_output_delay > 0)
4905 check_delay--;
4906 if (!XPROCESS (proc)->read_output_skip)
4907 continue;
4908 FD_CLR (channel, &Available);
4909 XPROCESS (proc)->read_output_skip = 0;
4910 if (XPROCESS (proc)->read_output_delay < nsecs)
4911 nsecs = XPROCESS (proc)->read_output_delay;
4914 timeout = make_timespec (0, nsecs);
4915 process_output_skip = 0;
4917 #endif
4919 #if defined (HAVE_NS)
4920 nfds = ns_select
4921 #elif defined (HAVE_GLIB)
4922 nfds = xg_select
4923 #else
4924 nfds = pselect
4925 #endif
4926 (max (max_process_desc, max_input_desc) + 1,
4927 &Available,
4928 (check_write ? &Writeok : 0),
4929 NULL, &timeout, NULL);
4931 #ifdef HAVE_GNUTLS
4932 /* GnuTLS buffers data internally. In lowat mode it leaves
4933 some data in the TCP buffers so that select works, but
4934 with custom pull/push functions we need to check if some
4935 data is available in the buffers manually. */
4936 if (nfds == 0)
4938 if (! wait_proc)
4940 /* We're not waiting on a specific process, so loop
4941 through all the channels and check for data.
4942 This is a workaround needed for some versions of
4943 the gnutls library -- 2.12.14 has been confirmed
4944 to need it. See
4945 http://comments.gmane.org/gmane.emacs.devel/145074 */
4946 for (channel = 0; channel < FD_SETSIZE; ++channel)
4947 if (! NILP (chan_process[channel]))
4949 struct Lisp_Process *p =
4950 XPROCESS (chan_process[channel]);
4951 if (p && p->gnutls_p && p->gnutls_state
4952 && ((emacs_gnutls_record_check_pending
4953 (p->gnutls_state))
4954 > 0))
4956 nfds++;
4957 eassert (p->infd == channel);
4958 FD_SET (p->infd, &Available);
4962 else
4964 /* Check this specific channel. */
4965 if (wait_proc->gnutls_p /* Check for valid process. */
4966 && wait_proc->gnutls_state
4967 /* Do we have pending data? */
4968 && ((emacs_gnutls_record_check_pending
4969 (wait_proc->gnutls_state))
4970 > 0))
4972 nfds = 1;
4973 eassert (0 <= wait_proc->infd);
4974 /* Set to Available. */
4975 FD_SET (wait_proc->infd, &Available);
4979 #endif
4982 xerrno = errno;
4984 /* Make C-g and alarm signals set flags again. */
4985 clear_waiting_for_input ();
4987 /* If we woke up due to SIGWINCH, actually change size now. */
4988 do_pending_window_change (0);
4990 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4991 /* We waited the full specified time, so return now. */
4992 break;
4993 if (nfds < 0)
4995 if (xerrno == EINTR)
4996 no_avail = 1;
4997 else if (xerrno == EBADF)
4998 emacs_abort ();
4999 else
5000 report_file_errno ("Failed select", Qnil, xerrno);
5003 /* Check for keyboard input. */
5004 /* If there is any, return immediately
5005 to give it higher priority than subprocesses. */
5007 if (read_kbd != 0)
5009 unsigned old_timers_run = timers_run;
5010 struct buffer *old_buffer = current_buffer;
5011 Lisp_Object old_window = selected_window;
5012 bool leave = false;
5014 if (detect_input_pending_run_timers (do_display))
5016 swallow_events (do_display);
5017 if (detect_input_pending_run_timers (do_display))
5018 leave = true;
5021 /* If a timer has run, this might have changed buffers
5022 an alike. Make read_key_sequence aware of that. */
5023 if (timers_run != old_timers_run
5024 && waiting_for_user_input_p == -1
5025 && (old_buffer != current_buffer
5026 || !EQ (old_window, selected_window)))
5027 record_asynch_buffer_change ();
5029 if (leave)
5030 break;
5033 /* If there is unread keyboard input, also return. */
5034 if (read_kbd != 0
5035 && requeued_events_pending_p ())
5036 break;
5038 /* If we are not checking for keyboard input now,
5039 do process events (but don't run any timers).
5040 This is so that X events will be processed.
5041 Otherwise they may have to wait until polling takes place.
5042 That would causes delays in pasting selections, for example.
5044 (We used to do this only if wait_for_cell.) */
5045 if (read_kbd == 0 && detect_input_pending ())
5047 swallow_events (do_display);
5048 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5049 if (detect_input_pending ())
5050 break;
5051 #endif
5054 /* Exit now if the cell we're waiting for became non-nil. */
5055 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5056 break;
5058 #ifdef USABLE_SIGIO
5059 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5060 go read it. This can happen with X on BSD after logging out.
5061 In that case, there really is no input and no SIGIO,
5062 but select says there is input. */
5064 if (read_kbd && interrupt_input
5065 && keyboard_bit_set (&Available) && ! noninteractive)
5066 handle_input_available_signal (SIGIO);
5067 #endif
5069 /* If checking input just got us a size-change event from X,
5070 obey it now if we should. */
5071 if (read_kbd || ! NILP (wait_for_cell))
5072 do_pending_window_change (0);
5074 /* Check for data from a process. */
5075 if (no_avail || nfds == 0)
5076 continue;
5078 for (channel = 0; channel <= max_input_desc; ++channel)
5080 struct fd_callback_data *d = &fd_callback_info[channel];
5081 if (d->func
5082 && ((d->condition & FOR_READ
5083 && FD_ISSET (channel, &Available))
5084 || (d->condition & FOR_WRITE
5085 && FD_ISSET (channel, &write_mask))))
5086 d->func (channel, d->data);
5089 for (channel = 0; channel <= max_process_desc; channel++)
5091 if (FD_ISSET (channel, &Available)
5092 && FD_ISSET (channel, &non_keyboard_wait_mask)
5093 && !FD_ISSET (channel, &non_process_wait_mask))
5095 int nread;
5097 /* If waiting for this channel, arrange to return as
5098 soon as no more input to be processed. No more
5099 waiting. */
5100 proc = chan_process[channel];
5101 if (NILP (proc))
5102 continue;
5104 /* If this is a server stream socket, accept connection. */
5105 if (EQ (XPROCESS (proc)->status, Qlisten))
5107 server_accept_connection (proc, channel);
5108 continue;
5111 /* Read data from the process, starting with our
5112 buffered-ahead character if we have one. */
5114 nread = read_process_output (proc, channel);
5115 if ((!wait_proc || wait_proc == XPROCESS (proc)) && got_some_input < nread)
5116 got_some_input = nread;
5117 if (nread > 0)
5119 /* Since read_process_output can run a filter,
5120 which can call accept-process-output,
5121 don't try to read from any other processes
5122 before doing the select again. */
5123 FD_ZERO (&Available);
5125 if (do_display)
5126 redisplay_preserve_echo_area (12);
5128 #ifdef EWOULDBLOCK
5129 else if (nread == -1 && errno == EWOULDBLOCK)
5131 #endif
5132 else if (nread == -1 && errno == EAGAIN)
5134 #ifdef WINDOWSNT
5135 /* FIXME: Is this special case still needed? */
5136 /* Note that we cannot distinguish between no input
5137 available now and a closed pipe.
5138 With luck, a closed pipe will be accompanied by
5139 subprocess termination and SIGCHLD. */
5140 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5141 && !PIPECONN_P (proc))
5143 #endif
5144 #ifdef HAVE_PTYS
5145 /* On some OSs with ptys, when the process on one end of
5146 a pty exits, the other end gets an error reading with
5147 errno = EIO instead of getting an EOF (0 bytes read).
5148 Therefore, if we get an error reading and errno =
5149 EIO, just continue, because the child process has
5150 exited and should clean itself up soon (e.g. when we
5151 get a SIGCHLD). */
5152 else if (nread == -1 && errno == EIO)
5154 struct Lisp_Process *p = XPROCESS (proc);
5156 /* Clear the descriptor now, so we only raise the
5157 signal once. */
5158 FD_CLR (channel, &input_wait_mask);
5159 FD_CLR (channel, &non_keyboard_wait_mask);
5161 if (p->pid == -2)
5163 /* If the EIO occurs on a pty, the SIGCHLD handler's
5164 waitpid call will not find the process object to
5165 delete. Do it here. */
5166 p->tick = ++process_tick;
5167 pset_status (p, Qfailed);
5170 #endif /* HAVE_PTYS */
5171 /* If we can detect process termination, don't consider the
5172 process gone just because its pipe is closed. */
5173 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5174 && !PIPECONN_P (proc))
5176 else if (nread == 0 && PIPECONN_P (proc))
5178 /* Preserve status of processes already terminated. */
5179 XPROCESS (proc)->tick = ++process_tick;
5180 deactivate_process (proc);
5181 if (EQ (XPROCESS (proc)->status, Qrun))
5182 pset_status (XPROCESS (proc),
5183 list2 (Qexit, make_number (0)));
5185 else
5187 /* Preserve status of processes already terminated. */
5188 XPROCESS (proc)->tick = ++process_tick;
5189 deactivate_process (proc);
5190 if (XPROCESS (proc)->raw_status_new)
5191 update_status (XPROCESS (proc));
5192 if (EQ (XPROCESS (proc)->status, Qrun))
5193 pset_status (XPROCESS (proc),
5194 list2 (Qexit, make_number (256)));
5197 #ifdef NON_BLOCKING_CONNECT
5198 if (FD_ISSET (channel, &Writeok)
5199 && FD_ISSET (channel, &connect_wait_mask))
5201 struct Lisp_Process *p;
5203 FD_CLR (channel, &connect_wait_mask);
5204 FD_CLR (channel, &write_mask);
5205 if (--num_pending_connects < 0)
5206 emacs_abort ();
5208 proc = chan_process[channel];
5209 if (NILP (proc))
5210 continue;
5212 p = XPROCESS (proc);
5214 #ifdef GNU_LINUX
5215 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5216 So only use it on systems where it is known to work. */
5218 socklen_t xlen = sizeof (xerrno);
5219 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5220 xerrno = errno;
5222 #else
5224 struct sockaddr pname;
5225 socklen_t pnamelen = sizeof (pname);
5227 /* If connection failed, getpeername will fail. */
5228 xerrno = 0;
5229 if (getpeername (channel, &pname, &pnamelen) < 0)
5231 /* Obtain connect failure code through error slippage. */
5232 char dummy;
5233 xerrno = errno;
5234 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5235 xerrno = errno;
5238 #endif
5239 if (xerrno)
5241 p->tick = ++process_tick;
5242 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5243 deactivate_process (proc);
5245 else
5247 pset_status (p, Qrun);
5248 /* Execute the sentinel here. If we had relied on
5249 status_notify to do it later, it will read input
5250 from the process before calling the sentinel. */
5251 exec_sentinel (proc, build_string ("open\n"));
5252 if (0 <= p->infd && !EQ (p->filter, Qt)
5253 && !EQ (p->command, Qt))
5255 FD_SET (p->infd, &input_wait_mask);
5256 FD_SET (p->infd, &non_keyboard_wait_mask);
5260 #endif /* NON_BLOCKING_CONNECT */
5261 } /* End for each file descriptor. */
5262 } /* End while exit conditions not met. */
5264 unbind_to (count, Qnil);
5266 /* If calling from keyboard input, do not quit
5267 since we want to return C-g as an input character.
5268 Otherwise, do pending quit if requested. */
5269 if (read_kbd >= 0)
5271 /* Prevent input_pending from remaining set if we quit. */
5272 clear_input_pending ();
5273 QUIT;
5276 return got_some_input;
5279 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5281 static Lisp_Object
5282 read_process_output_call (Lisp_Object fun_and_args)
5284 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5287 static Lisp_Object
5288 read_process_output_error_handler (Lisp_Object error_val)
5290 cmd_error_internal (error_val, "error in process filter: ");
5291 Vinhibit_quit = Qt;
5292 update_echo_area ();
5293 Fsleep_for (make_number (2), Qnil);
5294 return Qt;
5297 static void
5298 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5299 ssize_t nbytes,
5300 struct coding_system *coding);
5302 /* Read pending output from the process channel,
5303 starting with our buffered-ahead character if we have one.
5304 Yield number of decoded characters read.
5306 This function reads at most 4096 characters.
5307 If you want to read all available subprocess output,
5308 you must call it repeatedly until it returns zero.
5310 The characters read are decoded according to PROC's coding-system
5311 for decoding. */
5313 static int
5314 read_process_output (Lisp_Object proc, int channel)
5316 ssize_t nbytes;
5317 struct Lisp_Process *p = XPROCESS (proc);
5318 struct coding_system *coding = proc_decode_coding_system[channel];
5319 int carryover = p->decoding_carryover;
5320 enum { readmax = 4096 };
5321 ptrdiff_t count = SPECPDL_INDEX ();
5322 Lisp_Object odeactivate;
5323 char chars[sizeof coding->carryover + readmax];
5325 if (carryover)
5326 /* See the comment above. */
5327 memcpy (chars, SDATA (p->decoding_buf), carryover);
5329 #ifdef DATAGRAM_SOCKETS
5330 /* We have a working select, so proc_buffered_char is always -1. */
5331 if (DATAGRAM_CHAN_P (channel))
5333 socklen_t len = datagram_address[channel].len;
5334 nbytes = recvfrom (channel, chars + carryover, readmax,
5335 0, datagram_address[channel].sa, &len);
5337 else
5338 #endif
5340 bool buffered = proc_buffered_char[channel] >= 0;
5341 if (buffered)
5343 chars[carryover] = proc_buffered_char[channel];
5344 proc_buffered_char[channel] = -1;
5346 #ifdef HAVE_GNUTLS
5347 if (p->gnutls_p && p->gnutls_state)
5348 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5349 readmax - buffered);
5350 else
5351 #endif
5352 nbytes = emacs_read (channel, chars + carryover + buffered,
5353 readmax - buffered);
5354 #ifdef ADAPTIVE_READ_BUFFERING
5355 if (nbytes > 0 && p->adaptive_read_buffering)
5357 int delay = p->read_output_delay;
5358 if (nbytes < 256)
5360 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5362 if (delay == 0)
5363 process_output_delay_count++;
5364 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5367 else if (delay > 0 && nbytes == readmax - buffered)
5369 delay -= READ_OUTPUT_DELAY_INCREMENT;
5370 if (delay == 0)
5371 process_output_delay_count--;
5373 p->read_output_delay = delay;
5374 if (delay)
5376 p->read_output_skip = 1;
5377 process_output_skip = 1;
5380 #endif
5381 nbytes += buffered;
5382 nbytes += buffered && nbytes <= 0;
5385 p->decoding_carryover = 0;
5387 /* At this point, NBYTES holds number of bytes just received
5388 (including the one in proc_buffered_char[channel]). */
5389 if (nbytes <= 0)
5391 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5392 return nbytes;
5393 coding->mode |= CODING_MODE_LAST_BLOCK;
5396 /* Now set NBYTES how many bytes we must decode. */
5397 nbytes += carryover;
5399 odeactivate = Vdeactivate_mark;
5400 /* There's no good reason to let process filters change the current
5401 buffer, and many callers of accept-process-output, sit-for, and
5402 friends don't expect current-buffer to be changed from under them. */
5403 record_unwind_current_buffer ();
5405 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5407 /* Handling the process output should not deactivate the mark. */
5408 Vdeactivate_mark = odeactivate;
5410 unbind_to (count, Qnil);
5411 return nbytes;
5414 static void
5415 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5416 ssize_t nbytes,
5417 struct coding_system *coding)
5419 Lisp_Object outstream = p->filter;
5420 Lisp_Object text;
5421 bool outer_running_asynch_code = running_asynch_code;
5422 int waiting = waiting_for_user_input_p;
5424 /* No need to gcpro these, because all we do with them later
5425 is test them for EQness, and none of them should be a string. */
5426 #if 0
5427 Lisp_Object obuffer, okeymap;
5428 XSETBUFFER (obuffer, current_buffer);
5429 okeymap = BVAR (current_buffer, keymap);
5430 #endif
5432 /* We inhibit quit here instead of just catching it so that
5433 hitting ^G when a filter happens to be running won't screw
5434 it up. */
5435 specbind (Qinhibit_quit, Qt);
5436 specbind (Qlast_nonmenu_event, Qt);
5438 /* In case we get recursively called,
5439 and we already saved the match data nonrecursively,
5440 save the same match data in safely recursive fashion. */
5441 if (outer_running_asynch_code)
5443 Lisp_Object tem;
5444 /* Don't clobber the CURRENT match data, either! */
5445 tem = Fmatch_data (Qnil, Qnil, Qnil);
5446 restore_search_regs ();
5447 record_unwind_save_match_data ();
5448 Fset_match_data (tem, Qt);
5451 /* For speed, if a search happens within this code,
5452 save the match data in a special nonrecursive fashion. */
5453 running_asynch_code = 1;
5455 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5456 text = coding->dst_object;
5457 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5458 /* A new coding system might be found. */
5459 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5461 pset_decode_coding_system (p, Vlast_coding_system_used);
5463 /* Don't call setup_coding_system for
5464 proc_decode_coding_system[channel] here. It is done in
5465 detect_coding called via decode_coding above. */
5467 /* If a coding system for encoding is not yet decided, we set
5468 it as the same as coding-system for decoding.
5470 But, before doing that we must check if
5471 proc_encode_coding_system[p->outfd] surely points to a
5472 valid memory because p->outfd will be changed once EOF is
5473 sent to the process. */
5474 if (NILP (p->encode_coding_system) && p->outfd >= 0
5475 && proc_encode_coding_system[p->outfd])
5477 pset_encode_coding_system
5478 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5479 setup_coding_system (p->encode_coding_system,
5480 proc_encode_coding_system[p->outfd]);
5484 if (coding->carryover_bytes > 0)
5486 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5487 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5488 memcpy (SDATA (p->decoding_buf), coding->carryover,
5489 coding->carryover_bytes);
5490 p->decoding_carryover = coding->carryover_bytes;
5492 if (SBYTES (text) > 0)
5493 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5494 sometimes it's simply wrong to wrap (e.g. when called from
5495 accept-process-output). */
5496 internal_condition_case_1 (read_process_output_call,
5497 list3 (outstream, make_lisp_proc (p), text),
5498 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5499 read_process_output_error_handler);
5501 /* If we saved the match data nonrecursively, restore it now. */
5502 restore_search_regs ();
5503 running_asynch_code = outer_running_asynch_code;
5505 /* Restore waiting_for_user_input_p as it was
5506 when we were called, in case the filter clobbered it. */
5507 waiting_for_user_input_p = waiting;
5509 #if 0 /* Call record_asynch_buffer_change unconditionally,
5510 because we might have changed minor modes or other things
5511 that affect key bindings. */
5512 if (! EQ (Fcurrent_buffer (), obuffer)
5513 || ! EQ (current_buffer->keymap, okeymap))
5514 #endif
5515 /* But do it only if the caller is actually going to read events.
5516 Otherwise there's no need to make him wake up, and it could
5517 cause trouble (for example it would make sit_for return). */
5518 if (waiting_for_user_input_p == -1)
5519 record_asynch_buffer_change ();
5522 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5523 Sinternal_default_process_filter, 2, 2, 0,
5524 doc: /* Function used as default process filter.
5525 This inserts the process's output into its buffer, if there is one.
5526 Otherwise it discards the output. */)
5527 (Lisp_Object proc, Lisp_Object text)
5529 struct Lisp_Process *p;
5530 ptrdiff_t opoint;
5532 CHECK_PROCESS (proc);
5533 p = XPROCESS (proc);
5534 CHECK_STRING (text);
5536 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5538 Lisp_Object old_read_only;
5539 ptrdiff_t old_begv, old_zv;
5540 ptrdiff_t old_begv_byte, old_zv_byte;
5541 ptrdiff_t before, before_byte;
5542 ptrdiff_t opoint_byte;
5543 struct buffer *b;
5545 Fset_buffer (p->buffer);
5546 opoint = PT;
5547 opoint_byte = PT_BYTE;
5548 old_read_only = BVAR (current_buffer, read_only);
5549 old_begv = BEGV;
5550 old_zv = ZV;
5551 old_begv_byte = BEGV_BYTE;
5552 old_zv_byte = ZV_BYTE;
5554 bset_read_only (current_buffer, Qnil);
5556 /* Insert new output into buffer at the current end-of-output
5557 marker, thus preserving logical ordering of input and output. */
5558 if (XMARKER (p->mark)->buffer)
5559 set_point_from_marker (p->mark);
5560 else
5561 SET_PT_BOTH (ZV, ZV_BYTE);
5562 before = PT;
5563 before_byte = PT_BYTE;
5565 /* If the output marker is outside of the visible region, save
5566 the restriction and widen. */
5567 if (! (BEGV <= PT && PT <= ZV))
5568 Fwiden ();
5570 /* Adjust the multibyteness of TEXT to that of the buffer. */
5571 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5572 != ! STRING_MULTIBYTE (text))
5573 text = (STRING_MULTIBYTE (text)
5574 ? Fstring_as_unibyte (text)
5575 : Fstring_to_multibyte (text));
5576 /* Insert before markers in case we are inserting where
5577 the buffer's mark is, and the user's next command is Meta-y. */
5578 insert_from_string_before_markers (text, 0, 0,
5579 SCHARS (text), SBYTES (text), 0);
5581 /* Make sure the process marker's position is valid when the
5582 process buffer is changed in the signal_after_change above.
5583 W3 is known to do that. */
5584 if (BUFFERP (p->buffer)
5585 && (b = XBUFFER (p->buffer), b != current_buffer))
5586 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5587 else
5588 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5590 update_mode_lines = 23;
5592 /* Make sure opoint and the old restrictions
5593 float ahead of any new text just as point would. */
5594 if (opoint >= before)
5596 opoint += PT - before;
5597 opoint_byte += PT_BYTE - before_byte;
5599 if (old_begv > before)
5601 old_begv += PT - before;
5602 old_begv_byte += PT_BYTE - before_byte;
5604 if (old_zv >= before)
5606 old_zv += PT - before;
5607 old_zv_byte += PT_BYTE - before_byte;
5610 /* If the restriction isn't what it should be, set it. */
5611 if (old_begv != BEGV || old_zv != ZV)
5612 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5614 bset_read_only (current_buffer, old_read_only);
5615 SET_PT_BOTH (opoint, opoint_byte);
5617 return Qnil;
5620 /* Sending data to subprocess. */
5622 /* In send_process, when a write fails temporarily,
5623 wait_reading_process_output is called. It may execute user code,
5624 e.g. timers, that attempts to write new data to the same process.
5625 We must ensure that data is sent in the right order, and not
5626 interspersed half-completed with other writes (Bug#10815). This is
5627 handled by the write_queue element of struct process. It is a list
5628 with each entry having the form
5630 (string . (offset . length))
5632 where STRING is a lisp string, OFFSET is the offset into the
5633 string's byte sequence from which we should begin to send, and
5634 LENGTH is the number of bytes left to send. */
5636 /* Create a new entry in write_queue.
5637 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5638 BUF is a pointer to the string sequence of the input_obj or a C
5639 string in case of Qt or Qnil. */
5641 static void
5642 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5643 const char *buf, ptrdiff_t len, bool front)
5645 ptrdiff_t offset;
5646 Lisp_Object entry, obj;
5648 if (STRINGP (input_obj))
5650 offset = buf - SSDATA (input_obj);
5651 obj = input_obj;
5653 else
5655 offset = 0;
5656 obj = make_unibyte_string (buf, len);
5659 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5661 if (front)
5662 pset_write_queue (p, Fcons (entry, p->write_queue));
5663 else
5664 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5667 /* Remove the first element in the write_queue of process P, put its
5668 contents in OBJ, BUF and LEN, and return true. If the
5669 write_queue is empty, return false. */
5671 static bool
5672 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5673 const char **buf, ptrdiff_t *len)
5675 Lisp_Object entry, offset_length;
5676 ptrdiff_t offset;
5678 if (NILP (p->write_queue))
5679 return 0;
5681 entry = XCAR (p->write_queue);
5682 pset_write_queue (p, XCDR (p->write_queue));
5684 *obj = XCAR (entry);
5685 offset_length = XCDR (entry);
5687 *len = XINT (XCDR (offset_length));
5688 offset = XINT (XCAR (offset_length));
5689 *buf = SSDATA (*obj) + offset;
5691 return 1;
5694 /* Send some data to process PROC.
5695 BUF is the beginning of the data; LEN is the number of characters.
5696 OBJECT is the Lisp object that the data comes from. If OBJECT is
5697 nil or t, it means that the data comes from C string.
5699 If OBJECT is not nil, the data is encoded by PROC's coding-system
5700 for encoding before it is sent.
5702 This function can evaluate Lisp code and can garbage collect. */
5704 static void
5705 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5706 Lisp_Object object)
5708 struct Lisp_Process *p = XPROCESS (proc);
5709 ssize_t rv;
5710 struct coding_system *coding;
5712 if (p->raw_status_new)
5713 update_status (p);
5714 if (! EQ (p->status, Qrun))
5715 error ("Process %s not running", SDATA (p->name));
5716 if (p->outfd < 0)
5717 error ("Output file descriptor of %s is closed", SDATA (p->name));
5719 coding = proc_encode_coding_system[p->outfd];
5720 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5722 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5723 || (BUFFERP (object)
5724 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5725 || EQ (object, Qt))
5727 pset_encode_coding_system
5728 (p, complement_process_encoding_system (p->encode_coding_system));
5729 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5731 /* The coding system for encoding was changed to raw-text
5732 because we sent a unibyte text previously. Now we are
5733 sending a multibyte text, thus we must encode it by the
5734 original coding system specified for the current process.
5736 Another reason we come here is that the coding system
5737 was just complemented and a new one was returned by
5738 complement_process_encoding_system. */
5739 setup_coding_system (p->encode_coding_system, coding);
5740 Vlast_coding_system_used = p->encode_coding_system;
5742 coding->src_multibyte = 1;
5744 else
5746 coding->src_multibyte = 0;
5747 /* For sending a unibyte text, character code conversion should
5748 not take place but EOL conversion should. So, setup raw-text
5749 or one of the subsidiary if we have not yet done it. */
5750 if (CODING_REQUIRE_ENCODING (coding))
5752 if (CODING_REQUIRE_FLUSHING (coding))
5754 /* But, before changing the coding, we must flush out data. */
5755 coding->mode |= CODING_MODE_LAST_BLOCK;
5756 send_process (proc, "", 0, Qt);
5757 coding->mode &= CODING_MODE_LAST_BLOCK;
5759 setup_coding_system (raw_text_coding_system
5760 (Vlast_coding_system_used),
5761 coding);
5762 coding->src_multibyte = 0;
5765 coding->dst_multibyte = 0;
5767 if (CODING_REQUIRE_ENCODING (coding))
5769 coding->dst_object = Qt;
5770 if (BUFFERP (object))
5772 ptrdiff_t from_byte, from, to;
5773 ptrdiff_t save_pt, save_pt_byte;
5774 struct buffer *cur = current_buffer;
5776 set_buffer_internal (XBUFFER (object));
5777 save_pt = PT, save_pt_byte = PT_BYTE;
5779 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5780 from = BYTE_TO_CHAR (from_byte);
5781 to = BYTE_TO_CHAR (from_byte + len);
5782 TEMP_SET_PT_BOTH (from, from_byte);
5783 encode_coding_object (coding, object, from, from_byte,
5784 to, from_byte + len, Qt);
5785 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5786 set_buffer_internal (cur);
5788 else if (STRINGP (object))
5790 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5791 SBYTES (object), Qt);
5793 else
5795 coding->dst_object = make_unibyte_string (buf, len);
5796 coding->produced = len;
5799 len = coding->produced;
5800 object = coding->dst_object;
5801 buf = SSDATA (object);
5804 /* If there is already data in the write_queue, put the new data
5805 in the back of queue. Otherwise, ignore it. */
5806 if (!NILP (p->write_queue))
5807 write_queue_push (p, object, buf, len, 0);
5809 do /* while !NILP (p->write_queue) */
5811 ptrdiff_t cur_len = -1;
5812 const char *cur_buf;
5813 Lisp_Object cur_object;
5815 /* If write_queue is empty, ignore it. */
5816 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5818 cur_len = len;
5819 cur_buf = buf;
5820 cur_object = object;
5823 while (cur_len > 0)
5825 /* Send this batch, using one or more write calls. */
5826 ptrdiff_t written = 0;
5827 int outfd = p->outfd;
5828 #ifdef DATAGRAM_SOCKETS
5829 if (DATAGRAM_CHAN_P (outfd))
5831 rv = sendto (outfd, cur_buf, cur_len,
5832 0, datagram_address[outfd].sa,
5833 datagram_address[outfd].len);
5834 if (rv >= 0)
5835 written = rv;
5836 else if (errno == EMSGSIZE)
5837 report_file_error ("Sending datagram", proc);
5839 else
5840 #endif
5842 #ifdef HAVE_GNUTLS
5843 if (p->gnutls_p && p->gnutls_state)
5844 written = emacs_gnutls_write (p, cur_buf, cur_len);
5845 else
5846 #endif
5847 written = emacs_write_sig (outfd, cur_buf, cur_len);
5848 rv = (written ? 0 : -1);
5849 #ifdef ADAPTIVE_READ_BUFFERING
5850 if (p->read_output_delay > 0
5851 && p->adaptive_read_buffering == 1)
5853 p->read_output_delay = 0;
5854 process_output_delay_count--;
5855 p->read_output_skip = 0;
5857 #endif
5860 if (rv < 0)
5862 if (errno == EAGAIN
5863 #ifdef EWOULDBLOCK
5864 || errno == EWOULDBLOCK
5865 #endif
5867 /* Buffer is full. Wait, accepting input;
5868 that may allow the program
5869 to finish doing output and read more. */
5871 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5872 /* A gross hack to work around a bug in FreeBSD.
5873 In the following sequence, read(2) returns
5874 bogus data:
5876 write(2) 1022 bytes
5877 write(2) 954 bytes, get EAGAIN
5878 read(2) 1024 bytes in process_read_output
5879 read(2) 11 bytes in process_read_output
5881 That is, read(2) returns more bytes than have
5882 ever been written successfully. The 1033 bytes
5883 read are the 1022 bytes written successfully
5884 after processing (for example with CRs added if
5885 the terminal is set up that way which it is
5886 here). The same bytes will be seen again in a
5887 later read(2), without the CRs. */
5889 if (errno == EAGAIN)
5891 int flags = FWRITE;
5892 ioctl (p->outfd, TIOCFLUSH, &flags);
5894 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5896 /* Put what we should have written in wait_queue. */
5897 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5898 wait_reading_process_output (0, 20 * 1000 * 1000,
5899 0, 0, Qnil, NULL, 0);
5900 /* Reread queue, to see what is left. */
5901 break;
5903 else if (errno == EPIPE)
5905 p->raw_status_new = 0;
5906 pset_status (p, list2 (Qexit, make_number (256)));
5907 p->tick = ++process_tick;
5908 deactivate_process (proc);
5909 error ("process %s no longer connected to pipe; closed it",
5910 SDATA (p->name));
5912 else
5913 /* This is a real error. */
5914 report_file_error ("Writing to process", proc);
5916 cur_buf += written;
5917 cur_len -= written;
5920 while (!NILP (p->write_queue));
5923 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5924 3, 3, 0,
5925 doc: /* Send current contents of region as input to PROCESS.
5926 PROCESS may be a process, a buffer, the name of a process or buffer, or
5927 nil, indicating the current buffer's process.
5928 Called from program, takes three arguments, PROCESS, START and END.
5929 If the region is more than 500 characters long,
5930 it is sent in several bunches. This may happen even for shorter regions.
5931 Output from processes can arrive in between bunches. */)
5932 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5934 Lisp_Object proc = get_process (process);
5935 ptrdiff_t start_byte, end_byte;
5937 validate_region (&start, &end);
5939 start_byte = CHAR_TO_BYTE (XINT (start));
5940 end_byte = CHAR_TO_BYTE (XINT (end));
5942 if (XINT (start) < GPT && XINT (end) > GPT)
5943 move_gap_both (XINT (start), start_byte);
5945 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5946 end_byte - start_byte, Fcurrent_buffer ());
5948 return Qnil;
5951 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5952 2, 2, 0,
5953 doc: /* Send PROCESS the contents of STRING as input.
5954 PROCESS may be a process, a buffer, the name of a process or buffer, or
5955 nil, indicating the current buffer's process.
5956 If STRING is more than 500 characters long,
5957 it is sent in several bunches. This may happen even for shorter strings.
5958 Output from processes can arrive in between bunches. */)
5959 (Lisp_Object process, Lisp_Object string)
5961 Lisp_Object proc;
5962 CHECK_STRING (string);
5963 proc = get_process (process);
5964 send_process (proc, SSDATA (string),
5965 SBYTES (string), string);
5966 return Qnil;
5969 /* Return the foreground process group for the tty/pty that
5970 the process P uses. */
5971 static pid_t
5972 emacs_get_tty_pgrp (struct Lisp_Process *p)
5974 pid_t gid = -1;
5976 #ifdef TIOCGPGRP
5977 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5979 int fd;
5980 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5981 master side. Try the slave side. */
5982 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5984 if (fd != -1)
5986 ioctl (fd, TIOCGPGRP, &gid);
5987 emacs_close (fd);
5990 #endif /* defined (TIOCGPGRP ) */
5992 return gid;
5995 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5996 Sprocess_running_child_p, 0, 1, 0,
5997 doc: /* Return non-nil if PROCESS has given the terminal to a
5998 child. If the operating system does not make it possible to find out,
5999 return t. If we can find out, return the numeric ID of the foreground
6000 process group. */)
6001 (Lisp_Object process)
6003 /* Initialize in case ioctl doesn't exist or gives an error,
6004 in a way that will cause returning t. */
6005 pid_t gid;
6006 Lisp_Object proc;
6007 struct Lisp_Process *p;
6009 proc = get_process (process);
6010 p = XPROCESS (proc);
6012 if (!EQ (p->type, Qreal))
6013 error ("Process %s is not a subprocess",
6014 SDATA (p->name));
6015 if (p->infd < 0)
6016 error ("Process %s is not active",
6017 SDATA (p->name));
6019 gid = emacs_get_tty_pgrp (p);
6021 if (gid == p->pid)
6022 return Qnil;
6023 if (gid != -1)
6024 return make_number (gid);
6025 return Qt;
6028 /* Send a signal number SIGNO to PROCESS.
6029 If CURRENT_GROUP is t, that means send to the process group
6030 that currently owns the terminal being used to communicate with PROCESS.
6031 This is used for various commands in shell mode.
6032 If CURRENT_GROUP is lambda, that means send to the process group
6033 that currently owns the terminal, but only if it is NOT the shell itself.
6035 If NOMSG is false, insert signal-announcements into process's buffers
6036 right away.
6038 If we can, we try to signal PROCESS by sending control characters
6039 down the pty. This allows us to signal inferiors who have changed
6040 their uid, for which kill would return an EPERM error. */
6042 static void
6043 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
6044 bool nomsg)
6046 Lisp_Object proc;
6047 struct Lisp_Process *p;
6048 pid_t gid;
6049 bool no_pgrp = 0;
6051 proc = get_process (process);
6052 p = XPROCESS (proc);
6054 if (!EQ (p->type, Qreal))
6055 error ("Process %s is not a subprocess",
6056 SDATA (p->name));
6057 if (p->infd < 0)
6058 error ("Process %s is not active",
6059 SDATA (p->name));
6061 if (!p->pty_flag)
6062 current_group = Qnil;
6064 /* If we are using pgrps, get a pgrp number and make it negative. */
6065 if (NILP (current_group))
6066 /* Send the signal to the shell's process group. */
6067 gid = p->pid;
6068 else
6070 #ifdef SIGNALS_VIA_CHARACTERS
6071 /* If possible, send signals to the entire pgrp
6072 by sending an input character to it. */
6074 struct termios t;
6075 cc_t *sig_char = NULL;
6077 tcgetattr (p->infd, &t);
6079 switch (signo)
6081 case SIGINT:
6082 sig_char = &t.c_cc[VINTR];
6083 break;
6085 case SIGQUIT:
6086 sig_char = &t.c_cc[VQUIT];
6087 break;
6089 case SIGTSTP:
6090 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6091 sig_char = &t.c_cc[VSWTCH];
6092 #else
6093 sig_char = &t.c_cc[VSUSP];
6094 #endif
6095 break;
6098 if (sig_char && *sig_char != CDISABLE)
6100 send_process (proc, (char *) sig_char, 1, Qnil);
6101 return;
6103 /* If we can't send the signal with a character,
6104 fall through and send it another way. */
6106 /* The code above may fall through if it can't
6107 handle the signal. */
6108 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6110 #ifdef TIOCGPGRP
6111 /* Get the current pgrp using the tty itself, if we have that.
6112 Otherwise, use the pty to get the pgrp.
6113 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6114 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6115 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6116 His patch indicates that if TIOCGPGRP returns an error, then
6117 we should just assume that p->pid is also the process group id. */
6119 gid = emacs_get_tty_pgrp (p);
6121 if (gid == -1)
6122 /* If we can't get the information, assume
6123 the shell owns the tty. */
6124 gid = p->pid;
6126 /* It is not clear whether anything really can set GID to -1.
6127 Perhaps on some system one of those ioctls can or could do so.
6128 Or perhaps this is vestigial. */
6129 if (gid == -1)
6130 no_pgrp = 1;
6131 #else /* ! defined (TIOCGPGRP) */
6132 /* Can't select pgrps on this system, so we know that
6133 the child itself heads the pgrp. */
6134 gid = p->pid;
6135 #endif /* ! defined (TIOCGPGRP) */
6137 /* If current_group is lambda, and the shell owns the terminal,
6138 don't send any signal. */
6139 if (EQ (current_group, Qlambda) && gid == p->pid)
6140 return;
6143 #ifdef SIGCONT
6144 if (signo == SIGCONT)
6146 p->raw_status_new = 0;
6147 pset_status (p, Qrun);
6148 p->tick = ++process_tick;
6149 if (!nomsg)
6151 status_notify (NULL, NULL);
6152 redisplay_preserve_echo_area (13);
6155 #endif
6157 #ifdef TIOCSIGSEND
6158 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6159 We don't know whether the bug is fixed in later HP-UX versions. */
6160 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6161 return;
6162 #endif
6164 /* If we don't have process groups, send the signal to the immediate
6165 subprocess. That isn't really right, but it's better than any
6166 obvious alternative. */
6167 pid_t pid = no_pgrp ? gid : - gid;
6169 /* Do not kill an already-reaped process, as that could kill an
6170 innocent bystander that happens to have the same process ID. */
6171 sigset_t oldset;
6172 block_child_signal (&oldset);
6173 if (p->alive)
6174 kill (pid, signo);
6175 unblock_child_signal (&oldset);
6178 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6179 doc: /* Interrupt process PROCESS.
6180 PROCESS may be a process, a buffer, or the name of a process or buffer.
6181 No arg or nil means current buffer's process.
6182 Second arg CURRENT-GROUP non-nil means send signal to
6183 the current process-group of the process's controlling terminal
6184 rather than to the process's own process group.
6185 If the process is a shell, this means interrupt current subjob
6186 rather than the shell.
6188 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6189 don't send the signal. */)
6190 (Lisp_Object process, Lisp_Object current_group)
6192 process_send_signal (process, SIGINT, current_group, 0);
6193 return process;
6196 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6197 doc: /* Kill process PROCESS. May be process or name of one.
6198 See function `interrupt-process' for more details on usage. */)
6199 (Lisp_Object process, Lisp_Object current_group)
6201 process_send_signal (process, SIGKILL, current_group, 0);
6202 return process;
6205 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6206 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6207 See function `interrupt-process' for more details on usage. */)
6208 (Lisp_Object process, Lisp_Object current_group)
6210 process_send_signal (process, SIGQUIT, current_group, 0);
6211 return process;
6214 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6215 doc: /* Stop process PROCESS. May be process or name of one.
6216 See function `interrupt-process' for more details on usage.
6217 If PROCESS is a network or serial process, inhibit handling of incoming
6218 traffic. */)
6219 (Lisp_Object process, Lisp_Object current_group)
6221 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6222 || PIPECONN_P (process)))
6224 struct Lisp_Process *p;
6226 p = XPROCESS (process);
6227 if (NILP (p->command)
6228 && p->infd >= 0)
6230 FD_CLR (p->infd, &input_wait_mask);
6231 FD_CLR (p->infd, &non_keyboard_wait_mask);
6233 pset_command (p, Qt);
6234 return process;
6236 #ifndef SIGTSTP
6237 error ("No SIGTSTP support");
6238 #else
6239 process_send_signal (process, SIGTSTP, current_group, 0);
6240 #endif
6241 return process;
6244 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6245 doc: /* Continue process PROCESS. May be process or name of one.
6246 See function `interrupt-process' for more details on usage.
6247 If PROCESS is a network or serial process, resume handling of incoming
6248 traffic. */)
6249 (Lisp_Object process, Lisp_Object current_group)
6251 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6252 || PIPECONN_P (process)))
6254 struct Lisp_Process *p;
6256 p = XPROCESS (process);
6257 if (EQ (p->command, Qt)
6258 && p->infd >= 0
6259 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6261 FD_SET (p->infd, &input_wait_mask);
6262 FD_SET (p->infd, &non_keyboard_wait_mask);
6263 #ifdef WINDOWSNT
6264 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6265 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6266 #else /* not WINDOWSNT */
6267 tcflush (p->infd, TCIFLUSH);
6268 #endif /* not WINDOWSNT */
6270 pset_command (p, Qnil);
6271 return process;
6273 #ifdef SIGCONT
6274 process_send_signal (process, SIGCONT, current_group, 0);
6275 #else
6276 error ("No SIGCONT support");
6277 #endif
6278 return process;
6281 /* Return the integer value of the signal whose abbreviation is ABBR,
6282 or a negative number if there is no such signal. */
6283 static int
6284 abbr_to_signal (char const *name)
6286 int i, signo;
6287 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6289 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6290 name += 3;
6292 for (i = 0; i < sizeof sigbuf; i++)
6294 sigbuf[i] = c_toupper (name[i]);
6295 if (! sigbuf[i])
6296 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6299 return -1;
6302 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6303 2, 2, "sProcess (name or number): \nnSignal code: ",
6304 doc: /* Send PROCESS the signal with code SIGCODE.
6305 PROCESS may also be a number specifying the process id of the
6306 process to signal; in this case, the process need not be a child of
6307 this Emacs.
6308 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6309 (Lisp_Object process, Lisp_Object sigcode)
6311 pid_t pid;
6312 int signo;
6314 if (STRINGP (process))
6316 Lisp_Object tem = Fget_process (process);
6317 if (NILP (tem))
6319 Lisp_Object process_number
6320 = string_to_number (SSDATA (process), 10, 1);
6321 if (INTEGERP (process_number) || FLOATP (process_number))
6322 tem = process_number;
6324 process = tem;
6326 else if (!NUMBERP (process))
6327 process = get_process (process);
6329 if (NILP (process))
6330 return process;
6332 if (NUMBERP (process))
6333 CONS_TO_INTEGER (process, pid_t, pid);
6334 else
6336 CHECK_PROCESS (process);
6337 pid = XPROCESS (process)->pid;
6338 if (pid <= 0)
6339 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6342 if (INTEGERP (sigcode))
6344 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6345 signo = XINT (sigcode);
6347 else
6349 char *name;
6351 CHECK_SYMBOL (sigcode);
6352 name = SSDATA (SYMBOL_NAME (sigcode));
6354 signo = abbr_to_signal (name);
6355 if (signo < 0)
6356 error ("Undefined signal name %s", name);
6359 return make_number (kill (pid, signo));
6362 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6363 doc: /* Make PROCESS see end-of-file in its input.
6364 EOF comes after any text already sent to it.
6365 PROCESS may be a process, a buffer, the name of a process or buffer, or
6366 nil, indicating the current buffer's process.
6367 If PROCESS is a network connection, or is a process communicating
6368 through a pipe (as opposed to a pty), then you cannot send any more
6369 text to PROCESS after you call this function.
6370 If PROCESS is a serial process, wait until all output written to the
6371 process has been transmitted to the serial port. */)
6372 (Lisp_Object process)
6374 Lisp_Object proc;
6375 struct coding_system *coding = NULL;
6376 int outfd;
6378 if (DATAGRAM_CONN_P (process))
6379 return process;
6381 proc = get_process (process);
6382 outfd = XPROCESS (proc)->outfd;
6383 if (outfd >= 0)
6384 coding = proc_encode_coding_system[outfd];
6386 /* Make sure the process is really alive. */
6387 if (XPROCESS (proc)->raw_status_new)
6388 update_status (XPROCESS (proc));
6389 if (! EQ (XPROCESS (proc)->status, Qrun))
6390 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6392 if (coding && CODING_REQUIRE_FLUSHING (coding))
6394 coding->mode |= CODING_MODE_LAST_BLOCK;
6395 send_process (proc, "", 0, Qnil);
6398 if (XPROCESS (proc)->pty_flag)
6399 send_process (proc, "\004", 1, Qnil);
6400 else if (EQ (XPROCESS (proc)->type, Qserial))
6402 #ifndef WINDOWSNT
6403 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6404 report_file_error ("Failed tcdrain", Qnil);
6405 #endif /* not WINDOWSNT */
6406 /* Do nothing on Windows because writes are blocking. */
6408 else
6410 struct Lisp_Process *p = XPROCESS (proc);
6411 int old_outfd = p->outfd;
6412 int new_outfd;
6414 #ifdef HAVE_SHUTDOWN
6415 /* If this is a network connection, or socketpair is used
6416 for communication with the subprocess, call shutdown to cause EOF.
6417 (In some old system, shutdown to socketpair doesn't work.
6418 Then we just can't win.) */
6419 if (0 <= old_outfd
6420 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6421 shutdown (old_outfd, 1);
6422 #endif
6423 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6424 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6425 if (new_outfd < 0)
6426 report_file_error ("Opening null device", Qnil);
6427 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6428 p->outfd = new_outfd;
6430 if (!proc_encode_coding_system[new_outfd])
6431 proc_encode_coding_system[new_outfd]
6432 = xmalloc (sizeof (struct coding_system));
6433 if (old_outfd >= 0)
6435 *proc_encode_coding_system[new_outfd]
6436 = *proc_encode_coding_system[old_outfd];
6437 memset (proc_encode_coding_system[old_outfd], 0,
6438 sizeof (struct coding_system));
6440 else
6441 setup_coding_system (p->encode_coding_system,
6442 proc_encode_coding_system[new_outfd]);
6444 return process;
6447 /* The main Emacs thread records child processes in three places:
6449 - Vprocess_alist, for asynchronous subprocesses, which are child
6450 processes visible to Lisp.
6452 - deleted_pid_list, for child processes invisible to Lisp,
6453 typically because of delete-process. These are recorded so that
6454 the processes can be reaped when they exit, so that the operating
6455 system's process table is not cluttered by zombies.
6457 - the local variable PID in Fcall_process, call_process_cleanup and
6458 call_process_kill, for synchronous subprocesses.
6459 record_unwind_protect is used to make sure this process is not
6460 forgotten: if the user interrupts call-process and the child
6461 process refuses to exit immediately even with two C-g's,
6462 call_process_kill adds PID's contents to deleted_pid_list before
6463 returning.
6465 The main Emacs thread invokes waitpid only on child processes that
6466 it creates and that have not been reaped. This avoid races on
6467 platforms such as GTK, where other threads create their own
6468 subprocesses which the main thread should not reap. For example,
6469 if the main thread attempted to reap an already-reaped child, it
6470 might inadvertently reap a GTK-created process that happened to
6471 have the same process ID. */
6473 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6474 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6475 keep track of its own children. GNUstep is similar. */
6477 static void dummy_handler (int sig) {}
6478 static signal_handler_t volatile lib_child_handler;
6480 /* Handle a SIGCHLD signal by looking for known child processes of
6481 Emacs whose status have changed. For each one found, record its
6482 new status.
6484 All we do is change the status; we do not run sentinels or print
6485 notifications. That is saved for the next time keyboard input is
6486 done, in order to avoid timing errors.
6488 ** WARNING: this can be called during garbage collection.
6489 Therefore, it must not be fooled by the presence of mark bits in
6490 Lisp objects.
6492 ** USG WARNING: Although it is not obvious from the documentation
6493 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6494 signal() before executing at least one wait(), otherwise the
6495 handler will be called again, resulting in an infinite loop. The
6496 relevant portion of the documentation reads "SIGCLD signals will be
6497 queued and the signal-catching function will be continually
6498 reentered until the queue is empty". Invoking signal() causes the
6499 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6500 Inc.
6502 ** Malloc WARNING: This should never call malloc either directly or
6503 indirectly; if it does, that is a bug. */
6505 static void
6506 handle_child_signal (int sig)
6508 Lisp_Object tail, proc;
6510 /* Find the process that signaled us, and record its status. */
6512 /* The process can have been deleted by Fdelete_process, or have
6513 been started asynchronously by Fcall_process. */
6514 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6516 bool all_pids_are_fixnums
6517 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6518 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6519 Lisp_Object head = XCAR (tail);
6520 Lisp_Object xpid;
6521 if (! CONSP (head))
6522 continue;
6523 xpid = XCAR (head);
6524 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6526 pid_t deleted_pid;
6527 if (INTEGERP (xpid))
6528 deleted_pid = XINT (xpid);
6529 else
6530 deleted_pid = XFLOAT_DATA (xpid);
6531 if (child_status_changed (deleted_pid, 0, 0))
6533 if (STRINGP (XCDR (head)))
6534 unlink (SSDATA (XCDR (head)));
6535 XSETCAR (tail, Qnil);
6540 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6541 FOR_EACH_PROCESS (tail, proc)
6543 struct Lisp_Process *p = XPROCESS (proc);
6544 int status;
6546 if (p->alive
6547 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6549 /* Change the status of the process that was found. */
6550 p->tick = ++process_tick;
6551 p->raw_status = status;
6552 p->raw_status_new = 1;
6554 /* If process has terminated, stop waiting for its output. */
6555 if (WIFSIGNALED (status) || WIFEXITED (status))
6557 bool clear_desc_flag = 0;
6558 p->alive = 0;
6559 if (p->infd >= 0)
6560 clear_desc_flag = 1;
6562 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6563 if (clear_desc_flag)
6565 FD_CLR (p->infd, &input_wait_mask);
6566 FD_CLR (p->infd, &non_keyboard_wait_mask);
6572 lib_child_handler (sig);
6573 #ifdef NS_IMPL_GNUSTEP
6574 /* NSTask in GNUstep sets its child handler each time it is called.
6575 So we must re-set ours. */
6576 catch_child_signal ();
6577 #endif
6580 static void
6581 deliver_child_signal (int sig)
6583 deliver_process_signal (sig, handle_child_signal);
6587 static Lisp_Object
6588 exec_sentinel_error_handler (Lisp_Object error_val)
6590 cmd_error_internal (error_val, "error in process sentinel: ");
6591 Vinhibit_quit = Qt;
6592 update_echo_area ();
6593 Fsleep_for (make_number (2), Qnil);
6594 return Qt;
6597 static void
6598 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6600 Lisp_Object sentinel, odeactivate;
6601 struct Lisp_Process *p = XPROCESS (proc);
6602 ptrdiff_t count = SPECPDL_INDEX ();
6603 bool outer_running_asynch_code = running_asynch_code;
6604 int waiting = waiting_for_user_input_p;
6606 if (inhibit_sentinels)
6607 return;
6609 /* No need to gcpro these, because all we do with them later
6610 is test them for EQness, and none of them should be a string. */
6611 odeactivate = Vdeactivate_mark;
6612 #if 0
6613 Lisp_Object obuffer, okeymap;
6614 XSETBUFFER (obuffer, current_buffer);
6615 okeymap = BVAR (current_buffer, keymap);
6616 #endif
6618 /* There's no good reason to let sentinels change the current
6619 buffer, and many callers of accept-process-output, sit-for, and
6620 friends don't expect current-buffer to be changed from under them. */
6621 record_unwind_current_buffer ();
6623 sentinel = p->sentinel;
6625 /* Inhibit quit so that random quits don't screw up a running filter. */
6626 specbind (Qinhibit_quit, Qt);
6627 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6629 /* In case we get recursively called,
6630 and we already saved the match data nonrecursively,
6631 save the same match data in safely recursive fashion. */
6632 if (outer_running_asynch_code)
6634 Lisp_Object tem;
6635 tem = Fmatch_data (Qnil, Qnil, Qnil);
6636 restore_search_regs ();
6637 record_unwind_save_match_data ();
6638 Fset_match_data (tem, Qt);
6641 /* For speed, if a search happens within this code,
6642 save the match data in a special nonrecursive fashion. */
6643 running_asynch_code = 1;
6645 internal_condition_case_1 (read_process_output_call,
6646 list3 (sentinel, proc, reason),
6647 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6648 exec_sentinel_error_handler);
6650 /* If we saved the match data nonrecursively, restore it now. */
6651 restore_search_regs ();
6652 running_asynch_code = outer_running_asynch_code;
6654 Vdeactivate_mark = odeactivate;
6656 /* Restore waiting_for_user_input_p as it was
6657 when we were called, in case the filter clobbered it. */
6658 waiting_for_user_input_p = waiting;
6660 #if 0
6661 if (! EQ (Fcurrent_buffer (), obuffer)
6662 || ! EQ (current_buffer->keymap, okeymap))
6663 #endif
6664 /* But do it only if the caller is actually going to read events.
6665 Otherwise there's no need to make him wake up, and it could
6666 cause trouble (for example it would make sit_for return). */
6667 if (waiting_for_user_input_p == -1)
6668 record_asynch_buffer_change ();
6670 unbind_to (count, Qnil);
6673 /* Report all recent events of a change in process status
6674 (either run the sentinel or output a message).
6675 This is usually done while Emacs is waiting for keyboard input
6676 but can be done at other times.
6678 Return positive if any input was received from WAIT_PROC (or from
6679 any process if WAIT_PROC is null), zero if input was attempted but
6680 none received, and negative if we didn't even try. */
6682 static int
6683 status_notify (struct Lisp_Process *deleting_process,
6684 struct Lisp_Process *wait_proc)
6686 Lisp_Object proc;
6687 Lisp_Object tail, msg;
6688 struct gcpro gcpro1, gcpro2;
6689 int got_some_input = -1;
6691 tail = Qnil;
6692 msg = Qnil;
6693 /* We need to gcpro tail; if read_process_output calls a filter
6694 which deletes a process and removes the cons to which tail points
6695 from Vprocess_alist, and then causes a GC, tail is an unprotected
6696 reference. */
6697 GCPRO2 (tail, msg);
6699 /* Set this now, so that if new processes are created by sentinels
6700 that we run, we get called again to handle their status changes. */
6701 update_tick = process_tick;
6703 FOR_EACH_PROCESS (tail, proc)
6705 Lisp_Object symbol;
6706 register struct Lisp_Process *p = XPROCESS (proc);
6708 if (p->tick != p->update_tick)
6710 p->update_tick = p->tick;
6712 /* If process is still active, read any output that remains. */
6713 while (! EQ (p->filter, Qt)
6714 && ! EQ (p->status, Qconnect)
6715 && ! EQ (p->status, Qlisten)
6716 /* Network or serial process not stopped: */
6717 && ! EQ (p->command, Qt)
6718 && p->infd >= 0
6719 && p != deleting_process)
6721 int nread = read_process_output (proc, p->infd);
6722 if (got_some_input < nread)
6723 got_some_input = nread;
6724 if (nread <= 0)
6725 break;
6728 /* Get the text to use for the message. */
6729 if (p->raw_status_new)
6730 update_status (p);
6731 msg = status_message (p);
6733 /* If process is terminated, deactivate it or delete it. */
6734 symbol = p->status;
6735 if (CONSP (p->status))
6736 symbol = XCAR (p->status);
6738 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6739 || EQ (symbol, Qclosed))
6741 if (delete_exited_processes)
6742 remove_process (proc);
6743 else
6744 deactivate_process (proc);
6747 /* The actions above may have further incremented p->tick.
6748 So set p->update_tick again so that an error in the sentinel will
6749 not cause this code to be run again. */
6750 p->update_tick = p->tick;
6751 /* Now output the message suitably. */
6752 exec_sentinel (proc, msg);
6754 } /* end for */
6756 update_mode_lines = 24; /* In case buffers use %s in mode-line-format. */
6757 UNGCPRO;
6758 return got_some_input;
6761 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6762 Sinternal_default_process_sentinel, 2, 2, 0,
6763 doc: /* Function used as default sentinel for processes.
6764 This inserts a status message into the process's buffer, if there is one. */)
6765 (Lisp_Object proc, Lisp_Object msg)
6767 Lisp_Object buffer, symbol;
6768 struct Lisp_Process *p;
6769 CHECK_PROCESS (proc);
6770 p = XPROCESS (proc);
6771 buffer = p->buffer;
6772 symbol = p->status;
6773 if (CONSP (symbol))
6774 symbol = XCAR (symbol);
6776 if (!EQ (symbol, Qrun) && !NILP (buffer))
6778 Lisp_Object tem;
6779 struct buffer *old = current_buffer;
6780 ptrdiff_t opoint, opoint_byte;
6781 ptrdiff_t before, before_byte;
6783 /* Avoid error if buffer is deleted
6784 (probably that's why the process is dead, too). */
6785 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6786 return Qnil;
6787 Fset_buffer (buffer);
6789 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6790 msg = (code_convert_string_norecord
6791 (msg, Vlocale_coding_system, 1));
6793 opoint = PT;
6794 opoint_byte = PT_BYTE;
6795 /* Insert new output into buffer
6796 at the current end-of-output marker,
6797 thus preserving logical ordering of input and output. */
6798 if (XMARKER (p->mark)->buffer)
6799 Fgoto_char (p->mark);
6800 else
6801 SET_PT_BOTH (ZV, ZV_BYTE);
6803 before = PT;
6804 before_byte = PT_BYTE;
6806 tem = BVAR (current_buffer, read_only);
6807 bset_read_only (current_buffer, Qnil);
6808 insert_string ("\nProcess ");
6809 { /* FIXME: temporary kludge. */
6810 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6811 insert_string (" ");
6812 Finsert (1, &msg);
6813 bset_read_only (current_buffer, tem);
6814 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6816 if (opoint >= before)
6817 SET_PT_BOTH (opoint + (PT - before),
6818 opoint_byte + (PT_BYTE - before_byte));
6819 else
6820 SET_PT_BOTH (opoint, opoint_byte);
6822 set_buffer_internal (old);
6824 return Qnil;
6828 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6829 Sset_process_coding_system, 1, 3, 0,
6830 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6831 DECODING will be used to decode subprocess output and ENCODING to
6832 encode subprocess input. */)
6833 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6835 register struct Lisp_Process *p;
6837 CHECK_PROCESS (process);
6838 p = XPROCESS (process);
6839 if (p->infd < 0)
6840 error ("Input file descriptor of %s closed", SDATA (p->name));
6841 if (p->outfd < 0)
6842 error ("Output file descriptor of %s closed", SDATA (p->name));
6843 Fcheck_coding_system (decoding);
6844 Fcheck_coding_system (encoding);
6845 encoding = coding_inherit_eol_type (encoding, Qnil);
6846 pset_decode_coding_system (p, decoding);
6847 pset_encode_coding_system (p, encoding);
6848 setup_process_coding_systems (process);
6850 return Qnil;
6853 DEFUN ("process-coding-system",
6854 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6855 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6856 (register Lisp_Object process)
6858 CHECK_PROCESS (process);
6859 return Fcons (XPROCESS (process)->decode_coding_system,
6860 XPROCESS (process)->encode_coding_system);
6863 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6864 Sset_process_filter_multibyte, 2, 2, 0,
6865 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6866 If FLAG is non-nil, the filter is given multibyte strings.
6867 If FLAG is nil, the filter is given unibyte strings. In this case,
6868 all character code conversion except for end-of-line conversion is
6869 suppressed. */)
6870 (Lisp_Object process, Lisp_Object flag)
6872 register struct Lisp_Process *p;
6874 CHECK_PROCESS (process);
6875 p = XPROCESS (process);
6876 if (NILP (flag))
6877 pset_decode_coding_system
6878 (p, raw_text_coding_system (p->decode_coding_system));
6879 setup_process_coding_systems (process);
6881 return Qnil;
6884 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6885 Sprocess_filter_multibyte_p, 1, 1, 0,
6886 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6887 (Lisp_Object process)
6889 register struct Lisp_Process *p;
6890 struct coding_system *coding;
6892 CHECK_PROCESS (process);
6893 p = XPROCESS (process);
6894 if (p->infd < 0)
6895 return Qnil;
6896 coding = proc_decode_coding_system[p->infd];
6897 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6903 # ifdef HAVE_GPM
6905 void
6906 add_gpm_wait_descriptor (int desc)
6908 add_keyboard_wait_descriptor (desc);
6911 void
6912 delete_gpm_wait_descriptor (int desc)
6914 delete_keyboard_wait_descriptor (desc);
6917 # endif
6919 # ifdef USABLE_SIGIO
6921 /* Return true if *MASK has a bit set
6922 that corresponds to one of the keyboard input descriptors. */
6924 static bool
6925 keyboard_bit_set (fd_set *mask)
6927 int fd;
6929 for (fd = 0; fd <= max_input_desc; fd++)
6930 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6931 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6932 return 1;
6934 return 0;
6936 # endif
6938 #else /* not subprocesses */
6940 /* Defined in msdos.c. */
6941 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6942 struct timespec *, void *);
6944 /* Implementation of wait_reading_process_output, assuming that there
6945 are no subprocesses. Used only by the MS-DOS build.
6947 Wait for timeout to elapse and/or keyboard input to be available.
6949 TIME_LIMIT is:
6950 timeout in seconds
6951 If negative, gobble data immediately available but don't wait for any.
6953 NSECS is:
6954 an additional duration to wait, measured in nanoseconds
6955 If TIME_LIMIT is zero, then:
6956 If NSECS == 0, there is no limit.
6957 If NSECS > 0, the timeout consists of NSECS only.
6958 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6960 READ_KBD is:
6961 0 to ignore keyboard input, or
6962 1 to return when input is available, or
6963 -1 means caller will actually read the input, so don't throw to
6964 the quit handler.
6966 see full version for other parameters. We know that wait_proc will
6967 always be NULL, since `subprocesses' isn't defined.
6969 DO_DISPLAY means redisplay should be done to show subprocess
6970 output that arrives.
6972 Return positive if we received input from WAIT_PROC (or from any
6973 process if WAIT_PROC is null), zero if we attempted to receive
6974 input but got none, and negative if we didn't even try. */
6977 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6978 bool do_display,
6979 Lisp_Object wait_for_cell,
6980 struct Lisp_Process *wait_proc, int just_wait_proc)
6982 register int nfds;
6983 struct timespec end_time, timeout;
6985 if (time_limit < 0)
6987 time_limit = 0;
6988 nsecs = -1;
6990 else if (TYPE_MAXIMUM (time_t) < time_limit)
6991 time_limit = TYPE_MAXIMUM (time_t);
6993 /* What does time_limit really mean? */
6994 if (time_limit || nsecs > 0)
6996 timeout = make_timespec (time_limit, nsecs);
6997 end_time = timespec_add (current_timespec (), timeout);
7000 /* Turn off periodic alarms (in case they are in use)
7001 and then turn off any other atimers,
7002 because the select emulator uses alarms. */
7003 stop_polling ();
7004 turn_on_atimers (0);
7006 while (1)
7008 bool timeout_reduced_for_timers = false;
7009 fd_set waitchannels;
7010 int xerrno;
7012 /* If calling from keyboard input, do not quit
7013 since we want to return C-g as an input character.
7014 Otherwise, do pending quit if requested. */
7015 if (read_kbd >= 0)
7016 QUIT;
7018 /* Exit now if the cell we're waiting for became non-nil. */
7019 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7020 break;
7022 /* Compute time from now till when time limit is up. */
7023 /* Exit if already run out. */
7024 if (nsecs < 0)
7026 /* A negative timeout means
7027 gobble output available now
7028 but don't wait at all. */
7030 timeout = make_timespec (0, 0);
7032 else if (time_limit || nsecs > 0)
7034 struct timespec now = current_timespec ();
7035 if (timespec_cmp (end_time, now) <= 0)
7036 break;
7037 timeout = timespec_sub (end_time, now);
7039 else
7041 timeout = make_timespec (100000, 0);
7044 /* If our caller will not immediately handle keyboard events,
7045 run timer events directly.
7046 (Callers that will immediately read keyboard events
7047 call timer_delay on their own.) */
7048 if (NILP (wait_for_cell))
7050 struct timespec timer_delay;
7054 unsigned old_timers_run = timers_run;
7055 timer_delay = timer_check ();
7056 if (timers_run != old_timers_run && do_display)
7057 /* We must retry, since a timer may have requeued itself
7058 and that could alter the time delay. */
7059 redisplay_preserve_echo_area (14);
7060 else
7061 break;
7063 while (!detect_input_pending ());
7065 /* If there is unread keyboard input, also return. */
7066 if (read_kbd != 0
7067 && requeued_events_pending_p ())
7068 break;
7070 if (timespec_valid_p (timer_delay) && nsecs >= 0)
7072 if (timespec_cmp (timer_delay, timeout) < 0)
7074 timeout = timer_delay;
7075 timeout_reduced_for_timers = true;
7080 /* Cause C-g and alarm signals to take immediate action,
7081 and cause input available signals to zero out timeout. */
7082 if (read_kbd < 0)
7083 set_waiting_for_input (&timeout);
7085 /* If a frame has been newly mapped and needs updating,
7086 reprocess its display stuff. */
7087 if (frame_garbaged && do_display)
7089 clear_waiting_for_input ();
7090 redisplay_preserve_echo_area (15);
7091 if (read_kbd < 0)
7092 set_waiting_for_input (&timeout);
7095 /* Wait till there is something to do. */
7096 FD_ZERO (&waitchannels);
7097 if (read_kbd && detect_input_pending ())
7098 nfds = 0;
7099 else
7101 if (read_kbd || !NILP (wait_for_cell))
7102 FD_SET (0, &waitchannels);
7103 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7106 xerrno = errno;
7108 /* Make C-g and alarm signals set flags again. */
7109 clear_waiting_for_input ();
7111 /* If we woke up due to SIGWINCH, actually change size now. */
7112 do_pending_window_change (0);
7114 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
7115 /* We waited the full specified time, so return now. */
7116 break;
7118 if (nfds == -1)
7120 /* If the system call was interrupted, then go around the
7121 loop again. */
7122 if (xerrno == EINTR)
7123 FD_ZERO (&waitchannels);
7124 else
7125 report_file_errno ("Failed select", Qnil, xerrno);
7128 /* Check for keyboard input. */
7130 if (read_kbd
7131 && detect_input_pending_run_timers (do_display))
7133 swallow_events (do_display);
7134 if (detect_input_pending_run_timers (do_display))
7135 break;
7138 /* If there is unread keyboard input, also return. */
7139 if (read_kbd
7140 && requeued_events_pending_p ())
7141 break;
7143 /* If wait_for_cell. check for keyboard input
7144 but don't run any timers.
7145 ??? (It seems wrong to me to check for keyboard
7146 input at all when wait_for_cell, but the code
7147 has been this way since July 1994.
7148 Try changing this after version 19.31.) */
7149 if (! NILP (wait_for_cell)
7150 && detect_input_pending ())
7152 swallow_events (do_display);
7153 if (detect_input_pending ())
7154 break;
7157 /* Exit now if the cell we're waiting for became non-nil. */
7158 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7159 break;
7162 start_polling ();
7164 return -1;
7167 #endif /* not subprocesses */
7169 /* The following functions are needed even if async subprocesses are
7170 not supported. Some of them are no-op stubs in that case. */
7172 #ifdef HAVE_TIMERFD
7174 /* Add FD, which is a descriptor returned by timerfd_create,
7175 to the set of non-keyboard input descriptors. */
7177 void
7178 add_timer_wait_descriptor (int fd)
7180 FD_SET (fd, &input_wait_mask);
7181 FD_SET (fd, &non_keyboard_wait_mask);
7182 FD_SET (fd, &non_process_wait_mask);
7183 fd_callback_info[fd].func = timerfd_callback;
7184 fd_callback_info[fd].data = NULL;
7185 fd_callback_info[fd].condition |= FOR_READ;
7186 if (fd > max_input_desc)
7187 max_input_desc = fd;
7190 #endif /* HAVE_TIMERFD */
7192 /* Add DESC to the set of keyboard input descriptors. */
7194 void
7195 add_keyboard_wait_descriptor (int desc)
7197 #ifdef subprocesses /* Actually means "not MSDOS". */
7198 FD_SET (desc, &input_wait_mask);
7199 FD_SET (desc, &non_process_wait_mask);
7200 if (desc > max_input_desc)
7201 max_input_desc = desc;
7202 #endif
7205 /* From now on, do not expect DESC to give keyboard input. */
7207 void
7208 delete_keyboard_wait_descriptor (int desc)
7210 #ifdef subprocesses
7211 FD_CLR (desc, &input_wait_mask);
7212 FD_CLR (desc, &non_process_wait_mask);
7213 delete_input_desc (desc);
7214 #endif
7217 /* Setup coding systems of PROCESS. */
7219 void
7220 setup_process_coding_systems (Lisp_Object process)
7222 #ifdef subprocesses
7223 struct Lisp_Process *p = XPROCESS (process);
7224 int inch = p->infd;
7225 int outch = p->outfd;
7226 Lisp_Object coding_system;
7228 if (inch < 0 || outch < 0)
7229 return;
7231 if (!proc_decode_coding_system[inch])
7232 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7233 coding_system = p->decode_coding_system;
7234 if (EQ (p->filter, Qinternal_default_process_filter)
7235 && BUFFERP (p->buffer))
7237 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7238 coding_system = raw_text_coding_system (coding_system);
7240 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7242 if (!proc_encode_coding_system[outch])
7243 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7244 setup_coding_system (p->encode_coding_system,
7245 proc_encode_coding_system[outch]);
7246 #endif
7249 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7250 doc: /* Return the (or a) process associated with BUFFER.
7251 BUFFER may be a buffer or the name of one. */)
7252 (register Lisp_Object buffer)
7254 #ifdef subprocesses
7255 register Lisp_Object buf, tail, proc;
7257 if (NILP (buffer)) return Qnil;
7258 buf = Fget_buffer (buffer);
7259 if (NILP (buf)) return Qnil;
7261 FOR_EACH_PROCESS (tail, proc)
7262 if (EQ (XPROCESS (proc)->buffer, buf))
7263 return proc;
7264 #endif /* subprocesses */
7265 return Qnil;
7268 DEFUN ("process-inherit-coding-system-flag",
7269 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7270 1, 1, 0,
7271 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7272 If this flag is t, `buffer-file-coding-system' of the buffer
7273 associated with PROCESS will inherit the coding system used to decode
7274 the process output. */)
7275 (register Lisp_Object process)
7277 #ifdef subprocesses
7278 CHECK_PROCESS (process);
7279 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7280 #else
7281 /* Ignore the argument and return the value of
7282 inherit-process-coding-system. */
7283 return inherit_process_coding_system ? Qt : Qnil;
7284 #endif
7287 /* Kill all processes associated with `buffer'.
7288 If `buffer' is nil, kill all processes. */
7290 void
7291 kill_buffer_processes (Lisp_Object buffer)
7293 #ifdef subprocesses
7294 Lisp_Object tail, proc;
7296 FOR_EACH_PROCESS (tail, proc)
7297 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7299 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7300 Fdelete_process (proc);
7301 else if (XPROCESS (proc)->infd >= 0)
7302 process_send_signal (proc, SIGHUP, Qnil, 1);
7304 #else /* subprocesses */
7305 /* Since we have no subprocesses, this does nothing. */
7306 #endif /* subprocesses */
7309 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7310 Swaiting_for_user_input_p, 0, 0, 0,
7311 doc: /* Return non-nil if Emacs is waiting for input from the user.
7312 This is intended for use by asynchronous process output filters and sentinels. */)
7313 (void)
7315 #ifdef subprocesses
7316 return (waiting_for_user_input_p ? Qt : Qnil);
7317 #else
7318 return Qnil;
7319 #endif
7322 /* Stop reading input from keyboard sources. */
7324 void
7325 hold_keyboard_input (void)
7327 kbd_is_on_hold = 1;
7330 /* Resume reading input from keyboard sources. */
7332 void
7333 unhold_keyboard_input (void)
7335 kbd_is_on_hold = 0;
7338 /* Return true if keyboard input is on hold, zero otherwise. */
7340 bool
7341 kbd_on_hold_p (void)
7343 return kbd_is_on_hold;
7347 /* Enumeration of and access to system processes a-la ps(1). */
7349 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7350 0, 0, 0,
7351 doc: /* Return a list of numerical process IDs of all running processes.
7352 If this functionality is unsupported, return nil.
7354 See `process-attributes' for getting attributes of a process given its ID. */)
7355 (void)
7357 return list_system_processes ();
7360 DEFUN ("process-attributes", Fprocess_attributes,
7361 Sprocess_attributes, 1, 1, 0,
7362 doc: /* Return attributes of the process given by its PID, a number.
7364 Value is an alist where each element is a cons cell of the form
7366 \(KEY . VALUE)
7368 If this functionality is unsupported, the value is nil.
7370 See `list-system-processes' for getting a list of all process IDs.
7372 The KEYs of the attributes that this function may return are listed
7373 below, together with the type of the associated VALUE (in parentheses).
7374 Not all platforms support all of these attributes; unsupported
7375 attributes will not appear in the returned alist.
7376 Unless explicitly indicated otherwise, numbers can have either
7377 integer or floating point values.
7379 euid -- Effective user User ID of the process (number)
7380 user -- User name corresponding to euid (string)
7381 egid -- Effective user Group ID of the process (number)
7382 group -- Group name corresponding to egid (string)
7383 comm -- Command name (executable name only) (string)
7384 state -- Process state code, such as "S", "R", or "T" (string)
7385 ppid -- Parent process ID (number)
7386 pgrp -- Process group ID (number)
7387 sess -- Session ID, i.e. process ID of session leader (number)
7388 ttname -- Controlling tty name (string)
7389 tpgid -- ID of foreground process group on the process's tty (number)
7390 minflt -- number of minor page faults (number)
7391 majflt -- number of major page faults (number)
7392 cminflt -- cumulative number of minor page faults (number)
7393 cmajflt -- cumulative number of major page faults (number)
7394 utime -- user time used by the process, in (current-time) format,
7395 which is a list of integers (HIGH LOW USEC PSEC)
7396 stime -- system time used by the process (current-time)
7397 time -- sum of utime and stime (current-time)
7398 cutime -- user time used by the process and its children (current-time)
7399 cstime -- system time used by the process and its children (current-time)
7400 ctime -- sum of cutime and cstime (current-time)
7401 pri -- priority of the process (number)
7402 nice -- nice value of the process (number)
7403 thcount -- process thread count (number)
7404 start -- time the process started (current-time)
7405 vsize -- virtual memory size of the process in KB's (number)
7406 rss -- resident set size of the process in KB's (number)
7407 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7408 pcpu -- percents of CPU time used by the process (floating-point number)
7409 pmem -- percents of total physical memory used by process's resident set
7410 (floating-point number)
7411 args -- command line which invoked the process (string). */)
7412 ( Lisp_Object pid)
7414 return system_process_attributes (pid);
7417 #ifdef subprocesses
7418 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7419 Invoke this after init_process_emacs, and after glib and/or GNUstep
7420 futz with the SIGCHLD handler, but before Emacs forks any children.
7421 This function's caller should block SIGCHLD. */
7423 void
7424 catch_child_signal (void)
7426 struct sigaction action, old_action;
7427 sigset_t oldset;
7428 emacs_sigaction_init (&action, deliver_child_signal);
7429 block_child_signal (&oldset);
7430 sigaction (SIGCHLD, &action, &old_action);
7431 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7432 || ! (old_action.sa_flags & SA_SIGINFO));
7434 if (old_action.sa_handler != deliver_child_signal)
7435 lib_child_handler
7436 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7437 ? dummy_handler
7438 : old_action.sa_handler);
7439 unblock_child_signal (&oldset);
7441 #endif /* subprocesses */
7444 /* This is not called "init_process" because that is the name of a
7445 Mach system call, so it would cause problems on Darwin systems. */
7446 void
7447 init_process_emacs (void)
7449 #ifdef subprocesses
7450 register int i;
7452 inhibit_sentinels = 0;
7454 #ifndef CANNOT_DUMP
7455 if (! noninteractive || initialized)
7456 #endif
7458 #if defined HAVE_GLIB && !defined WINDOWSNT
7459 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7460 this should always fail, but is enough to initialize glib's
7461 private SIGCHLD handler, allowing catch_child_signal to copy
7462 it into lib_child_handler. */
7463 g_source_unref (g_child_watch_source_new (getpid ()));
7464 #endif
7465 catch_child_signal ();
7468 FD_ZERO (&input_wait_mask);
7469 FD_ZERO (&non_keyboard_wait_mask);
7470 FD_ZERO (&non_process_wait_mask);
7471 FD_ZERO (&write_mask);
7472 max_process_desc = max_input_desc = -1;
7473 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7475 #ifdef NON_BLOCKING_CONNECT
7476 FD_ZERO (&connect_wait_mask);
7477 num_pending_connects = 0;
7478 #endif
7480 #ifdef ADAPTIVE_READ_BUFFERING
7481 process_output_delay_count = 0;
7482 process_output_skip = 0;
7483 #endif
7485 /* Don't do this, it caused infinite select loops. The display
7486 method should call add_keyboard_wait_descriptor on stdin if it
7487 needs that. */
7488 #if 0
7489 FD_SET (0, &input_wait_mask);
7490 #endif
7492 Vprocess_alist = Qnil;
7493 deleted_pid_list = Qnil;
7494 for (i = 0; i < FD_SETSIZE; i++)
7496 chan_process[i] = Qnil;
7497 proc_buffered_char[i] = -1;
7499 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7500 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7501 #ifdef DATAGRAM_SOCKETS
7502 memset (datagram_address, 0, sizeof datagram_address);
7503 #endif
7505 #if defined (DARWIN_OS)
7506 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7507 processes. As such, we only change the default value. */
7508 if (initialized)
7510 char const *release = (STRINGP (Voperating_system_release)
7511 ? SSDATA (Voperating_system_release)
7512 : 0);
7513 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7514 Vprocess_connection_type = Qnil;
7517 #endif
7518 #endif /* subprocesses */
7519 kbd_is_on_hold = 0;
7522 void
7523 syms_of_process (void)
7525 #ifdef subprocesses
7527 DEFSYM (Qprocessp, "processp");
7528 DEFSYM (Qrun, "run");
7529 DEFSYM (Qstop, "stop");
7530 DEFSYM (Qsignal, "signal");
7532 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7533 here again. */
7535 DEFSYM (Qopen, "open");
7536 DEFSYM (Qclosed, "closed");
7537 DEFSYM (Qconnect, "connect");
7538 DEFSYM (Qfailed, "failed");
7539 DEFSYM (Qlisten, "listen");
7540 DEFSYM (Qlocal, "local");
7541 DEFSYM (Qipv4, "ipv4");
7542 #ifdef AF_INET6
7543 DEFSYM (Qipv6, "ipv6");
7544 #endif
7545 DEFSYM (Qdatagram, "datagram");
7546 DEFSYM (Qseqpacket, "seqpacket");
7548 DEFSYM (QCport, ":port");
7549 DEFSYM (QCspeed, ":speed");
7550 DEFSYM (QCprocess, ":process");
7552 DEFSYM (QCbytesize, ":bytesize");
7553 DEFSYM (QCstopbits, ":stopbits");
7554 DEFSYM (QCparity, ":parity");
7555 DEFSYM (Qodd, "odd");
7556 DEFSYM (Qeven, "even");
7557 DEFSYM (QCflowcontrol, ":flowcontrol");
7558 DEFSYM (Qhw, "hw");
7559 DEFSYM (Qsw, "sw");
7560 DEFSYM (QCsummary, ":summary");
7562 DEFSYM (Qreal, "real");
7563 DEFSYM (Qnetwork, "network");
7564 DEFSYM (Qserial, "serial");
7565 DEFSYM (Qpipe, "pipe");
7566 DEFSYM (QCbuffer, ":buffer");
7567 DEFSYM (QChost, ":host");
7568 DEFSYM (QCservice, ":service");
7569 DEFSYM (QClocal, ":local");
7570 DEFSYM (QCremote, ":remote");
7571 DEFSYM (QCcoding, ":coding");
7572 DEFSYM (QCserver, ":server");
7573 DEFSYM (QCnowait, ":nowait");
7574 DEFSYM (QCsentinel, ":sentinel");
7575 DEFSYM (QClog, ":log");
7576 DEFSYM (QCnoquery, ":noquery");
7577 DEFSYM (QCstop, ":stop");
7578 DEFSYM (QCoptions, ":options");
7579 DEFSYM (QCplist, ":plist");
7580 DEFSYM (QCcommand, ":command");
7581 DEFSYM (QCconnection_type, ":connection-type");
7582 DEFSYM (QCstderr, ":stderr");
7583 DEFSYM (Qpty, "pty");
7584 DEFSYM (Qpipe, "pipe");
7586 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7588 staticpro (&Vprocess_alist);
7589 staticpro (&deleted_pid_list);
7591 #endif /* subprocesses */
7593 DEFSYM (QCname, ":name");
7594 DEFSYM (QCtype, ":type");
7596 DEFSYM (Qeuid, "euid");
7597 DEFSYM (Qegid, "egid");
7598 DEFSYM (Quser, "user");
7599 DEFSYM (Qgroup, "group");
7600 DEFSYM (Qcomm, "comm");
7601 DEFSYM (Qstate, "state");
7602 DEFSYM (Qppid, "ppid");
7603 DEFSYM (Qpgrp, "pgrp");
7604 DEFSYM (Qsess, "sess");
7605 DEFSYM (Qttname, "ttname");
7606 DEFSYM (Qtpgid, "tpgid");
7607 DEFSYM (Qminflt, "minflt");
7608 DEFSYM (Qmajflt, "majflt");
7609 DEFSYM (Qcminflt, "cminflt");
7610 DEFSYM (Qcmajflt, "cmajflt");
7611 DEFSYM (Qutime, "utime");
7612 DEFSYM (Qstime, "stime");
7613 DEFSYM (Qtime, "time");
7614 DEFSYM (Qcutime, "cutime");
7615 DEFSYM (Qcstime, "cstime");
7616 DEFSYM (Qctime, "ctime");
7617 #ifdef subprocesses
7618 DEFSYM (Qinternal_default_process_sentinel,
7619 "internal-default-process-sentinel");
7620 DEFSYM (Qinternal_default_process_filter,
7621 "internal-default-process-filter");
7622 #endif
7623 DEFSYM (Qpri, "pri");
7624 DEFSYM (Qnice, "nice");
7625 DEFSYM (Qthcount, "thcount");
7626 DEFSYM (Qstart, "start");
7627 DEFSYM (Qvsize, "vsize");
7628 DEFSYM (Qrss, "rss");
7629 DEFSYM (Qetime, "etime");
7630 DEFSYM (Qpcpu, "pcpu");
7631 DEFSYM (Qpmem, "pmem");
7632 DEFSYM (Qargs, "args");
7634 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7635 doc: /* Non-nil means delete processes immediately when they exit.
7636 A value of nil means don't delete them until `list-processes' is run. */);
7638 delete_exited_processes = 1;
7640 #ifdef subprocesses
7641 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7642 doc: /* Control type of device used to communicate with subprocesses.
7643 Values are nil to use a pipe, or t or `pty' to use a pty.
7644 The value has no effect if the system has no ptys or if all ptys are busy:
7645 then a pipe is used in any case.
7646 The value takes effect when `start-process' is called. */);
7647 Vprocess_connection_type = Qt;
7649 #ifdef ADAPTIVE_READ_BUFFERING
7650 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7651 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7652 On some systems, when Emacs reads the output from a subprocess, the output data
7653 is read in very small blocks, potentially resulting in very poor performance.
7654 This behavior can be remedied to some extent by setting this variable to a
7655 non-nil value, as it will automatically delay reading from such processes, to
7656 allow them to produce more output before Emacs tries to read it.
7657 If the value is t, the delay is reset after each write to the process; any other
7658 non-nil value means that the delay is not reset on write.
7659 The variable takes effect when `start-process' is called. */);
7660 Vprocess_adaptive_read_buffering = Qt;
7661 #endif
7663 defsubr (&Sprocessp);
7664 defsubr (&Sget_process);
7665 defsubr (&Sdelete_process);
7666 defsubr (&Sprocess_status);
7667 defsubr (&Sprocess_exit_status);
7668 defsubr (&Sprocess_id);
7669 defsubr (&Sprocess_name);
7670 defsubr (&Sprocess_tty_name);
7671 defsubr (&Sprocess_command);
7672 defsubr (&Sset_process_buffer);
7673 defsubr (&Sprocess_buffer);
7674 defsubr (&Sprocess_mark);
7675 defsubr (&Sset_process_filter);
7676 defsubr (&Sprocess_filter);
7677 defsubr (&Sset_process_sentinel);
7678 defsubr (&Sprocess_sentinel);
7679 defsubr (&Sset_process_window_size);
7680 defsubr (&Sset_process_inherit_coding_system_flag);
7681 defsubr (&Sset_process_query_on_exit_flag);
7682 defsubr (&Sprocess_query_on_exit_flag);
7683 defsubr (&Sprocess_contact);
7684 defsubr (&Sprocess_plist);
7685 defsubr (&Sset_process_plist);
7686 defsubr (&Sprocess_list);
7687 defsubr (&Smake_process);
7688 defsubr (&Smake_pipe_process);
7689 defsubr (&Sserial_process_configure);
7690 defsubr (&Smake_serial_process);
7691 defsubr (&Sset_network_process_option);
7692 defsubr (&Smake_network_process);
7693 defsubr (&Sformat_network_address);
7694 defsubr (&Snetwork_interface_list);
7695 defsubr (&Snetwork_interface_info);
7696 #ifdef DATAGRAM_SOCKETS
7697 defsubr (&Sprocess_datagram_address);
7698 defsubr (&Sset_process_datagram_address);
7699 #endif
7700 defsubr (&Saccept_process_output);
7701 defsubr (&Sprocess_send_region);
7702 defsubr (&Sprocess_send_string);
7703 defsubr (&Sinterrupt_process);
7704 defsubr (&Skill_process);
7705 defsubr (&Squit_process);
7706 defsubr (&Sstop_process);
7707 defsubr (&Scontinue_process);
7708 defsubr (&Sprocess_running_child_p);
7709 defsubr (&Sprocess_send_eof);
7710 defsubr (&Ssignal_process);
7711 defsubr (&Swaiting_for_user_input_p);
7712 defsubr (&Sprocess_type);
7713 defsubr (&Sinternal_default_process_sentinel);
7714 defsubr (&Sinternal_default_process_filter);
7715 defsubr (&Sset_process_coding_system);
7716 defsubr (&Sprocess_coding_system);
7717 defsubr (&Sset_process_filter_multibyte);
7718 defsubr (&Sprocess_filter_multibyte_p);
7720 #endif /* subprocesses */
7722 defsubr (&Sget_buffer_process);
7723 defsubr (&Sprocess_inherit_coding_system_flag);
7724 defsubr (&Slist_system_processes);
7725 defsubr (&Sprocess_attributes);
7728 Lisp_Object subfeatures = Qnil;
7729 const struct socket_options *sopt;
7731 #define ADD_SUBFEATURE(key, val) \
7732 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7734 #ifdef NON_BLOCKING_CONNECT
7735 ADD_SUBFEATURE (QCnowait, Qt);
7736 #endif
7737 #ifdef DATAGRAM_SOCKETS
7738 ADD_SUBFEATURE (QCtype, Qdatagram);
7739 #endif
7740 #ifdef HAVE_SEQPACKET
7741 ADD_SUBFEATURE (QCtype, Qseqpacket);
7742 #endif
7743 #ifdef HAVE_LOCAL_SOCKETS
7744 ADD_SUBFEATURE (QCfamily, Qlocal);
7745 #endif
7746 ADD_SUBFEATURE (QCfamily, Qipv4);
7747 #ifdef AF_INET6
7748 ADD_SUBFEATURE (QCfamily, Qipv6);
7749 #endif
7750 #ifdef HAVE_GETSOCKNAME
7751 ADD_SUBFEATURE (QCservice, Qt);
7752 #endif
7753 ADD_SUBFEATURE (QCserver, Qt);
7755 for (sopt = socket_options; sopt->name; sopt++)
7756 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7758 Fprovide (intern_c_string ("make-network-process"), subfeatures);