Some progress towards starting with PWD deleted. (Bug#18851)
[emacs.git] / src / process.c
blobb4f979fd4840431a61de5dcbe10aa8944552b0d1
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2015 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
27 #include <sys/file.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30 #include <fcntl.h>
32 #include "lisp.h"
34 /* Only MS-DOS does not define `subprocesses'. */
35 #ifdef subprocesses
37 #include <sys/socket.h>
38 #include <netdb.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
42 /* Are local (unix) sockets supported? */
43 #if defined (HAVE_SYS_UN_H)
44 #if !defined (AF_LOCAL) && defined (AF_UNIX)
45 #define AF_LOCAL AF_UNIX
46 #endif
47 #ifdef AF_LOCAL
48 #define HAVE_LOCAL_SOCKETS
49 #include <sys/un.h>
50 #endif
51 #endif
53 #include <sys/ioctl.h>
54 #if defined (HAVE_NET_IF_H)
55 #include <net/if.h>
56 #endif /* HAVE_NET_IF_H */
58 #if defined (HAVE_IFADDRS_H)
59 /* Must be after net/if.h */
60 #include <ifaddrs.h>
62 /* We only use structs from this header when we use getifaddrs. */
63 #if defined (HAVE_NET_IF_DL_H)
64 #include <net/if_dl.h>
65 #endif
67 #endif
69 #ifdef NEED_BSDTTY
70 #include <bsdtty.h>
71 #endif
73 #ifdef USG5_4
74 # include <sys/stream.h>
75 # include <sys/stropts.h>
76 #endif
78 #ifdef HAVE_RES_INIT
79 #include <arpa/nameser.h>
80 #include <resolv.h>
81 #endif
83 #ifdef HAVE_UTIL_H
84 #include <util.h>
85 #endif
87 #ifdef HAVE_PTY_H
88 #include <pty.h>
89 #endif
91 #include <c-ctype.h>
92 #include <sig2str.h>
93 #include <verify.h>
95 #endif /* subprocesses */
97 #include "systime.h"
98 #include "systty.h"
100 #include "window.h"
101 #include "character.h"
102 #include "buffer.h"
103 #include "coding.h"
104 #include "process.h"
105 #include "frame.h"
106 #include "termhooks.h"
107 #include "termopts.h"
108 #include "commands.h"
109 #include "keyboard.h"
110 #include "blockinput.h"
111 #include "dispextern.h"
112 #include "composite.h"
113 #include "atimer.h"
114 #include "sysselect.h"
115 #include "syssignal.h"
116 #include "syswait.h"
117 #ifdef HAVE_GNUTLS
118 #include "gnutls.h"
119 #endif
121 #ifdef HAVE_WINDOW_SYSTEM
122 #include TERM_HEADER
123 #endif /* HAVE_WINDOW_SYSTEM */
125 #ifdef HAVE_GLIB
126 #include "xgselect.h"
127 #ifndef WINDOWSNT
128 #include <glib.h>
129 #endif
130 #endif
132 #ifdef WINDOWSNT
133 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
134 struct timespec *, void *);
135 #endif
137 /* Work around GCC 4.7.0 bug with strict overflow checking; see
138 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
139 This bug appears to be fixed in GCC 5.1, so don't work around it there. */
140 #if __GNUC__ == 4 && __GNUC_MINOR__ >= 3
141 # pragma GCC diagnostic ignored "-Wstrict-overflow"
142 #endif
144 /* True if keyboard input is on hold, zero otherwise. */
146 static bool kbd_is_on_hold;
148 /* Nonzero means don't run process sentinels. This is used
149 when exiting. */
150 bool inhibit_sentinels;
152 #ifdef subprocesses
154 #ifndef SOCK_CLOEXEC
155 # define SOCK_CLOEXEC 0
156 #endif
158 #ifndef HAVE_ACCEPT4
160 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
162 static int
163 close_on_exec (int fd)
165 if (0 <= fd)
166 fcntl (fd, F_SETFD, FD_CLOEXEC);
167 return fd;
170 # undef accept4
171 # define accept4(sockfd, addr, addrlen, flags) \
172 process_accept4 (sockfd, addr, addrlen, flags)
173 static int
174 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
176 return close_on_exec (accept (sockfd, addr, addrlen));
179 static int
180 process_socket (int domain, int type, int protocol)
182 return close_on_exec (socket (domain, type, protocol));
184 # undef socket
185 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
186 #endif
188 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
189 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
190 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
191 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
192 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
193 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
195 /* Number of events of change of status of a process. */
196 static EMACS_INT process_tick;
197 /* Number of events for which the user or sentinel has been notified. */
198 static EMACS_INT update_tick;
200 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects.
201 The code can be simplified by assuming NON_BLOCKING_CONNECT once
202 Emacs starts assuming POSIX 1003.1-2001 or later. */
204 #if (defined HAVE_SELECT \
205 && (defined GNU_LINUX || defined HAVE_GETPEERNAME) \
206 && (defined EWOULDBLOCK || defined EINPROGRESS))
207 # define NON_BLOCKING_CONNECT
208 #endif
210 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
211 this system. We need to read full packets, so we need a
212 "non-destructive" select. So we require either native select,
213 or emulation of select using FIONREAD. */
215 #ifndef BROKEN_DATAGRAM_SOCKETS
216 # if defined HAVE_SELECT || defined USABLE_FIONREAD
217 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
218 # define DATAGRAM_SOCKETS
219 # endif
220 # endif
221 #endif
223 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
224 # define HAVE_SEQPACKET
225 #endif
227 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
228 #define ADAPTIVE_READ_BUFFERING
229 #endif
231 #ifdef ADAPTIVE_READ_BUFFERING
232 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
233 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
234 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
236 /* Number of processes which have a non-zero read_output_delay,
237 and therefore might be delayed for adaptive read buffering. */
239 static int process_output_delay_count;
241 /* True if any process has non-nil read_output_skip. */
243 static bool process_output_skip;
245 #else
246 #define process_output_delay_count 0
247 #endif
249 static void create_process (Lisp_Object, char **, Lisp_Object);
250 #ifdef USABLE_SIGIO
251 static bool keyboard_bit_set (fd_set *);
252 #endif
253 static void deactivate_process (Lisp_Object);
254 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
255 static int read_process_output (Lisp_Object, int);
256 static void handle_child_signal (int);
257 static void create_pty (Lisp_Object);
259 static Lisp_Object get_process (register Lisp_Object name);
260 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
262 /* Mask of bits indicating the descriptors that we wait for input on. */
264 static fd_set input_wait_mask;
266 /* Mask that excludes keyboard input descriptor(s). */
268 static fd_set non_keyboard_wait_mask;
270 /* Mask that excludes process input descriptor(s). */
272 static fd_set non_process_wait_mask;
274 /* Mask for selecting for write. */
276 static fd_set write_mask;
278 #ifdef NON_BLOCKING_CONNECT
279 /* Mask of bits indicating the descriptors that we wait for connect to
280 complete on. Once they complete, they are removed from this mask
281 and added to the input_wait_mask and non_keyboard_wait_mask. */
283 static fd_set connect_wait_mask;
285 /* Number of bits set in connect_wait_mask. */
286 static int num_pending_connects;
287 #endif /* NON_BLOCKING_CONNECT */
289 /* The largest descriptor currently in use for a process object; -1 if none. */
290 static int max_process_desc;
292 /* The largest descriptor currently in use for input; -1 if none. */
293 static int max_input_desc;
295 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
296 static Lisp_Object chan_process[FD_SETSIZE];
298 /* Alist of elements (NAME . PROCESS). */
299 static Lisp_Object Vprocess_alist;
301 /* Buffered-ahead input char from process, indexed by channel.
302 -1 means empty (no char is buffered).
303 Used on sys V where the only way to tell if there is any
304 output from the process is to read at least one char.
305 Always -1 on systems that support FIONREAD. */
307 static int proc_buffered_char[FD_SETSIZE];
309 /* Table of `struct coding-system' for each process. */
310 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
311 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
313 #ifdef DATAGRAM_SOCKETS
314 /* Table of `partner address' for datagram sockets. */
315 static struct sockaddr_and_len {
316 struct sockaddr *sa;
317 int len;
318 } datagram_address[FD_SETSIZE];
319 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
320 #define DATAGRAM_CONN_P(proc) \
321 (PROCESSP (proc) && \
322 XPROCESS (proc)->infd >= 0 && \
323 datagram_address[XPROCESS (proc)->infd].sa != 0)
324 #else
325 #define DATAGRAM_CHAN_P(chan) (0)
326 #define DATAGRAM_CONN_P(proc) (0)
327 #endif
329 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
330 a `for' loop which iterates over processes from Vprocess_alist. */
332 #define FOR_EACH_PROCESS(list_var, proc_var) \
333 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
335 /* These setters are used only in this file, so they can be private. */
336 static void
337 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
339 p->buffer = val;
341 static void
342 pset_command (struct Lisp_Process *p, Lisp_Object val)
344 p->command = val;
346 static void
347 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
349 p->decode_coding_system = val;
351 static void
352 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
354 p->decoding_buf = val;
356 static void
357 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
359 p->encode_coding_system = val;
361 static void
362 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
364 p->encoding_buf = val;
366 static void
367 pset_filter (struct Lisp_Process *p, Lisp_Object val)
369 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
371 static void
372 pset_log (struct Lisp_Process *p, Lisp_Object val)
374 p->log = val;
376 static void
377 pset_mark (struct Lisp_Process *p, Lisp_Object val)
379 p->mark = val;
381 static void
382 pset_name (struct Lisp_Process *p, Lisp_Object val)
384 p->name = val;
386 static void
387 pset_plist (struct Lisp_Process *p, Lisp_Object val)
389 p->plist = val;
391 static void
392 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
394 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
396 static void
397 pset_status (struct Lisp_Process *p, Lisp_Object val)
399 p->status = val;
401 static void
402 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
404 p->tty_name = val;
406 static void
407 pset_type (struct Lisp_Process *p, Lisp_Object val)
409 p->type = val;
411 static void
412 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
414 p->write_queue = val;
416 static void
417 pset_stderrproc (struct Lisp_Process *p, Lisp_Object val)
419 p->stderrproc = val;
423 static Lisp_Object
424 make_lisp_proc (struct Lisp_Process *p)
426 return make_lisp_ptr (p, Lisp_Vectorlike);
429 static struct fd_callback_data
431 fd_callback func;
432 void *data;
433 #define FOR_READ 1
434 #define FOR_WRITE 2
435 int condition; /* Mask of the defines above. */
436 } fd_callback_info[FD_SETSIZE];
439 /* Add a file descriptor FD to be monitored for when read is possible.
440 When read is possible, call FUNC with argument DATA. */
442 void
443 add_read_fd (int fd, fd_callback func, void *data)
445 add_keyboard_wait_descriptor (fd);
447 fd_callback_info[fd].func = func;
448 fd_callback_info[fd].data = data;
449 fd_callback_info[fd].condition |= FOR_READ;
452 /* Stop monitoring file descriptor FD for when read is possible. */
454 void
455 delete_read_fd (int fd)
457 delete_keyboard_wait_descriptor (fd);
459 fd_callback_info[fd].condition &= ~FOR_READ;
460 if (fd_callback_info[fd].condition == 0)
462 fd_callback_info[fd].func = 0;
463 fd_callback_info[fd].data = 0;
467 /* Add a file descriptor FD to be monitored for when write is possible.
468 When write is possible, call FUNC with argument DATA. */
470 void
471 add_write_fd (int fd, fd_callback func, void *data)
473 FD_SET (fd, &write_mask);
474 if (fd > max_input_desc)
475 max_input_desc = fd;
477 fd_callback_info[fd].func = func;
478 fd_callback_info[fd].data = data;
479 fd_callback_info[fd].condition |= FOR_WRITE;
482 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
484 static void
485 delete_input_desc (int fd)
487 if (fd == max_input_desc)
490 fd--;
491 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
492 || FD_ISSET (fd, &write_mask)));
494 max_input_desc = fd;
498 /* Stop monitoring file descriptor FD for when write is possible. */
500 void
501 delete_write_fd (int fd)
503 FD_CLR (fd, &write_mask);
504 fd_callback_info[fd].condition &= ~FOR_WRITE;
505 if (fd_callback_info[fd].condition == 0)
507 fd_callback_info[fd].func = 0;
508 fd_callback_info[fd].data = 0;
509 delete_input_desc (fd);
514 /* Compute the Lisp form of the process status, p->status, from
515 the numeric status that was returned by `wait'. */
517 static Lisp_Object status_convert (int);
519 static void
520 update_status (struct Lisp_Process *p)
522 eassert (p->raw_status_new);
523 pset_status (p, status_convert (p->raw_status));
524 p->raw_status_new = 0;
527 /* Convert a process status word in Unix format to
528 the list that we use internally. */
530 static Lisp_Object
531 status_convert (int w)
533 if (WIFSTOPPED (w))
534 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
535 else if (WIFEXITED (w))
536 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
537 WCOREDUMP (w) ? Qt : Qnil));
538 else if (WIFSIGNALED (w))
539 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
540 WCOREDUMP (w) ? Qt : Qnil));
541 else
542 return Qrun;
545 /* Given a status-list, extract the three pieces of information
546 and store them individually through the three pointers. */
548 static void
549 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
551 Lisp_Object tem;
553 if (SYMBOLP (l))
555 *symbol = l;
556 *code = 0;
557 *coredump = 0;
559 else
561 *symbol = XCAR (l);
562 tem = XCDR (l);
563 *code = XFASTINT (XCAR (tem));
564 tem = XCDR (tem);
565 *coredump = !NILP (tem);
569 /* Return a string describing a process status list. */
571 static Lisp_Object
572 status_message (struct Lisp_Process *p)
574 Lisp_Object status = p->status;
575 Lisp_Object symbol;
576 int code;
577 bool coredump;
578 Lisp_Object string;
580 decode_status (status, &symbol, &code, &coredump);
582 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
584 char const *signame;
585 synchronize_system_messages_locale ();
586 signame = strsignal (code);
587 if (signame == 0)
588 string = build_string ("unknown");
589 else
591 int c1, c2;
593 string = build_unibyte_string (signame);
594 if (! NILP (Vlocale_coding_system))
595 string = (code_convert_string_norecord
596 (string, Vlocale_coding_system, 0));
597 c1 = STRING_CHAR (SDATA (string));
598 c2 = downcase (c1);
599 if (c1 != c2)
600 Faset (string, make_number (0), make_number (c2));
602 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
603 return concat2 (string, suffix);
605 else if (EQ (symbol, Qexit))
607 if (NETCONN1_P (p))
608 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
609 if (code == 0)
610 return build_string ("finished\n");
611 AUTO_STRING (prefix, "exited abnormally with code ");
612 string = Fnumber_to_string (make_number (code));
613 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
614 return concat3 (prefix, string, suffix);
616 else if (EQ (symbol, Qfailed))
618 AUTO_STRING (prefix, "failed with code ");
619 string = Fnumber_to_string (make_number (code));
620 AUTO_STRING (suffix, "\n");
621 return concat3 (prefix, string, suffix);
623 else
624 return Fcopy_sequence (Fsymbol_name (symbol));
627 enum { PTY_NAME_SIZE = 24 };
629 /* Open an available pty, returning a file descriptor.
630 Store into PTY_NAME the file name of the terminal corresponding to the pty.
631 Return -1 on failure. */
633 static int
634 allocate_pty (char pty_name[PTY_NAME_SIZE])
636 #ifdef HAVE_PTYS
637 int fd;
639 #ifdef PTY_ITERATION
640 PTY_ITERATION
641 #else
642 register int c, i;
643 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
644 for (i = 0; i < 16; i++)
645 #endif
647 #ifdef PTY_NAME_SPRINTF
648 PTY_NAME_SPRINTF
649 #else
650 sprintf (pty_name, "/dev/pty%c%x", c, i);
651 #endif /* no PTY_NAME_SPRINTF */
653 #ifdef PTY_OPEN
654 PTY_OPEN;
655 #else /* no PTY_OPEN */
656 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
657 #endif /* no PTY_OPEN */
659 if (fd >= 0)
661 #ifdef PTY_TTY_NAME_SPRINTF
662 PTY_TTY_NAME_SPRINTF
663 #else
664 sprintf (pty_name, "/dev/tty%c%x", c, i);
665 #endif /* no PTY_TTY_NAME_SPRINTF */
667 /* Set FD's close-on-exec flag. This is needed even if
668 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
669 doesn't require support for that combination.
670 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
671 doesn't work if the close-on-exec flag is set (Bug#20555).
672 Multithreaded platforms where posix_openpt ignores
673 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
674 have a race condition between the PTY_OPEN and here. */
675 fcntl (fd, F_SETFD, FD_CLOEXEC);
677 /* Check to make certain that both sides are available.
678 This avoids a nasty yet stupid bug in rlogins. */
679 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
681 emacs_close (fd);
682 # ifndef __sgi
683 continue;
684 # else
685 return -1;
686 # endif /* __sgi */
688 setup_pty (fd);
689 return fd;
692 #endif /* HAVE_PTYS */
693 return -1;
696 /* Allocate basically initialized process. */
698 static struct Lisp_Process *
699 allocate_process (void)
701 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
704 static Lisp_Object
705 make_process (Lisp_Object name)
707 register Lisp_Object val, tem, name1;
708 register struct Lisp_Process *p;
709 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
710 printmax_t i;
712 p = allocate_process ();
713 /* Initialize Lisp data. Note that allocate_process initializes all
714 Lisp data to nil, so do it only for slots which should not be nil. */
715 pset_status (p, Qrun);
716 pset_mark (p, Fmake_marker ());
718 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
719 non-Lisp data, so do it only for slots which should not be zero. */
720 p->infd = -1;
721 p->outfd = -1;
722 for (i = 0; i < PROCESS_OPEN_FDS; i++)
723 p->open_fd[i] = -1;
725 #ifdef HAVE_GNUTLS
726 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
727 #endif
729 /* If name is already in use, modify it until it is unused. */
731 name1 = name;
732 for (i = 1; ; i++)
734 tem = Fget_process (name1);
735 if (NILP (tem)) break;
736 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
738 name = name1;
739 pset_name (p, name);
740 pset_sentinel (p, Qinternal_default_process_sentinel);
741 pset_filter (p, Qinternal_default_process_filter);
742 XSETPROCESS (val, p);
743 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
744 return val;
747 static void
748 remove_process (register Lisp_Object proc)
750 register Lisp_Object pair;
752 pair = Frassq (proc, Vprocess_alist);
753 Vprocess_alist = Fdelq (pair, Vprocess_alist);
755 deactivate_process (proc);
759 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
760 doc: /* Return t if OBJECT is a process. */)
761 (Lisp_Object object)
763 return PROCESSP (object) ? Qt : Qnil;
766 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
767 doc: /* Return the process named NAME, or nil if there is none. */)
768 (register Lisp_Object name)
770 if (PROCESSP (name))
771 return name;
772 CHECK_STRING (name);
773 return Fcdr (Fassoc (name, Vprocess_alist));
776 /* This is how commands for the user decode process arguments. It
777 accepts a process, a process name, a buffer, a buffer name, or nil.
778 Buffers denote the first process in the buffer, and nil denotes the
779 current buffer. */
781 static Lisp_Object
782 get_process (register Lisp_Object name)
784 register Lisp_Object proc, obj;
785 if (STRINGP (name))
787 obj = Fget_process (name);
788 if (NILP (obj))
789 obj = Fget_buffer (name);
790 if (NILP (obj))
791 error ("Process %s does not exist", SDATA (name));
793 else if (NILP (name))
794 obj = Fcurrent_buffer ();
795 else
796 obj = name;
798 /* Now obj should be either a buffer object or a process object. */
799 if (BUFFERP (obj))
801 if (NILP (BVAR (XBUFFER (obj), name)))
802 error ("Attempt to get process for a dead buffer");
803 proc = Fget_buffer_process (obj);
804 if (NILP (proc))
805 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
807 else
809 CHECK_PROCESS (obj);
810 proc = obj;
812 return proc;
816 /* Fdelete_process promises to immediately forget about the process, but in
817 reality, Emacs needs to remember those processes until they have been
818 treated by the SIGCHLD handler and waitpid has been invoked on them;
819 otherwise they might fill up the kernel's process table.
821 Some processes created by call-process are also put onto this list.
823 Members of this list are (process-ID . filename) pairs. The
824 process-ID is a number; the filename, if a string, is a file that
825 needs to be removed after the process exits. */
826 static Lisp_Object deleted_pid_list;
828 void
829 record_deleted_pid (pid_t pid, Lisp_Object filename)
831 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
832 /* GC treated elements set to nil. */
833 Fdelq (Qnil, deleted_pid_list));
837 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
838 doc: /* Delete PROCESS: kill it and forget about it immediately.
839 PROCESS may be a process, a buffer, the name of a process or buffer, or
840 nil, indicating the current buffer's process. */)
841 (register Lisp_Object process)
843 register struct Lisp_Process *p;
845 process = get_process (process);
846 p = XPROCESS (process);
848 p->raw_status_new = 0;
849 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
851 pset_status (p, list2 (Qexit, make_number (0)));
852 p->tick = ++process_tick;
853 status_notify (p, NULL);
854 redisplay_preserve_echo_area (13);
856 else
858 if (p->alive)
859 record_kill_process (p, Qnil);
861 if (p->infd >= 0)
863 /* Update P's status, since record_kill_process will make the
864 SIGCHLD handler update deleted_pid_list, not *P. */
865 Lisp_Object symbol;
866 if (p->raw_status_new)
867 update_status (p);
868 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
869 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
870 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
872 p->tick = ++process_tick;
873 status_notify (p, NULL);
874 redisplay_preserve_echo_area (13);
877 remove_process (process);
878 return Qnil;
881 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
882 doc: /* Return the status of PROCESS.
883 The returned value is one of the following symbols:
884 run -- for a process that is running.
885 stop -- for a process stopped but continuable.
886 exit -- for a process that has exited.
887 signal -- for a process that has got a fatal signal.
888 open -- for a network stream connection that is open.
889 listen -- for a network stream server that is listening.
890 closed -- for a network stream connection that is closed.
891 connect -- when waiting for a non-blocking connection to complete.
892 failed -- when a non-blocking connection has failed.
893 nil -- if arg is a process name and no such process exists.
894 PROCESS may be a process, a buffer, the name of a process, or
895 nil, indicating the current buffer's process. */)
896 (register Lisp_Object process)
898 register struct Lisp_Process *p;
899 register Lisp_Object status;
901 if (STRINGP (process))
902 process = Fget_process (process);
903 else
904 process = get_process (process);
906 if (NILP (process))
907 return process;
909 p = XPROCESS (process);
910 if (p->raw_status_new)
911 update_status (p);
912 status = p->status;
913 if (CONSP (status))
914 status = XCAR (status);
915 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
917 if (EQ (status, Qexit))
918 status = Qclosed;
919 else if (EQ (p->command, Qt))
920 status = Qstop;
921 else if (EQ (status, Qrun))
922 status = Qopen;
924 return status;
927 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
928 1, 1, 0,
929 doc: /* Return the exit status of PROCESS or the signal number that killed it.
930 If PROCESS has not yet exited or died, return 0. */)
931 (register Lisp_Object process)
933 CHECK_PROCESS (process);
934 if (XPROCESS (process)->raw_status_new)
935 update_status (XPROCESS (process));
936 if (CONSP (XPROCESS (process)->status))
937 return XCAR (XCDR (XPROCESS (process)->status));
938 return make_number (0);
941 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
942 doc: /* Return the process id of PROCESS.
943 This is the pid of the external process which PROCESS uses or talks to.
944 For a network connection, this value is nil. */)
945 (register Lisp_Object process)
947 pid_t pid;
949 CHECK_PROCESS (process);
950 pid = XPROCESS (process)->pid;
951 return (pid ? make_fixnum_or_float (pid) : Qnil);
954 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
955 doc: /* Return the name of PROCESS, as a string.
956 This is the name of the program invoked in PROCESS,
957 possibly modified to make it unique among process names. */)
958 (register Lisp_Object process)
960 CHECK_PROCESS (process);
961 return XPROCESS (process)->name;
964 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
965 doc: /* Return the command that was executed to start PROCESS.
966 This is a list of strings, the first string being the program executed
967 and the rest of the strings being the arguments given to it.
968 For a network or serial process, this is nil (process is running) or t
969 \(process is stopped). */)
970 (register Lisp_Object process)
972 CHECK_PROCESS (process);
973 return XPROCESS (process)->command;
976 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
977 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
978 This is the terminal that the process itself reads and writes on,
979 not the name of the pty that Emacs uses to talk with that terminal. */)
980 (register Lisp_Object process)
982 CHECK_PROCESS (process);
983 return XPROCESS (process)->tty_name;
986 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
987 2, 2, 0,
988 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
989 Return BUFFER. */)
990 (register Lisp_Object process, Lisp_Object buffer)
992 struct Lisp_Process *p;
994 CHECK_PROCESS (process);
995 if (!NILP (buffer))
996 CHECK_BUFFER (buffer);
997 p = XPROCESS (process);
998 pset_buffer (p, buffer);
999 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1000 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1001 setup_process_coding_systems (process);
1002 return buffer;
1005 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1006 1, 1, 0,
1007 doc: /* Return the buffer PROCESS is associated with.
1008 The default process filter inserts output from PROCESS into this buffer. */)
1009 (register Lisp_Object process)
1011 CHECK_PROCESS (process);
1012 return XPROCESS (process)->buffer;
1015 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1016 1, 1, 0,
1017 doc: /* Return the marker for the end of the last output from PROCESS. */)
1018 (register Lisp_Object process)
1020 CHECK_PROCESS (process);
1021 return XPROCESS (process)->mark;
1024 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1025 2, 2, 0,
1026 doc: /* Give PROCESS the filter function FILTER; nil means default.
1027 A value of t means stop accepting output from the process.
1029 When a process has a non-default filter, its buffer is not used for output.
1030 Instead, each time it does output, the entire string of output is
1031 passed to the filter.
1033 The filter gets two arguments: the process and the string of output.
1034 The string argument is normally a multibyte string, except:
1035 - if the process's input coding system is no-conversion or raw-text,
1036 it is a unibyte string (the non-converted input), or else
1037 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1038 string (the result of converting the decoded input multibyte
1039 string to unibyte with `string-make-unibyte'). */)
1040 (register Lisp_Object process, Lisp_Object filter)
1042 struct Lisp_Process *p;
1044 CHECK_PROCESS (process);
1045 p = XPROCESS (process);
1047 /* Don't signal an error if the process's input file descriptor
1048 is closed. This could make debugging Lisp more difficult,
1049 for example when doing something like
1051 (setq process (start-process ...))
1052 (debug)
1053 (set-process-filter process ...) */
1055 if (NILP (filter))
1056 filter = Qinternal_default_process_filter;
1058 if (p->infd >= 0)
1060 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1062 FD_CLR (p->infd, &input_wait_mask);
1063 FD_CLR (p->infd, &non_keyboard_wait_mask);
1065 else if (EQ (p->filter, Qt)
1066 /* Network or serial process not stopped: */
1067 && !EQ (p->command, Qt))
1069 FD_SET (p->infd, &input_wait_mask);
1070 FD_SET (p->infd, &non_keyboard_wait_mask);
1074 pset_filter (p, filter);
1075 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1076 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1077 setup_process_coding_systems (process);
1078 return filter;
1081 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1082 1, 1, 0,
1083 doc: /* Return the filter function of PROCESS.
1084 See `set-process-filter' for more info on filter functions. */)
1085 (register Lisp_Object process)
1087 CHECK_PROCESS (process);
1088 return XPROCESS (process)->filter;
1091 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1092 2, 2, 0,
1093 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1094 The sentinel is called as a function when the process changes state.
1095 It gets two arguments: the process, and a string describing the change. */)
1096 (register Lisp_Object process, Lisp_Object sentinel)
1098 struct Lisp_Process *p;
1100 CHECK_PROCESS (process);
1101 p = XPROCESS (process);
1103 if (NILP (sentinel))
1104 sentinel = Qinternal_default_process_sentinel;
1106 pset_sentinel (p, sentinel);
1107 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1108 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1109 return sentinel;
1112 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1113 1, 1, 0,
1114 doc: /* Return the sentinel of PROCESS.
1115 See `set-process-sentinel' for more info on sentinels. */)
1116 (register Lisp_Object process)
1118 CHECK_PROCESS (process);
1119 return XPROCESS (process)->sentinel;
1122 DEFUN ("set-process-window-size", Fset_process_window_size,
1123 Sset_process_window_size, 3, 3, 0,
1124 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1125 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1127 CHECK_PROCESS (process);
1129 /* All known platforms store window sizes as 'unsigned short'. */
1130 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1131 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1133 if (XPROCESS (process)->infd < 0
1134 || (set_window_size (XPROCESS (process)->infd,
1135 XINT (height), XINT (width))
1136 < 0))
1137 return Qnil;
1138 else
1139 return Qt;
1142 DEFUN ("set-process-inherit-coding-system-flag",
1143 Fset_process_inherit_coding_system_flag,
1144 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1145 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1146 If the second argument FLAG is non-nil, then the variable
1147 `buffer-file-coding-system' of the buffer associated with PROCESS
1148 will be bound to the value of the coding system used to decode
1149 the process output.
1151 This is useful when the coding system specified for the process buffer
1152 leaves either the character code conversion or the end-of-line conversion
1153 unspecified, or if the coding system used to decode the process output
1154 is more appropriate for saving the process buffer.
1156 Binding the variable `inherit-process-coding-system' to non-nil before
1157 starting the process is an alternative way of setting the inherit flag
1158 for the process which will run.
1160 This function returns FLAG. */)
1161 (register Lisp_Object process, Lisp_Object flag)
1163 CHECK_PROCESS (process);
1164 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1165 return flag;
1168 DEFUN ("set-process-query-on-exit-flag",
1169 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1170 2, 2, 0,
1171 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1172 If the second argument FLAG is non-nil, Emacs will query the user before
1173 exiting or killing a buffer if PROCESS is running. This function
1174 returns FLAG. */)
1175 (register Lisp_Object process, Lisp_Object flag)
1177 CHECK_PROCESS (process);
1178 XPROCESS (process)->kill_without_query = NILP (flag);
1179 return flag;
1182 DEFUN ("process-query-on-exit-flag",
1183 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1184 1, 1, 0,
1185 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1186 (register Lisp_Object process)
1188 CHECK_PROCESS (process);
1189 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1192 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1193 1, 2, 0,
1194 doc: /* Return the contact info of PROCESS; t for a real child.
1195 For a network or serial connection, the value depends on the optional
1196 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1197 SERVICE) for a network connection or (PORT SPEED) for a serial
1198 connection. If KEY is t, the complete contact information for the
1199 connection is returned, else the specific value for the keyword KEY is
1200 returned. See `make-network-process' or `make-serial-process' for a
1201 list of keywords. */)
1202 (register Lisp_Object process, Lisp_Object key)
1204 Lisp_Object contact;
1206 CHECK_PROCESS (process);
1207 contact = XPROCESS (process)->childp;
1209 #ifdef DATAGRAM_SOCKETS
1210 if (DATAGRAM_CONN_P (process)
1211 && (EQ (key, Qt) || EQ (key, QCremote)))
1212 contact = Fplist_put (contact, QCremote,
1213 Fprocess_datagram_address (process));
1214 #endif
1216 if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1217 || EQ (key, Qt))
1218 return contact;
1219 if (NILP (key) && NETCONN_P (process))
1220 return list2 (Fplist_get (contact, QChost),
1221 Fplist_get (contact, QCservice));
1222 if (NILP (key) && SERIALCONN_P (process))
1223 return list2 (Fplist_get (contact, QCport),
1224 Fplist_get (contact, QCspeed));
1225 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1226 if the pipe process is useful for purposes other than receiving
1227 stderr. */
1228 if (NILP (key) && PIPECONN_P (process))
1229 return Qt;
1230 return Fplist_get (contact, key);
1233 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1234 1, 1, 0,
1235 doc: /* Return the plist of PROCESS. */)
1236 (register Lisp_Object process)
1238 CHECK_PROCESS (process);
1239 return XPROCESS (process)->plist;
1242 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1243 2, 2, 0,
1244 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1245 (register Lisp_Object process, Lisp_Object plist)
1247 CHECK_PROCESS (process);
1248 CHECK_LIST (plist);
1250 pset_plist (XPROCESS (process), plist);
1251 return plist;
1254 #if 0 /* Turned off because we don't currently record this info
1255 in the process. Perhaps add it. */
1256 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1257 doc: /* Return the connection type of PROCESS.
1258 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1259 a socket connection. */)
1260 (Lisp_Object process)
1262 return XPROCESS (process)->type;
1264 #endif
1266 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1267 doc: /* Return the connection type of PROCESS.
1268 The value is either the symbol `real', `network', or `serial'.
1269 PROCESS may be a process, a buffer, the name of a process or buffer, or
1270 nil, indicating the current buffer's process. */)
1271 (Lisp_Object process)
1273 Lisp_Object proc;
1274 proc = get_process (process);
1275 return XPROCESS (proc)->type;
1278 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1279 1, 2, 0,
1280 doc: /* Convert network ADDRESS from internal format to a string.
1281 A 4 or 5 element vector represents an IPv4 address (with port number).
1282 An 8 or 9 element vector represents an IPv6 address (with port number).
1283 If optional second argument OMIT-PORT is non-nil, don't include a port
1284 number in the string, even when present in ADDRESS.
1285 Returns nil if format of ADDRESS is invalid. */)
1286 (Lisp_Object address, Lisp_Object omit_port)
1288 if (NILP (address))
1289 return Qnil;
1291 if (STRINGP (address)) /* AF_LOCAL */
1292 return address;
1294 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1296 register struct Lisp_Vector *p = XVECTOR (address);
1297 ptrdiff_t size = p->header.size;
1298 Lisp_Object args[10];
1299 int nargs, i;
1300 char const *format;
1302 if (size == 4 || (size == 5 && !NILP (omit_port)))
1304 format = "%d.%d.%d.%d";
1305 nargs = 4;
1307 else if (size == 5)
1309 format = "%d.%d.%d.%d:%d";
1310 nargs = 5;
1312 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1314 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1315 nargs = 8;
1317 else if (size == 9)
1319 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1320 nargs = 9;
1322 else
1323 return Qnil;
1325 AUTO_STRING (format_obj, format);
1326 args[0] = format_obj;
1328 for (i = 0; i < nargs; i++)
1330 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1331 return Qnil;
1333 if (nargs <= 5 /* IPv4 */
1334 && i < 4 /* host, not port */
1335 && XINT (p->contents[i]) > 255)
1336 return Qnil;
1338 args[i + 1] = p->contents[i];
1341 return Fformat (nargs + 1, args);
1344 if (CONSP (address))
1346 AUTO_STRING (format, "<Family %d>");
1347 return CALLN (Fformat, format, Fcar (address));
1350 return Qnil;
1353 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1354 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1355 (void)
1357 return Fmapcar (Qcdr, Vprocess_alist);
1360 /* Starting asynchronous inferior processes. */
1362 static void start_process_unwind (Lisp_Object proc);
1364 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1365 doc: /* Start a program in a subprocess. Return the process object for it.
1367 This is similar to `start-process', but arguments are specified as
1368 keyword/argument pairs. The following arguments are defined:
1370 :name NAME -- NAME is name for process. It is modified if necessary
1371 to make it unique.
1373 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1374 with the process. Process output goes at end of that buffer, unless
1375 you specify an output stream or filter function to handle the output.
1376 BUFFER may be also nil, meaning that this process is not associated
1377 with any buffer.
1379 :command COMMAND -- COMMAND is a list starting with the program file
1380 name, followed by strings to give to the program as arguments.
1382 :coding CODING -- If CODING is a symbol, it specifies the coding
1383 system used for both reading and writing for this process. If CODING
1384 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1385 ENCODING is used for writing.
1387 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1388 the process is running. If BOOL is not given, query before exiting.
1390 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1391 In the stopped state, a process does not accept incoming data, but you
1392 can send outgoing data. The stopped state is cleared by
1393 `continue-process' and set by `stop-process'.
1395 :connection-type TYPE -- TYPE is control type of device used to
1396 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1397 to use a pty, or nil to use the default specified through
1398 `process-connection-type'.
1400 :filter FILTER -- Install FILTER as the process filter.
1402 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1404 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1405 to the standard error of subprocess. Specifying this implies
1406 `:connection-type' is set to `pipe'.
1408 usage: (make-process &rest ARGS) */)
1409 (ptrdiff_t nargs, Lisp_Object *args)
1411 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1412 Lisp_Object xstderr, stderrproc;
1413 ptrdiff_t count = SPECPDL_INDEX ();
1414 struct gcpro gcpro1;
1415 USE_SAFE_ALLOCA;
1417 if (nargs == 0)
1418 return Qnil;
1420 /* Save arguments for process-contact and clone-process. */
1421 contact = Flist (nargs, args);
1422 GCPRO1 (contact);
1424 buffer = Fplist_get (contact, QCbuffer);
1425 if (!NILP (buffer))
1426 buffer = Fget_buffer_create (buffer);
1428 /* Make sure that the child will be able to chdir to the current
1429 buffer's current directory, or its unhandled equivalent. We
1430 can't just have the child check for an error when it does the
1431 chdir, since it's in a vfork.
1433 We have to GCPRO around this because Fexpand_file_name and
1434 Funhandled_file_name_directory might call a file name handling
1435 function. The argument list is protected by the caller, so all
1436 we really have to worry about is buffer. */
1438 struct gcpro gcpro1;
1439 GCPRO1 (buffer);
1440 current_dir = encode_current_directory ();
1441 UNGCPRO;
1444 name = Fplist_get (contact, QCname);
1445 CHECK_STRING (name);
1447 command = Fplist_get (contact, QCcommand);
1448 if (CONSP (command))
1449 program = XCAR (command);
1450 else
1451 program = Qnil;
1453 if (!NILP (program))
1454 CHECK_STRING (program);
1456 stderrproc = Qnil;
1457 xstderr = Fplist_get (contact, QCstderr);
1458 if (PROCESSP (xstderr))
1460 if (!PIPECONN_P (xstderr))
1461 error ("Process is not a pipe process");
1462 stderrproc = xstderr;
1464 else if (!NILP (xstderr))
1466 struct gcpro gcpro1, gcpro2;
1467 CHECK_STRING (program);
1468 GCPRO2 (buffer, current_dir);
1469 stderrproc = CALLN (Fmake_pipe_process,
1470 QCname,
1471 concat2 (name, build_string (" stderr")),
1472 QCbuffer,
1473 Fget_buffer_create (xstderr));
1474 UNGCPRO;
1477 proc = make_process (name);
1478 /* If an error occurs and we can't start the process, we want to
1479 remove it from the process list. This means that each error
1480 check in create_process doesn't need to call remove_process
1481 itself; it's all taken care of here. */
1482 record_unwind_protect (start_process_unwind, proc);
1484 pset_childp (XPROCESS (proc), Qt);
1485 pset_plist (XPROCESS (proc), Qnil);
1486 pset_type (XPROCESS (proc), Qreal);
1487 pset_buffer (XPROCESS (proc), buffer);
1488 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1489 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1490 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1492 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
1493 XPROCESS (proc)->kill_without_query = 1;
1494 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1495 pset_command (XPROCESS (proc), Qt);
1497 tem = Fplist_get (contact, QCconnection_type);
1498 if (EQ (tem, Qpty))
1499 XPROCESS (proc)->pty_flag = true;
1500 else if (EQ (tem, Qpipe))
1501 XPROCESS (proc)->pty_flag = false;
1502 else if (NILP (tem))
1503 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1504 else
1505 report_file_error ("Unknown connection type", tem);
1507 if (!NILP (stderrproc))
1509 pset_stderrproc (XPROCESS (proc), stderrproc);
1511 XPROCESS (proc)->pty_flag = false;
1514 #ifdef HAVE_GNUTLS
1515 /* AKA GNUTLS_INITSTAGE(proc). */
1516 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1517 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1518 #endif
1520 #ifdef ADAPTIVE_READ_BUFFERING
1521 XPROCESS (proc)->adaptive_read_buffering
1522 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1523 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1524 #endif
1526 /* Make the process marker point into the process buffer (if any). */
1527 if (BUFFERP (buffer))
1528 set_marker_both (XPROCESS (proc)->mark, buffer,
1529 BUF_ZV (XBUFFER (buffer)),
1530 BUF_ZV_BYTE (XBUFFER (buffer)));
1533 /* Decide coding systems for communicating with the process. Here
1534 we don't setup the structure coding_system nor pay attention to
1535 unibyte mode. They are done in create_process. */
1537 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1538 Lisp_Object coding_systems = Qt;
1539 Lisp_Object val, *args2;
1540 struct gcpro gcpro1, gcpro2;
1542 tem = Fplist_get (contact, QCcoding);
1543 if (!NILP (tem))
1545 val = tem;
1546 if (CONSP (val))
1547 val = XCAR (val);
1549 else
1550 val = Vcoding_system_for_read;
1551 if (NILP (val))
1553 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1554 Lisp_Object tem2;
1555 SAFE_ALLOCA_LISP (args2, nargs2);
1556 ptrdiff_t i = 0;
1557 args2[i++] = Qstart_process;
1558 args2[i++] = name;
1559 args2[i++] = buffer;
1560 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1561 args2[i++] = XCAR (tem2);
1562 GCPRO2 (proc, current_dir);
1563 if (!NILP (program))
1564 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1565 UNGCPRO;
1566 if (CONSP (coding_systems))
1567 val = XCAR (coding_systems);
1568 else if (CONSP (Vdefault_process_coding_system))
1569 val = XCAR (Vdefault_process_coding_system);
1571 pset_decode_coding_system (XPROCESS (proc), val);
1573 if (!NILP (tem))
1575 val = tem;
1576 if (CONSP (val))
1577 val = XCDR (val);
1579 else
1580 val = Vcoding_system_for_write;
1581 if (NILP (val))
1583 if (EQ (coding_systems, Qt))
1585 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1586 Lisp_Object tem2;
1587 SAFE_ALLOCA_LISP (args2, nargs2);
1588 ptrdiff_t i = 0;
1589 args2[i++] = Qstart_process;
1590 args2[i++] = name;
1591 args2[i++] = buffer;
1592 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1593 args2[i++] = XCAR (tem2);
1594 GCPRO2 (proc, current_dir);
1595 if (!NILP (program))
1596 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1597 UNGCPRO;
1599 if (CONSP (coding_systems))
1600 val = XCDR (coding_systems);
1601 else if (CONSP (Vdefault_process_coding_system))
1602 val = XCDR (Vdefault_process_coding_system);
1604 pset_encode_coding_system (XPROCESS (proc), val);
1605 /* Note: At this moment, the above coding system may leave
1606 text-conversion or eol-conversion unspecified. They will be
1607 decided after we read output from the process and decode it by
1608 some coding system, or just before we actually send a text to
1609 the process. */
1613 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1614 XPROCESS (proc)->decoding_carryover = 0;
1615 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1617 XPROCESS (proc)->inherit_coding_system_flag
1618 = !(NILP (buffer) || !inherit_process_coding_system);
1620 if (!NILP (program))
1622 Lisp_Object program_args = XCDR (command);
1624 /* If program file name is not absolute, search our path for it.
1625 Put the name we will really use in TEM. */
1626 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1627 && !(SCHARS (program) > 1
1628 && IS_DEVICE_SEP (SREF (program, 1))))
1630 struct gcpro gcpro1, gcpro2;
1632 tem = Qnil;
1633 GCPRO2 (buffer, current_dir);
1634 openp (Vexec_path, program, Vexec_suffixes, &tem,
1635 make_number (X_OK), false);
1636 UNGCPRO;
1637 if (NILP (tem))
1638 report_file_error ("Searching for program", program);
1639 tem = Fexpand_file_name (tem, Qnil);
1641 else
1643 if (!NILP (Ffile_directory_p (program)))
1644 error ("Specified program for new process is a directory");
1645 tem = program;
1648 /* Remove "/:" from TEM. */
1649 tem = remove_slash_colon (tem);
1651 Lisp_Object arg_encoding = Qnil;
1652 struct gcpro gcpro1;
1653 GCPRO1 (tem);
1655 /* Encode the file name and put it in NEW_ARGV.
1656 That's where the child will use it to execute the program. */
1657 tem = list1 (ENCODE_FILE (tem));
1658 ptrdiff_t new_argc = 1;
1660 /* Here we encode arguments by the coding system used for sending
1661 data to the process. We don't support using different coding
1662 systems for encoding arguments and for encoding data sent to the
1663 process. */
1665 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1667 Lisp_Object arg = XCAR (tem2);
1668 CHECK_STRING (arg);
1669 if (STRING_MULTIBYTE (arg))
1671 if (NILP (arg_encoding))
1672 arg_encoding = (complement_process_encoding_system
1673 (XPROCESS (proc)->encode_coding_system));
1674 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1676 tem = Fcons (arg, tem);
1677 new_argc++;
1680 UNGCPRO;
1682 /* Now that everything is encoded we can collect the strings into
1683 NEW_ARGV. */
1684 char **new_argv;
1685 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1686 new_argv[new_argc] = 0;
1688 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1690 new_argv[i] = SSDATA (XCAR (tem));
1691 tem = XCDR (tem);
1694 create_process (proc, new_argv, current_dir);
1696 else
1697 create_pty (proc);
1699 UNGCPRO;
1700 SAFE_FREE ();
1701 return unbind_to (count, proc);
1704 /* This function is the unwind_protect form for Fstart_process. If
1705 PROC doesn't have its pid set, then we know someone has signaled
1706 an error and the process wasn't started successfully, so we should
1707 remove it from the process list. */
1708 static void
1709 start_process_unwind (Lisp_Object proc)
1711 if (!PROCESSP (proc))
1712 emacs_abort ();
1714 /* Was PROC started successfully?
1715 -2 is used for a pty with no process, eg for gdb. */
1716 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1717 remove_process (proc);
1720 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1722 static void
1723 close_process_fd (int *fd_addr)
1725 int fd = *fd_addr;
1726 if (0 <= fd)
1728 *fd_addr = -1;
1729 emacs_close (fd);
1733 /* Indexes of file descriptors in open_fds. */
1734 enum
1736 /* The pipe from Emacs to its subprocess. */
1737 SUBPROCESS_STDIN,
1738 WRITE_TO_SUBPROCESS,
1740 /* The main pipe from the subprocess to Emacs. */
1741 READ_FROM_SUBPROCESS,
1742 SUBPROCESS_STDOUT,
1744 /* The pipe from the subprocess to Emacs that is closed when the
1745 subprocess execs. */
1746 READ_FROM_EXEC_MONITOR,
1747 EXEC_MONITOR_OUTPUT
1750 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1752 static void
1753 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1755 struct Lisp_Process *p = XPROCESS (process);
1756 int inchannel, outchannel;
1757 pid_t pid;
1758 int vfork_errno;
1759 int forkin, forkout, forkerr = -1;
1760 bool pty_flag = 0;
1761 char pty_name[PTY_NAME_SIZE];
1762 Lisp_Object lisp_pty_name = Qnil;
1763 sigset_t oldset;
1765 inchannel = outchannel = -1;
1767 if (p->pty_flag)
1768 outchannel = inchannel = allocate_pty (pty_name);
1770 if (inchannel >= 0)
1772 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1773 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1774 /* On most USG systems it does not work to open the pty's tty here,
1775 then close it and reopen it in the child. */
1776 /* Don't let this terminal become our controlling terminal
1777 (in case we don't have one). */
1778 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1779 if (forkin < 0)
1780 report_file_error ("Opening pty", Qnil);
1781 p->open_fd[SUBPROCESS_STDIN] = forkin;
1782 #else
1783 forkin = forkout = -1;
1784 #endif /* not USG, or USG_SUBTTY_WORKS */
1785 pty_flag = 1;
1786 lisp_pty_name = build_string (pty_name);
1788 else
1790 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1791 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1792 report_file_error ("Creating pipe", Qnil);
1793 forkin = p->open_fd[SUBPROCESS_STDIN];
1794 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1795 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1796 forkout = p->open_fd[SUBPROCESS_STDOUT];
1798 if (!NILP (p->stderrproc))
1800 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
1802 forkerr = pp->open_fd[SUBPROCESS_STDOUT];
1804 /* Close unnecessary file descriptors. */
1805 close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
1806 close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
1810 #ifndef WINDOWSNT
1811 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1812 report_file_error ("Creating pipe", Qnil);
1813 #endif
1815 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1816 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1818 /* Record this as an active process, with its channels. */
1819 chan_process[inchannel] = process;
1820 p->infd = inchannel;
1821 p->outfd = outchannel;
1823 /* Previously we recorded the tty descriptor used in the subprocess.
1824 It was only used for getting the foreground tty process, so now
1825 we just reopen the device (see emacs_get_tty_pgrp) as this is
1826 more portable (see USG_SUBTTY_WORKS above). */
1828 p->pty_flag = pty_flag;
1829 pset_status (p, Qrun);
1831 if (!EQ (p->command, Qt))
1833 FD_SET (inchannel, &input_wait_mask);
1834 FD_SET (inchannel, &non_keyboard_wait_mask);
1837 if (inchannel > max_process_desc)
1838 max_process_desc = inchannel;
1840 /* This may signal an error. */
1841 setup_process_coding_systems (process);
1843 block_input ();
1844 block_child_signal (&oldset);
1846 #ifndef WINDOWSNT
1847 /* vfork, and prevent local vars from being clobbered by the vfork. */
1849 Lisp_Object volatile current_dir_volatile = current_dir;
1850 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1851 char **volatile new_argv_volatile = new_argv;
1852 int volatile forkin_volatile = forkin;
1853 int volatile forkout_volatile = forkout;
1854 int volatile forkerr_volatile = forkerr;
1855 struct Lisp_Process *p_volatile = p;
1857 pid = vfork ();
1859 current_dir = current_dir_volatile;
1860 lisp_pty_name = lisp_pty_name_volatile;
1861 new_argv = new_argv_volatile;
1862 forkin = forkin_volatile;
1863 forkout = forkout_volatile;
1864 forkerr = forkerr_volatile;
1865 p = p_volatile;
1867 pty_flag = p->pty_flag;
1870 if (pid == 0)
1871 #endif /* not WINDOWSNT */
1873 int xforkin = forkin;
1874 int xforkout = forkout;
1875 int xforkerr = forkerr;
1877 /* Make the pty be the controlling terminal of the process. */
1878 #ifdef HAVE_PTYS
1879 /* First, disconnect its current controlling terminal. */
1880 /* We tried doing setsid only if pty_flag, but it caused
1881 process_set_signal to fail on SGI when using a pipe. */
1882 setsid ();
1883 /* Make the pty's terminal the controlling terminal. */
1884 if (pty_flag && xforkin >= 0)
1886 #ifdef TIOCSCTTY
1887 /* We ignore the return value
1888 because faith@cs.unc.edu says that is necessary on Linux. */
1889 ioctl (xforkin, TIOCSCTTY, 0);
1890 #endif
1892 #if defined (LDISC1)
1893 if (pty_flag && xforkin >= 0)
1895 struct termios t;
1896 tcgetattr (xforkin, &t);
1897 t.c_lflag = LDISC1;
1898 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1899 emacs_perror ("create_process/tcsetattr LDISC1");
1901 #else
1902 #if defined (NTTYDISC) && defined (TIOCSETD)
1903 if (pty_flag && xforkin >= 0)
1905 /* Use new line discipline. */
1906 int ldisc = NTTYDISC;
1907 ioctl (xforkin, TIOCSETD, &ldisc);
1909 #endif
1910 #endif
1911 #ifdef TIOCNOTTY
1912 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1913 can do TIOCSPGRP only to the process's controlling tty. */
1914 if (pty_flag)
1916 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1917 I can't test it since I don't have 4.3. */
1918 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1919 if (j >= 0)
1921 ioctl (j, TIOCNOTTY, 0);
1922 emacs_close (j);
1925 #endif /* TIOCNOTTY */
1927 #if !defined (DONT_REOPEN_PTY)
1928 /*** There is a suggestion that this ought to be a
1929 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1930 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1931 that system does seem to need this code, even though
1932 both TIOCSCTTY is defined. */
1933 /* Now close the pty (if we had it open) and reopen it.
1934 This makes the pty the controlling terminal of the subprocess. */
1935 if (pty_flag)
1938 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1939 would work? */
1940 if (xforkin >= 0)
1941 emacs_close (xforkin);
1942 xforkout = xforkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1944 if (xforkin < 0)
1946 emacs_perror (SSDATA (lisp_pty_name));
1947 _exit (EXIT_CANCELED);
1951 #endif /* not DONT_REOPEN_PTY */
1953 #ifdef SETUP_SLAVE_PTY
1954 if (pty_flag)
1956 SETUP_SLAVE_PTY;
1958 #endif /* SETUP_SLAVE_PTY */
1959 #endif /* HAVE_PTYS */
1961 signal (SIGINT, SIG_DFL);
1962 signal (SIGQUIT, SIG_DFL);
1963 #ifdef SIGPROF
1964 signal (SIGPROF, SIG_DFL);
1965 #endif
1967 /* Emacs ignores SIGPIPE, but the child should not. */
1968 signal (SIGPIPE, SIG_DFL);
1970 /* Stop blocking SIGCHLD in the child. */
1971 unblock_child_signal (&oldset);
1973 if (pty_flag)
1974 child_setup_tty (xforkout);
1976 if (xforkerr < 0)
1977 xforkerr = xforkout;
1978 #ifdef WINDOWSNT
1979 pid = child_setup (xforkin, xforkout, xforkerr, new_argv, 1, current_dir);
1980 #else /* not WINDOWSNT */
1981 child_setup (xforkin, xforkout, xforkerr, new_argv, 1, current_dir);
1982 #endif /* not WINDOWSNT */
1985 /* Back in the parent process. */
1987 vfork_errno = errno;
1988 p->pid = pid;
1989 if (pid >= 0)
1990 p->alive = 1;
1992 /* Stop blocking in the parent. */
1993 unblock_child_signal (&oldset);
1994 unblock_input ();
1996 if (pid < 0)
1997 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1998 else
2000 /* vfork succeeded. */
2002 /* Close the pipe ends that the child uses, or the child's pty. */
2003 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
2004 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
2006 #ifdef WINDOWSNT
2007 register_child (pid, inchannel);
2008 #endif /* WINDOWSNT */
2010 pset_tty_name (p, lisp_pty_name);
2012 #ifndef WINDOWSNT
2013 /* Wait for child_setup to complete in case that vfork is
2014 actually defined as fork. The descriptor
2015 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2016 of a pipe is closed at the child side either by close-on-exec
2017 on successful execve or the _exit call in child_setup. */
2019 char dummy;
2021 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
2022 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
2023 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
2025 #endif
2026 if (!NILP (p->stderrproc))
2028 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2029 close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
2034 static void
2035 create_pty (Lisp_Object process)
2037 struct Lisp_Process *p = XPROCESS (process);
2038 char pty_name[PTY_NAME_SIZE];
2039 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
2041 if (pty_fd >= 0)
2043 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
2044 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2045 /* On most USG systems it does not work to open the pty's tty here,
2046 then close it and reopen it in the child. */
2047 /* Don't let this terminal become our controlling terminal
2048 (in case we don't have one). */
2049 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2050 if (forkout < 0)
2051 report_file_error ("Opening pty", Qnil);
2052 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2053 #if defined (DONT_REOPEN_PTY)
2054 /* In the case that vfork is defined as fork, the parent process
2055 (Emacs) may send some data before the child process completes
2056 tty options setup. So we setup tty before forking. */
2057 child_setup_tty (forkout);
2058 #endif /* DONT_REOPEN_PTY */
2059 #endif /* not USG, or USG_SUBTTY_WORKS */
2061 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2063 /* Record this as an active process, with its channels.
2064 As a result, child_setup will close Emacs's side of the pipes. */
2065 chan_process[pty_fd] = process;
2066 p->infd = pty_fd;
2067 p->outfd = pty_fd;
2069 /* Previously we recorded the tty descriptor used in the subprocess.
2070 It was only used for getting the foreground tty process, so now
2071 we just reopen the device (see emacs_get_tty_pgrp) as this is
2072 more portable (see USG_SUBTTY_WORKS above). */
2074 p->pty_flag = 1;
2075 pset_status (p, Qrun);
2076 setup_process_coding_systems (process);
2078 FD_SET (pty_fd, &input_wait_mask);
2079 FD_SET (pty_fd, &non_keyboard_wait_mask);
2080 if (pty_fd > max_process_desc)
2081 max_process_desc = pty_fd;
2083 pset_tty_name (p, build_string (pty_name));
2086 p->pid = -2;
2089 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2090 0, MANY, 0,
2091 doc: /* Create and return a bidirectional pipe process.
2093 In Emacs, pipes are represented by process objects, so input and
2094 output work as for subprocesses, and `delete-process' closes a pipe.
2095 However, a pipe process has no process id, it cannot be signaled,
2096 and the status codes are different from normal processes.
2098 Arguments are specified as keyword/argument pairs. The following
2099 arguments are defined:
2101 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2103 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2104 with the process. Process output goes at the end of that buffer,
2105 unless you specify an output stream or filter function to handle the
2106 output. If BUFFER is not given, the value of NAME is used.
2108 :coding CODING -- If CODING is a symbol, it specifies the coding
2109 system used for both reading and writing for this process. If CODING
2110 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2111 ENCODING is used for writing.
2113 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2114 the process is running. If BOOL is not given, query before exiting.
2116 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2117 In the stopped state, a pipe process does not accept incoming data,
2118 but you can send outgoing data. The stopped state is cleared by
2119 `continue-process' and set by `stop-process'.
2121 :filter FILTER -- Install FILTER as the process filter.
2123 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2125 usage: (make-pipe-process &rest ARGS) */)
2126 (ptrdiff_t nargs, Lisp_Object *args)
2128 Lisp_Object proc, contact;
2129 struct Lisp_Process *p;
2130 struct gcpro gcpro1;
2131 Lisp_Object name, buffer;
2132 Lisp_Object tem;
2133 ptrdiff_t specpdl_count;
2134 int inchannel, outchannel;
2136 if (nargs == 0)
2137 return Qnil;
2139 contact = Flist (nargs, args);
2140 GCPRO1 (contact);
2142 name = Fplist_get (contact, QCname);
2143 CHECK_STRING (name);
2144 proc = make_process (name);
2145 specpdl_count = SPECPDL_INDEX ();
2146 record_unwind_protect (remove_process, proc);
2147 p = XPROCESS (proc);
2149 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2150 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2151 report_file_error ("Creating pipe", Qnil);
2152 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2153 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2155 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2156 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2158 #ifdef WINDOWSNT
2159 register_aux_fd (inchannel);
2160 #endif
2162 /* Record this as an active process, with its channels. */
2163 chan_process[inchannel] = proc;
2164 p->infd = inchannel;
2165 p->outfd = outchannel;
2167 if (inchannel > max_process_desc)
2168 max_process_desc = inchannel;
2170 buffer = Fplist_get (contact, QCbuffer);
2171 if (NILP (buffer))
2172 buffer = name;
2173 buffer = Fget_buffer_create (buffer);
2174 pset_buffer (p, buffer);
2176 pset_childp (p, contact);
2177 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2178 pset_type (p, Qpipe);
2179 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2180 pset_filter (p, Fplist_get (contact, QCfilter));
2181 pset_log (p, Qnil);
2182 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2183 p->kill_without_query = 1;
2184 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2185 pset_command (p, Qt);
2186 eassert (! p->pty_flag);
2188 if (!EQ (p->command, Qt))
2190 FD_SET (inchannel, &input_wait_mask);
2191 FD_SET (inchannel, &non_keyboard_wait_mask);
2193 #ifdef ADAPTIVE_READ_BUFFERING
2194 p->adaptive_read_buffering
2195 = (NILP (Vprocess_adaptive_read_buffering) ? 0
2196 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2197 #endif
2199 /* Make the process marker point into the process buffer (if any). */
2200 if (BUFFERP (buffer))
2201 set_marker_both (p->mark, buffer,
2202 BUF_ZV (XBUFFER (buffer)),
2203 BUF_ZV_BYTE (XBUFFER (buffer)));
2206 /* Setup coding systems for communicating with the network stream. */
2208 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2209 Lisp_Object coding_systems = Qt;
2210 Lisp_Object val;
2212 tem = Fplist_get (contact, QCcoding);
2213 val = Qnil;
2214 if (!NILP (tem))
2216 val = tem;
2217 if (CONSP (val))
2218 val = XCAR (val);
2220 else if (!NILP (Vcoding_system_for_read))
2221 val = Vcoding_system_for_read;
2222 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2223 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2224 /* We dare not decode end-of-line format by setting VAL to
2225 Qraw_text, because the existing Emacs Lisp libraries
2226 assume that they receive bare code including a sequence of
2227 CR LF. */
2228 val = Qnil;
2229 else
2231 if (CONSP (coding_systems))
2232 val = XCAR (coding_systems);
2233 else if (CONSP (Vdefault_process_coding_system))
2234 val = XCAR (Vdefault_process_coding_system);
2235 else
2236 val = Qnil;
2238 pset_decode_coding_system (p, val);
2240 if (!NILP (tem))
2242 val = tem;
2243 if (CONSP (val))
2244 val = XCDR (val);
2246 else if (!NILP (Vcoding_system_for_write))
2247 val = Vcoding_system_for_write;
2248 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2249 val = Qnil;
2250 else
2252 if (CONSP (coding_systems))
2253 val = XCDR (coding_systems);
2254 else if (CONSP (Vdefault_process_coding_system))
2255 val = XCDR (Vdefault_process_coding_system);
2256 else
2257 val = Qnil;
2259 pset_encode_coding_system (p, val);
2261 /* This may signal an error. */
2262 setup_process_coding_systems (proc);
2264 specpdl_ptr = specpdl + specpdl_count;
2266 UNGCPRO;
2267 return proc;
2271 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2272 The address family of sa is not included in the result. */
2274 Lisp_Object
2275 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2277 Lisp_Object address;
2278 int i;
2279 unsigned char *cp;
2280 register struct Lisp_Vector *p;
2282 /* Workaround for a bug in getsockname on BSD: Names bound to
2283 sockets in the UNIX domain are inaccessible; getsockname returns
2284 a zero length name. */
2285 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2286 return empty_unibyte_string;
2288 switch (sa->sa_family)
2290 case AF_INET:
2292 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2293 len = sizeof (sin->sin_addr) + 1;
2294 address = Fmake_vector (make_number (len), Qnil);
2295 p = XVECTOR (address);
2296 p->contents[--len] = make_number (ntohs (sin->sin_port));
2297 cp = (unsigned char *) &sin->sin_addr;
2298 break;
2300 #ifdef AF_INET6
2301 case AF_INET6:
2303 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2304 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2305 len = sizeof (sin6->sin6_addr) / 2 + 1;
2306 address = Fmake_vector (make_number (len), Qnil);
2307 p = XVECTOR (address);
2308 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2309 for (i = 0; i < len; i++)
2310 p->contents[i] = make_number (ntohs (ip6[i]));
2311 return address;
2313 #endif
2314 #ifdef HAVE_LOCAL_SOCKETS
2315 case AF_LOCAL:
2317 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2318 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2319 /* If the first byte is NUL, the name is a Linux abstract
2320 socket name, and the name can contain embedded NULs. If
2321 it's not, we have a NUL-terminated string. Be careful not
2322 to walk past the end of the object looking for the name
2323 terminator, however. */
2324 if (name_length > 0 && sockun->sun_path[0] != '\0')
2326 const char *terminator
2327 = memchr (sockun->sun_path, '\0', name_length);
2329 if (terminator)
2330 name_length = terminator - (const char *) sockun->sun_path;
2333 return make_unibyte_string (sockun->sun_path, name_length);
2335 #endif
2336 default:
2337 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2338 address = Fcons (make_number (sa->sa_family),
2339 Fmake_vector (make_number (len), Qnil));
2340 p = XVECTOR (XCDR (address));
2341 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2342 break;
2345 i = 0;
2346 while (i < len)
2347 p->contents[i++] = make_number (*cp++);
2349 return address;
2353 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2355 static int
2356 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2358 register struct Lisp_Vector *p;
2360 if (VECTORP (address))
2362 p = XVECTOR (address);
2363 if (p->header.size == 5)
2365 *familyp = AF_INET;
2366 return sizeof (struct sockaddr_in);
2368 #ifdef AF_INET6
2369 else if (p->header.size == 9)
2371 *familyp = AF_INET6;
2372 return sizeof (struct sockaddr_in6);
2374 #endif
2376 #ifdef HAVE_LOCAL_SOCKETS
2377 else if (STRINGP (address))
2379 *familyp = AF_LOCAL;
2380 return sizeof (struct sockaddr_un);
2382 #endif
2383 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2384 && VECTORP (XCDR (address)))
2386 struct sockaddr *sa;
2387 p = XVECTOR (XCDR (address));
2388 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2389 return 0;
2390 *familyp = XINT (XCAR (address));
2391 return p->header.size + sizeof (sa->sa_family);
2393 return 0;
2396 /* Convert an address object (vector or string) to an internal sockaddr.
2398 The address format has been basically validated by
2399 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2400 it could have come from user data. So if FAMILY is not valid,
2401 we return after zeroing *SA. */
2403 static void
2404 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2406 register struct Lisp_Vector *p;
2407 register unsigned char *cp = NULL;
2408 register int i;
2409 EMACS_INT hostport;
2411 memset (sa, 0, len);
2413 if (VECTORP (address))
2415 p = XVECTOR (address);
2416 if (family == AF_INET)
2418 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2419 len = sizeof (sin->sin_addr) + 1;
2420 hostport = XINT (p->contents[--len]);
2421 sin->sin_port = htons (hostport);
2422 cp = (unsigned char *)&sin->sin_addr;
2423 sa->sa_family = family;
2425 #ifdef AF_INET6
2426 else if (family == AF_INET6)
2428 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2429 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2430 len = sizeof (sin6->sin6_addr) + 1;
2431 hostport = XINT (p->contents[--len]);
2432 sin6->sin6_port = htons (hostport);
2433 for (i = 0; i < len; i++)
2434 if (INTEGERP (p->contents[i]))
2436 int j = XFASTINT (p->contents[i]) & 0xffff;
2437 ip6[i] = ntohs (j);
2439 sa->sa_family = family;
2440 return;
2442 #endif
2443 else
2444 return;
2446 else if (STRINGP (address))
2448 #ifdef HAVE_LOCAL_SOCKETS
2449 if (family == AF_LOCAL)
2451 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2452 cp = SDATA (address);
2453 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2454 sockun->sun_path[i] = *cp++;
2455 sa->sa_family = family;
2457 #endif
2458 return;
2460 else
2462 p = XVECTOR (XCDR (address));
2463 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2466 for (i = 0; i < len; i++)
2467 if (INTEGERP (p->contents[i]))
2468 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2471 #ifdef DATAGRAM_SOCKETS
2472 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2473 1, 1, 0,
2474 doc: /* Get the current datagram address associated with PROCESS. */)
2475 (Lisp_Object process)
2477 int channel;
2479 CHECK_PROCESS (process);
2481 if (!DATAGRAM_CONN_P (process))
2482 return Qnil;
2484 channel = XPROCESS (process)->infd;
2485 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2486 datagram_address[channel].len);
2489 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2490 2, 2, 0,
2491 doc: /* Set the datagram address for PROCESS to ADDRESS.
2492 Returns nil upon error setting address, ADDRESS otherwise. */)
2493 (Lisp_Object process, Lisp_Object address)
2495 int channel;
2496 int family, len;
2498 CHECK_PROCESS (process);
2500 if (!DATAGRAM_CONN_P (process))
2501 return Qnil;
2503 channel = XPROCESS (process)->infd;
2505 len = get_lisp_to_sockaddr_size (address, &family);
2506 if (len == 0 || datagram_address[channel].len != len)
2507 return Qnil;
2508 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2509 return address;
2511 #endif
2514 static const struct socket_options {
2515 /* The name of this option. Should be lowercase version of option
2516 name without SO_ prefix. */
2517 const char *name;
2518 /* Option level SOL_... */
2519 int optlevel;
2520 /* Option number SO_... */
2521 int optnum;
2522 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2523 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2524 } socket_options[] =
2526 #ifdef SO_BINDTODEVICE
2527 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2528 #endif
2529 #ifdef SO_BROADCAST
2530 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2531 #endif
2532 #ifdef SO_DONTROUTE
2533 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2534 #endif
2535 #ifdef SO_KEEPALIVE
2536 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2537 #endif
2538 #ifdef SO_LINGER
2539 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2540 #endif
2541 #ifdef SO_OOBINLINE
2542 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2543 #endif
2544 #ifdef SO_PRIORITY
2545 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2546 #endif
2547 #ifdef SO_REUSEADDR
2548 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2549 #endif
2550 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2553 /* Set option OPT to value VAL on socket S.
2555 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2556 Signals an error if setting a known option fails.
2559 static int
2560 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2562 char *name;
2563 const struct socket_options *sopt;
2564 int ret = 0;
2566 CHECK_SYMBOL (opt);
2568 name = SSDATA (SYMBOL_NAME (opt));
2569 for (sopt = socket_options; sopt->name; sopt++)
2570 if (strcmp (name, sopt->name) == 0)
2571 break;
2573 switch (sopt->opttype)
2575 case SOPT_BOOL:
2577 int optval;
2578 optval = NILP (val) ? 0 : 1;
2579 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2580 &optval, sizeof (optval));
2581 break;
2584 case SOPT_INT:
2586 int optval;
2587 if (TYPE_RANGED_INTEGERP (int, val))
2588 optval = XINT (val);
2589 else
2590 error ("Bad option value for %s", name);
2591 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2592 &optval, sizeof (optval));
2593 break;
2596 #ifdef SO_BINDTODEVICE
2597 case SOPT_IFNAME:
2599 char devname[IFNAMSIZ + 1];
2601 /* This is broken, at least in the Linux 2.4 kernel.
2602 To unbind, the arg must be a zero integer, not the empty string.
2603 This should work on all systems. KFS. 2003-09-23. */
2604 memset (devname, 0, sizeof devname);
2605 if (STRINGP (val))
2607 char *arg = SSDATA (val);
2608 int len = min (strlen (arg), IFNAMSIZ);
2609 memcpy (devname, arg, len);
2611 else if (!NILP (val))
2612 error ("Bad option value for %s", name);
2613 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2614 devname, IFNAMSIZ);
2615 break;
2617 #endif
2619 #ifdef SO_LINGER
2620 case SOPT_LINGER:
2622 struct linger linger;
2624 linger.l_onoff = 1;
2625 linger.l_linger = 0;
2626 if (TYPE_RANGED_INTEGERP (int, val))
2627 linger.l_linger = XINT (val);
2628 else
2629 linger.l_onoff = NILP (val) ? 0 : 1;
2630 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2631 &linger, sizeof (linger));
2632 break;
2634 #endif
2636 default:
2637 return 0;
2640 if (ret < 0)
2642 int setsockopt_errno = errno;
2643 report_file_errno ("Cannot set network option", list2 (opt, val),
2644 setsockopt_errno);
2647 return (1 << sopt->optbit);
2651 DEFUN ("set-network-process-option",
2652 Fset_network_process_option, Sset_network_process_option,
2653 3, 4, 0,
2654 doc: /* For network process PROCESS set option OPTION to value VALUE.
2655 See `make-network-process' for a list of options and values.
2656 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2657 OPTION is not a supported option, return nil instead; otherwise return t. */)
2658 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2660 int s;
2661 struct Lisp_Process *p;
2663 CHECK_PROCESS (process);
2664 p = XPROCESS (process);
2665 if (!NETCONN1_P (p))
2666 error ("Process is not a network process");
2668 s = p->infd;
2669 if (s < 0)
2670 error ("Process is not running");
2672 if (set_socket_option (s, option, value))
2674 pset_childp (p, Fplist_put (p->childp, option, value));
2675 return Qt;
2678 if (NILP (no_error))
2679 error ("Unknown or unsupported option");
2681 return Qnil;
2685 DEFUN ("serial-process-configure",
2686 Fserial_process_configure,
2687 Sserial_process_configure,
2688 0, MANY, 0,
2689 doc: /* Configure speed, bytesize, etc. of a serial process.
2691 Arguments are specified as keyword/argument pairs. Attributes that
2692 are not given are re-initialized from the process's current
2693 configuration (available via the function `process-contact') or set to
2694 reasonable default values. The following arguments are defined:
2696 :process PROCESS
2697 :name NAME
2698 :buffer BUFFER
2699 :port PORT
2700 -- Any of these arguments can be given to identify the process that is
2701 to be configured. If none of these arguments is given, the current
2702 buffer's process is used.
2704 :speed SPEED -- SPEED is the speed of the serial port in bits per
2705 second, also called baud rate. Any value can be given for SPEED, but
2706 most serial ports work only at a few defined values between 1200 and
2707 115200, with 9600 being the most common value. If SPEED is nil, the
2708 serial port is not configured any further, i.e., all other arguments
2709 are ignored. This may be useful for special serial ports such as
2710 Bluetooth-to-serial converters which can only be configured through AT
2711 commands. A value of nil for SPEED can be used only when passed
2712 through `make-serial-process' or `serial-term'.
2714 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2715 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2717 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2718 `odd' (use odd parity), or the symbol `even' (use even parity). If
2719 PARITY is not given, no parity is used.
2721 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2722 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2723 is not given or nil, 1 stopbit is used.
2725 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2726 flowcontrol to be used, which is either nil (don't use flowcontrol),
2727 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2728 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2729 flowcontrol is used.
2731 `serial-process-configure' is called by `make-serial-process' for the
2732 initial configuration of the serial port.
2734 Examples:
2736 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2738 \(serial-process-configure
2739 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2741 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2743 usage: (serial-process-configure &rest ARGS) */)
2744 (ptrdiff_t nargs, Lisp_Object *args)
2746 struct Lisp_Process *p;
2747 Lisp_Object contact = Qnil;
2748 Lisp_Object proc = Qnil;
2749 struct gcpro gcpro1;
2751 contact = Flist (nargs, args);
2752 GCPRO1 (contact);
2754 proc = Fplist_get (contact, QCprocess);
2755 if (NILP (proc))
2756 proc = Fplist_get (contact, QCname);
2757 if (NILP (proc))
2758 proc = Fplist_get (contact, QCbuffer);
2759 if (NILP (proc))
2760 proc = Fplist_get (contact, QCport);
2761 proc = get_process (proc);
2762 p = XPROCESS (proc);
2763 if (!EQ (p->type, Qserial))
2764 error ("Not a serial process");
2766 if (NILP (Fplist_get (p->childp, QCspeed)))
2768 UNGCPRO;
2769 return Qnil;
2772 serial_configure (p, contact);
2774 UNGCPRO;
2775 return Qnil;
2778 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2779 0, MANY, 0,
2780 doc: /* Create and return a serial port process.
2782 In Emacs, serial port connections are represented by process objects,
2783 so input and output work as for subprocesses, and `delete-process'
2784 closes a serial port connection. However, a serial process has no
2785 process id, it cannot be signaled, and the status codes are different
2786 from normal processes.
2788 `make-serial-process' creates a process and a buffer, on which you
2789 probably want to use `process-send-string'. Try \\[serial-term] for
2790 an interactive terminal. See below for examples.
2792 Arguments are specified as keyword/argument pairs. The following
2793 arguments are defined:
2795 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2796 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2797 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2798 the backslashes in strings).
2800 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2801 which this function calls.
2803 :name NAME -- NAME is the name of the process. If NAME is not given,
2804 the value of PORT is used.
2806 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2807 with the process. Process output goes at the end of that buffer,
2808 unless you specify an output stream or filter function to handle the
2809 output. If BUFFER is not given, the value of NAME is used.
2811 :coding CODING -- If CODING is a symbol, it specifies the coding
2812 system used for both reading and writing for this process. If CODING
2813 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2814 ENCODING is used for writing.
2816 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2817 the process is running. If BOOL is not given, query before exiting.
2819 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2820 In the stopped state, a serial process does not accept incoming data,
2821 but you can send outgoing data. The stopped state is cleared by
2822 `continue-process' and set by `stop-process'.
2824 :filter FILTER -- Install FILTER as the process filter.
2826 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2828 :plist PLIST -- Install PLIST as the initial plist of the process.
2830 :bytesize
2831 :parity
2832 :stopbits
2833 :flowcontrol
2834 -- This function calls `serial-process-configure' to handle these
2835 arguments.
2837 The original argument list, possibly modified by later configuration,
2838 is available via the function `process-contact'.
2840 Examples:
2842 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2844 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2846 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2848 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2850 usage: (make-serial-process &rest ARGS) */)
2851 (ptrdiff_t nargs, Lisp_Object *args)
2853 int fd = -1;
2854 Lisp_Object proc, contact, port;
2855 struct Lisp_Process *p;
2856 struct gcpro gcpro1;
2857 Lisp_Object name, buffer;
2858 Lisp_Object tem, val;
2859 ptrdiff_t specpdl_count;
2861 if (nargs == 0)
2862 return Qnil;
2864 contact = Flist (nargs, args);
2865 GCPRO1 (contact);
2867 port = Fplist_get (contact, QCport);
2868 if (NILP (port))
2869 error ("No port specified");
2870 CHECK_STRING (port);
2872 if (NILP (Fplist_member (contact, QCspeed)))
2873 error (":speed not specified");
2874 if (!NILP (Fplist_get (contact, QCspeed)))
2875 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2877 name = Fplist_get (contact, QCname);
2878 if (NILP (name))
2879 name = port;
2880 CHECK_STRING (name);
2881 proc = make_process (name);
2882 specpdl_count = SPECPDL_INDEX ();
2883 record_unwind_protect (remove_process, proc);
2884 p = XPROCESS (proc);
2886 fd = serial_open (port);
2887 p->open_fd[SUBPROCESS_STDIN] = fd;
2888 p->infd = fd;
2889 p->outfd = fd;
2890 if (fd > max_process_desc)
2891 max_process_desc = fd;
2892 chan_process[fd] = proc;
2894 buffer = Fplist_get (contact, QCbuffer);
2895 if (NILP (buffer))
2896 buffer = name;
2897 buffer = Fget_buffer_create (buffer);
2898 pset_buffer (p, buffer);
2900 pset_childp (p, contact);
2901 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2902 pset_type (p, Qserial);
2903 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2904 pset_filter (p, Fplist_get (contact, QCfilter));
2905 pset_log (p, Qnil);
2906 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2907 p->kill_without_query = 1;
2908 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2909 pset_command (p, Qt);
2910 eassert (! p->pty_flag);
2912 if (!EQ (p->command, Qt))
2914 FD_SET (fd, &input_wait_mask);
2915 FD_SET (fd, &non_keyboard_wait_mask);
2918 if (BUFFERP (buffer))
2920 set_marker_both (p->mark, buffer,
2921 BUF_ZV (XBUFFER (buffer)),
2922 BUF_ZV_BYTE (XBUFFER (buffer)));
2925 tem = Fplist_member (contact, QCcoding);
2926 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2927 tem = Qnil;
2929 val = Qnil;
2930 if (!NILP (tem))
2932 val = XCAR (XCDR (tem));
2933 if (CONSP (val))
2934 val = XCAR (val);
2936 else if (!NILP (Vcoding_system_for_read))
2937 val = Vcoding_system_for_read;
2938 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2939 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2940 val = Qnil;
2941 pset_decode_coding_system (p, val);
2943 val = Qnil;
2944 if (!NILP (tem))
2946 val = XCAR (XCDR (tem));
2947 if (CONSP (val))
2948 val = XCDR (val);
2950 else if (!NILP (Vcoding_system_for_write))
2951 val = Vcoding_system_for_write;
2952 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2953 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2954 val = Qnil;
2955 pset_encode_coding_system (p, val);
2957 setup_process_coding_systems (proc);
2958 pset_decoding_buf (p, empty_unibyte_string);
2959 p->decoding_carryover = 0;
2960 pset_encoding_buf (p, empty_unibyte_string);
2961 p->inherit_coding_system_flag
2962 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2964 Fserial_process_configure (nargs, args);
2966 specpdl_ptr = specpdl + specpdl_count;
2968 UNGCPRO;
2969 return proc;
2972 /* Create a network stream/datagram client/server process. Treated
2973 exactly like a normal process when reading and writing. Primary
2974 differences are in status display and process deletion. A network
2975 connection has no PID; you cannot signal it. All you can do is
2976 stop/continue it and deactivate/close it via delete-process. */
2978 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2979 0, MANY, 0,
2980 doc: /* Create and return a network server or client process.
2982 In Emacs, network connections are represented by process objects, so
2983 input and output work as for subprocesses and `delete-process' closes
2984 a network connection. However, a network process has no process id,
2985 it cannot be signaled, and the status codes are different from normal
2986 processes.
2988 Arguments are specified as keyword/argument pairs. The following
2989 arguments are defined:
2991 :name NAME -- NAME is name for process. It is modified if necessary
2992 to make it unique.
2994 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2995 with the process. Process output goes at end of that buffer, unless
2996 you specify an output stream or filter function to handle the output.
2997 BUFFER may be also nil, meaning that this process is not associated
2998 with any buffer.
3000 :host HOST -- HOST is name of the host to connect to, or its IP
3001 address. The symbol `local' specifies the local host. If specified
3002 for a server process, it must be a valid name or address for the local
3003 host, and only clients connecting to that address will be accepted.
3005 :service SERVICE -- SERVICE is name of the service desired, or an
3006 integer specifying a port number to connect to. If SERVICE is t,
3007 a random port number is selected for the server. (If Emacs was
3008 compiled with getaddrinfo, a port number can also be specified as a
3009 string, e.g. "80", as well as an integer. This is not portable.)
3011 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3012 stream type connection, `datagram' creates a datagram type connection,
3013 `seqpacket' creates a reliable datagram connection.
3015 :family FAMILY -- FAMILY is the address (and protocol) family for the
3016 service specified by HOST and SERVICE. The default (nil) is to use
3017 whatever address family (IPv4 or IPv6) that is defined for the host
3018 and port number specified by HOST and SERVICE. Other address families
3019 supported are:
3020 local -- for a local (i.e. UNIX) address specified by SERVICE.
3021 ipv4 -- use IPv4 address family only.
3022 ipv6 -- use IPv6 address family only.
3024 :local ADDRESS -- ADDRESS is the local address used for the connection.
3025 This parameter is ignored when opening a client process. When specified
3026 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3028 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3029 connection. This parameter is ignored when opening a stream server
3030 process. For a datagram server process, it specifies the initial
3031 setting of the remote datagram address. When specified for a client
3032 process, the FAMILY, HOST, and SERVICE args are ignored.
3034 The format of ADDRESS depends on the address family:
3035 - An IPv4 address is represented as an vector of integers [A B C D P]
3036 corresponding to numeric IP address A.B.C.D and port number P.
3037 - A local address is represented as a string with the address in the
3038 local address space.
3039 - An "unsupported family" address is represented by a cons (F . AV)
3040 where F is the family number and AV is a vector containing the socket
3041 address data with one element per address data byte. Do not rely on
3042 this format in portable code, as it may depend on implementation
3043 defined constants, data sizes, and data structure alignment.
3045 :coding CODING -- If CODING is a symbol, it specifies the coding
3046 system used for both reading and writing for this process. If CODING
3047 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3048 ENCODING is used for writing.
3050 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3051 return without waiting for the connection to complete; instead, the
3052 sentinel function will be called with second arg matching "open" (if
3053 successful) or "failed" when the connect completes. Default is to use
3054 a blocking connect (i.e. wait) for stream type connections.
3056 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3057 running when Emacs is exited.
3059 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3060 In the stopped state, a server process does not accept new
3061 connections, and a client process does not handle incoming traffic.
3062 The stopped state is cleared by `continue-process' and set by
3063 `stop-process'.
3065 :filter FILTER -- Install FILTER as the process filter.
3067 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3068 process filter are multibyte, otherwise they are unibyte.
3069 If this keyword is not specified, the strings are multibyte if
3070 the default value of `enable-multibyte-characters' is non-nil.
3072 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3074 :log LOG -- Install LOG as the server process log function. This
3075 function is called when the server accepts a network connection from a
3076 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3077 is the server process, CLIENT is the new process for the connection,
3078 and MESSAGE is a string.
3080 :plist PLIST -- Install PLIST as the new process's initial plist.
3082 :server QLEN -- if QLEN is non-nil, create a server process for the
3083 specified FAMILY, SERVICE, and connection type (stream or datagram).
3084 If QLEN is an integer, it is used as the max. length of the server's
3085 pending connection queue (also known as the backlog); the default
3086 queue length is 5. Default is to create a client process.
3088 The following network options can be specified for this connection:
3090 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3091 :dontroute BOOL -- Only send to directly connected hosts.
3092 :keepalive BOOL -- Send keep-alive messages on network stream.
3093 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3094 :oobinline BOOL -- Place out-of-band data in receive data stream.
3095 :priority INT -- Set protocol defined priority for sent packets.
3096 :reuseaddr BOOL -- Allow reusing a recently used local address
3097 (this is allowed by default for a server process).
3098 :bindtodevice NAME -- bind to interface NAME. Using this may require
3099 special privileges on some systems.
3101 Consult the relevant system programmer's manual pages for more
3102 information on using these options.
3105 A server process will listen for and accept connections from clients.
3106 When a client connection is accepted, a new network process is created
3107 for the connection with the following parameters:
3109 - The client's process name is constructed by concatenating the server
3110 process's NAME and a client identification string.
3111 - If the FILTER argument is non-nil, the client process will not get a
3112 separate process buffer; otherwise, the client's process buffer is a newly
3113 created buffer named after the server process's BUFFER name or process
3114 NAME concatenated with the client identification string.
3115 - The connection type and the process filter and sentinel parameters are
3116 inherited from the server process's TYPE, FILTER and SENTINEL.
3117 - The client process's contact info is set according to the client's
3118 addressing information (typically an IP address and a port number).
3119 - The client process's plist is initialized from the server's plist.
3121 Notice that the FILTER and SENTINEL args are never used directly by
3122 the server process. Also, the BUFFER argument is not used directly by
3123 the server process, but via the optional :log function, accepted (and
3124 failed) connections may be logged in the server process's buffer.
3126 The original argument list, modified with the actual connection
3127 information, is available via the `process-contact' function.
3129 usage: (make-network-process &rest ARGS) */)
3130 (ptrdiff_t nargs, Lisp_Object *args)
3132 Lisp_Object proc;
3133 Lisp_Object contact;
3134 struct Lisp_Process *p;
3135 #ifdef HAVE_GETADDRINFO
3136 struct addrinfo ai, *res, *lres;
3137 struct addrinfo hints;
3138 const char *portstring;
3139 char portbuf[128];
3140 #else /* HAVE_GETADDRINFO */
3141 struct _emacs_addrinfo
3143 int ai_family;
3144 int ai_socktype;
3145 int ai_protocol;
3146 int ai_addrlen;
3147 struct sockaddr *ai_addr;
3148 struct _emacs_addrinfo *ai_next;
3149 } ai, *res, *lres;
3150 #endif /* HAVE_GETADDRINFO */
3151 struct sockaddr_in address_in;
3152 #ifdef HAVE_LOCAL_SOCKETS
3153 struct sockaddr_un address_un;
3154 #endif
3155 int port;
3156 int ret = 0;
3157 int xerrno = 0;
3158 int s = -1, outch, inch;
3159 struct gcpro gcpro1;
3160 ptrdiff_t count = SPECPDL_INDEX ();
3161 ptrdiff_t count1;
3162 Lisp_Object colon_address; /* Either QClocal or QCremote. */
3163 Lisp_Object tem;
3164 Lisp_Object name, buffer, host, service, address;
3165 Lisp_Object filter, sentinel;
3166 bool is_non_blocking_client = 0;
3167 bool is_server = 0;
3168 int backlog = 5;
3169 int socktype;
3170 int family = -1;
3172 if (nargs == 0)
3173 return Qnil;
3175 /* Save arguments for process-contact and clone-process. */
3176 contact = Flist (nargs, args);
3177 GCPRO1 (contact);
3179 #ifdef WINDOWSNT
3180 /* Ensure socket support is loaded if available. */
3181 init_winsock (TRUE);
3182 #endif
3184 /* :type TYPE (nil: stream, datagram */
3185 tem = Fplist_get (contact, QCtype);
3186 if (NILP (tem))
3187 socktype = SOCK_STREAM;
3188 #ifdef DATAGRAM_SOCKETS
3189 else if (EQ (tem, Qdatagram))
3190 socktype = SOCK_DGRAM;
3191 #endif
3192 #ifdef HAVE_SEQPACKET
3193 else if (EQ (tem, Qseqpacket))
3194 socktype = SOCK_SEQPACKET;
3195 #endif
3196 else
3197 error ("Unsupported connection type");
3199 /* :server BOOL */
3200 tem = Fplist_get (contact, QCserver);
3201 if (!NILP (tem))
3203 /* Don't support network sockets when non-blocking mode is
3204 not available, since a blocked Emacs is not useful. */
3205 is_server = 1;
3206 if (TYPE_RANGED_INTEGERP (int, tem))
3207 backlog = XINT (tem);
3210 /* Make colon_address an alias for :local (server) or :remote (client). */
3211 colon_address = is_server ? QClocal : QCremote;
3213 /* :nowait BOOL */
3214 if (!is_server && socktype != SOCK_DGRAM
3215 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3217 #ifndef NON_BLOCKING_CONNECT
3218 error ("Non-blocking connect not supported");
3219 #else
3220 is_non_blocking_client = 1;
3221 #endif
3224 name = Fplist_get (contact, QCname);
3225 buffer = Fplist_get (contact, QCbuffer);
3226 filter = Fplist_get (contact, QCfilter);
3227 sentinel = Fplist_get (contact, QCsentinel);
3229 CHECK_STRING (name);
3231 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3232 ai.ai_socktype = socktype;
3233 ai.ai_protocol = 0;
3234 ai.ai_next = NULL;
3235 res = &ai;
3237 /* :local ADDRESS or :remote ADDRESS */
3238 address = Fplist_get (contact, colon_address);
3239 if (!NILP (address))
3241 host = service = Qnil;
3243 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3244 error ("Malformed :address");
3245 ai.ai_family = family;
3246 ai.ai_addr = alloca (ai.ai_addrlen);
3247 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3248 goto open_socket;
3251 /* :family FAMILY -- nil (for Inet), local, or integer. */
3252 tem = Fplist_get (contact, QCfamily);
3253 if (NILP (tem))
3255 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3256 family = AF_UNSPEC;
3257 #else
3258 family = AF_INET;
3259 #endif
3261 #ifdef HAVE_LOCAL_SOCKETS
3262 else if (EQ (tem, Qlocal))
3263 family = AF_LOCAL;
3264 #endif
3265 #ifdef AF_INET6
3266 else if (EQ (tem, Qipv6))
3267 family = AF_INET6;
3268 #endif
3269 else if (EQ (tem, Qipv4))
3270 family = AF_INET;
3271 else if (TYPE_RANGED_INTEGERP (int, tem))
3272 family = XINT (tem);
3273 else
3274 error ("Unknown address family");
3276 ai.ai_family = family;
3278 /* :service SERVICE -- string, integer (port number), or t (random port). */
3279 service = Fplist_get (contact, QCservice);
3281 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3282 host = Fplist_get (contact, QChost);
3283 if (!NILP (host))
3285 if (EQ (host, Qlocal))
3286 /* Depending on setup, "localhost" may map to different IPv4 and/or
3287 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3288 host = build_string ("127.0.0.1");
3289 CHECK_STRING (host);
3292 #ifdef HAVE_LOCAL_SOCKETS
3293 if (family == AF_LOCAL)
3295 if (!NILP (host))
3297 message (":family local ignores the :host property");
3298 contact = Fplist_put (contact, QChost, Qnil);
3299 host = Qnil;
3301 CHECK_STRING (service);
3302 memset (&address_un, 0, sizeof address_un);
3303 address_un.sun_family = AF_LOCAL;
3304 if (sizeof address_un.sun_path <= SBYTES (service))
3305 error ("Service name too long");
3306 lispstpcpy (address_un.sun_path, service);
3307 ai.ai_addr = (struct sockaddr *) &address_un;
3308 ai.ai_addrlen = sizeof address_un;
3309 goto open_socket;
3311 #endif
3313 /* Slow down polling to every ten seconds.
3314 Some kernels have a bug which causes retrying connect to fail
3315 after a connect. Polling can interfere with gethostbyname too. */
3316 #ifdef POLL_FOR_INPUT
3317 if (socktype != SOCK_DGRAM)
3319 record_unwind_protect_void (run_all_atimers);
3320 bind_polling_period (10);
3322 #endif
3324 #ifdef HAVE_GETADDRINFO
3325 /* If we have a host, use getaddrinfo to resolve both host and service.
3326 Otherwise, use getservbyname to lookup the service. */
3327 if (!NILP (host))
3330 /* SERVICE can either be a string or int.
3331 Convert to a C string for later use by getaddrinfo. */
3332 if (EQ (service, Qt))
3333 portstring = "0";
3334 else if (INTEGERP (service))
3336 sprintf (portbuf, "%"pI"d", XINT (service));
3337 portstring = portbuf;
3339 else
3341 CHECK_STRING (service);
3342 portstring = SSDATA (service);
3345 immediate_quit = 1;
3346 QUIT;
3347 memset (&hints, 0, sizeof (hints));
3348 hints.ai_flags = 0;
3349 hints.ai_family = family;
3350 hints.ai_socktype = socktype;
3351 hints.ai_protocol = 0;
3353 #ifdef HAVE_RES_INIT
3354 res_init ();
3355 #endif
3357 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3358 if (ret)
3359 #ifdef HAVE_GAI_STRERROR
3360 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3361 #else
3362 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3363 #endif
3364 immediate_quit = 0;
3366 goto open_socket;
3368 #endif /* HAVE_GETADDRINFO */
3370 /* We end up here if getaddrinfo is not defined, or in case no hostname
3371 has been specified (e.g. for a local server process). */
3373 if (EQ (service, Qt))
3374 port = 0;
3375 else if (INTEGERP (service))
3376 port = htons ((unsigned short) XINT (service));
3377 else
3379 struct servent *svc_info;
3380 CHECK_STRING (service);
3381 svc_info = getservbyname (SSDATA (service),
3382 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3383 if (svc_info == 0)
3384 error ("Unknown service: %s", SDATA (service));
3385 port = svc_info->s_port;
3388 memset (&address_in, 0, sizeof address_in);
3389 address_in.sin_family = family;
3390 address_in.sin_addr.s_addr = INADDR_ANY;
3391 address_in.sin_port = port;
3393 #ifndef HAVE_GETADDRINFO
3394 if (!NILP (host))
3396 struct hostent *host_info_ptr;
3398 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3399 as it may `hang' Emacs for a very long time. */
3400 immediate_quit = 1;
3401 QUIT;
3403 #ifdef HAVE_RES_INIT
3404 res_init ();
3405 #endif
3407 host_info_ptr = gethostbyname (SDATA (host));
3408 immediate_quit = 0;
3410 if (host_info_ptr)
3412 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3413 host_info_ptr->h_length);
3414 family = host_info_ptr->h_addrtype;
3415 address_in.sin_family = family;
3417 else
3418 /* Attempt to interpret host as numeric inet address. */
3420 unsigned long numeric_addr;
3421 numeric_addr = inet_addr (SSDATA (host));
3422 if (numeric_addr == -1)
3423 error ("Unknown host \"%s\"", SDATA (host));
3425 memcpy (&address_in.sin_addr, &numeric_addr,
3426 sizeof (address_in.sin_addr));
3430 #endif /* not HAVE_GETADDRINFO */
3432 ai.ai_family = family;
3433 ai.ai_addr = (struct sockaddr *) &address_in;
3434 ai.ai_addrlen = sizeof address_in;
3436 open_socket:
3438 /* Do this in case we never enter the for-loop below. */
3439 count1 = SPECPDL_INDEX ();
3440 s = -1;
3442 for (lres = res; lres; lres = lres->ai_next)
3444 ptrdiff_t optn;
3445 int optbits;
3447 #ifdef WINDOWSNT
3448 retry_connect:
3449 #endif
3451 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3452 lres->ai_protocol);
3453 if (s < 0)
3455 xerrno = errno;
3456 continue;
3459 #ifdef DATAGRAM_SOCKETS
3460 if (!is_server && socktype == SOCK_DGRAM)
3461 break;
3462 #endif /* DATAGRAM_SOCKETS */
3464 #ifdef NON_BLOCKING_CONNECT
3465 if (is_non_blocking_client)
3467 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3468 if (ret < 0)
3470 xerrno = errno;
3471 emacs_close (s);
3472 s = -1;
3473 continue;
3476 #endif
3478 /* Make us close S if quit. */
3479 record_unwind_protect_int (close_file_unwind, s);
3481 /* Parse network options in the arg list.
3482 We simply ignore anything which isn't a known option (including other keywords).
3483 An error is signaled if setting a known option fails. */
3484 for (optn = optbits = 0; optn < nargs - 1; optn += 2)
3485 optbits |= set_socket_option (s, args[optn], args[optn + 1]);
3487 if (is_server)
3489 /* Configure as a server socket. */
3491 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3492 explicit :reuseaddr key to override this. */
3493 #ifdef HAVE_LOCAL_SOCKETS
3494 if (family != AF_LOCAL)
3495 #endif
3496 if (!(optbits & (1 << OPIX_REUSEADDR)))
3498 int optval = 1;
3499 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3500 report_file_error ("Cannot set reuse option on server socket", Qnil);
3503 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3504 report_file_error ("Cannot bind server socket", Qnil);
3506 #ifdef HAVE_GETSOCKNAME
3507 if (EQ (service, Qt))
3509 struct sockaddr_in sa1;
3510 socklen_t len1 = sizeof (sa1);
3511 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3513 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3514 service = make_number (ntohs (sa1.sin_port));
3515 contact = Fplist_put (contact, QCservice, service);
3518 #endif
3520 if (socktype != SOCK_DGRAM && listen (s, backlog))
3521 report_file_error ("Cannot listen on server socket", Qnil);
3523 break;
3526 immediate_quit = 1;
3527 QUIT;
3529 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3530 xerrno = errno;
3532 if (ret == 0 || xerrno == EISCONN)
3534 /* The unwind-protect will be discarded afterwards.
3535 Likewise for immediate_quit. */
3536 break;
3539 #ifdef NON_BLOCKING_CONNECT
3540 #ifdef EINPROGRESS
3541 if (is_non_blocking_client && xerrno == EINPROGRESS)
3542 break;
3543 #else
3544 #ifdef EWOULDBLOCK
3545 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3546 break;
3547 #endif
3548 #endif
3549 #endif
3551 #ifndef WINDOWSNT
3552 if (xerrno == EINTR)
3554 /* Unlike most other syscalls connect() cannot be called
3555 again. (That would return EALREADY.) The proper way to
3556 wait for completion is pselect(). */
3557 int sc;
3558 socklen_t len;
3559 fd_set fdset;
3560 retry_select:
3561 FD_ZERO (&fdset);
3562 FD_SET (s, &fdset);
3563 QUIT;
3564 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3565 if (sc == -1)
3567 if (errno == EINTR)
3568 goto retry_select;
3569 else
3570 report_file_error ("Failed select", Qnil);
3572 eassert (sc > 0);
3574 len = sizeof xerrno;
3575 eassert (FD_ISSET (s, &fdset));
3576 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3577 report_file_error ("Failed getsockopt", Qnil);
3578 if (xerrno)
3579 report_file_errno ("Failed connect", Qnil, xerrno);
3580 break;
3582 #endif /* !WINDOWSNT */
3584 immediate_quit = 0;
3586 /* Discard the unwind protect closing S. */
3587 specpdl_ptr = specpdl + count1;
3588 emacs_close (s);
3589 s = -1;
3591 #ifdef WINDOWSNT
3592 if (xerrno == EINTR)
3593 goto retry_connect;
3594 #endif
3597 if (s >= 0)
3599 #ifdef DATAGRAM_SOCKETS
3600 if (socktype == SOCK_DGRAM)
3602 if (datagram_address[s].sa)
3603 emacs_abort ();
3604 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3605 datagram_address[s].len = lres->ai_addrlen;
3606 if (is_server)
3608 Lisp_Object remote;
3609 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3610 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3612 int rfamily, rlen;
3613 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3614 if (rlen != 0 && rfamily == lres->ai_family
3615 && rlen == lres->ai_addrlen)
3616 conv_lisp_to_sockaddr (rfamily, remote,
3617 datagram_address[s].sa, rlen);
3620 else
3621 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3623 #endif
3624 contact = Fplist_put (contact, colon_address,
3625 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3626 #ifdef HAVE_GETSOCKNAME
3627 if (!is_server)
3629 struct sockaddr_in sa1;
3630 socklen_t len1 = sizeof (sa1);
3631 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3632 contact = Fplist_put (contact, QClocal,
3633 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3635 #endif
3638 immediate_quit = 0;
3640 #ifdef HAVE_GETADDRINFO
3641 if (res != &ai)
3643 block_input ();
3644 freeaddrinfo (res);
3645 unblock_input ();
3647 #endif
3649 if (s < 0)
3651 /* If non-blocking got this far - and failed - assume non-blocking is
3652 not supported after all. This is probably a wrong assumption, but
3653 the normal blocking calls to open-network-stream handles this error
3654 better. */
3655 if (is_non_blocking_client)
3656 return Qnil;
3658 report_file_errno ((is_server
3659 ? "make server process failed"
3660 : "make client process failed"),
3661 contact, xerrno);
3664 inch = s;
3665 outch = s;
3667 if (!NILP (buffer))
3668 buffer = Fget_buffer_create (buffer);
3669 proc = make_process (name);
3671 chan_process[inch] = proc;
3673 fcntl (inch, F_SETFL, O_NONBLOCK);
3675 p = XPROCESS (proc);
3677 pset_childp (p, contact);
3678 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3679 pset_type (p, Qnetwork);
3681 pset_buffer (p, buffer);
3682 pset_sentinel (p, sentinel);
3683 pset_filter (p, filter);
3684 pset_log (p, Fplist_get (contact, QClog));
3685 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3686 p->kill_without_query = 1;
3687 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3688 pset_command (p, Qt);
3689 p->pid = 0;
3691 p->open_fd[SUBPROCESS_STDIN] = inch;
3692 p->infd = inch;
3693 p->outfd = outch;
3695 /* Discard the unwind protect for closing S, if any. */
3696 specpdl_ptr = specpdl + count1;
3698 /* Unwind bind_polling_period and request_sigio. */
3699 unbind_to (count, Qnil);
3701 if (is_server && socktype != SOCK_DGRAM)
3702 pset_status (p, Qlisten);
3704 /* Make the process marker point into the process buffer (if any). */
3705 if (BUFFERP (buffer))
3706 set_marker_both (p->mark, buffer,
3707 BUF_ZV (XBUFFER (buffer)),
3708 BUF_ZV_BYTE (XBUFFER (buffer)));
3710 #ifdef NON_BLOCKING_CONNECT
3711 if (is_non_blocking_client)
3713 /* We may get here if connect did succeed immediately. However,
3714 in that case, we still need to signal this like a non-blocking
3715 connection. */
3716 pset_status (p, Qconnect);
3717 if (!FD_ISSET (inch, &connect_wait_mask))
3719 FD_SET (inch, &connect_wait_mask);
3720 FD_SET (inch, &write_mask);
3721 num_pending_connects++;
3724 else
3725 #endif
3726 /* A server may have a client filter setting of Qt, but it must
3727 still listen for incoming connects unless it is stopped. */
3728 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3729 || (EQ (p->status, Qlisten) && NILP (p->command)))
3731 FD_SET (inch, &input_wait_mask);
3732 FD_SET (inch, &non_keyboard_wait_mask);
3735 if (inch > max_process_desc)
3736 max_process_desc = inch;
3738 tem = Fplist_member (contact, QCcoding);
3739 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3740 tem = Qnil; /* No error message (too late!). */
3743 /* Setup coding systems for communicating with the network stream. */
3744 struct gcpro gcpro1;
3745 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3746 Lisp_Object coding_systems = Qt;
3747 Lisp_Object val;
3749 if (!NILP (tem))
3751 val = XCAR (XCDR (tem));
3752 if (CONSP (val))
3753 val = XCAR (val);
3755 else if (!NILP (Vcoding_system_for_read))
3756 val = Vcoding_system_for_read;
3757 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3758 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3759 /* We dare not decode end-of-line format by setting VAL to
3760 Qraw_text, because the existing Emacs Lisp libraries
3761 assume that they receive bare code including a sequence of
3762 CR LF. */
3763 val = Qnil;
3764 else
3766 if (NILP (host) || NILP (service))
3767 coding_systems = Qnil;
3768 else
3770 GCPRO1 (proc);
3771 coding_systems = CALLN (Ffind_operation_coding_system,
3772 Qopen_network_stream, name, buffer,
3773 host, service);
3774 UNGCPRO;
3776 if (CONSP (coding_systems))
3777 val = XCAR (coding_systems);
3778 else if (CONSP (Vdefault_process_coding_system))
3779 val = XCAR (Vdefault_process_coding_system);
3780 else
3781 val = Qnil;
3783 pset_decode_coding_system (p, val);
3785 if (!NILP (tem))
3787 val = XCAR (XCDR (tem));
3788 if (CONSP (val))
3789 val = XCDR (val);
3791 else if (!NILP (Vcoding_system_for_write))
3792 val = Vcoding_system_for_write;
3793 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3794 val = Qnil;
3795 else
3797 if (EQ (coding_systems, Qt))
3799 if (NILP (host) || NILP (service))
3800 coding_systems = Qnil;
3801 else
3803 GCPRO1 (proc);
3804 coding_systems = CALLN (Ffind_operation_coding_system,
3805 Qopen_network_stream, name, buffer,
3806 host, service);
3807 UNGCPRO;
3810 if (CONSP (coding_systems))
3811 val = XCDR (coding_systems);
3812 else if (CONSP (Vdefault_process_coding_system))
3813 val = XCDR (Vdefault_process_coding_system);
3814 else
3815 val = Qnil;
3817 pset_encode_coding_system (p, val);
3819 setup_process_coding_systems (proc);
3821 pset_decoding_buf (p, empty_unibyte_string);
3822 p->decoding_carryover = 0;
3823 pset_encoding_buf (p, empty_unibyte_string);
3825 p->inherit_coding_system_flag
3826 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3828 UNGCPRO;
3829 return proc;
3833 #ifdef HAVE_NET_IF_H
3835 #ifdef SIOCGIFCONF
3836 static Lisp_Object
3837 network_interface_list (void)
3839 struct ifconf ifconf;
3840 struct ifreq *ifreq;
3841 void *buf = NULL;
3842 ptrdiff_t buf_size = 512;
3843 int s;
3844 Lisp_Object res;
3845 ptrdiff_t count;
3847 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3848 if (s < 0)
3849 return Qnil;
3850 count = SPECPDL_INDEX ();
3851 record_unwind_protect_int (close_file_unwind, s);
3855 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3856 ifconf.ifc_buf = buf;
3857 ifconf.ifc_len = buf_size;
3858 if (ioctl (s, SIOCGIFCONF, &ifconf))
3860 emacs_close (s);
3861 xfree (buf);
3862 return Qnil;
3865 while (ifconf.ifc_len == buf_size);
3867 res = unbind_to (count, Qnil);
3868 ifreq = ifconf.ifc_req;
3869 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3871 struct ifreq *ifq = ifreq;
3872 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3873 #define SIZEOF_IFREQ(sif) \
3874 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3875 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3877 int len = SIZEOF_IFREQ (ifq);
3878 #else
3879 int len = sizeof (*ifreq);
3880 #endif
3881 char namebuf[sizeof (ifq->ifr_name) + 1];
3882 ifreq = (struct ifreq *) ((char *) ifreq + len);
3884 if (ifq->ifr_addr.sa_family != AF_INET)
3885 continue;
3887 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3888 namebuf[sizeof (ifq->ifr_name)] = 0;
3889 res = Fcons (Fcons (build_string (namebuf),
3890 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3891 sizeof (struct sockaddr))),
3892 res);
3895 xfree (buf);
3896 return res;
3898 #endif /* SIOCGIFCONF */
3900 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3902 struct ifflag_def {
3903 int flag_bit;
3904 const char *flag_sym;
3907 static const struct ifflag_def ifflag_table[] = {
3908 #ifdef IFF_UP
3909 { IFF_UP, "up" },
3910 #endif
3911 #ifdef IFF_BROADCAST
3912 { IFF_BROADCAST, "broadcast" },
3913 #endif
3914 #ifdef IFF_DEBUG
3915 { IFF_DEBUG, "debug" },
3916 #endif
3917 #ifdef IFF_LOOPBACK
3918 { IFF_LOOPBACK, "loopback" },
3919 #endif
3920 #ifdef IFF_POINTOPOINT
3921 { IFF_POINTOPOINT, "pointopoint" },
3922 #endif
3923 #ifdef IFF_RUNNING
3924 { IFF_RUNNING, "running" },
3925 #endif
3926 #ifdef IFF_NOARP
3927 { IFF_NOARP, "noarp" },
3928 #endif
3929 #ifdef IFF_PROMISC
3930 { IFF_PROMISC, "promisc" },
3931 #endif
3932 #ifdef IFF_NOTRAILERS
3933 #ifdef NS_IMPL_COCOA
3934 /* Really means smart, notrailers is obsolete. */
3935 { IFF_NOTRAILERS, "smart" },
3936 #else
3937 { IFF_NOTRAILERS, "notrailers" },
3938 #endif
3939 #endif
3940 #ifdef IFF_ALLMULTI
3941 { IFF_ALLMULTI, "allmulti" },
3942 #endif
3943 #ifdef IFF_MASTER
3944 { IFF_MASTER, "master" },
3945 #endif
3946 #ifdef IFF_SLAVE
3947 { IFF_SLAVE, "slave" },
3948 #endif
3949 #ifdef IFF_MULTICAST
3950 { IFF_MULTICAST, "multicast" },
3951 #endif
3952 #ifdef IFF_PORTSEL
3953 { IFF_PORTSEL, "portsel" },
3954 #endif
3955 #ifdef IFF_AUTOMEDIA
3956 { IFF_AUTOMEDIA, "automedia" },
3957 #endif
3958 #ifdef IFF_DYNAMIC
3959 { IFF_DYNAMIC, "dynamic" },
3960 #endif
3961 #ifdef IFF_OACTIVE
3962 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
3963 #endif
3964 #ifdef IFF_SIMPLEX
3965 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
3966 #endif
3967 #ifdef IFF_LINK0
3968 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
3969 #endif
3970 #ifdef IFF_LINK1
3971 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
3972 #endif
3973 #ifdef IFF_LINK2
3974 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
3975 #endif
3976 { 0, 0 }
3979 static Lisp_Object
3980 network_interface_info (Lisp_Object ifname)
3982 struct ifreq rq;
3983 Lisp_Object res = Qnil;
3984 Lisp_Object elt;
3985 int s;
3986 bool any = 0;
3987 ptrdiff_t count;
3988 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3989 && defined HAVE_GETIFADDRS && defined LLADDR)
3990 struct ifaddrs *ifap;
3991 #endif
3993 CHECK_STRING (ifname);
3995 if (sizeof rq.ifr_name <= SBYTES (ifname))
3996 error ("interface name too long");
3997 lispstpcpy (rq.ifr_name, ifname);
3999 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4000 if (s < 0)
4001 return Qnil;
4002 count = SPECPDL_INDEX ();
4003 record_unwind_protect_int (close_file_unwind, s);
4005 elt = Qnil;
4006 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4007 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4009 int flags = rq.ifr_flags;
4010 const struct ifflag_def *fp;
4011 int fnum;
4013 /* If flags is smaller than int (i.e. short) it may have the high bit set
4014 due to IFF_MULTICAST. In that case, sign extending it into
4015 an int is wrong. */
4016 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
4017 flags = (unsigned short) rq.ifr_flags;
4019 any = 1;
4020 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4022 if (flags & fp->flag_bit)
4024 elt = Fcons (intern (fp->flag_sym), elt);
4025 flags -= fp->flag_bit;
4028 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
4030 if (flags & 1)
4032 elt = Fcons (make_number (fnum), elt);
4036 #endif
4037 res = Fcons (elt, res);
4039 elt = Qnil;
4040 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4041 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4043 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4044 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4045 int n;
4047 any = 1;
4048 for (n = 0; n < 6; n++)
4049 p->contents[n] = make_number (((unsigned char *)
4050 &rq.ifr_hwaddr.sa_data[0])
4051 [n]);
4052 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4054 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4055 if (getifaddrs (&ifap) != -1)
4057 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4058 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4059 struct ifaddrs *it;
4061 for (it = ifap; it != NULL; it = it->ifa_next)
4063 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
4064 unsigned char linkaddr[6];
4065 int n;
4067 if (it->ifa_addr->sa_family != AF_LINK
4068 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4069 || sdl->sdl_alen != 6)
4070 continue;
4072 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4073 for (n = 0; n < 6; n++)
4074 p->contents[n] = make_number (linkaddr[n]);
4076 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4077 break;
4080 #ifdef HAVE_FREEIFADDRS
4081 freeifaddrs (ifap);
4082 #endif
4084 #endif /* HAVE_GETIFADDRS && LLADDR */
4086 res = Fcons (elt, res);
4088 elt = Qnil;
4089 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4090 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4092 any = 1;
4093 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4094 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4095 #else
4096 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4097 #endif
4099 #endif
4100 res = Fcons (elt, res);
4102 elt = Qnil;
4103 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4104 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4106 any = 1;
4107 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4109 #endif
4110 res = Fcons (elt, res);
4112 elt = Qnil;
4113 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4114 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4116 any = 1;
4117 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4119 #endif
4120 res = Fcons (elt, res);
4122 return unbind_to (count, any ? res : Qnil);
4124 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4125 #endif /* defined (HAVE_NET_IF_H) */
4127 DEFUN ("network-interface-list", Fnetwork_interface_list,
4128 Snetwork_interface_list, 0, 0, 0,
4129 doc: /* Return an alist of all network interfaces and their network address.
4130 Each element is a cons, the car of which is a string containing the
4131 interface name, and the cdr is the network address in internal
4132 format; see the description of ADDRESS in `make-network-process'.
4134 If the information is not available, return nil. */)
4135 (void)
4137 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4138 return network_interface_list ();
4139 #else
4140 return Qnil;
4141 #endif
4144 DEFUN ("network-interface-info", Fnetwork_interface_info,
4145 Snetwork_interface_info, 1, 1, 0,
4146 doc: /* Return information about network interface named IFNAME.
4147 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4148 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4149 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4150 FLAGS is the current flags of the interface.
4152 Data that is unavailable is returned as nil. */)
4153 (Lisp_Object ifname)
4155 #if ((defined HAVE_NET_IF_H \
4156 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4157 || defined SIOCGIFFLAGS)) \
4158 || defined WINDOWSNT)
4159 return network_interface_info (ifname);
4160 #else
4161 return Qnil;
4162 #endif
4165 /* If program file NAME starts with /: for quoting a magic
4166 name, remove that, preserving the multibyteness of NAME. */
4168 Lisp_Object
4169 remove_slash_colon (Lisp_Object name)
4171 return
4172 ((SBYTES (name) > 2 && SREF (name, 0) == '/' && SREF (name, 1) == ':')
4173 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
4174 SBYTES (name) - 2, STRING_MULTIBYTE (name))
4175 : name);
4178 /* Turn off input and output for process PROC. */
4180 static void
4181 deactivate_process (Lisp_Object proc)
4183 int inchannel;
4184 struct Lisp_Process *p = XPROCESS (proc);
4185 int i;
4187 #ifdef HAVE_GNUTLS
4188 /* Delete GnuTLS structures in PROC, if any. */
4189 emacs_gnutls_deinit (proc);
4190 #endif /* HAVE_GNUTLS */
4192 #ifdef ADAPTIVE_READ_BUFFERING
4193 if (p->read_output_delay > 0)
4195 if (--process_output_delay_count < 0)
4196 process_output_delay_count = 0;
4197 p->read_output_delay = 0;
4198 p->read_output_skip = 0;
4200 #endif
4202 /* Beware SIGCHLD hereabouts. */
4204 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4205 close_process_fd (&p->open_fd[i]);
4207 inchannel = p->infd;
4208 if (inchannel >= 0)
4210 p->infd = -1;
4211 p->outfd = -1;
4212 #ifdef DATAGRAM_SOCKETS
4213 if (DATAGRAM_CHAN_P (inchannel))
4215 xfree (datagram_address[inchannel].sa);
4216 datagram_address[inchannel].sa = 0;
4217 datagram_address[inchannel].len = 0;
4219 #endif
4220 chan_process[inchannel] = Qnil;
4221 FD_CLR (inchannel, &input_wait_mask);
4222 FD_CLR (inchannel, &non_keyboard_wait_mask);
4223 #ifdef NON_BLOCKING_CONNECT
4224 if (FD_ISSET (inchannel, &connect_wait_mask))
4226 FD_CLR (inchannel, &connect_wait_mask);
4227 FD_CLR (inchannel, &write_mask);
4228 if (--num_pending_connects < 0)
4229 emacs_abort ();
4231 #endif
4232 if (inchannel == max_process_desc)
4234 /* We just closed the highest-numbered process input descriptor,
4235 so recompute the highest-numbered one now. */
4236 int i = inchannel;
4238 i--;
4239 while (0 <= i && NILP (chan_process[i]));
4241 max_process_desc = i;
4247 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4248 0, 4, 0,
4249 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4250 It is given to their filter functions.
4251 Optional argument PROCESS means do not return until output has been
4252 received from PROCESS.
4254 Optional second argument SECONDS and third argument MILLISEC
4255 specify a timeout; return after that much time even if there is
4256 no subprocess output. If SECONDS is a floating point number,
4257 it specifies a fractional number of seconds to wait.
4258 The MILLISEC argument is obsolete and should be avoided.
4260 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4261 from PROCESS only, suspending reading output from other processes.
4262 If JUST-THIS-ONE is an integer, don't run any timers either.
4263 Return non-nil if we received any output from PROCESS (or, if PROCESS
4264 is nil, from any process) before the timeout expired. */)
4265 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4267 intmax_t secs;
4268 int nsecs;
4270 if (! NILP (process))
4271 CHECK_PROCESS (process);
4272 else
4273 just_this_one = Qnil;
4275 if (!NILP (millisec))
4276 { /* Obsolete calling convention using integers rather than floats. */
4277 CHECK_NUMBER (millisec);
4278 if (NILP (seconds))
4279 seconds = make_float (XINT (millisec) / 1000.0);
4280 else
4282 CHECK_NUMBER (seconds);
4283 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4287 secs = 0;
4288 nsecs = -1;
4290 if (!NILP (seconds))
4292 if (INTEGERP (seconds))
4294 if (XINT (seconds) > 0)
4296 secs = XINT (seconds);
4297 nsecs = 0;
4300 else if (FLOATP (seconds))
4302 if (XFLOAT_DATA (seconds) > 0)
4304 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4305 secs = min (t.tv_sec, WAIT_READING_MAX);
4306 nsecs = t.tv_nsec;
4309 else
4310 wrong_type_argument (Qnumberp, seconds);
4312 else if (! NILP (process))
4313 nsecs = 0;
4315 return
4316 ((wait_reading_process_output (secs, nsecs, 0, 0,
4317 Qnil,
4318 !NILP (process) ? XPROCESS (process) : NULL,
4319 (NILP (just_this_one) ? 0
4320 : !INTEGERP (just_this_one) ? 1 : -1))
4321 <= 0)
4322 ? Qnil : Qt);
4325 /* Accept a connection for server process SERVER on CHANNEL. */
4327 static EMACS_INT connect_counter = 0;
4329 static void
4330 server_accept_connection (Lisp_Object server, int channel)
4332 Lisp_Object proc, caller, name, buffer;
4333 Lisp_Object contact, host, service;
4334 struct Lisp_Process *ps = XPROCESS (server);
4335 struct Lisp_Process *p;
4336 int s;
4337 union u_sockaddr {
4338 struct sockaddr sa;
4339 struct sockaddr_in in;
4340 #ifdef AF_INET6
4341 struct sockaddr_in6 in6;
4342 #endif
4343 #ifdef HAVE_LOCAL_SOCKETS
4344 struct sockaddr_un un;
4345 #endif
4346 } saddr;
4347 socklen_t len = sizeof saddr;
4348 ptrdiff_t count;
4350 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4352 if (s < 0)
4354 int code = errno;
4356 if (code == EAGAIN)
4357 return;
4358 #ifdef EWOULDBLOCK
4359 if (code == EWOULDBLOCK)
4360 return;
4361 #endif
4363 if (!NILP (ps->log))
4364 call3 (ps->log, server, Qnil,
4365 concat3 (build_string ("accept failed with code"),
4366 Fnumber_to_string (make_number (code)),
4367 build_string ("\n")));
4368 return;
4371 count = SPECPDL_INDEX ();
4372 record_unwind_protect_int (close_file_unwind, s);
4374 connect_counter++;
4376 /* Setup a new process to handle the connection. */
4378 /* Generate a unique identification of the caller, and build contact
4379 information for this process. */
4380 host = Qt;
4381 service = Qnil;
4382 switch (saddr.sa.sa_family)
4384 case AF_INET:
4386 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4388 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4389 host = CALLN (Fformat, ipv4_format,
4390 make_number (ip[0]), make_number (ip[1]),
4391 make_number (ip[2]), make_number (ip[3]));
4392 service = make_number (ntohs (saddr.in.sin_port));
4393 AUTO_STRING (caller_format, " <%s:%d>");
4394 caller = CALLN (Fformat, caller_format, host, service);
4396 break;
4398 #ifdef AF_INET6
4399 case AF_INET6:
4401 Lisp_Object args[9];
4402 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4403 int i;
4405 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4406 args[0] = ipv6_format;
4407 for (i = 0; i < 8; i++)
4408 args[i + 1] = make_number (ntohs (ip6[i]));
4409 host = CALLMANY (Fformat, args);
4410 service = make_number (ntohs (saddr.in.sin_port));
4411 AUTO_STRING (caller_format, " <[%s]:%d>");
4412 caller = CALLN (Fformat, caller_format, host, service);
4414 break;
4415 #endif
4417 #ifdef HAVE_LOCAL_SOCKETS
4418 case AF_LOCAL:
4419 #endif
4420 default:
4421 caller = Fnumber_to_string (make_number (connect_counter));
4422 AUTO_STRING (space_less_than, " <");
4423 AUTO_STRING (greater_than, ">");
4424 caller = concat3 (space_less_than, caller, greater_than);
4425 break;
4428 /* Create a new buffer name for this process if it doesn't have a
4429 filter. The new buffer name is based on the buffer name or
4430 process name of the server process concatenated with the caller
4431 identification. */
4433 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4434 || EQ (ps->filter, Qt)))
4435 buffer = Qnil;
4436 else
4438 buffer = ps->buffer;
4439 if (!NILP (buffer))
4440 buffer = Fbuffer_name (buffer);
4441 else
4442 buffer = ps->name;
4443 if (!NILP (buffer))
4445 buffer = concat2 (buffer, caller);
4446 buffer = Fget_buffer_create (buffer);
4450 /* Generate a unique name for the new server process. Combine the
4451 server process name with the caller identification. */
4453 name = concat2 (ps->name, caller);
4454 proc = make_process (name);
4456 chan_process[s] = proc;
4458 fcntl (s, F_SETFL, O_NONBLOCK);
4460 p = XPROCESS (proc);
4462 /* Build new contact information for this setup. */
4463 contact = Fcopy_sequence (ps->childp);
4464 contact = Fplist_put (contact, QCserver, Qnil);
4465 contact = Fplist_put (contact, QChost, host);
4466 if (!NILP (service))
4467 contact = Fplist_put (contact, QCservice, service);
4468 contact = Fplist_put (contact, QCremote,
4469 conv_sockaddr_to_lisp (&saddr.sa, len));
4470 #ifdef HAVE_GETSOCKNAME
4471 len = sizeof saddr;
4472 if (getsockname (s, &saddr.sa, &len) == 0)
4473 contact = Fplist_put (contact, QClocal,
4474 conv_sockaddr_to_lisp (&saddr.sa, len));
4475 #endif
4477 pset_childp (p, contact);
4478 pset_plist (p, Fcopy_sequence (ps->plist));
4479 pset_type (p, Qnetwork);
4481 pset_buffer (p, buffer);
4482 pset_sentinel (p, ps->sentinel);
4483 pset_filter (p, ps->filter);
4484 pset_command (p, Qnil);
4485 p->pid = 0;
4487 /* Discard the unwind protect for closing S. */
4488 specpdl_ptr = specpdl + count;
4490 p->open_fd[SUBPROCESS_STDIN] = s;
4491 p->infd = s;
4492 p->outfd = s;
4493 pset_status (p, Qrun);
4495 /* Client processes for accepted connections are not stopped initially. */
4496 if (!EQ (p->filter, Qt))
4498 FD_SET (s, &input_wait_mask);
4499 FD_SET (s, &non_keyboard_wait_mask);
4502 if (s > max_process_desc)
4503 max_process_desc = s;
4505 /* Setup coding system for new process based on server process.
4506 This seems to be the proper thing to do, as the coding system
4507 of the new process should reflect the settings at the time the
4508 server socket was opened; not the current settings. */
4510 pset_decode_coding_system (p, ps->decode_coding_system);
4511 pset_encode_coding_system (p, ps->encode_coding_system);
4512 setup_process_coding_systems (proc);
4514 pset_decoding_buf (p, empty_unibyte_string);
4515 p->decoding_carryover = 0;
4516 pset_encoding_buf (p, empty_unibyte_string);
4518 p->inherit_coding_system_flag
4519 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4521 AUTO_STRING (dash, "-");
4522 AUTO_STRING (nl, "\n");
4523 Lisp_Object host_string = STRINGP (host) ? host : dash;
4525 if (!NILP (ps->log))
4527 AUTO_STRING (accept_from, "accept from ");
4528 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4531 AUTO_STRING (open_from, "open from ");
4532 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4535 /* This variable is different from waiting_for_input in keyboard.c.
4536 It is used to communicate to a lisp process-filter/sentinel (via the
4537 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4538 for user-input when that process-filter was called.
4539 waiting_for_input cannot be used as that is by definition 0 when
4540 lisp code is being evalled.
4541 This is also used in record_asynch_buffer_change.
4542 For that purpose, this must be 0
4543 when not inside wait_reading_process_output. */
4544 static int waiting_for_user_input_p;
4546 static void
4547 wait_reading_process_output_unwind (int data)
4549 waiting_for_user_input_p = data;
4552 /* This is here so breakpoints can be put on it. */
4553 static void
4554 wait_reading_process_output_1 (void)
4558 /* Read and dispose of subprocess output while waiting for timeout to
4559 elapse and/or keyboard input to be available.
4561 TIME_LIMIT is:
4562 timeout in seconds
4563 If negative, gobble data immediately available but don't wait for any.
4565 NSECS is:
4566 an additional duration to wait, measured in nanoseconds
4567 If TIME_LIMIT is zero, then:
4568 If NSECS == 0, there is no limit.
4569 If NSECS > 0, the timeout consists of NSECS only.
4570 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4572 READ_KBD is:
4573 0 to ignore keyboard input, or
4574 1 to return when input is available, or
4575 -1 meaning caller will actually read the input, so don't throw to
4576 the quit handler, or
4578 DO_DISPLAY means redisplay should be done to show subprocess
4579 output that arrives.
4581 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4582 (and gobble terminal input into the buffer if any arrives).
4584 If WAIT_PROC is specified, wait until something arrives from that
4585 process.
4587 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4588 (suspending output from other processes). A negative value
4589 means don't run any timers either.
4591 Return positive if we received input from WAIT_PROC (or from any
4592 process if WAIT_PROC is null), zero if we attempted to receive
4593 input but got none, and negative if we didn't even try. */
4596 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4597 bool do_display,
4598 Lisp_Object wait_for_cell,
4599 struct Lisp_Process *wait_proc, int just_wait_proc)
4601 int channel, nfds;
4602 fd_set Available;
4603 fd_set Writeok;
4604 bool check_write;
4605 int check_delay;
4606 bool no_avail;
4607 int xerrno;
4608 Lisp_Object proc;
4609 struct timespec timeout, end_time;
4610 int got_some_input = -1;
4611 ptrdiff_t count = SPECPDL_INDEX ();
4613 FD_ZERO (&Available);
4614 FD_ZERO (&Writeok);
4616 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4617 && !(CONSP (wait_proc->status)
4618 && EQ (XCAR (wait_proc->status), Qexit)))
4619 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4621 record_unwind_protect_int (wait_reading_process_output_unwind,
4622 waiting_for_user_input_p);
4623 waiting_for_user_input_p = read_kbd;
4625 if (time_limit < 0)
4627 time_limit = 0;
4628 nsecs = -1;
4630 else if (TYPE_MAXIMUM (time_t) < time_limit)
4631 time_limit = TYPE_MAXIMUM (time_t);
4633 /* Since we may need to wait several times,
4634 compute the absolute time to return at. */
4635 if (time_limit || nsecs > 0)
4637 timeout = make_timespec (time_limit, nsecs);
4638 end_time = timespec_add (current_timespec (), timeout);
4641 while (1)
4643 bool timeout_reduced_for_timers = false;
4645 /* If calling from keyboard input, do not quit
4646 since we want to return C-g as an input character.
4647 Otherwise, do pending quit if requested. */
4648 if (read_kbd >= 0)
4649 QUIT;
4650 else if (pending_signals)
4651 process_pending_signals ();
4653 /* Exit now if the cell we're waiting for became non-nil. */
4654 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4655 break;
4657 /* After reading input, vacuum up any leftovers without waiting. */
4658 if (0 <= got_some_input)
4659 nsecs = -1;
4661 /* Compute time from now till when time limit is up. */
4662 /* Exit if already run out. */
4663 if (nsecs < 0)
4665 /* A negative timeout means
4666 gobble output available now
4667 but don't wait at all. */
4669 timeout = make_timespec (0, 0);
4671 else if (time_limit || nsecs > 0)
4673 struct timespec now = current_timespec ();
4674 if (timespec_cmp (end_time, now) <= 0)
4675 break;
4676 timeout = timespec_sub (end_time, now);
4678 else
4680 timeout = make_timespec (100000, 0);
4683 /* Normally we run timers here.
4684 But not if wait_for_cell; in those cases,
4685 the wait is supposed to be short,
4686 and those callers cannot handle running arbitrary Lisp code here. */
4687 if (NILP (wait_for_cell)
4688 && just_wait_proc >= 0)
4690 struct timespec timer_delay;
4694 unsigned old_timers_run = timers_run;
4695 struct buffer *old_buffer = current_buffer;
4696 Lisp_Object old_window = selected_window;
4698 timer_delay = timer_check ();
4700 /* If a timer has run, this might have changed buffers
4701 an alike. Make read_key_sequence aware of that. */
4702 if (timers_run != old_timers_run
4703 && (old_buffer != current_buffer
4704 || !EQ (old_window, selected_window))
4705 && waiting_for_user_input_p == -1)
4706 record_asynch_buffer_change ();
4708 if (timers_run != old_timers_run && do_display)
4709 /* We must retry, since a timer may have requeued itself
4710 and that could alter the time_delay. */
4711 redisplay_preserve_echo_area (9);
4712 else
4713 break;
4715 while (!detect_input_pending ());
4717 /* If there is unread keyboard input, also return. */
4718 if (read_kbd != 0
4719 && requeued_events_pending_p ())
4720 break;
4722 /* A negative timeout means do not wait at all. */
4723 if (nsecs >= 0)
4725 if (timespec_valid_p (timer_delay))
4727 if (timespec_cmp (timer_delay, timeout) < 0)
4729 timeout = timer_delay;
4730 timeout_reduced_for_timers = true;
4733 else
4735 /* This is so a breakpoint can be put here. */
4736 wait_reading_process_output_1 ();
4741 /* Cause C-g and alarm signals to take immediate action,
4742 and cause input available signals to zero out timeout.
4744 It is important that we do this before checking for process
4745 activity. If we get a SIGCHLD after the explicit checks for
4746 process activity, timeout is the only way we will know. */
4747 if (read_kbd < 0)
4748 set_waiting_for_input (&timeout);
4750 /* If status of something has changed, and no input is
4751 available, notify the user of the change right away. After
4752 this explicit check, we'll let the SIGCHLD handler zap
4753 timeout to get our attention. */
4754 if (update_tick != process_tick)
4756 fd_set Atemp;
4757 fd_set Ctemp;
4759 if (kbd_on_hold_p ())
4760 FD_ZERO (&Atemp);
4761 else
4762 Atemp = input_wait_mask;
4763 Ctemp = write_mask;
4765 timeout = make_timespec (0, 0);
4766 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4767 &Atemp,
4768 #ifdef NON_BLOCKING_CONNECT
4769 (num_pending_connects > 0 ? &Ctemp : NULL),
4770 #else
4771 NULL,
4772 #endif
4773 NULL, &timeout, NULL)
4774 <= 0))
4776 /* It's okay for us to do this and then continue with
4777 the loop, since timeout has already been zeroed out. */
4778 clear_waiting_for_input ();
4779 got_some_input = status_notify (NULL, wait_proc);
4780 if (do_display) redisplay_preserve_echo_area (13);
4784 /* Don't wait for output from a non-running process. Just
4785 read whatever data has already been received. */
4786 if (wait_proc && wait_proc->raw_status_new)
4787 update_status (wait_proc);
4788 if (wait_proc
4789 && ! EQ (wait_proc->status, Qrun)
4790 && ! EQ (wait_proc->status, Qconnect))
4792 bool read_some_bytes = false;
4794 clear_waiting_for_input ();
4796 /* If data can be read from the process, do so until exhausted. */
4797 if (wait_proc->infd >= 0)
4799 XSETPROCESS (proc, wait_proc);
4801 while (true)
4803 int nread = read_process_output (proc, wait_proc->infd);
4804 if (nread < 0)
4806 if (errno == EIO || errno == EAGAIN)
4807 break;
4808 #ifdef EWOULDBLOCK
4809 if (errno == EWOULDBLOCK)
4810 break;
4811 #endif
4813 else
4815 if (got_some_input < nread)
4816 got_some_input = nread;
4817 if (nread == 0)
4818 break;
4819 read_some_bytes = true;
4824 if (read_some_bytes && do_display)
4825 redisplay_preserve_echo_area (10);
4827 break;
4830 /* Wait till there is something to do. */
4832 if (wait_proc && just_wait_proc)
4834 if (wait_proc->infd < 0) /* Terminated. */
4835 break;
4836 FD_SET (wait_proc->infd, &Available);
4837 check_delay = 0;
4838 check_write = 0;
4840 else if (!NILP (wait_for_cell))
4842 Available = non_process_wait_mask;
4843 check_delay = 0;
4844 check_write = 0;
4846 else
4848 if (! read_kbd)
4849 Available = non_keyboard_wait_mask;
4850 else
4851 Available = input_wait_mask;
4852 Writeok = write_mask;
4853 check_delay = wait_proc ? 0 : process_output_delay_count;
4854 check_write = true;
4857 /* If frame size has changed or the window is newly mapped,
4858 redisplay now, before we start to wait. There is a race
4859 condition here; if a SIGIO arrives between now and the select
4860 and indicates that a frame is trashed, the select may block
4861 displaying a trashed screen. */
4862 if (frame_garbaged && do_display)
4864 clear_waiting_for_input ();
4865 redisplay_preserve_echo_area (11);
4866 if (read_kbd < 0)
4867 set_waiting_for_input (&timeout);
4870 /* Skip the `select' call if input is available and we're
4871 waiting for keyboard input or a cell change (which can be
4872 triggered by processing X events). In the latter case, set
4873 nfds to 1 to avoid breaking the loop. */
4874 no_avail = 0;
4875 if ((read_kbd || !NILP (wait_for_cell))
4876 && detect_input_pending ())
4878 nfds = read_kbd ? 0 : 1;
4879 no_avail = 1;
4880 FD_ZERO (&Available);
4883 if (!no_avail)
4886 #ifdef ADAPTIVE_READ_BUFFERING
4887 /* Set the timeout for adaptive read buffering if any
4888 process has non-zero read_output_skip and non-zero
4889 read_output_delay, and we are not reading output for a
4890 specific process. It is not executed if
4891 Vprocess_adaptive_read_buffering is nil. */
4892 if (process_output_skip && check_delay > 0)
4894 int nsecs = timeout.tv_nsec;
4895 if (timeout.tv_sec > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4896 nsecs = READ_OUTPUT_DELAY_MAX;
4897 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4899 proc = chan_process[channel];
4900 if (NILP (proc))
4901 continue;
4902 /* Find minimum non-zero read_output_delay among the
4903 processes with non-zero read_output_skip. */
4904 if (XPROCESS (proc)->read_output_delay > 0)
4906 check_delay--;
4907 if (!XPROCESS (proc)->read_output_skip)
4908 continue;
4909 FD_CLR (channel, &Available);
4910 XPROCESS (proc)->read_output_skip = 0;
4911 if (XPROCESS (proc)->read_output_delay < nsecs)
4912 nsecs = XPROCESS (proc)->read_output_delay;
4915 timeout = make_timespec (0, nsecs);
4916 process_output_skip = 0;
4918 #endif
4920 #if defined (HAVE_NS)
4921 nfds = ns_select
4922 #elif defined (HAVE_GLIB)
4923 nfds = xg_select
4924 #else
4925 nfds = pselect
4926 #endif
4927 (max (max_process_desc, max_input_desc) + 1,
4928 &Available,
4929 (check_write ? &Writeok : 0),
4930 NULL, &timeout, NULL);
4932 #ifdef HAVE_GNUTLS
4933 /* GnuTLS buffers data internally. In lowat mode it leaves
4934 some data in the TCP buffers so that select works, but
4935 with custom pull/push functions we need to check if some
4936 data is available in the buffers manually. */
4937 if (nfds == 0)
4939 if (! wait_proc)
4941 /* We're not waiting on a specific process, so loop
4942 through all the channels and check for data.
4943 This is a workaround needed for some versions of
4944 the gnutls library -- 2.12.14 has been confirmed
4945 to need it. See
4946 http://comments.gmane.org/gmane.emacs.devel/145074 */
4947 for (channel = 0; channel < FD_SETSIZE; ++channel)
4948 if (! NILP (chan_process[channel]))
4950 struct Lisp_Process *p =
4951 XPROCESS (chan_process[channel]);
4952 if (p && p->gnutls_p && p->gnutls_state
4953 && ((emacs_gnutls_record_check_pending
4954 (p->gnutls_state))
4955 > 0))
4957 nfds++;
4958 eassert (p->infd == channel);
4959 FD_SET (p->infd, &Available);
4963 else
4965 /* Check this specific channel. */
4966 if (wait_proc->gnutls_p /* Check for valid process. */
4967 && wait_proc->gnutls_state
4968 /* Do we have pending data? */
4969 && ((emacs_gnutls_record_check_pending
4970 (wait_proc->gnutls_state))
4971 > 0))
4973 nfds = 1;
4974 eassert (0 <= wait_proc->infd);
4975 /* Set to Available. */
4976 FD_SET (wait_proc->infd, &Available);
4980 #endif
4983 xerrno = errno;
4985 /* Make C-g and alarm signals set flags again. */
4986 clear_waiting_for_input ();
4988 /* If we woke up due to SIGWINCH, actually change size now. */
4989 do_pending_window_change (0);
4991 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4992 /* We waited the full specified time, so return now. */
4993 break;
4994 if (nfds < 0)
4996 if (xerrno == EINTR)
4997 no_avail = 1;
4998 else if (xerrno == EBADF)
4999 emacs_abort ();
5000 else
5001 report_file_errno ("Failed select", Qnil, xerrno);
5004 /* Check for keyboard input. */
5005 /* If there is any, return immediately
5006 to give it higher priority than subprocesses. */
5008 if (read_kbd != 0)
5010 unsigned old_timers_run = timers_run;
5011 struct buffer *old_buffer = current_buffer;
5012 Lisp_Object old_window = selected_window;
5013 bool leave = false;
5015 if (detect_input_pending_run_timers (do_display))
5017 swallow_events (do_display);
5018 if (detect_input_pending_run_timers (do_display))
5019 leave = true;
5022 /* If a timer has run, this might have changed buffers
5023 an alike. Make read_key_sequence aware of that. */
5024 if (timers_run != old_timers_run
5025 && waiting_for_user_input_p == -1
5026 && (old_buffer != current_buffer
5027 || !EQ (old_window, selected_window)))
5028 record_asynch_buffer_change ();
5030 if (leave)
5031 break;
5034 /* If there is unread keyboard input, also return. */
5035 if (read_kbd != 0
5036 && requeued_events_pending_p ())
5037 break;
5039 /* If we are not checking for keyboard input now,
5040 do process events (but don't run any timers).
5041 This is so that X events will be processed.
5042 Otherwise they may have to wait until polling takes place.
5043 That would causes delays in pasting selections, for example.
5045 (We used to do this only if wait_for_cell.) */
5046 if (read_kbd == 0 && detect_input_pending ())
5048 swallow_events (do_display);
5049 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5050 if (detect_input_pending ())
5051 break;
5052 #endif
5055 /* Exit now if the cell we're waiting for became non-nil. */
5056 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5057 break;
5059 #ifdef USABLE_SIGIO
5060 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5061 go read it. This can happen with X on BSD after logging out.
5062 In that case, there really is no input and no SIGIO,
5063 but select says there is input. */
5065 if (read_kbd && interrupt_input
5066 && keyboard_bit_set (&Available) && ! noninteractive)
5067 handle_input_available_signal (SIGIO);
5068 #endif
5070 /* If checking input just got us a size-change event from X,
5071 obey it now if we should. */
5072 if (read_kbd || ! NILP (wait_for_cell))
5073 do_pending_window_change (0);
5075 /* Check for data from a process. */
5076 if (no_avail || nfds == 0)
5077 continue;
5079 for (channel = 0; channel <= max_input_desc; ++channel)
5081 struct fd_callback_data *d = &fd_callback_info[channel];
5082 if (d->func
5083 && ((d->condition & FOR_READ
5084 && FD_ISSET (channel, &Available))
5085 || (d->condition & FOR_WRITE
5086 && FD_ISSET (channel, &write_mask))))
5087 d->func (channel, d->data);
5090 for (channel = 0; channel <= max_process_desc; channel++)
5092 if (FD_ISSET (channel, &Available)
5093 && FD_ISSET (channel, &non_keyboard_wait_mask)
5094 && !FD_ISSET (channel, &non_process_wait_mask))
5096 int nread;
5098 /* If waiting for this channel, arrange to return as
5099 soon as no more input to be processed. No more
5100 waiting. */
5101 proc = chan_process[channel];
5102 if (NILP (proc))
5103 continue;
5105 /* If this is a server stream socket, accept connection. */
5106 if (EQ (XPROCESS (proc)->status, Qlisten))
5108 server_accept_connection (proc, channel);
5109 continue;
5112 /* Read data from the process, starting with our
5113 buffered-ahead character if we have one. */
5115 nread = read_process_output (proc, channel);
5116 if ((!wait_proc || wait_proc == XPROCESS (proc)) && got_some_input < nread)
5117 got_some_input = nread;
5118 if (nread > 0)
5120 /* Since read_process_output can run a filter,
5121 which can call accept-process-output,
5122 don't try to read from any other processes
5123 before doing the select again. */
5124 FD_ZERO (&Available);
5126 if (do_display)
5127 redisplay_preserve_echo_area (12);
5129 #ifdef EWOULDBLOCK
5130 else if (nread == -1 && errno == EWOULDBLOCK)
5132 #endif
5133 else if (nread == -1 && errno == EAGAIN)
5135 #ifdef WINDOWSNT
5136 /* FIXME: Is this special case still needed? */
5137 /* Note that we cannot distinguish between no input
5138 available now and a closed pipe.
5139 With luck, a closed pipe will be accompanied by
5140 subprocess termination and SIGCHLD. */
5141 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5142 && !PIPECONN_P (proc))
5144 #endif
5145 #ifdef HAVE_PTYS
5146 /* On some OSs with ptys, when the process on one end of
5147 a pty exits, the other end gets an error reading with
5148 errno = EIO instead of getting an EOF (0 bytes read).
5149 Therefore, if we get an error reading and errno =
5150 EIO, just continue, because the child process has
5151 exited and should clean itself up soon (e.g. when we
5152 get a SIGCHLD). */
5153 else if (nread == -1 && errno == EIO)
5155 struct Lisp_Process *p = XPROCESS (proc);
5157 /* Clear the descriptor now, so we only raise the
5158 signal once. */
5159 FD_CLR (channel, &input_wait_mask);
5160 FD_CLR (channel, &non_keyboard_wait_mask);
5162 if (p->pid == -2)
5164 /* If the EIO occurs on a pty, the SIGCHLD handler's
5165 waitpid call will not find the process object to
5166 delete. Do it here. */
5167 p->tick = ++process_tick;
5168 pset_status (p, Qfailed);
5171 #endif /* HAVE_PTYS */
5172 /* If we can detect process termination, don't consider the
5173 process gone just because its pipe is closed. */
5174 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5175 && !PIPECONN_P (proc))
5177 else if (nread == 0 && PIPECONN_P (proc))
5179 /* Preserve status of processes already terminated. */
5180 XPROCESS (proc)->tick = ++process_tick;
5181 deactivate_process (proc);
5182 if (EQ (XPROCESS (proc)->status, Qrun))
5183 pset_status (XPROCESS (proc),
5184 list2 (Qexit, make_number (0)));
5186 else
5188 /* Preserve status of processes already terminated. */
5189 XPROCESS (proc)->tick = ++process_tick;
5190 deactivate_process (proc);
5191 if (XPROCESS (proc)->raw_status_new)
5192 update_status (XPROCESS (proc));
5193 if (EQ (XPROCESS (proc)->status, Qrun))
5194 pset_status (XPROCESS (proc),
5195 list2 (Qexit, make_number (256)));
5198 #ifdef NON_BLOCKING_CONNECT
5199 if (FD_ISSET (channel, &Writeok)
5200 && FD_ISSET (channel, &connect_wait_mask))
5202 struct Lisp_Process *p;
5204 FD_CLR (channel, &connect_wait_mask);
5205 FD_CLR (channel, &write_mask);
5206 if (--num_pending_connects < 0)
5207 emacs_abort ();
5209 proc = chan_process[channel];
5210 if (NILP (proc))
5211 continue;
5213 p = XPROCESS (proc);
5215 #ifdef GNU_LINUX
5216 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5217 So only use it on systems where it is known to work. */
5219 socklen_t xlen = sizeof (xerrno);
5220 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5221 xerrno = errno;
5223 #else
5225 struct sockaddr pname;
5226 socklen_t pnamelen = sizeof (pname);
5228 /* If connection failed, getpeername will fail. */
5229 xerrno = 0;
5230 if (getpeername (channel, &pname, &pnamelen) < 0)
5232 /* Obtain connect failure code through error slippage. */
5233 char dummy;
5234 xerrno = errno;
5235 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5236 xerrno = errno;
5239 #endif
5240 if (xerrno)
5242 p->tick = ++process_tick;
5243 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5244 deactivate_process (proc);
5246 else
5248 pset_status (p, Qrun);
5249 /* Execute the sentinel here. If we had relied on
5250 status_notify to do it later, it will read input
5251 from the process before calling the sentinel. */
5252 exec_sentinel (proc, build_string ("open\n"));
5253 if (0 <= p->infd && !EQ (p->filter, Qt)
5254 && !EQ (p->command, Qt))
5256 FD_SET (p->infd, &input_wait_mask);
5257 FD_SET (p->infd, &non_keyboard_wait_mask);
5261 #endif /* NON_BLOCKING_CONNECT */
5262 } /* End for each file descriptor. */
5263 } /* End while exit conditions not met. */
5265 unbind_to (count, Qnil);
5267 /* If calling from keyboard input, do not quit
5268 since we want to return C-g as an input character.
5269 Otherwise, do pending quit if requested. */
5270 if (read_kbd >= 0)
5272 /* Prevent input_pending from remaining set if we quit. */
5273 clear_input_pending ();
5274 QUIT;
5277 return got_some_input;
5280 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5282 static Lisp_Object
5283 read_process_output_call (Lisp_Object fun_and_args)
5285 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5288 static Lisp_Object
5289 read_process_output_error_handler (Lisp_Object error_val)
5291 cmd_error_internal (error_val, "error in process filter: ");
5292 Vinhibit_quit = Qt;
5293 update_echo_area ();
5294 Fsleep_for (make_number (2), Qnil);
5295 return Qt;
5298 static void
5299 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5300 ssize_t nbytes,
5301 struct coding_system *coding);
5303 /* Read pending output from the process channel,
5304 starting with our buffered-ahead character if we have one.
5305 Yield number of decoded characters read.
5307 This function reads at most 4096 characters.
5308 If you want to read all available subprocess output,
5309 you must call it repeatedly until it returns zero.
5311 The characters read are decoded according to PROC's coding-system
5312 for decoding. */
5314 static int
5315 read_process_output (Lisp_Object proc, int channel)
5317 ssize_t nbytes;
5318 struct Lisp_Process *p = XPROCESS (proc);
5319 struct coding_system *coding = proc_decode_coding_system[channel];
5320 int carryover = p->decoding_carryover;
5321 enum { readmax = 4096 };
5322 ptrdiff_t count = SPECPDL_INDEX ();
5323 Lisp_Object odeactivate;
5324 char chars[sizeof coding->carryover + readmax];
5326 if (carryover)
5327 /* See the comment above. */
5328 memcpy (chars, SDATA (p->decoding_buf), carryover);
5330 #ifdef DATAGRAM_SOCKETS
5331 /* We have a working select, so proc_buffered_char is always -1. */
5332 if (DATAGRAM_CHAN_P (channel))
5334 socklen_t len = datagram_address[channel].len;
5335 nbytes = recvfrom (channel, chars + carryover, readmax,
5336 0, datagram_address[channel].sa, &len);
5338 else
5339 #endif
5341 bool buffered = proc_buffered_char[channel] >= 0;
5342 if (buffered)
5344 chars[carryover] = proc_buffered_char[channel];
5345 proc_buffered_char[channel] = -1;
5347 #ifdef HAVE_GNUTLS
5348 if (p->gnutls_p && p->gnutls_state)
5349 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5350 readmax - buffered);
5351 else
5352 #endif
5353 nbytes = emacs_read (channel, chars + carryover + buffered,
5354 readmax - buffered);
5355 #ifdef ADAPTIVE_READ_BUFFERING
5356 if (nbytes > 0 && p->adaptive_read_buffering)
5358 int delay = p->read_output_delay;
5359 if (nbytes < 256)
5361 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5363 if (delay == 0)
5364 process_output_delay_count++;
5365 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5368 else if (delay > 0 && nbytes == readmax - buffered)
5370 delay -= READ_OUTPUT_DELAY_INCREMENT;
5371 if (delay == 0)
5372 process_output_delay_count--;
5374 p->read_output_delay = delay;
5375 if (delay)
5377 p->read_output_skip = 1;
5378 process_output_skip = 1;
5381 #endif
5382 nbytes += buffered;
5383 nbytes += buffered && nbytes <= 0;
5386 p->decoding_carryover = 0;
5388 /* At this point, NBYTES holds number of bytes just received
5389 (including the one in proc_buffered_char[channel]). */
5390 if (nbytes <= 0)
5392 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5393 return nbytes;
5394 coding->mode |= CODING_MODE_LAST_BLOCK;
5397 /* Now set NBYTES how many bytes we must decode. */
5398 nbytes += carryover;
5400 odeactivate = Vdeactivate_mark;
5401 /* There's no good reason to let process filters change the current
5402 buffer, and many callers of accept-process-output, sit-for, and
5403 friends don't expect current-buffer to be changed from under them. */
5404 record_unwind_current_buffer ();
5406 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5408 /* Handling the process output should not deactivate the mark. */
5409 Vdeactivate_mark = odeactivate;
5411 unbind_to (count, Qnil);
5412 return nbytes;
5415 static void
5416 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5417 ssize_t nbytes,
5418 struct coding_system *coding)
5420 Lisp_Object outstream = p->filter;
5421 Lisp_Object text;
5422 bool outer_running_asynch_code = running_asynch_code;
5423 int waiting = waiting_for_user_input_p;
5425 /* No need to gcpro these, because all we do with them later
5426 is test them for EQness, and none of them should be a string. */
5427 #if 0
5428 Lisp_Object obuffer, okeymap;
5429 XSETBUFFER (obuffer, current_buffer);
5430 okeymap = BVAR (current_buffer, keymap);
5431 #endif
5433 /* We inhibit quit here instead of just catching it so that
5434 hitting ^G when a filter happens to be running won't screw
5435 it up. */
5436 specbind (Qinhibit_quit, Qt);
5437 specbind (Qlast_nonmenu_event, Qt);
5439 /* In case we get recursively called,
5440 and we already saved the match data nonrecursively,
5441 save the same match data in safely recursive fashion. */
5442 if (outer_running_asynch_code)
5444 Lisp_Object tem;
5445 /* Don't clobber the CURRENT match data, either! */
5446 tem = Fmatch_data (Qnil, Qnil, Qnil);
5447 restore_search_regs ();
5448 record_unwind_save_match_data ();
5449 Fset_match_data (tem, Qt);
5452 /* For speed, if a search happens within this code,
5453 save the match data in a special nonrecursive fashion. */
5454 running_asynch_code = 1;
5456 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5457 text = coding->dst_object;
5458 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5459 /* A new coding system might be found. */
5460 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5462 pset_decode_coding_system (p, Vlast_coding_system_used);
5464 /* Don't call setup_coding_system for
5465 proc_decode_coding_system[channel] here. It is done in
5466 detect_coding called via decode_coding above. */
5468 /* If a coding system for encoding is not yet decided, we set
5469 it as the same as coding-system for decoding.
5471 But, before doing that we must check if
5472 proc_encode_coding_system[p->outfd] surely points to a
5473 valid memory because p->outfd will be changed once EOF is
5474 sent to the process. */
5475 if (NILP (p->encode_coding_system) && p->outfd >= 0
5476 && proc_encode_coding_system[p->outfd])
5478 pset_encode_coding_system
5479 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5480 setup_coding_system (p->encode_coding_system,
5481 proc_encode_coding_system[p->outfd]);
5485 if (coding->carryover_bytes > 0)
5487 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5488 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5489 memcpy (SDATA (p->decoding_buf), coding->carryover,
5490 coding->carryover_bytes);
5491 p->decoding_carryover = coding->carryover_bytes;
5493 if (SBYTES (text) > 0)
5494 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5495 sometimes it's simply wrong to wrap (e.g. when called from
5496 accept-process-output). */
5497 internal_condition_case_1 (read_process_output_call,
5498 list3 (outstream, make_lisp_proc (p), text),
5499 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5500 read_process_output_error_handler);
5502 /* If we saved the match data nonrecursively, restore it now. */
5503 restore_search_regs ();
5504 running_asynch_code = outer_running_asynch_code;
5506 /* Restore waiting_for_user_input_p as it was
5507 when we were called, in case the filter clobbered it. */
5508 waiting_for_user_input_p = waiting;
5510 #if 0 /* Call record_asynch_buffer_change unconditionally,
5511 because we might have changed minor modes or other things
5512 that affect key bindings. */
5513 if (! EQ (Fcurrent_buffer (), obuffer)
5514 || ! EQ (current_buffer->keymap, okeymap))
5515 #endif
5516 /* But do it only if the caller is actually going to read events.
5517 Otherwise there's no need to make him wake up, and it could
5518 cause trouble (for example it would make sit_for return). */
5519 if (waiting_for_user_input_p == -1)
5520 record_asynch_buffer_change ();
5523 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5524 Sinternal_default_process_filter, 2, 2, 0,
5525 doc: /* Function used as default process filter.
5526 This inserts the process's output into its buffer, if there is one.
5527 Otherwise it discards the output. */)
5528 (Lisp_Object proc, Lisp_Object text)
5530 struct Lisp_Process *p;
5531 ptrdiff_t opoint;
5533 CHECK_PROCESS (proc);
5534 p = XPROCESS (proc);
5535 CHECK_STRING (text);
5537 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5539 Lisp_Object old_read_only;
5540 ptrdiff_t old_begv, old_zv;
5541 ptrdiff_t old_begv_byte, old_zv_byte;
5542 ptrdiff_t before, before_byte;
5543 ptrdiff_t opoint_byte;
5544 struct buffer *b;
5546 Fset_buffer (p->buffer);
5547 opoint = PT;
5548 opoint_byte = PT_BYTE;
5549 old_read_only = BVAR (current_buffer, read_only);
5550 old_begv = BEGV;
5551 old_zv = ZV;
5552 old_begv_byte = BEGV_BYTE;
5553 old_zv_byte = ZV_BYTE;
5555 bset_read_only (current_buffer, Qnil);
5557 /* Insert new output into buffer at the current end-of-output
5558 marker, thus preserving logical ordering of input and output. */
5559 if (XMARKER (p->mark)->buffer)
5560 set_point_from_marker (p->mark);
5561 else
5562 SET_PT_BOTH (ZV, ZV_BYTE);
5563 before = PT;
5564 before_byte = PT_BYTE;
5566 /* If the output marker is outside of the visible region, save
5567 the restriction and widen. */
5568 if (! (BEGV <= PT && PT <= ZV))
5569 Fwiden ();
5571 /* Adjust the multibyteness of TEXT to that of the buffer. */
5572 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5573 != ! STRING_MULTIBYTE (text))
5574 text = (STRING_MULTIBYTE (text)
5575 ? Fstring_as_unibyte (text)
5576 : Fstring_to_multibyte (text));
5577 /* Insert before markers in case we are inserting where
5578 the buffer's mark is, and the user's next command is Meta-y. */
5579 insert_from_string_before_markers (text, 0, 0,
5580 SCHARS (text), SBYTES (text), 0);
5582 /* Make sure the process marker's position is valid when the
5583 process buffer is changed in the signal_after_change above.
5584 W3 is known to do that. */
5585 if (BUFFERP (p->buffer)
5586 && (b = XBUFFER (p->buffer), b != current_buffer))
5587 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5588 else
5589 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5591 update_mode_lines = 23;
5593 /* Make sure opoint and the old restrictions
5594 float ahead of any new text just as point would. */
5595 if (opoint >= before)
5597 opoint += PT - before;
5598 opoint_byte += PT_BYTE - before_byte;
5600 if (old_begv > before)
5602 old_begv += PT - before;
5603 old_begv_byte += PT_BYTE - before_byte;
5605 if (old_zv >= before)
5607 old_zv += PT - before;
5608 old_zv_byte += PT_BYTE - before_byte;
5611 /* If the restriction isn't what it should be, set it. */
5612 if (old_begv != BEGV || old_zv != ZV)
5613 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5615 bset_read_only (current_buffer, old_read_only);
5616 SET_PT_BOTH (opoint, opoint_byte);
5618 return Qnil;
5621 /* Sending data to subprocess. */
5623 /* In send_process, when a write fails temporarily,
5624 wait_reading_process_output is called. It may execute user code,
5625 e.g. timers, that attempts to write new data to the same process.
5626 We must ensure that data is sent in the right order, and not
5627 interspersed half-completed with other writes (Bug#10815). This is
5628 handled by the write_queue element of struct process. It is a list
5629 with each entry having the form
5631 (string . (offset . length))
5633 where STRING is a lisp string, OFFSET is the offset into the
5634 string's byte sequence from which we should begin to send, and
5635 LENGTH is the number of bytes left to send. */
5637 /* Create a new entry in write_queue.
5638 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5639 BUF is a pointer to the string sequence of the input_obj or a C
5640 string in case of Qt or Qnil. */
5642 static void
5643 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5644 const char *buf, ptrdiff_t len, bool front)
5646 ptrdiff_t offset;
5647 Lisp_Object entry, obj;
5649 if (STRINGP (input_obj))
5651 offset = buf - SSDATA (input_obj);
5652 obj = input_obj;
5654 else
5656 offset = 0;
5657 obj = make_unibyte_string (buf, len);
5660 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5662 if (front)
5663 pset_write_queue (p, Fcons (entry, p->write_queue));
5664 else
5665 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5668 /* Remove the first element in the write_queue of process P, put its
5669 contents in OBJ, BUF and LEN, and return true. If the
5670 write_queue is empty, return false. */
5672 static bool
5673 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5674 const char **buf, ptrdiff_t *len)
5676 Lisp_Object entry, offset_length;
5677 ptrdiff_t offset;
5679 if (NILP (p->write_queue))
5680 return 0;
5682 entry = XCAR (p->write_queue);
5683 pset_write_queue (p, XCDR (p->write_queue));
5685 *obj = XCAR (entry);
5686 offset_length = XCDR (entry);
5688 *len = XINT (XCDR (offset_length));
5689 offset = XINT (XCAR (offset_length));
5690 *buf = SSDATA (*obj) + offset;
5692 return 1;
5695 /* Send some data to process PROC.
5696 BUF is the beginning of the data; LEN is the number of characters.
5697 OBJECT is the Lisp object that the data comes from. If OBJECT is
5698 nil or t, it means that the data comes from C string.
5700 If OBJECT is not nil, the data is encoded by PROC's coding-system
5701 for encoding before it is sent.
5703 This function can evaluate Lisp code and can garbage collect. */
5705 static void
5706 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5707 Lisp_Object object)
5709 struct Lisp_Process *p = XPROCESS (proc);
5710 ssize_t rv;
5711 struct coding_system *coding;
5713 if (p->raw_status_new)
5714 update_status (p);
5715 if (! EQ (p->status, Qrun))
5716 error ("Process %s not running", SDATA (p->name));
5717 if (p->outfd < 0)
5718 error ("Output file descriptor of %s is closed", SDATA (p->name));
5720 coding = proc_encode_coding_system[p->outfd];
5721 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5723 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5724 || (BUFFERP (object)
5725 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5726 || EQ (object, Qt))
5728 pset_encode_coding_system
5729 (p, complement_process_encoding_system (p->encode_coding_system));
5730 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5732 /* The coding system for encoding was changed to raw-text
5733 because we sent a unibyte text previously. Now we are
5734 sending a multibyte text, thus we must encode it by the
5735 original coding system specified for the current process.
5737 Another reason we come here is that the coding system
5738 was just complemented and a new one was returned by
5739 complement_process_encoding_system. */
5740 setup_coding_system (p->encode_coding_system, coding);
5741 Vlast_coding_system_used = p->encode_coding_system;
5743 coding->src_multibyte = 1;
5745 else
5747 coding->src_multibyte = 0;
5748 /* For sending a unibyte text, character code conversion should
5749 not take place but EOL conversion should. So, setup raw-text
5750 or one of the subsidiary if we have not yet done it. */
5751 if (CODING_REQUIRE_ENCODING (coding))
5753 if (CODING_REQUIRE_FLUSHING (coding))
5755 /* But, before changing the coding, we must flush out data. */
5756 coding->mode |= CODING_MODE_LAST_BLOCK;
5757 send_process (proc, "", 0, Qt);
5758 coding->mode &= CODING_MODE_LAST_BLOCK;
5760 setup_coding_system (raw_text_coding_system
5761 (Vlast_coding_system_used),
5762 coding);
5763 coding->src_multibyte = 0;
5766 coding->dst_multibyte = 0;
5768 if (CODING_REQUIRE_ENCODING (coding))
5770 coding->dst_object = Qt;
5771 if (BUFFERP (object))
5773 ptrdiff_t from_byte, from, to;
5774 ptrdiff_t save_pt, save_pt_byte;
5775 struct buffer *cur = current_buffer;
5777 set_buffer_internal (XBUFFER (object));
5778 save_pt = PT, save_pt_byte = PT_BYTE;
5780 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5781 from = BYTE_TO_CHAR (from_byte);
5782 to = BYTE_TO_CHAR (from_byte + len);
5783 TEMP_SET_PT_BOTH (from, from_byte);
5784 encode_coding_object (coding, object, from, from_byte,
5785 to, from_byte + len, Qt);
5786 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5787 set_buffer_internal (cur);
5789 else if (STRINGP (object))
5791 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5792 SBYTES (object), Qt);
5794 else
5796 coding->dst_object = make_unibyte_string (buf, len);
5797 coding->produced = len;
5800 len = coding->produced;
5801 object = coding->dst_object;
5802 buf = SSDATA (object);
5805 /* If there is already data in the write_queue, put the new data
5806 in the back of queue. Otherwise, ignore it. */
5807 if (!NILP (p->write_queue))
5808 write_queue_push (p, object, buf, len, 0);
5810 do /* while !NILP (p->write_queue) */
5812 ptrdiff_t cur_len = -1;
5813 const char *cur_buf;
5814 Lisp_Object cur_object;
5816 /* If write_queue is empty, ignore it. */
5817 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5819 cur_len = len;
5820 cur_buf = buf;
5821 cur_object = object;
5824 while (cur_len > 0)
5826 /* Send this batch, using one or more write calls. */
5827 ptrdiff_t written = 0;
5828 int outfd = p->outfd;
5829 #ifdef DATAGRAM_SOCKETS
5830 if (DATAGRAM_CHAN_P (outfd))
5832 rv = sendto (outfd, cur_buf, cur_len,
5833 0, datagram_address[outfd].sa,
5834 datagram_address[outfd].len);
5835 if (rv >= 0)
5836 written = rv;
5837 else if (errno == EMSGSIZE)
5838 report_file_error ("Sending datagram", proc);
5840 else
5841 #endif
5843 #ifdef HAVE_GNUTLS
5844 if (p->gnutls_p && p->gnutls_state)
5845 written = emacs_gnutls_write (p, cur_buf, cur_len);
5846 else
5847 #endif
5848 written = emacs_write_sig (outfd, cur_buf, cur_len);
5849 rv = (written ? 0 : -1);
5850 #ifdef ADAPTIVE_READ_BUFFERING
5851 if (p->read_output_delay > 0
5852 && p->adaptive_read_buffering == 1)
5854 p->read_output_delay = 0;
5855 process_output_delay_count--;
5856 p->read_output_skip = 0;
5858 #endif
5861 if (rv < 0)
5863 if (errno == EAGAIN
5864 #ifdef EWOULDBLOCK
5865 || errno == EWOULDBLOCK
5866 #endif
5868 /* Buffer is full. Wait, accepting input;
5869 that may allow the program
5870 to finish doing output and read more. */
5872 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5873 /* A gross hack to work around a bug in FreeBSD.
5874 In the following sequence, read(2) returns
5875 bogus data:
5877 write(2) 1022 bytes
5878 write(2) 954 bytes, get EAGAIN
5879 read(2) 1024 bytes in process_read_output
5880 read(2) 11 bytes in process_read_output
5882 That is, read(2) returns more bytes than have
5883 ever been written successfully. The 1033 bytes
5884 read are the 1022 bytes written successfully
5885 after processing (for example with CRs added if
5886 the terminal is set up that way which it is
5887 here). The same bytes will be seen again in a
5888 later read(2), without the CRs. */
5890 if (errno == EAGAIN)
5892 int flags = FWRITE;
5893 ioctl (p->outfd, TIOCFLUSH, &flags);
5895 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5897 /* Put what we should have written in wait_queue. */
5898 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5899 wait_reading_process_output (0, 20 * 1000 * 1000,
5900 0, 0, Qnil, NULL, 0);
5901 /* Reread queue, to see what is left. */
5902 break;
5904 else if (errno == EPIPE)
5906 p->raw_status_new = 0;
5907 pset_status (p, list2 (Qexit, make_number (256)));
5908 p->tick = ++process_tick;
5909 deactivate_process (proc);
5910 error ("process %s no longer connected to pipe; closed it",
5911 SDATA (p->name));
5913 else
5914 /* This is a real error. */
5915 report_file_error ("Writing to process", proc);
5917 cur_buf += written;
5918 cur_len -= written;
5921 while (!NILP (p->write_queue));
5924 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5925 3, 3, 0,
5926 doc: /* Send current contents of region as input to PROCESS.
5927 PROCESS may be a process, a buffer, the name of a process or buffer, or
5928 nil, indicating the current buffer's process.
5929 Called from program, takes three arguments, PROCESS, START and END.
5930 If the region is more than 500 characters long,
5931 it is sent in several bunches. This may happen even for shorter regions.
5932 Output from processes can arrive in between bunches. */)
5933 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5935 Lisp_Object proc = get_process (process);
5936 ptrdiff_t start_byte, end_byte;
5938 validate_region (&start, &end);
5940 start_byte = CHAR_TO_BYTE (XINT (start));
5941 end_byte = CHAR_TO_BYTE (XINT (end));
5943 if (XINT (start) < GPT && XINT (end) > GPT)
5944 move_gap_both (XINT (start), start_byte);
5946 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5947 end_byte - start_byte, Fcurrent_buffer ());
5949 return Qnil;
5952 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5953 2, 2, 0,
5954 doc: /* Send PROCESS the contents of STRING as input.
5955 PROCESS may be a process, a buffer, the name of a process or buffer, or
5956 nil, indicating the current buffer's process.
5957 If STRING is more than 500 characters long,
5958 it is sent in several bunches. This may happen even for shorter strings.
5959 Output from processes can arrive in between bunches. */)
5960 (Lisp_Object process, Lisp_Object string)
5962 Lisp_Object proc;
5963 CHECK_STRING (string);
5964 proc = get_process (process);
5965 send_process (proc, SSDATA (string),
5966 SBYTES (string), string);
5967 return Qnil;
5970 /* Return the foreground process group for the tty/pty that
5971 the process P uses. */
5972 static pid_t
5973 emacs_get_tty_pgrp (struct Lisp_Process *p)
5975 pid_t gid = -1;
5977 #ifdef TIOCGPGRP
5978 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5980 int fd;
5981 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5982 master side. Try the slave side. */
5983 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5985 if (fd != -1)
5987 ioctl (fd, TIOCGPGRP, &gid);
5988 emacs_close (fd);
5991 #endif /* defined (TIOCGPGRP ) */
5993 return gid;
5996 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5997 Sprocess_running_child_p, 0, 1, 0,
5998 doc: /* Return non-nil if PROCESS has given the terminal to a
5999 child. If the operating system does not make it possible to find out,
6000 return t. If we can find out, return the numeric ID of the foreground
6001 process group. */)
6002 (Lisp_Object process)
6004 /* Initialize in case ioctl doesn't exist or gives an error,
6005 in a way that will cause returning t. */
6006 pid_t gid;
6007 Lisp_Object proc;
6008 struct Lisp_Process *p;
6010 proc = get_process (process);
6011 p = XPROCESS (proc);
6013 if (!EQ (p->type, Qreal))
6014 error ("Process %s is not a subprocess",
6015 SDATA (p->name));
6016 if (p->infd < 0)
6017 error ("Process %s is not active",
6018 SDATA (p->name));
6020 gid = emacs_get_tty_pgrp (p);
6022 if (gid == p->pid)
6023 return Qnil;
6024 if (gid != -1)
6025 return make_number (gid);
6026 return Qt;
6029 /* Send a signal number SIGNO to PROCESS.
6030 If CURRENT_GROUP is t, that means send to the process group
6031 that currently owns the terminal being used to communicate with PROCESS.
6032 This is used for various commands in shell mode.
6033 If CURRENT_GROUP is lambda, that means send to the process group
6034 that currently owns the terminal, but only if it is NOT the shell itself.
6036 If NOMSG is false, insert signal-announcements into process's buffers
6037 right away.
6039 If we can, we try to signal PROCESS by sending control characters
6040 down the pty. This allows us to signal inferiors who have changed
6041 their uid, for which kill would return an EPERM error. */
6043 static void
6044 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
6045 bool nomsg)
6047 Lisp_Object proc;
6048 struct Lisp_Process *p;
6049 pid_t gid;
6050 bool no_pgrp = 0;
6052 proc = get_process (process);
6053 p = XPROCESS (proc);
6055 if (!EQ (p->type, Qreal))
6056 error ("Process %s is not a subprocess",
6057 SDATA (p->name));
6058 if (p->infd < 0)
6059 error ("Process %s is not active",
6060 SDATA (p->name));
6062 if (!p->pty_flag)
6063 current_group = Qnil;
6065 /* If we are using pgrps, get a pgrp number and make it negative. */
6066 if (NILP (current_group))
6067 /* Send the signal to the shell's process group. */
6068 gid = p->pid;
6069 else
6071 #ifdef SIGNALS_VIA_CHARACTERS
6072 /* If possible, send signals to the entire pgrp
6073 by sending an input character to it. */
6075 struct termios t;
6076 cc_t *sig_char = NULL;
6078 tcgetattr (p->infd, &t);
6080 switch (signo)
6082 case SIGINT:
6083 sig_char = &t.c_cc[VINTR];
6084 break;
6086 case SIGQUIT:
6087 sig_char = &t.c_cc[VQUIT];
6088 break;
6090 case SIGTSTP:
6091 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6092 sig_char = &t.c_cc[VSWTCH];
6093 #else
6094 sig_char = &t.c_cc[VSUSP];
6095 #endif
6096 break;
6099 if (sig_char && *sig_char != CDISABLE)
6101 send_process (proc, (char *) sig_char, 1, Qnil);
6102 return;
6104 /* If we can't send the signal with a character,
6105 fall through and send it another way. */
6107 /* The code above may fall through if it can't
6108 handle the signal. */
6109 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6111 #ifdef TIOCGPGRP
6112 /* Get the current pgrp using the tty itself, if we have that.
6113 Otherwise, use the pty to get the pgrp.
6114 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6115 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6116 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6117 His patch indicates that if TIOCGPGRP returns an error, then
6118 we should just assume that p->pid is also the process group id. */
6120 gid = emacs_get_tty_pgrp (p);
6122 if (gid == -1)
6123 /* If we can't get the information, assume
6124 the shell owns the tty. */
6125 gid = p->pid;
6127 /* It is not clear whether anything really can set GID to -1.
6128 Perhaps on some system one of those ioctls can or could do so.
6129 Or perhaps this is vestigial. */
6130 if (gid == -1)
6131 no_pgrp = 1;
6132 #else /* ! defined (TIOCGPGRP) */
6133 /* Can't select pgrps on this system, so we know that
6134 the child itself heads the pgrp. */
6135 gid = p->pid;
6136 #endif /* ! defined (TIOCGPGRP) */
6138 /* If current_group is lambda, and the shell owns the terminal,
6139 don't send any signal. */
6140 if (EQ (current_group, Qlambda) && gid == p->pid)
6141 return;
6144 #ifdef SIGCONT
6145 if (signo == SIGCONT)
6147 p->raw_status_new = 0;
6148 pset_status (p, Qrun);
6149 p->tick = ++process_tick;
6150 if (!nomsg)
6152 status_notify (NULL, NULL);
6153 redisplay_preserve_echo_area (13);
6156 #endif
6158 #ifdef TIOCSIGSEND
6159 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6160 We don't know whether the bug is fixed in later HP-UX versions. */
6161 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6162 return;
6163 #endif
6165 /* If we don't have process groups, send the signal to the immediate
6166 subprocess. That isn't really right, but it's better than any
6167 obvious alternative. */
6168 pid_t pid = no_pgrp ? gid : - gid;
6170 /* Do not kill an already-reaped process, as that could kill an
6171 innocent bystander that happens to have the same process ID. */
6172 sigset_t oldset;
6173 block_child_signal (&oldset);
6174 if (p->alive)
6175 kill (pid, signo);
6176 unblock_child_signal (&oldset);
6179 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6180 doc: /* Interrupt process PROCESS.
6181 PROCESS may be a process, a buffer, or the name of a process or buffer.
6182 No arg or nil means current buffer's process.
6183 Second arg CURRENT-GROUP non-nil means send signal to
6184 the current process-group of the process's controlling terminal
6185 rather than to the process's own process group.
6186 If the process is a shell, this means interrupt current subjob
6187 rather than the shell.
6189 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6190 don't send the signal. */)
6191 (Lisp_Object process, Lisp_Object current_group)
6193 process_send_signal (process, SIGINT, current_group, 0);
6194 return process;
6197 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6198 doc: /* Kill process PROCESS. May be process or name of one.
6199 See function `interrupt-process' for more details on usage. */)
6200 (Lisp_Object process, Lisp_Object current_group)
6202 process_send_signal (process, SIGKILL, current_group, 0);
6203 return process;
6206 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6207 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6208 See function `interrupt-process' for more details on usage. */)
6209 (Lisp_Object process, Lisp_Object current_group)
6211 process_send_signal (process, SIGQUIT, current_group, 0);
6212 return process;
6215 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6216 doc: /* Stop process PROCESS. May be process or name of one.
6217 See function `interrupt-process' for more details on usage.
6218 If PROCESS is a network or serial process, inhibit handling of incoming
6219 traffic. */)
6220 (Lisp_Object process, Lisp_Object current_group)
6222 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6223 || PIPECONN_P (process)))
6225 struct Lisp_Process *p;
6227 p = XPROCESS (process);
6228 if (NILP (p->command)
6229 && p->infd >= 0)
6231 FD_CLR (p->infd, &input_wait_mask);
6232 FD_CLR (p->infd, &non_keyboard_wait_mask);
6234 pset_command (p, Qt);
6235 return process;
6237 #ifndef SIGTSTP
6238 error ("No SIGTSTP support");
6239 #else
6240 process_send_signal (process, SIGTSTP, current_group, 0);
6241 #endif
6242 return process;
6245 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6246 doc: /* Continue process PROCESS. May be process or name of one.
6247 See function `interrupt-process' for more details on usage.
6248 If PROCESS is a network or serial process, resume handling of incoming
6249 traffic. */)
6250 (Lisp_Object process, Lisp_Object current_group)
6252 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6253 || PIPECONN_P (process)))
6255 struct Lisp_Process *p;
6257 p = XPROCESS (process);
6258 if (EQ (p->command, Qt)
6259 && p->infd >= 0
6260 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6262 FD_SET (p->infd, &input_wait_mask);
6263 FD_SET (p->infd, &non_keyboard_wait_mask);
6264 #ifdef WINDOWSNT
6265 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6266 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6267 #else /* not WINDOWSNT */
6268 tcflush (p->infd, TCIFLUSH);
6269 #endif /* not WINDOWSNT */
6271 pset_command (p, Qnil);
6272 return process;
6274 #ifdef SIGCONT
6275 process_send_signal (process, SIGCONT, current_group, 0);
6276 #else
6277 error ("No SIGCONT support");
6278 #endif
6279 return process;
6282 /* Return the integer value of the signal whose abbreviation is ABBR,
6283 or a negative number if there is no such signal. */
6284 static int
6285 abbr_to_signal (char const *name)
6287 int i, signo;
6288 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6290 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6291 name += 3;
6293 for (i = 0; i < sizeof sigbuf; i++)
6295 sigbuf[i] = c_toupper (name[i]);
6296 if (! sigbuf[i])
6297 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6300 return -1;
6303 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6304 2, 2, "sProcess (name or number): \nnSignal code: ",
6305 doc: /* Send PROCESS the signal with code SIGCODE.
6306 PROCESS may also be a number specifying the process id of the
6307 process to signal; in this case, the process need not be a child of
6308 this Emacs.
6309 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6310 (Lisp_Object process, Lisp_Object sigcode)
6312 pid_t pid;
6313 int signo;
6315 if (STRINGP (process))
6317 Lisp_Object tem = Fget_process (process);
6318 if (NILP (tem))
6320 Lisp_Object process_number
6321 = string_to_number (SSDATA (process), 10, 1);
6322 if (INTEGERP (process_number) || FLOATP (process_number))
6323 tem = process_number;
6325 process = tem;
6327 else if (!NUMBERP (process))
6328 process = get_process (process);
6330 if (NILP (process))
6331 return process;
6333 if (NUMBERP (process))
6334 CONS_TO_INTEGER (process, pid_t, pid);
6335 else
6337 CHECK_PROCESS (process);
6338 pid = XPROCESS (process)->pid;
6339 if (pid <= 0)
6340 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6343 if (INTEGERP (sigcode))
6345 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6346 signo = XINT (sigcode);
6348 else
6350 char *name;
6352 CHECK_SYMBOL (sigcode);
6353 name = SSDATA (SYMBOL_NAME (sigcode));
6355 signo = abbr_to_signal (name);
6356 if (signo < 0)
6357 error ("Undefined signal name %s", name);
6360 return make_number (kill (pid, signo));
6363 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6364 doc: /* Make PROCESS see end-of-file in its input.
6365 EOF comes after any text already sent to it.
6366 PROCESS may be a process, a buffer, the name of a process or buffer, or
6367 nil, indicating the current buffer's process.
6368 If PROCESS is a network connection, or is a process communicating
6369 through a pipe (as opposed to a pty), then you cannot send any more
6370 text to PROCESS after you call this function.
6371 If PROCESS is a serial process, wait until all output written to the
6372 process has been transmitted to the serial port. */)
6373 (Lisp_Object process)
6375 Lisp_Object proc;
6376 struct coding_system *coding = NULL;
6377 int outfd;
6379 if (DATAGRAM_CONN_P (process))
6380 return process;
6382 proc = get_process (process);
6383 outfd = XPROCESS (proc)->outfd;
6384 if (outfd >= 0)
6385 coding = proc_encode_coding_system[outfd];
6387 /* Make sure the process is really alive. */
6388 if (XPROCESS (proc)->raw_status_new)
6389 update_status (XPROCESS (proc));
6390 if (! EQ (XPROCESS (proc)->status, Qrun))
6391 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6393 if (coding && CODING_REQUIRE_FLUSHING (coding))
6395 coding->mode |= CODING_MODE_LAST_BLOCK;
6396 send_process (proc, "", 0, Qnil);
6399 if (XPROCESS (proc)->pty_flag)
6400 send_process (proc, "\004", 1, Qnil);
6401 else if (EQ (XPROCESS (proc)->type, Qserial))
6403 #ifndef WINDOWSNT
6404 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6405 report_file_error ("Failed tcdrain", Qnil);
6406 #endif /* not WINDOWSNT */
6407 /* Do nothing on Windows because writes are blocking. */
6409 else
6411 struct Lisp_Process *p = XPROCESS (proc);
6412 int old_outfd = p->outfd;
6413 int new_outfd;
6415 #ifdef HAVE_SHUTDOWN
6416 /* If this is a network connection, or socketpair is used
6417 for communication with the subprocess, call shutdown to cause EOF.
6418 (In some old system, shutdown to socketpair doesn't work.
6419 Then we just can't win.) */
6420 if (0 <= old_outfd
6421 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6422 shutdown (old_outfd, 1);
6423 #endif
6424 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6425 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6426 if (new_outfd < 0)
6427 report_file_error ("Opening null device", Qnil);
6428 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6429 p->outfd = new_outfd;
6431 if (!proc_encode_coding_system[new_outfd])
6432 proc_encode_coding_system[new_outfd]
6433 = xmalloc (sizeof (struct coding_system));
6434 if (old_outfd >= 0)
6436 *proc_encode_coding_system[new_outfd]
6437 = *proc_encode_coding_system[old_outfd];
6438 memset (proc_encode_coding_system[old_outfd], 0,
6439 sizeof (struct coding_system));
6441 else
6442 setup_coding_system (p->encode_coding_system,
6443 proc_encode_coding_system[new_outfd]);
6445 return process;
6448 /* The main Emacs thread records child processes in three places:
6450 - Vprocess_alist, for asynchronous subprocesses, which are child
6451 processes visible to Lisp.
6453 - deleted_pid_list, for child processes invisible to Lisp,
6454 typically because of delete-process. These are recorded so that
6455 the processes can be reaped when they exit, so that the operating
6456 system's process table is not cluttered by zombies.
6458 - the local variable PID in Fcall_process, call_process_cleanup and
6459 call_process_kill, for synchronous subprocesses.
6460 record_unwind_protect is used to make sure this process is not
6461 forgotten: if the user interrupts call-process and the child
6462 process refuses to exit immediately even with two C-g's,
6463 call_process_kill adds PID's contents to deleted_pid_list before
6464 returning.
6466 The main Emacs thread invokes waitpid only on child processes that
6467 it creates and that have not been reaped. This avoid races on
6468 platforms such as GTK, where other threads create their own
6469 subprocesses which the main thread should not reap. For example,
6470 if the main thread attempted to reap an already-reaped child, it
6471 might inadvertently reap a GTK-created process that happened to
6472 have the same process ID. */
6474 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6475 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6476 keep track of its own children. GNUstep is similar. */
6478 static void dummy_handler (int sig) {}
6479 static signal_handler_t volatile lib_child_handler;
6481 /* Handle a SIGCHLD signal by looking for known child processes of
6482 Emacs whose status have changed. For each one found, record its
6483 new status.
6485 All we do is change the status; we do not run sentinels or print
6486 notifications. That is saved for the next time keyboard input is
6487 done, in order to avoid timing errors.
6489 ** WARNING: this can be called during garbage collection.
6490 Therefore, it must not be fooled by the presence of mark bits in
6491 Lisp objects.
6493 ** USG WARNING: Although it is not obvious from the documentation
6494 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6495 signal() before executing at least one wait(), otherwise the
6496 handler will be called again, resulting in an infinite loop. The
6497 relevant portion of the documentation reads "SIGCLD signals will be
6498 queued and the signal-catching function will be continually
6499 reentered until the queue is empty". Invoking signal() causes the
6500 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6501 Inc.
6503 ** Malloc WARNING: This should never call malloc either directly or
6504 indirectly; if it does, that is a bug. */
6506 static void
6507 handle_child_signal (int sig)
6509 Lisp_Object tail, proc;
6511 /* Find the process that signaled us, and record its status. */
6513 /* The process can have been deleted by Fdelete_process, or have
6514 been started asynchronously by Fcall_process. */
6515 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6517 bool all_pids_are_fixnums
6518 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6519 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6520 Lisp_Object head = XCAR (tail);
6521 Lisp_Object xpid;
6522 if (! CONSP (head))
6523 continue;
6524 xpid = XCAR (head);
6525 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6527 pid_t deleted_pid;
6528 if (INTEGERP (xpid))
6529 deleted_pid = XINT (xpid);
6530 else
6531 deleted_pid = XFLOAT_DATA (xpid);
6532 if (child_status_changed (deleted_pid, 0, 0))
6534 if (STRINGP (XCDR (head)))
6535 unlink (SSDATA (XCDR (head)));
6536 XSETCAR (tail, Qnil);
6541 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6542 FOR_EACH_PROCESS (tail, proc)
6544 struct Lisp_Process *p = XPROCESS (proc);
6545 int status;
6547 if (p->alive
6548 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6550 /* Change the status of the process that was found. */
6551 p->tick = ++process_tick;
6552 p->raw_status = status;
6553 p->raw_status_new = 1;
6555 /* If process has terminated, stop waiting for its output. */
6556 if (WIFSIGNALED (status) || WIFEXITED (status))
6558 bool clear_desc_flag = 0;
6559 p->alive = 0;
6560 if (p->infd >= 0)
6561 clear_desc_flag = 1;
6563 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6564 if (clear_desc_flag)
6566 FD_CLR (p->infd, &input_wait_mask);
6567 FD_CLR (p->infd, &non_keyboard_wait_mask);
6573 lib_child_handler (sig);
6574 #ifdef NS_IMPL_GNUSTEP
6575 /* NSTask in GNUstep sets its child handler each time it is called.
6576 So we must re-set ours. */
6577 catch_child_signal ();
6578 #endif
6581 static void
6582 deliver_child_signal (int sig)
6584 deliver_process_signal (sig, handle_child_signal);
6588 static Lisp_Object
6589 exec_sentinel_error_handler (Lisp_Object error_val)
6591 cmd_error_internal (error_val, "error in process sentinel: ");
6592 Vinhibit_quit = Qt;
6593 update_echo_area ();
6594 Fsleep_for (make_number (2), Qnil);
6595 return Qt;
6598 static void
6599 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6601 Lisp_Object sentinel, odeactivate;
6602 struct Lisp_Process *p = XPROCESS (proc);
6603 ptrdiff_t count = SPECPDL_INDEX ();
6604 bool outer_running_asynch_code = running_asynch_code;
6605 int waiting = waiting_for_user_input_p;
6607 if (inhibit_sentinels)
6608 return;
6610 /* No need to gcpro these, because all we do with them later
6611 is test them for EQness, and none of them should be a string. */
6612 odeactivate = Vdeactivate_mark;
6613 #if 0
6614 Lisp_Object obuffer, okeymap;
6615 XSETBUFFER (obuffer, current_buffer);
6616 okeymap = BVAR (current_buffer, keymap);
6617 #endif
6619 /* There's no good reason to let sentinels change the current
6620 buffer, and many callers of accept-process-output, sit-for, and
6621 friends don't expect current-buffer to be changed from under them. */
6622 record_unwind_current_buffer ();
6624 sentinel = p->sentinel;
6626 /* Inhibit quit so that random quits don't screw up a running filter. */
6627 specbind (Qinhibit_quit, Qt);
6628 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6630 /* In case we get recursively called,
6631 and we already saved the match data nonrecursively,
6632 save the same match data in safely recursive fashion. */
6633 if (outer_running_asynch_code)
6635 Lisp_Object tem;
6636 tem = Fmatch_data (Qnil, Qnil, Qnil);
6637 restore_search_regs ();
6638 record_unwind_save_match_data ();
6639 Fset_match_data (tem, Qt);
6642 /* For speed, if a search happens within this code,
6643 save the match data in a special nonrecursive fashion. */
6644 running_asynch_code = 1;
6646 internal_condition_case_1 (read_process_output_call,
6647 list3 (sentinel, proc, reason),
6648 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6649 exec_sentinel_error_handler);
6651 /* If we saved the match data nonrecursively, restore it now. */
6652 restore_search_regs ();
6653 running_asynch_code = outer_running_asynch_code;
6655 Vdeactivate_mark = odeactivate;
6657 /* Restore waiting_for_user_input_p as it was
6658 when we were called, in case the filter clobbered it. */
6659 waiting_for_user_input_p = waiting;
6661 #if 0
6662 if (! EQ (Fcurrent_buffer (), obuffer)
6663 || ! EQ (current_buffer->keymap, okeymap))
6664 #endif
6665 /* But do it only if the caller is actually going to read events.
6666 Otherwise there's no need to make him wake up, and it could
6667 cause trouble (for example it would make sit_for return). */
6668 if (waiting_for_user_input_p == -1)
6669 record_asynch_buffer_change ();
6671 unbind_to (count, Qnil);
6674 /* Report all recent events of a change in process status
6675 (either run the sentinel or output a message).
6676 This is usually done while Emacs is waiting for keyboard input
6677 but can be done at other times.
6679 Return positive if any input was received from WAIT_PROC (or from
6680 any process if WAIT_PROC is null), zero if input was attempted but
6681 none received, and negative if we didn't even try. */
6683 static int
6684 status_notify (struct Lisp_Process *deleting_process,
6685 struct Lisp_Process *wait_proc)
6687 Lisp_Object proc;
6688 Lisp_Object tail, msg;
6689 struct gcpro gcpro1, gcpro2;
6690 int got_some_input = -1;
6692 tail = Qnil;
6693 msg = Qnil;
6694 /* We need to gcpro tail; if read_process_output calls a filter
6695 which deletes a process and removes the cons to which tail points
6696 from Vprocess_alist, and then causes a GC, tail is an unprotected
6697 reference. */
6698 GCPRO2 (tail, msg);
6700 /* Set this now, so that if new processes are created by sentinels
6701 that we run, we get called again to handle their status changes. */
6702 update_tick = process_tick;
6704 FOR_EACH_PROCESS (tail, proc)
6706 Lisp_Object symbol;
6707 register struct Lisp_Process *p = XPROCESS (proc);
6709 if (p->tick != p->update_tick)
6711 p->update_tick = p->tick;
6713 /* If process is still active, read any output that remains. */
6714 while (! EQ (p->filter, Qt)
6715 && ! EQ (p->status, Qconnect)
6716 && ! EQ (p->status, Qlisten)
6717 /* Network or serial process not stopped: */
6718 && ! EQ (p->command, Qt)
6719 && p->infd >= 0
6720 && p != deleting_process)
6722 int nread = read_process_output (proc, p->infd);
6723 if (got_some_input < nread)
6724 got_some_input = nread;
6725 if (nread <= 0)
6726 break;
6729 /* Get the text to use for the message. */
6730 if (p->raw_status_new)
6731 update_status (p);
6732 msg = status_message (p);
6734 /* If process is terminated, deactivate it or delete it. */
6735 symbol = p->status;
6736 if (CONSP (p->status))
6737 symbol = XCAR (p->status);
6739 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6740 || EQ (symbol, Qclosed))
6742 if (delete_exited_processes)
6743 remove_process (proc);
6744 else
6745 deactivate_process (proc);
6748 /* The actions above may have further incremented p->tick.
6749 So set p->update_tick again so that an error in the sentinel will
6750 not cause this code to be run again. */
6751 p->update_tick = p->tick;
6752 /* Now output the message suitably. */
6753 exec_sentinel (proc, msg);
6755 } /* end for */
6757 update_mode_lines = 24; /* In case buffers use %s in mode-line-format. */
6758 UNGCPRO;
6759 return got_some_input;
6762 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6763 Sinternal_default_process_sentinel, 2, 2, 0,
6764 doc: /* Function used as default sentinel for processes.
6765 This inserts a status message into the process's buffer, if there is one. */)
6766 (Lisp_Object proc, Lisp_Object msg)
6768 Lisp_Object buffer, symbol;
6769 struct Lisp_Process *p;
6770 CHECK_PROCESS (proc);
6771 p = XPROCESS (proc);
6772 buffer = p->buffer;
6773 symbol = p->status;
6774 if (CONSP (symbol))
6775 symbol = XCAR (symbol);
6777 if (!EQ (symbol, Qrun) && !NILP (buffer))
6779 Lisp_Object tem;
6780 struct buffer *old = current_buffer;
6781 ptrdiff_t opoint, opoint_byte;
6782 ptrdiff_t before, before_byte;
6784 /* Avoid error if buffer is deleted
6785 (probably that's why the process is dead, too). */
6786 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6787 return Qnil;
6788 Fset_buffer (buffer);
6790 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6791 msg = (code_convert_string_norecord
6792 (msg, Vlocale_coding_system, 1));
6794 opoint = PT;
6795 opoint_byte = PT_BYTE;
6796 /* Insert new output into buffer
6797 at the current end-of-output marker,
6798 thus preserving logical ordering of input and output. */
6799 if (XMARKER (p->mark)->buffer)
6800 Fgoto_char (p->mark);
6801 else
6802 SET_PT_BOTH (ZV, ZV_BYTE);
6804 before = PT;
6805 before_byte = PT_BYTE;
6807 tem = BVAR (current_buffer, read_only);
6808 bset_read_only (current_buffer, Qnil);
6809 insert_string ("\nProcess ");
6810 { /* FIXME: temporary kludge. */
6811 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6812 insert_string (" ");
6813 Finsert (1, &msg);
6814 bset_read_only (current_buffer, tem);
6815 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6817 if (opoint >= before)
6818 SET_PT_BOTH (opoint + (PT - before),
6819 opoint_byte + (PT_BYTE - before_byte));
6820 else
6821 SET_PT_BOTH (opoint, opoint_byte);
6823 set_buffer_internal (old);
6825 return Qnil;
6829 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6830 Sset_process_coding_system, 1, 3, 0,
6831 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6832 DECODING will be used to decode subprocess output and ENCODING to
6833 encode subprocess input. */)
6834 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6836 register struct Lisp_Process *p;
6838 CHECK_PROCESS (process);
6839 p = XPROCESS (process);
6840 if (p->infd < 0)
6841 error ("Input file descriptor of %s closed", SDATA (p->name));
6842 if (p->outfd < 0)
6843 error ("Output file descriptor of %s closed", SDATA (p->name));
6844 Fcheck_coding_system (decoding);
6845 Fcheck_coding_system (encoding);
6846 encoding = coding_inherit_eol_type (encoding, Qnil);
6847 pset_decode_coding_system (p, decoding);
6848 pset_encode_coding_system (p, encoding);
6849 setup_process_coding_systems (process);
6851 return Qnil;
6854 DEFUN ("process-coding-system",
6855 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6856 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6857 (register Lisp_Object process)
6859 CHECK_PROCESS (process);
6860 return Fcons (XPROCESS (process)->decode_coding_system,
6861 XPROCESS (process)->encode_coding_system);
6864 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6865 Sset_process_filter_multibyte, 2, 2, 0,
6866 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6867 If FLAG is non-nil, the filter is given multibyte strings.
6868 If FLAG is nil, the filter is given unibyte strings. In this case,
6869 all character code conversion except for end-of-line conversion is
6870 suppressed. */)
6871 (Lisp_Object process, Lisp_Object flag)
6873 register struct Lisp_Process *p;
6875 CHECK_PROCESS (process);
6876 p = XPROCESS (process);
6877 if (NILP (flag))
6878 pset_decode_coding_system
6879 (p, raw_text_coding_system (p->decode_coding_system));
6880 setup_process_coding_systems (process);
6882 return Qnil;
6885 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6886 Sprocess_filter_multibyte_p, 1, 1, 0,
6887 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6888 (Lisp_Object process)
6890 register struct Lisp_Process *p;
6891 struct coding_system *coding;
6893 CHECK_PROCESS (process);
6894 p = XPROCESS (process);
6895 if (p->infd < 0)
6896 return Qnil;
6897 coding = proc_decode_coding_system[p->infd];
6898 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6904 # ifdef HAVE_GPM
6906 void
6907 add_gpm_wait_descriptor (int desc)
6909 add_keyboard_wait_descriptor (desc);
6912 void
6913 delete_gpm_wait_descriptor (int desc)
6915 delete_keyboard_wait_descriptor (desc);
6918 # endif
6920 # ifdef USABLE_SIGIO
6922 /* Return true if *MASK has a bit set
6923 that corresponds to one of the keyboard input descriptors. */
6925 static bool
6926 keyboard_bit_set (fd_set *mask)
6928 int fd;
6930 for (fd = 0; fd <= max_input_desc; fd++)
6931 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6932 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6933 return 1;
6935 return 0;
6937 # endif
6939 #else /* not subprocesses */
6941 /* Defined in msdos.c. */
6942 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6943 struct timespec *, void *);
6945 /* Implementation of wait_reading_process_output, assuming that there
6946 are no subprocesses. Used only by the MS-DOS build.
6948 Wait for timeout to elapse and/or keyboard input to be available.
6950 TIME_LIMIT is:
6951 timeout in seconds
6952 If negative, gobble data immediately available but don't wait for any.
6954 NSECS is:
6955 an additional duration to wait, measured in nanoseconds
6956 If TIME_LIMIT is zero, then:
6957 If NSECS == 0, there is no limit.
6958 If NSECS > 0, the timeout consists of NSECS only.
6959 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6961 READ_KBD is:
6962 0 to ignore keyboard input, or
6963 1 to return when input is available, or
6964 -1 means caller will actually read the input, so don't throw to
6965 the quit handler.
6967 see full version for other parameters. We know that wait_proc will
6968 always be NULL, since `subprocesses' isn't defined.
6970 DO_DISPLAY means redisplay should be done to show subprocess
6971 output that arrives.
6973 Return positive if we received input from WAIT_PROC (or from any
6974 process if WAIT_PROC is null), zero if we attempted to receive
6975 input but got none, and negative if we didn't even try. */
6978 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6979 bool do_display,
6980 Lisp_Object wait_for_cell,
6981 struct Lisp_Process *wait_proc, int just_wait_proc)
6983 register int nfds;
6984 struct timespec end_time, timeout;
6986 if (time_limit < 0)
6988 time_limit = 0;
6989 nsecs = -1;
6991 else if (TYPE_MAXIMUM (time_t) < time_limit)
6992 time_limit = TYPE_MAXIMUM (time_t);
6994 /* What does time_limit really mean? */
6995 if (time_limit || nsecs > 0)
6997 timeout = make_timespec (time_limit, nsecs);
6998 end_time = timespec_add (current_timespec (), timeout);
7001 /* Turn off periodic alarms (in case they are in use)
7002 and then turn off any other atimers,
7003 because the select emulator uses alarms. */
7004 stop_polling ();
7005 turn_on_atimers (0);
7007 while (1)
7009 bool timeout_reduced_for_timers = false;
7010 fd_set waitchannels;
7011 int xerrno;
7013 /* If calling from keyboard input, do not quit
7014 since we want to return C-g as an input character.
7015 Otherwise, do pending quit if requested. */
7016 if (read_kbd >= 0)
7017 QUIT;
7019 /* Exit now if the cell we're waiting for became non-nil. */
7020 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7021 break;
7023 /* Compute time from now till when time limit is up. */
7024 /* Exit if already run out. */
7025 if (nsecs < 0)
7027 /* A negative timeout means
7028 gobble output available now
7029 but don't wait at all. */
7031 timeout = make_timespec (0, 0);
7033 else if (time_limit || nsecs > 0)
7035 struct timespec now = current_timespec ();
7036 if (timespec_cmp (end_time, now) <= 0)
7037 break;
7038 timeout = timespec_sub (end_time, now);
7040 else
7042 timeout = make_timespec (100000, 0);
7045 /* If our caller will not immediately handle keyboard events,
7046 run timer events directly.
7047 (Callers that will immediately read keyboard events
7048 call timer_delay on their own.) */
7049 if (NILP (wait_for_cell))
7051 struct timespec timer_delay;
7055 unsigned old_timers_run = timers_run;
7056 timer_delay = timer_check ();
7057 if (timers_run != old_timers_run && do_display)
7058 /* We must retry, since a timer may have requeued itself
7059 and that could alter the time delay. */
7060 redisplay_preserve_echo_area (14);
7061 else
7062 break;
7064 while (!detect_input_pending ());
7066 /* If there is unread keyboard input, also return. */
7067 if (read_kbd != 0
7068 && requeued_events_pending_p ())
7069 break;
7071 if (timespec_valid_p (timer_delay) && nsecs >= 0)
7073 if (timespec_cmp (timer_delay, timeout) < 0)
7075 timeout = timer_delay;
7076 timeout_reduced_for_timers = true;
7081 /* Cause C-g and alarm signals to take immediate action,
7082 and cause input available signals to zero out timeout. */
7083 if (read_kbd < 0)
7084 set_waiting_for_input (&timeout);
7086 /* If a frame has been newly mapped and needs updating,
7087 reprocess its display stuff. */
7088 if (frame_garbaged && do_display)
7090 clear_waiting_for_input ();
7091 redisplay_preserve_echo_area (15);
7092 if (read_kbd < 0)
7093 set_waiting_for_input (&timeout);
7096 /* Wait till there is something to do. */
7097 FD_ZERO (&waitchannels);
7098 if (read_kbd && detect_input_pending ())
7099 nfds = 0;
7100 else
7102 if (read_kbd || !NILP (wait_for_cell))
7103 FD_SET (0, &waitchannels);
7104 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7107 xerrno = errno;
7109 /* Make C-g and alarm signals set flags again. */
7110 clear_waiting_for_input ();
7112 /* If we woke up due to SIGWINCH, actually change size now. */
7113 do_pending_window_change (0);
7115 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
7116 /* We waited the full specified time, so return now. */
7117 break;
7119 if (nfds == -1)
7121 /* If the system call was interrupted, then go around the
7122 loop again. */
7123 if (xerrno == EINTR)
7124 FD_ZERO (&waitchannels);
7125 else
7126 report_file_errno ("Failed select", Qnil, xerrno);
7129 /* Check for keyboard input. */
7131 if (read_kbd
7132 && detect_input_pending_run_timers (do_display))
7134 swallow_events (do_display);
7135 if (detect_input_pending_run_timers (do_display))
7136 break;
7139 /* If there is unread keyboard input, also return. */
7140 if (read_kbd
7141 && requeued_events_pending_p ())
7142 break;
7144 /* If wait_for_cell. check for keyboard input
7145 but don't run any timers.
7146 ??? (It seems wrong to me to check for keyboard
7147 input at all when wait_for_cell, but the code
7148 has been this way since July 1994.
7149 Try changing this after version 19.31.) */
7150 if (! NILP (wait_for_cell)
7151 && detect_input_pending ())
7153 swallow_events (do_display);
7154 if (detect_input_pending ())
7155 break;
7158 /* Exit now if the cell we're waiting for became non-nil. */
7159 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7160 break;
7163 start_polling ();
7165 return -1;
7168 #endif /* not subprocesses */
7170 /* The following functions are needed even if async subprocesses are
7171 not supported. Some of them are no-op stubs in that case. */
7173 #ifdef HAVE_TIMERFD
7175 /* Add FD, which is a descriptor returned by timerfd_create,
7176 to the set of non-keyboard input descriptors. */
7178 void
7179 add_timer_wait_descriptor (int fd)
7181 FD_SET (fd, &input_wait_mask);
7182 FD_SET (fd, &non_keyboard_wait_mask);
7183 FD_SET (fd, &non_process_wait_mask);
7184 fd_callback_info[fd].func = timerfd_callback;
7185 fd_callback_info[fd].data = NULL;
7186 fd_callback_info[fd].condition |= FOR_READ;
7187 if (fd > max_input_desc)
7188 max_input_desc = fd;
7191 #endif /* HAVE_TIMERFD */
7193 /* Add DESC to the set of keyboard input descriptors. */
7195 void
7196 add_keyboard_wait_descriptor (int desc)
7198 #ifdef subprocesses /* Actually means "not MSDOS". */
7199 FD_SET (desc, &input_wait_mask);
7200 FD_SET (desc, &non_process_wait_mask);
7201 if (desc > max_input_desc)
7202 max_input_desc = desc;
7203 #endif
7206 /* From now on, do not expect DESC to give keyboard input. */
7208 void
7209 delete_keyboard_wait_descriptor (int desc)
7211 #ifdef subprocesses
7212 FD_CLR (desc, &input_wait_mask);
7213 FD_CLR (desc, &non_process_wait_mask);
7214 delete_input_desc (desc);
7215 #endif
7218 /* Setup coding systems of PROCESS. */
7220 void
7221 setup_process_coding_systems (Lisp_Object process)
7223 #ifdef subprocesses
7224 struct Lisp_Process *p = XPROCESS (process);
7225 int inch = p->infd;
7226 int outch = p->outfd;
7227 Lisp_Object coding_system;
7229 if (inch < 0 || outch < 0)
7230 return;
7232 if (!proc_decode_coding_system[inch])
7233 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7234 coding_system = p->decode_coding_system;
7235 if (EQ (p->filter, Qinternal_default_process_filter)
7236 && BUFFERP (p->buffer))
7238 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7239 coding_system = raw_text_coding_system (coding_system);
7241 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7243 if (!proc_encode_coding_system[outch])
7244 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7245 setup_coding_system (p->encode_coding_system,
7246 proc_encode_coding_system[outch]);
7247 #endif
7250 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7251 doc: /* Return the (or a) process associated with BUFFER.
7252 BUFFER may be a buffer or the name of one. */)
7253 (register Lisp_Object buffer)
7255 #ifdef subprocesses
7256 register Lisp_Object buf, tail, proc;
7258 if (NILP (buffer)) return Qnil;
7259 buf = Fget_buffer (buffer);
7260 if (NILP (buf)) return Qnil;
7262 FOR_EACH_PROCESS (tail, proc)
7263 if (EQ (XPROCESS (proc)->buffer, buf))
7264 return proc;
7265 #endif /* subprocesses */
7266 return Qnil;
7269 DEFUN ("process-inherit-coding-system-flag",
7270 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7271 1, 1, 0,
7272 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7273 If this flag is t, `buffer-file-coding-system' of the buffer
7274 associated with PROCESS will inherit the coding system used to decode
7275 the process output. */)
7276 (register Lisp_Object process)
7278 #ifdef subprocesses
7279 CHECK_PROCESS (process);
7280 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7281 #else
7282 /* Ignore the argument and return the value of
7283 inherit-process-coding-system. */
7284 return inherit_process_coding_system ? Qt : Qnil;
7285 #endif
7288 /* Kill all processes associated with `buffer'.
7289 If `buffer' is nil, kill all processes. */
7291 void
7292 kill_buffer_processes (Lisp_Object buffer)
7294 #ifdef subprocesses
7295 Lisp_Object tail, proc;
7297 FOR_EACH_PROCESS (tail, proc)
7298 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7300 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7301 Fdelete_process (proc);
7302 else if (XPROCESS (proc)->infd >= 0)
7303 process_send_signal (proc, SIGHUP, Qnil, 1);
7305 #else /* subprocesses */
7306 /* Since we have no subprocesses, this does nothing. */
7307 #endif /* subprocesses */
7310 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7311 Swaiting_for_user_input_p, 0, 0, 0,
7312 doc: /* Return non-nil if Emacs is waiting for input from the user.
7313 This is intended for use by asynchronous process output filters and sentinels. */)
7314 (void)
7316 #ifdef subprocesses
7317 return (waiting_for_user_input_p ? Qt : Qnil);
7318 #else
7319 return Qnil;
7320 #endif
7323 /* Stop reading input from keyboard sources. */
7325 void
7326 hold_keyboard_input (void)
7328 kbd_is_on_hold = 1;
7331 /* Resume reading input from keyboard sources. */
7333 void
7334 unhold_keyboard_input (void)
7336 kbd_is_on_hold = 0;
7339 /* Return true if keyboard input is on hold, zero otherwise. */
7341 bool
7342 kbd_on_hold_p (void)
7344 return kbd_is_on_hold;
7348 /* Enumeration of and access to system processes a-la ps(1). */
7350 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7351 0, 0, 0,
7352 doc: /* Return a list of numerical process IDs of all running processes.
7353 If this functionality is unsupported, return nil.
7355 See `process-attributes' for getting attributes of a process given its ID. */)
7356 (void)
7358 return list_system_processes ();
7361 DEFUN ("process-attributes", Fprocess_attributes,
7362 Sprocess_attributes, 1, 1, 0,
7363 doc: /* Return attributes of the process given by its PID, a number.
7365 Value is an alist where each element is a cons cell of the form
7367 \(KEY . VALUE)
7369 If this functionality is unsupported, the value is nil.
7371 See `list-system-processes' for getting a list of all process IDs.
7373 The KEYs of the attributes that this function may return are listed
7374 below, together with the type of the associated VALUE (in parentheses).
7375 Not all platforms support all of these attributes; unsupported
7376 attributes will not appear in the returned alist.
7377 Unless explicitly indicated otherwise, numbers can have either
7378 integer or floating point values.
7380 euid -- Effective user User ID of the process (number)
7381 user -- User name corresponding to euid (string)
7382 egid -- Effective user Group ID of the process (number)
7383 group -- Group name corresponding to egid (string)
7384 comm -- Command name (executable name only) (string)
7385 state -- Process state code, such as "S", "R", or "T" (string)
7386 ppid -- Parent process ID (number)
7387 pgrp -- Process group ID (number)
7388 sess -- Session ID, i.e. process ID of session leader (number)
7389 ttname -- Controlling tty name (string)
7390 tpgid -- ID of foreground process group on the process's tty (number)
7391 minflt -- number of minor page faults (number)
7392 majflt -- number of major page faults (number)
7393 cminflt -- cumulative number of minor page faults (number)
7394 cmajflt -- cumulative number of major page faults (number)
7395 utime -- user time used by the process, in (current-time) format,
7396 which is a list of integers (HIGH LOW USEC PSEC)
7397 stime -- system time used by the process (current-time)
7398 time -- sum of utime and stime (current-time)
7399 cutime -- user time used by the process and its children (current-time)
7400 cstime -- system time used by the process and its children (current-time)
7401 ctime -- sum of cutime and cstime (current-time)
7402 pri -- priority of the process (number)
7403 nice -- nice value of the process (number)
7404 thcount -- process thread count (number)
7405 start -- time the process started (current-time)
7406 vsize -- virtual memory size of the process in KB's (number)
7407 rss -- resident set size of the process in KB's (number)
7408 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7409 pcpu -- percents of CPU time used by the process (floating-point number)
7410 pmem -- percents of total physical memory used by process's resident set
7411 (floating-point number)
7412 args -- command line which invoked the process (string). */)
7413 ( Lisp_Object pid)
7415 return system_process_attributes (pid);
7418 #ifdef subprocesses
7419 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7420 Invoke this after init_process_emacs, and after glib and/or GNUstep
7421 futz with the SIGCHLD handler, but before Emacs forks any children.
7422 This function's caller should block SIGCHLD. */
7424 void
7425 catch_child_signal (void)
7427 struct sigaction action, old_action;
7428 sigset_t oldset;
7429 emacs_sigaction_init (&action, deliver_child_signal);
7430 block_child_signal (&oldset);
7431 sigaction (SIGCHLD, &action, &old_action);
7432 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7433 || ! (old_action.sa_flags & SA_SIGINFO));
7435 if (old_action.sa_handler != deliver_child_signal)
7436 lib_child_handler
7437 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7438 ? dummy_handler
7439 : old_action.sa_handler);
7440 unblock_child_signal (&oldset);
7442 #endif /* subprocesses */
7445 /* This is not called "init_process" because that is the name of a
7446 Mach system call, so it would cause problems on Darwin systems. */
7447 void
7448 init_process_emacs (void)
7450 #ifdef subprocesses
7451 register int i;
7453 inhibit_sentinels = 0;
7455 #ifndef CANNOT_DUMP
7456 if (! noninteractive || initialized)
7457 #endif
7459 #if defined HAVE_GLIB && !defined WINDOWSNT
7460 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7461 this should always fail, but is enough to initialize glib's
7462 private SIGCHLD handler, allowing catch_child_signal to copy
7463 it into lib_child_handler. */
7464 g_source_unref (g_child_watch_source_new (getpid ()));
7465 #endif
7466 catch_child_signal ();
7469 FD_ZERO (&input_wait_mask);
7470 FD_ZERO (&non_keyboard_wait_mask);
7471 FD_ZERO (&non_process_wait_mask);
7472 FD_ZERO (&write_mask);
7473 max_process_desc = max_input_desc = -1;
7474 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7476 #ifdef NON_BLOCKING_CONNECT
7477 FD_ZERO (&connect_wait_mask);
7478 num_pending_connects = 0;
7479 #endif
7481 #ifdef ADAPTIVE_READ_BUFFERING
7482 process_output_delay_count = 0;
7483 process_output_skip = 0;
7484 #endif
7486 /* Don't do this, it caused infinite select loops. The display
7487 method should call add_keyboard_wait_descriptor on stdin if it
7488 needs that. */
7489 #if 0
7490 FD_SET (0, &input_wait_mask);
7491 #endif
7493 Vprocess_alist = Qnil;
7494 deleted_pid_list = Qnil;
7495 for (i = 0; i < FD_SETSIZE; i++)
7497 chan_process[i] = Qnil;
7498 proc_buffered_char[i] = -1;
7500 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7501 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7502 #ifdef DATAGRAM_SOCKETS
7503 memset (datagram_address, 0, sizeof datagram_address);
7504 #endif
7506 #if defined (DARWIN_OS)
7507 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7508 processes. As such, we only change the default value. */
7509 if (initialized)
7511 char const *release = (STRINGP (Voperating_system_release)
7512 ? SSDATA (Voperating_system_release)
7513 : 0);
7514 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7515 Vprocess_connection_type = Qnil;
7518 #endif
7519 #endif /* subprocesses */
7520 kbd_is_on_hold = 0;
7523 void
7524 syms_of_process (void)
7526 #ifdef subprocesses
7528 DEFSYM (Qprocessp, "processp");
7529 DEFSYM (Qrun, "run");
7530 DEFSYM (Qstop, "stop");
7531 DEFSYM (Qsignal, "signal");
7533 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7534 here again. */
7536 DEFSYM (Qopen, "open");
7537 DEFSYM (Qclosed, "closed");
7538 DEFSYM (Qconnect, "connect");
7539 DEFSYM (Qfailed, "failed");
7540 DEFSYM (Qlisten, "listen");
7541 DEFSYM (Qlocal, "local");
7542 DEFSYM (Qipv4, "ipv4");
7543 #ifdef AF_INET6
7544 DEFSYM (Qipv6, "ipv6");
7545 #endif
7546 DEFSYM (Qdatagram, "datagram");
7547 DEFSYM (Qseqpacket, "seqpacket");
7549 DEFSYM (QCport, ":port");
7550 DEFSYM (QCspeed, ":speed");
7551 DEFSYM (QCprocess, ":process");
7553 DEFSYM (QCbytesize, ":bytesize");
7554 DEFSYM (QCstopbits, ":stopbits");
7555 DEFSYM (QCparity, ":parity");
7556 DEFSYM (Qodd, "odd");
7557 DEFSYM (Qeven, "even");
7558 DEFSYM (QCflowcontrol, ":flowcontrol");
7559 DEFSYM (Qhw, "hw");
7560 DEFSYM (Qsw, "sw");
7561 DEFSYM (QCsummary, ":summary");
7563 DEFSYM (Qreal, "real");
7564 DEFSYM (Qnetwork, "network");
7565 DEFSYM (Qserial, "serial");
7566 DEFSYM (Qpipe, "pipe");
7567 DEFSYM (QCbuffer, ":buffer");
7568 DEFSYM (QChost, ":host");
7569 DEFSYM (QCservice, ":service");
7570 DEFSYM (QClocal, ":local");
7571 DEFSYM (QCremote, ":remote");
7572 DEFSYM (QCcoding, ":coding");
7573 DEFSYM (QCserver, ":server");
7574 DEFSYM (QCnowait, ":nowait");
7575 DEFSYM (QCsentinel, ":sentinel");
7576 DEFSYM (QClog, ":log");
7577 DEFSYM (QCnoquery, ":noquery");
7578 DEFSYM (QCstop, ":stop");
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);