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