Use PAT rather than UPAT in pcase macros
[emacs.git] / src / process.c
blobf4613be28edf8c6edcad5b88007433933145d186
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 USE_SAFE_ALLOCA;
1407 if (nargs == 0)
1408 return Qnil;
1410 /* Save arguments for process-contact and clone-process. */
1411 contact = Flist (nargs, args);
1413 buffer = Fplist_get (contact, QCbuffer);
1414 if (!NILP (buffer))
1415 buffer = Fget_buffer_create (buffer);
1417 /* Make sure that the child will be able to chdir to the current
1418 buffer's current directory, or its unhandled equivalent. We
1419 can't just have the child check for an error when it does the
1420 chdir, since it's in a vfork. */
1421 current_dir = encode_current_directory ();
1423 name = Fplist_get (contact, QCname);
1424 CHECK_STRING (name);
1426 command = Fplist_get (contact, QCcommand);
1427 if (CONSP (command))
1428 program = XCAR (command);
1429 else
1430 program = Qnil;
1432 if (!NILP (program))
1433 CHECK_STRING (program);
1435 stderrproc = Qnil;
1436 xstderr = Fplist_get (contact, QCstderr);
1437 if (PROCESSP (xstderr))
1439 if (!PIPECONN_P (xstderr))
1440 error ("Process is not a pipe process");
1441 stderrproc = xstderr;
1443 else if (!NILP (xstderr))
1445 CHECK_STRING (program);
1446 stderrproc = CALLN (Fmake_pipe_process,
1447 QCname,
1448 concat2 (name, build_string (" stderr")),
1449 QCbuffer,
1450 Fget_buffer_create (xstderr));
1453 proc = make_process (name);
1454 /* If an error occurs and we can't start the process, we want to
1455 remove it from the process list. This means that each error
1456 check in create_process doesn't need to call remove_process
1457 itself; it's all taken care of here. */
1458 record_unwind_protect (start_process_unwind, proc);
1460 pset_childp (XPROCESS (proc), Qt);
1461 pset_plist (XPROCESS (proc), Qnil);
1462 pset_type (XPROCESS (proc), Qreal);
1463 pset_buffer (XPROCESS (proc), buffer);
1464 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1465 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1466 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1468 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
1469 XPROCESS (proc)->kill_without_query = 1;
1470 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1471 pset_command (XPROCESS (proc), Qt);
1473 tem = Fplist_get (contact, QCconnection_type);
1474 if (EQ (tem, Qpty))
1475 XPROCESS (proc)->pty_flag = true;
1476 else if (EQ (tem, Qpipe))
1477 XPROCESS (proc)->pty_flag = false;
1478 else if (NILP (tem))
1479 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1480 else
1481 report_file_error ("Unknown connection type", tem);
1483 if (!NILP (stderrproc))
1485 pset_stderrproc (XPROCESS (proc), stderrproc);
1487 XPROCESS (proc)->pty_flag = false;
1490 #ifdef HAVE_GNUTLS
1491 /* AKA GNUTLS_INITSTAGE(proc). */
1492 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1493 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1494 #endif
1496 XPROCESS (proc)->adaptive_read_buffering
1497 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1498 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1500 /* Make the process marker point into the process buffer (if any). */
1501 if (BUFFERP (buffer))
1502 set_marker_both (XPROCESS (proc)->mark, buffer,
1503 BUF_ZV (XBUFFER (buffer)),
1504 BUF_ZV_BYTE (XBUFFER (buffer)));
1507 /* Decide coding systems for communicating with the process. Here
1508 we don't setup the structure coding_system nor pay attention to
1509 unibyte mode. They are done in create_process. */
1511 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1512 Lisp_Object coding_systems = Qt;
1513 Lisp_Object val, *args2;
1515 tem = Fplist_get (contact, QCcoding);
1516 if (!NILP (tem))
1518 val = tem;
1519 if (CONSP (val))
1520 val = XCAR (val);
1522 else
1523 val = Vcoding_system_for_read;
1524 if (NILP (val))
1526 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1527 Lisp_Object tem2;
1528 SAFE_ALLOCA_LISP (args2, nargs2);
1529 ptrdiff_t i = 0;
1530 args2[i++] = Qstart_process;
1531 args2[i++] = name;
1532 args2[i++] = buffer;
1533 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1534 args2[i++] = XCAR (tem2);
1535 if (!NILP (program))
1536 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1537 if (CONSP (coding_systems))
1538 val = XCAR (coding_systems);
1539 else if (CONSP (Vdefault_process_coding_system))
1540 val = XCAR (Vdefault_process_coding_system);
1542 pset_decode_coding_system (XPROCESS (proc), val);
1544 if (!NILP (tem))
1546 val = tem;
1547 if (CONSP (val))
1548 val = XCDR (val);
1550 else
1551 val = Vcoding_system_for_write;
1552 if (NILP (val))
1554 if (EQ (coding_systems, Qt))
1556 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1557 Lisp_Object tem2;
1558 SAFE_ALLOCA_LISP (args2, nargs2);
1559 ptrdiff_t i = 0;
1560 args2[i++] = Qstart_process;
1561 args2[i++] = name;
1562 args2[i++] = buffer;
1563 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1564 args2[i++] = XCAR (tem2);
1565 if (!NILP (program))
1566 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1568 if (CONSP (coding_systems))
1569 val = XCDR (coding_systems);
1570 else if (CONSP (Vdefault_process_coding_system))
1571 val = XCDR (Vdefault_process_coding_system);
1573 pset_encode_coding_system (XPROCESS (proc), val);
1574 /* Note: At this moment, the above coding system may leave
1575 text-conversion or eol-conversion unspecified. They will be
1576 decided after we read output from the process and decode it by
1577 some coding system, or just before we actually send a text to
1578 the process. */
1582 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1583 XPROCESS (proc)->decoding_carryover = 0;
1584 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1586 XPROCESS (proc)->inherit_coding_system_flag
1587 = !(NILP (buffer) || !inherit_process_coding_system);
1589 if (!NILP (program))
1591 Lisp_Object program_args = XCDR (command);
1593 /* If program file name is not absolute, search our path for it.
1594 Put the name we will really use in TEM. */
1595 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1596 && !(SCHARS (program) > 1
1597 && IS_DEVICE_SEP (SREF (program, 1))))
1599 tem = Qnil;
1600 openp (Vexec_path, program, Vexec_suffixes, &tem,
1601 make_number (X_OK), false);
1602 if (NILP (tem))
1603 report_file_error ("Searching for program", program);
1604 tem = Fexpand_file_name (tem, Qnil);
1606 else
1608 if (!NILP (Ffile_directory_p (program)))
1609 error ("Specified program for new process is a directory");
1610 tem = program;
1613 /* Remove "/:" from TEM. */
1614 tem = remove_slash_colon (tem);
1616 Lisp_Object arg_encoding = Qnil;
1618 /* Encode the file name and put it in NEW_ARGV.
1619 That's where the child will use it to execute the program. */
1620 tem = list1 (ENCODE_FILE (tem));
1621 ptrdiff_t new_argc = 1;
1623 /* Here we encode arguments by the coding system used for sending
1624 data to the process. We don't support using different coding
1625 systems for encoding arguments and for encoding data sent to the
1626 process. */
1628 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1630 Lisp_Object arg = XCAR (tem2);
1631 CHECK_STRING (arg);
1632 if (STRING_MULTIBYTE (arg))
1634 if (NILP (arg_encoding))
1635 arg_encoding = (complement_process_encoding_system
1636 (XPROCESS (proc)->encode_coding_system));
1637 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1639 tem = Fcons (arg, tem);
1640 new_argc++;
1643 /* Now that everything is encoded we can collect the strings into
1644 NEW_ARGV. */
1645 char **new_argv;
1646 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1647 new_argv[new_argc] = 0;
1649 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1651 new_argv[i] = SSDATA (XCAR (tem));
1652 tem = XCDR (tem);
1655 create_process (proc, new_argv, current_dir);
1657 else
1658 create_pty (proc);
1660 SAFE_FREE ();
1661 return unbind_to (count, proc);
1664 /* This function is the unwind_protect form for Fstart_process. If
1665 PROC doesn't have its pid set, then we know someone has signaled
1666 an error and the process wasn't started successfully, so we should
1667 remove it from the process list. */
1668 static void
1669 start_process_unwind (Lisp_Object proc)
1671 if (!PROCESSP (proc))
1672 emacs_abort ();
1674 /* Was PROC started successfully?
1675 -2 is used for a pty with no process, eg for gdb. */
1676 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1677 remove_process (proc);
1680 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1682 static void
1683 close_process_fd (int *fd_addr)
1685 int fd = *fd_addr;
1686 if (0 <= fd)
1688 *fd_addr = -1;
1689 emacs_close (fd);
1693 /* Indexes of file descriptors in open_fds. */
1694 enum
1696 /* The pipe from Emacs to its subprocess. */
1697 SUBPROCESS_STDIN,
1698 WRITE_TO_SUBPROCESS,
1700 /* The main pipe from the subprocess to Emacs. */
1701 READ_FROM_SUBPROCESS,
1702 SUBPROCESS_STDOUT,
1704 /* The pipe from the subprocess to Emacs that is closed when the
1705 subprocess execs. */
1706 READ_FROM_EXEC_MONITOR,
1707 EXEC_MONITOR_OUTPUT
1710 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1712 static void
1713 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1715 struct Lisp_Process *p = XPROCESS (process);
1716 int inchannel, outchannel;
1717 pid_t pid;
1718 int vfork_errno;
1719 int forkin, forkout, forkerr = -1;
1720 bool pty_flag = 0;
1721 char pty_name[PTY_NAME_SIZE];
1722 Lisp_Object lisp_pty_name = Qnil;
1723 sigset_t oldset;
1725 inchannel = outchannel = -1;
1727 if (p->pty_flag)
1728 outchannel = inchannel = allocate_pty (pty_name);
1730 if (inchannel >= 0)
1732 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1733 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1734 /* On most USG systems it does not work to open the pty's tty here,
1735 then close it and reopen it in the child. */
1736 /* Don't let this terminal become our controlling terminal
1737 (in case we don't have one). */
1738 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1739 if (forkin < 0)
1740 report_file_error ("Opening pty", Qnil);
1741 p->open_fd[SUBPROCESS_STDIN] = forkin;
1742 #else
1743 forkin = forkout = -1;
1744 #endif /* not USG, or USG_SUBTTY_WORKS */
1745 pty_flag = 1;
1746 lisp_pty_name = build_string (pty_name);
1748 else
1750 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1751 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1752 report_file_error ("Creating pipe", Qnil);
1753 forkin = p->open_fd[SUBPROCESS_STDIN];
1754 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1755 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1756 forkout = p->open_fd[SUBPROCESS_STDOUT];
1758 if (!NILP (p->stderrproc))
1760 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
1762 forkerr = pp->open_fd[SUBPROCESS_STDOUT];
1764 /* Close unnecessary file descriptors. */
1765 close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
1766 close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
1770 #ifndef WINDOWSNT
1771 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1772 report_file_error ("Creating pipe", Qnil);
1773 #endif
1775 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1776 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1778 /* Record this as an active process, with its channels. */
1779 chan_process[inchannel] = process;
1780 p->infd = inchannel;
1781 p->outfd = outchannel;
1783 /* Previously we recorded the tty descriptor used in the subprocess.
1784 It was only used for getting the foreground tty process, so now
1785 we just reopen the device (see emacs_get_tty_pgrp) as this is
1786 more portable (see USG_SUBTTY_WORKS above). */
1788 p->pty_flag = pty_flag;
1789 pset_status (p, Qrun);
1791 if (!EQ (p->command, Qt))
1793 FD_SET (inchannel, &input_wait_mask);
1794 FD_SET (inchannel, &non_keyboard_wait_mask);
1797 if (inchannel > max_process_desc)
1798 max_process_desc = inchannel;
1800 /* This may signal an error. */
1801 setup_process_coding_systems (process);
1803 block_input ();
1804 block_child_signal (&oldset);
1806 #ifndef WINDOWSNT
1807 /* vfork, and prevent local vars from being clobbered by the vfork. */
1808 Lisp_Object volatile current_dir_volatile = current_dir;
1809 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1810 char **volatile new_argv_volatile = new_argv;
1811 int volatile forkin_volatile = forkin;
1812 int volatile forkout_volatile = forkout;
1813 int volatile forkerr_volatile = forkerr;
1814 struct Lisp_Process *p_volatile = p;
1816 pid = vfork ();
1818 current_dir = current_dir_volatile;
1819 lisp_pty_name = lisp_pty_name_volatile;
1820 new_argv = new_argv_volatile;
1821 forkin = forkin_volatile;
1822 forkout = forkout_volatile;
1823 forkerr = forkerr_volatile;
1824 p = p_volatile;
1826 pty_flag = p->pty_flag;
1828 if (pid == 0)
1829 #endif /* not WINDOWSNT */
1831 /* Make the pty be the controlling terminal of the process. */
1832 #ifdef HAVE_PTYS
1833 /* First, disconnect its current controlling terminal. */
1834 /* We tried doing setsid only if pty_flag, but it caused
1835 process_set_signal to fail on SGI when using a pipe. */
1836 setsid ();
1837 /* Make the pty's terminal the controlling terminal. */
1838 if (pty_flag && forkin >= 0)
1840 #ifdef TIOCSCTTY
1841 /* We ignore the return value
1842 because faith@cs.unc.edu says that is necessary on Linux. */
1843 ioctl (forkin, TIOCSCTTY, 0);
1844 #endif
1846 #if defined (LDISC1)
1847 if (pty_flag && forkin >= 0)
1849 struct termios t;
1850 tcgetattr (forkin, &t);
1851 t.c_lflag = LDISC1;
1852 if (tcsetattr (forkin, TCSANOW, &t) < 0)
1853 emacs_perror ("create_process/tcsetattr LDISC1");
1855 #else
1856 #if defined (NTTYDISC) && defined (TIOCSETD)
1857 if (pty_flag && forkin >= 0)
1859 /* Use new line discipline. */
1860 int ldisc = NTTYDISC;
1861 ioctl (forkin, TIOCSETD, &ldisc);
1863 #endif
1864 #endif
1865 #ifdef TIOCNOTTY
1866 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1867 can do TIOCSPGRP only to the process's controlling tty. */
1868 if (pty_flag)
1870 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1871 I can't test it since I don't have 4.3. */
1872 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1873 if (j >= 0)
1875 ioctl (j, TIOCNOTTY, 0);
1876 emacs_close (j);
1879 #endif /* TIOCNOTTY */
1881 #if !defined (DONT_REOPEN_PTY)
1882 /*** There is a suggestion that this ought to be a
1883 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1884 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1885 that system does seem to need this code, even though
1886 both TIOCSCTTY is defined. */
1887 /* Now close the pty (if we had it open) and reopen it.
1888 This makes the pty the controlling terminal of the subprocess. */
1889 if (pty_flag)
1892 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1893 would work? */
1894 if (forkin >= 0)
1895 emacs_close (forkin);
1896 forkout = forkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1898 if (forkin < 0)
1900 emacs_perror (SSDATA (lisp_pty_name));
1901 _exit (EXIT_CANCELED);
1905 #endif /* not DONT_REOPEN_PTY */
1907 #ifdef SETUP_SLAVE_PTY
1908 if (pty_flag)
1910 SETUP_SLAVE_PTY;
1912 #endif /* SETUP_SLAVE_PTY */
1913 #endif /* HAVE_PTYS */
1915 signal (SIGINT, SIG_DFL);
1916 signal (SIGQUIT, SIG_DFL);
1917 #ifdef SIGPROF
1918 signal (SIGPROF, SIG_DFL);
1919 #endif
1921 /* Emacs ignores SIGPIPE, but the child should not. */
1922 signal (SIGPIPE, SIG_DFL);
1924 /* Stop blocking SIGCHLD in the child. */
1925 unblock_child_signal (&oldset);
1927 if (pty_flag)
1928 child_setup_tty (forkout);
1930 if (forkerr < 0)
1931 forkerr = forkout;
1932 #ifdef WINDOWSNT
1933 pid = child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1934 #else /* not WINDOWSNT */
1935 child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1936 #endif /* not WINDOWSNT */
1939 /* Back in the parent process. */
1941 vfork_errno = errno;
1942 p->pid = pid;
1943 if (pid >= 0)
1944 p->alive = 1;
1946 /* Stop blocking in the parent. */
1947 unblock_child_signal (&oldset);
1948 unblock_input ();
1950 if (pid < 0)
1951 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1952 else
1954 /* vfork succeeded. */
1956 /* Close the pipe ends that the child uses, or the child's pty. */
1957 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
1958 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
1960 #ifdef WINDOWSNT
1961 register_child (pid, inchannel);
1962 #endif /* WINDOWSNT */
1964 pset_tty_name (p, lisp_pty_name);
1966 #ifndef WINDOWSNT
1967 /* Wait for child_setup to complete in case that vfork is
1968 actually defined as fork. The descriptor
1969 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1970 of a pipe is closed at the child side either by close-on-exec
1971 on successful execve or the _exit call in child_setup. */
1973 char dummy;
1975 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
1976 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
1977 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
1979 #endif
1980 if (!NILP (p->stderrproc))
1982 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
1983 close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
1988 static void
1989 create_pty (Lisp_Object process)
1991 struct Lisp_Process *p = XPROCESS (process);
1992 char pty_name[PTY_NAME_SIZE];
1993 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
1995 if (pty_fd >= 0)
1997 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
1998 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1999 /* On most USG systems it does not work to open the pty's tty here,
2000 then close it and reopen it in the child. */
2001 /* Don't let this terminal become our controlling terminal
2002 (in case we don't have one). */
2003 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2004 if (forkout < 0)
2005 report_file_error ("Opening pty", Qnil);
2006 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2007 #if defined (DONT_REOPEN_PTY)
2008 /* In the case that vfork is defined as fork, the parent process
2009 (Emacs) may send some data before the child process completes
2010 tty options setup. So we setup tty before forking. */
2011 child_setup_tty (forkout);
2012 #endif /* DONT_REOPEN_PTY */
2013 #endif /* not USG, or USG_SUBTTY_WORKS */
2015 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2017 /* Record this as an active process, with its channels.
2018 As a result, child_setup will close Emacs's side of the pipes. */
2019 chan_process[pty_fd] = process;
2020 p->infd = pty_fd;
2021 p->outfd = pty_fd;
2023 /* Previously we recorded the tty descriptor used in the subprocess.
2024 It was only used for getting the foreground tty process, so now
2025 we just reopen the device (see emacs_get_tty_pgrp) as this is
2026 more portable (see USG_SUBTTY_WORKS above). */
2028 p->pty_flag = 1;
2029 pset_status (p, Qrun);
2030 setup_process_coding_systems (process);
2032 FD_SET (pty_fd, &input_wait_mask);
2033 FD_SET (pty_fd, &non_keyboard_wait_mask);
2034 if (pty_fd > max_process_desc)
2035 max_process_desc = pty_fd;
2037 pset_tty_name (p, build_string (pty_name));
2040 p->pid = -2;
2043 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2044 0, MANY, 0,
2045 doc: /* Create and return a bidirectional pipe process.
2047 In Emacs, pipes are represented by process objects, so input and
2048 output work as for subprocesses, and `delete-process' closes a pipe.
2049 However, a pipe process has no process id, it cannot be signaled,
2050 and the status codes are different from normal processes.
2052 Arguments are specified as keyword/argument pairs. The following
2053 arguments are defined:
2055 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2057 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2058 with the process. Process output goes at the end of that buffer,
2059 unless you specify an output stream or filter function to handle the
2060 output. If BUFFER is not given, the value of NAME is used.
2062 :coding CODING -- If CODING is a symbol, it specifies the coding
2063 system used for both reading and writing for this process. If CODING
2064 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2065 ENCODING is used for writing.
2067 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2068 the process is running. If BOOL is not given, query before exiting.
2070 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2071 In the stopped state, a pipe process does not accept incoming data,
2072 but you can send outgoing data. The stopped state is cleared by
2073 `continue-process' and set by `stop-process'.
2075 :filter FILTER -- Install FILTER as the process filter.
2077 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2079 usage: (make-pipe-process &rest ARGS) */)
2080 (ptrdiff_t nargs, Lisp_Object *args)
2082 Lisp_Object proc, contact;
2083 struct Lisp_Process *p;
2084 Lisp_Object name, buffer;
2085 Lisp_Object tem;
2086 ptrdiff_t specpdl_count;
2087 int inchannel, outchannel;
2089 if (nargs == 0)
2090 return Qnil;
2092 contact = Flist (nargs, args);
2094 name = Fplist_get (contact, QCname);
2095 CHECK_STRING (name);
2096 proc = make_process (name);
2097 specpdl_count = SPECPDL_INDEX ();
2098 record_unwind_protect (remove_process, proc);
2099 p = XPROCESS (proc);
2101 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2102 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2103 report_file_error ("Creating pipe", Qnil);
2104 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2105 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2107 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2108 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2110 #ifdef WINDOWSNT
2111 register_aux_fd (inchannel);
2112 #endif
2114 /* Record this as an active process, with its channels. */
2115 chan_process[inchannel] = proc;
2116 p->infd = inchannel;
2117 p->outfd = outchannel;
2119 if (inchannel > max_process_desc)
2120 max_process_desc = inchannel;
2122 buffer = Fplist_get (contact, QCbuffer);
2123 if (NILP (buffer))
2124 buffer = name;
2125 buffer = Fget_buffer_create (buffer);
2126 pset_buffer (p, buffer);
2128 pset_childp (p, contact);
2129 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2130 pset_type (p, Qpipe);
2131 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2132 pset_filter (p, Fplist_get (contact, QCfilter));
2133 pset_log (p, Qnil);
2134 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2135 p->kill_without_query = 1;
2136 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2137 pset_command (p, Qt);
2138 eassert (! p->pty_flag);
2140 if (!EQ (p->command, Qt))
2142 FD_SET (inchannel, &input_wait_mask);
2143 FD_SET (inchannel, &non_keyboard_wait_mask);
2145 p->adaptive_read_buffering
2146 = (NILP (Vprocess_adaptive_read_buffering) ? 0
2147 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2149 /* Make the process marker point into the process buffer (if any). */
2150 if (BUFFERP (buffer))
2151 set_marker_both (p->mark, buffer,
2152 BUF_ZV (XBUFFER (buffer)),
2153 BUF_ZV_BYTE (XBUFFER (buffer)));
2156 /* Setup coding systems for communicating with the network stream. */
2158 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2159 Lisp_Object coding_systems = Qt;
2160 Lisp_Object val;
2162 tem = Fplist_get (contact, QCcoding);
2163 val = Qnil;
2164 if (!NILP (tem))
2166 val = tem;
2167 if (CONSP (val))
2168 val = XCAR (val);
2170 else if (!NILP (Vcoding_system_for_read))
2171 val = Vcoding_system_for_read;
2172 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2173 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2174 /* We dare not decode end-of-line format by setting VAL to
2175 Qraw_text, because the existing Emacs Lisp libraries
2176 assume that they receive bare code including a sequence of
2177 CR LF. */
2178 val = Qnil;
2179 else
2181 if (CONSP (coding_systems))
2182 val = XCAR (coding_systems);
2183 else if (CONSP (Vdefault_process_coding_system))
2184 val = XCAR (Vdefault_process_coding_system);
2185 else
2186 val = Qnil;
2188 pset_decode_coding_system (p, val);
2190 if (!NILP (tem))
2192 val = tem;
2193 if (CONSP (val))
2194 val = XCDR (val);
2196 else if (!NILP (Vcoding_system_for_write))
2197 val = Vcoding_system_for_write;
2198 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2199 val = Qnil;
2200 else
2202 if (CONSP (coding_systems))
2203 val = XCDR (coding_systems);
2204 else if (CONSP (Vdefault_process_coding_system))
2205 val = XCDR (Vdefault_process_coding_system);
2206 else
2207 val = Qnil;
2209 pset_encode_coding_system (p, val);
2211 /* This may signal an error. */
2212 setup_process_coding_systems (proc);
2214 specpdl_ptr = specpdl + specpdl_count;
2216 return proc;
2220 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2221 The address family of sa is not included in the result. */
2223 Lisp_Object
2224 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2226 Lisp_Object address;
2227 int i;
2228 unsigned char *cp;
2229 register struct Lisp_Vector *p;
2231 /* Workaround for a bug in getsockname on BSD: Names bound to
2232 sockets in the UNIX domain are inaccessible; getsockname returns
2233 a zero length name. */
2234 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2235 return empty_unibyte_string;
2237 switch (sa->sa_family)
2239 case AF_INET:
2241 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2242 len = sizeof (sin->sin_addr) + 1;
2243 address = Fmake_vector (make_number (len), Qnil);
2244 p = XVECTOR (address);
2245 p->contents[--len] = make_number (ntohs (sin->sin_port));
2246 cp = (unsigned char *) &sin->sin_addr;
2247 break;
2249 #ifdef AF_INET6
2250 case AF_INET6:
2252 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2253 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2254 len = sizeof (sin6->sin6_addr) / 2 + 1;
2255 address = Fmake_vector (make_number (len), Qnil);
2256 p = XVECTOR (address);
2257 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2258 for (i = 0; i < len; i++)
2259 p->contents[i] = make_number (ntohs (ip6[i]));
2260 return address;
2262 #endif
2263 #ifdef HAVE_LOCAL_SOCKETS
2264 case AF_LOCAL:
2266 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2267 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2268 /* If the first byte is NUL, the name is a Linux abstract
2269 socket name, and the name can contain embedded NULs. If
2270 it's not, we have a NUL-terminated string. Be careful not
2271 to walk past the end of the object looking for the name
2272 terminator, however. */
2273 if (name_length > 0 && sockun->sun_path[0] != '\0')
2275 const char *terminator
2276 = memchr (sockun->sun_path, '\0', name_length);
2278 if (terminator)
2279 name_length = terminator - (const char *) sockun->sun_path;
2282 return make_unibyte_string (sockun->sun_path, name_length);
2284 #endif
2285 default:
2286 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2287 address = Fcons (make_number (sa->sa_family),
2288 Fmake_vector (make_number (len), Qnil));
2289 p = XVECTOR (XCDR (address));
2290 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2291 break;
2294 i = 0;
2295 while (i < len)
2296 p->contents[i++] = make_number (*cp++);
2298 return address;
2302 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2304 static int
2305 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2307 register struct Lisp_Vector *p;
2309 if (VECTORP (address))
2311 p = XVECTOR (address);
2312 if (p->header.size == 5)
2314 *familyp = AF_INET;
2315 return sizeof (struct sockaddr_in);
2317 #ifdef AF_INET6
2318 else if (p->header.size == 9)
2320 *familyp = AF_INET6;
2321 return sizeof (struct sockaddr_in6);
2323 #endif
2325 #ifdef HAVE_LOCAL_SOCKETS
2326 else if (STRINGP (address))
2328 *familyp = AF_LOCAL;
2329 return sizeof (struct sockaddr_un);
2331 #endif
2332 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2333 && VECTORP (XCDR (address)))
2335 struct sockaddr *sa;
2336 p = XVECTOR (XCDR (address));
2337 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2338 return 0;
2339 *familyp = XINT (XCAR (address));
2340 return p->header.size + sizeof (sa->sa_family);
2342 return 0;
2345 /* Convert an address object (vector or string) to an internal sockaddr.
2347 The address format has been basically validated by
2348 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2349 it could have come from user data. So if FAMILY is not valid,
2350 we return after zeroing *SA. */
2352 static void
2353 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2355 register struct Lisp_Vector *p;
2356 register unsigned char *cp = NULL;
2357 register int i;
2358 EMACS_INT hostport;
2360 memset (sa, 0, len);
2362 if (VECTORP (address))
2364 p = XVECTOR (address);
2365 if (family == AF_INET)
2367 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2368 len = sizeof (sin->sin_addr) + 1;
2369 hostport = XINT (p->contents[--len]);
2370 sin->sin_port = htons (hostport);
2371 cp = (unsigned char *)&sin->sin_addr;
2372 sa->sa_family = family;
2374 #ifdef AF_INET6
2375 else if (family == AF_INET6)
2377 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2378 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2379 len = sizeof (sin6->sin6_addr) + 1;
2380 hostport = XINT (p->contents[--len]);
2381 sin6->sin6_port = htons (hostport);
2382 for (i = 0; i < len; i++)
2383 if (INTEGERP (p->contents[i]))
2385 int j = XFASTINT (p->contents[i]) & 0xffff;
2386 ip6[i] = ntohs (j);
2388 sa->sa_family = family;
2389 return;
2391 #endif
2392 else
2393 return;
2395 else if (STRINGP (address))
2397 #ifdef HAVE_LOCAL_SOCKETS
2398 if (family == AF_LOCAL)
2400 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2401 cp = SDATA (address);
2402 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2403 sockun->sun_path[i] = *cp++;
2404 sa->sa_family = family;
2406 #endif
2407 return;
2409 else
2411 p = XVECTOR (XCDR (address));
2412 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2415 for (i = 0; i < len; i++)
2416 if (INTEGERP (p->contents[i]))
2417 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2420 #ifdef DATAGRAM_SOCKETS
2421 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2422 1, 1, 0,
2423 doc: /* Get the current datagram address associated with PROCESS. */)
2424 (Lisp_Object process)
2426 int channel;
2428 CHECK_PROCESS (process);
2430 if (!DATAGRAM_CONN_P (process))
2431 return Qnil;
2433 channel = XPROCESS (process)->infd;
2434 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2435 datagram_address[channel].len);
2438 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2439 2, 2, 0,
2440 doc: /* Set the datagram address for PROCESS to ADDRESS.
2441 Returns nil upon error setting address, ADDRESS otherwise. */)
2442 (Lisp_Object process, Lisp_Object address)
2444 int channel;
2445 int family, len;
2447 CHECK_PROCESS (process);
2449 if (!DATAGRAM_CONN_P (process))
2450 return Qnil;
2452 channel = XPROCESS (process)->infd;
2454 len = get_lisp_to_sockaddr_size (address, &family);
2455 if (len == 0 || datagram_address[channel].len != len)
2456 return Qnil;
2457 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2458 return address;
2460 #endif
2463 static const struct socket_options {
2464 /* The name of this option. Should be lowercase version of option
2465 name without SO_ prefix. */
2466 const char *name;
2467 /* Option level SOL_... */
2468 int optlevel;
2469 /* Option number SO_... */
2470 int optnum;
2471 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2472 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2473 } socket_options[] =
2475 #ifdef SO_BINDTODEVICE
2476 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2477 #endif
2478 #ifdef SO_BROADCAST
2479 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2480 #endif
2481 #ifdef SO_DONTROUTE
2482 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2483 #endif
2484 #ifdef SO_KEEPALIVE
2485 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2486 #endif
2487 #ifdef SO_LINGER
2488 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2489 #endif
2490 #ifdef SO_OOBINLINE
2491 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2492 #endif
2493 #ifdef SO_PRIORITY
2494 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2495 #endif
2496 #ifdef SO_REUSEADDR
2497 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2498 #endif
2499 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2502 /* Set option OPT to value VAL on socket S.
2504 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2505 Signals an error if setting a known option fails.
2508 static int
2509 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2511 char *name;
2512 const struct socket_options *sopt;
2513 int ret = 0;
2515 CHECK_SYMBOL (opt);
2517 name = SSDATA (SYMBOL_NAME (opt));
2518 for (sopt = socket_options; sopt->name; sopt++)
2519 if (strcmp (name, sopt->name) == 0)
2520 break;
2522 switch (sopt->opttype)
2524 case SOPT_BOOL:
2526 int optval;
2527 optval = NILP (val) ? 0 : 1;
2528 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2529 &optval, sizeof (optval));
2530 break;
2533 case SOPT_INT:
2535 int optval;
2536 if (TYPE_RANGED_INTEGERP (int, val))
2537 optval = XINT (val);
2538 else
2539 error ("Bad option value for %s", name);
2540 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2541 &optval, sizeof (optval));
2542 break;
2545 #ifdef SO_BINDTODEVICE
2546 case SOPT_IFNAME:
2548 char devname[IFNAMSIZ + 1];
2550 /* This is broken, at least in the Linux 2.4 kernel.
2551 To unbind, the arg must be a zero integer, not the empty string.
2552 This should work on all systems. KFS. 2003-09-23. */
2553 memset (devname, 0, sizeof devname);
2554 if (STRINGP (val))
2556 char *arg = SSDATA (val);
2557 int len = min (strlen (arg), IFNAMSIZ);
2558 memcpy (devname, arg, len);
2560 else if (!NILP (val))
2561 error ("Bad option value for %s", name);
2562 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2563 devname, IFNAMSIZ);
2564 break;
2566 #endif
2568 #ifdef SO_LINGER
2569 case SOPT_LINGER:
2571 struct linger linger;
2573 linger.l_onoff = 1;
2574 linger.l_linger = 0;
2575 if (TYPE_RANGED_INTEGERP (int, val))
2576 linger.l_linger = XINT (val);
2577 else
2578 linger.l_onoff = NILP (val) ? 0 : 1;
2579 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2580 &linger, sizeof (linger));
2581 break;
2583 #endif
2585 default:
2586 return 0;
2589 if (ret < 0)
2591 int setsockopt_errno = errno;
2592 report_file_errno ("Cannot set network option", list2 (opt, val),
2593 setsockopt_errno);
2596 return (1 << sopt->optbit);
2600 DEFUN ("set-network-process-option",
2601 Fset_network_process_option, Sset_network_process_option,
2602 3, 4, 0,
2603 doc: /* For network process PROCESS set option OPTION to value VALUE.
2604 See `make-network-process' for a list of options and values.
2605 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2606 OPTION is not a supported option, return nil instead; otherwise return t. */)
2607 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2609 int s;
2610 struct Lisp_Process *p;
2612 CHECK_PROCESS (process);
2613 p = XPROCESS (process);
2614 if (!NETCONN1_P (p))
2615 error ("Process is not a network process");
2617 s = p->infd;
2618 if (s < 0)
2619 error ("Process is not running");
2621 if (set_socket_option (s, option, value))
2623 pset_childp (p, Fplist_put (p->childp, option, value));
2624 return Qt;
2627 if (NILP (no_error))
2628 error ("Unknown or unsupported option");
2630 return Qnil;
2634 DEFUN ("serial-process-configure",
2635 Fserial_process_configure,
2636 Sserial_process_configure,
2637 0, MANY, 0,
2638 doc: /* Configure speed, bytesize, etc. of a serial process.
2640 Arguments are specified as keyword/argument pairs. Attributes that
2641 are not given are re-initialized from the process's current
2642 configuration (available via the function `process-contact') or set to
2643 reasonable default values. The following arguments are defined:
2645 :process PROCESS
2646 :name NAME
2647 :buffer BUFFER
2648 :port PORT
2649 -- Any of these arguments can be given to identify the process that is
2650 to be configured. If none of these arguments is given, the current
2651 buffer's process is used.
2653 :speed SPEED -- SPEED is the speed of the serial port in bits per
2654 second, also called baud rate. Any value can be given for SPEED, but
2655 most serial ports work only at a few defined values between 1200 and
2656 115200, with 9600 being the most common value. If SPEED is nil, the
2657 serial port is not configured any further, i.e., all other arguments
2658 are ignored. This may be useful for special serial ports such as
2659 Bluetooth-to-serial converters which can only be configured through AT
2660 commands. A value of nil for SPEED can be used only when passed
2661 through `make-serial-process' or `serial-term'.
2663 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2664 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2666 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2667 `odd' (use odd parity), or the symbol `even' (use even parity). If
2668 PARITY is not given, no parity is used.
2670 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2671 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2672 is not given or nil, 1 stopbit is used.
2674 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2675 flowcontrol to be used, which is either nil (don't use flowcontrol),
2676 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2677 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2678 flowcontrol is used.
2680 `serial-process-configure' is called by `make-serial-process' for the
2681 initial configuration of the serial port.
2683 Examples:
2685 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2687 \(serial-process-configure
2688 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2690 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2692 usage: (serial-process-configure &rest ARGS) */)
2693 (ptrdiff_t nargs, Lisp_Object *args)
2695 struct Lisp_Process *p;
2696 Lisp_Object contact = Qnil;
2697 Lisp_Object proc = Qnil;
2699 contact = Flist (nargs, args);
2701 proc = Fplist_get (contact, QCprocess);
2702 if (NILP (proc))
2703 proc = Fplist_get (contact, QCname);
2704 if (NILP (proc))
2705 proc = Fplist_get (contact, QCbuffer);
2706 if (NILP (proc))
2707 proc = Fplist_get (contact, QCport);
2708 proc = get_process (proc);
2709 p = XPROCESS (proc);
2710 if (!EQ (p->type, Qserial))
2711 error ("Not a serial process");
2713 if (NILP (Fplist_get (p->childp, QCspeed)))
2714 return Qnil;
2716 serial_configure (p, contact);
2717 return Qnil;
2720 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2721 0, MANY, 0,
2722 doc: /* Create and return a serial port process.
2724 In Emacs, serial port connections are represented by process objects,
2725 so input and output work as for subprocesses, and `delete-process'
2726 closes a serial port connection. However, a serial process has no
2727 process id, it cannot be signaled, and the status codes are different
2728 from normal processes.
2730 `make-serial-process' creates a process and a buffer, on which you
2731 probably want to use `process-send-string'. Try \\[serial-term] for
2732 an interactive terminal. See below for examples.
2734 Arguments are specified as keyword/argument pairs. The following
2735 arguments are defined:
2737 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2738 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2739 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2740 the backslashes in strings).
2742 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2743 which this function calls.
2745 :name NAME -- NAME is the name of the process. If NAME is not given,
2746 the value of PORT is used.
2748 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2749 with the process. Process output goes at the end of that buffer,
2750 unless you specify an output stream or filter function to handle the
2751 output. If BUFFER is not given, the value of NAME is used.
2753 :coding CODING -- If CODING is a symbol, it specifies the coding
2754 system used for both reading and writing for this process. If CODING
2755 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2756 ENCODING is used for writing.
2758 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2759 the process is running. If BOOL is not given, query before exiting.
2761 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2762 In the stopped state, a serial process does not accept incoming data,
2763 but you can send outgoing data. The stopped state is cleared by
2764 `continue-process' and set by `stop-process'.
2766 :filter FILTER -- Install FILTER as the process filter.
2768 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2770 :plist PLIST -- Install PLIST as the initial plist of the process.
2772 :bytesize
2773 :parity
2774 :stopbits
2775 :flowcontrol
2776 -- This function calls `serial-process-configure' to handle these
2777 arguments.
2779 The original argument list, possibly modified by later configuration,
2780 is available via the function `process-contact'.
2782 Examples:
2784 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2786 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2788 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2790 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2792 usage: (make-serial-process &rest ARGS) */)
2793 (ptrdiff_t nargs, Lisp_Object *args)
2795 int fd = -1;
2796 Lisp_Object proc, contact, port;
2797 struct Lisp_Process *p;
2798 Lisp_Object name, buffer;
2799 Lisp_Object tem, val;
2800 ptrdiff_t specpdl_count;
2802 if (nargs == 0)
2803 return Qnil;
2805 contact = Flist (nargs, args);
2807 port = Fplist_get (contact, QCport);
2808 if (NILP (port))
2809 error ("No port specified");
2810 CHECK_STRING (port);
2812 if (NILP (Fplist_member (contact, QCspeed)))
2813 error (":speed not specified");
2814 if (!NILP (Fplist_get (contact, QCspeed)))
2815 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2817 name = Fplist_get (contact, QCname);
2818 if (NILP (name))
2819 name = port;
2820 CHECK_STRING (name);
2821 proc = make_process (name);
2822 specpdl_count = SPECPDL_INDEX ();
2823 record_unwind_protect (remove_process, proc);
2824 p = XPROCESS (proc);
2826 fd = serial_open (port);
2827 p->open_fd[SUBPROCESS_STDIN] = fd;
2828 p->infd = fd;
2829 p->outfd = fd;
2830 if (fd > max_process_desc)
2831 max_process_desc = fd;
2832 chan_process[fd] = proc;
2834 buffer = Fplist_get (contact, QCbuffer);
2835 if (NILP (buffer))
2836 buffer = name;
2837 buffer = Fget_buffer_create (buffer);
2838 pset_buffer (p, buffer);
2840 pset_childp (p, contact);
2841 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2842 pset_type (p, Qserial);
2843 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2844 pset_filter (p, Fplist_get (contact, QCfilter));
2845 pset_log (p, Qnil);
2846 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2847 p->kill_without_query = 1;
2848 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2849 pset_command (p, Qt);
2850 eassert (! p->pty_flag);
2852 if (!EQ (p->command, Qt))
2854 FD_SET (fd, &input_wait_mask);
2855 FD_SET (fd, &non_keyboard_wait_mask);
2858 if (BUFFERP (buffer))
2860 set_marker_both (p->mark, buffer,
2861 BUF_ZV (XBUFFER (buffer)),
2862 BUF_ZV_BYTE (XBUFFER (buffer)));
2865 tem = Fplist_member (contact, QCcoding);
2866 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2867 tem = Qnil;
2869 val = Qnil;
2870 if (!NILP (tem))
2872 val = XCAR (XCDR (tem));
2873 if (CONSP (val))
2874 val = XCAR (val);
2876 else if (!NILP (Vcoding_system_for_read))
2877 val = Vcoding_system_for_read;
2878 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2879 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2880 val = Qnil;
2881 pset_decode_coding_system (p, val);
2883 val = Qnil;
2884 if (!NILP (tem))
2886 val = XCAR (XCDR (tem));
2887 if (CONSP (val))
2888 val = XCDR (val);
2890 else if (!NILP (Vcoding_system_for_write))
2891 val = Vcoding_system_for_write;
2892 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2893 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2894 val = Qnil;
2895 pset_encode_coding_system (p, val);
2897 setup_process_coding_systems (proc);
2898 pset_decoding_buf (p, empty_unibyte_string);
2899 p->decoding_carryover = 0;
2900 pset_encoding_buf (p, empty_unibyte_string);
2901 p->inherit_coding_system_flag
2902 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2904 Fserial_process_configure (nargs, args);
2906 specpdl_ptr = specpdl + specpdl_count;
2908 return proc;
2911 /* Create a network stream/datagram client/server process. Treated
2912 exactly like a normal process when reading and writing. Primary
2913 differences are in status display and process deletion. A network
2914 connection has no PID; you cannot signal it. All you can do is
2915 stop/continue it and deactivate/close it via delete-process. */
2917 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2918 0, MANY, 0,
2919 doc: /* Create and return a network server or client process.
2921 In Emacs, network connections are represented by process objects, so
2922 input and output work as for subprocesses and `delete-process' closes
2923 a network connection. However, a network process has no process id,
2924 it cannot be signaled, and the status codes are different from normal
2925 processes.
2927 Arguments are specified as keyword/argument pairs. The following
2928 arguments are defined:
2930 :name NAME -- NAME is name for process. It is modified if necessary
2931 to make it unique.
2933 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2934 with the process. Process output goes at end of that buffer, unless
2935 you specify an output stream or filter function to handle the output.
2936 BUFFER may be also nil, meaning that this process is not associated
2937 with any buffer.
2939 :host HOST -- HOST is name of the host to connect to, or its IP
2940 address. The symbol `local' specifies the local host. If specified
2941 for a server process, it must be a valid name or address for the local
2942 host, and only clients connecting to that address will be accepted.
2944 :service SERVICE -- SERVICE is name of the service desired, or an
2945 integer specifying a port number to connect to. If SERVICE is t,
2946 a random port number is selected for the server. (If Emacs was
2947 compiled with getaddrinfo, a port number can also be specified as a
2948 string, e.g. "80", as well as an integer. This is not portable.)
2950 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2951 stream type connection, `datagram' creates a datagram type connection,
2952 `seqpacket' creates a reliable datagram connection.
2954 :family FAMILY -- FAMILY is the address (and protocol) family for the
2955 service specified by HOST and SERVICE. The default (nil) is to use
2956 whatever address family (IPv4 or IPv6) that is defined for the host
2957 and port number specified by HOST and SERVICE. Other address families
2958 supported are:
2959 local -- for a local (i.e. UNIX) address specified by SERVICE.
2960 ipv4 -- use IPv4 address family only.
2961 ipv6 -- use IPv6 address family only.
2963 :local ADDRESS -- ADDRESS is the local address used for the connection.
2964 This parameter is ignored when opening a client process. When specified
2965 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2967 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2968 connection. This parameter is ignored when opening a stream server
2969 process. For a datagram server process, it specifies the initial
2970 setting of the remote datagram address. When specified for a client
2971 process, the FAMILY, HOST, and SERVICE args are ignored.
2973 The format of ADDRESS depends on the address family:
2974 - An IPv4 address is represented as an vector of integers [A B C D P]
2975 corresponding to numeric IP address A.B.C.D and port number P.
2976 - A local address is represented as a string with the address in the
2977 local address space.
2978 - An "unsupported family" address is represented by a cons (F . AV)
2979 where F is the family number and AV is a vector containing the socket
2980 address data with one element per address data byte. Do not rely on
2981 this format in portable code, as it may depend on implementation
2982 defined constants, data sizes, and data structure alignment.
2984 :coding CODING -- If CODING is a symbol, it specifies the coding
2985 system used for both reading and writing for this process. If CODING
2986 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2987 ENCODING is used for writing.
2989 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2990 return without waiting for the connection to complete; instead, the
2991 sentinel function will be called with second arg matching "open" (if
2992 successful) or "failed" when the connect completes. Default is to use
2993 a blocking connect (i.e. wait) for stream type connections.
2995 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2996 running when Emacs is exited.
2998 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2999 In the stopped state, a server process does not accept new
3000 connections, and a client process does not handle incoming traffic.
3001 The stopped state is cleared by `continue-process' and set by
3002 `stop-process'.
3004 :filter FILTER -- Install FILTER as the process filter.
3006 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3007 process filter are multibyte, otherwise they are unibyte.
3008 If this keyword is not specified, the strings are multibyte if
3009 the default value of `enable-multibyte-characters' is non-nil.
3011 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3013 :log LOG -- Install LOG as the server process log function. This
3014 function is called when the server accepts a network connection from a
3015 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3016 is the server process, CLIENT is the new process for the connection,
3017 and MESSAGE is a string.
3019 :plist PLIST -- Install PLIST as the new process's initial plist.
3021 :server QLEN -- if QLEN is non-nil, create a server process for the
3022 specified FAMILY, SERVICE, and connection type (stream or datagram).
3023 If QLEN is an integer, it is used as the max. length of the server's
3024 pending connection queue (also known as the backlog); the default
3025 queue length is 5. Default is to create a client process.
3027 The following network options can be specified for this connection:
3029 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3030 :dontroute BOOL -- Only send to directly connected hosts.
3031 :keepalive BOOL -- Send keep-alive messages on network stream.
3032 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3033 :oobinline BOOL -- Place out-of-band data in receive data stream.
3034 :priority INT -- Set protocol defined priority for sent packets.
3035 :reuseaddr BOOL -- Allow reusing a recently used local address
3036 (this is allowed by default for a server process).
3037 :bindtodevice NAME -- bind to interface NAME. Using this may require
3038 special privileges on some systems.
3040 Consult the relevant system programmer's manual pages for more
3041 information on using these options.
3044 A server process will listen for and accept connections from clients.
3045 When a client connection is accepted, a new network process is created
3046 for the connection with the following parameters:
3048 - The client's process name is constructed by concatenating the server
3049 process's NAME and a client identification string.
3050 - If the FILTER argument is non-nil, the client process will not get a
3051 separate process buffer; otherwise, the client's process buffer is a newly
3052 created buffer named after the server process's BUFFER name or process
3053 NAME concatenated with the client identification string.
3054 - The connection type and the process filter and sentinel parameters are
3055 inherited from the server process's TYPE, FILTER and SENTINEL.
3056 - The client process's contact info is set according to the client's
3057 addressing information (typically an IP address and a port number).
3058 - The client process's plist is initialized from the server's plist.
3060 Notice that the FILTER and SENTINEL args are never used directly by
3061 the server process. Also, the BUFFER argument is not used directly by
3062 the server process, but via the optional :log function, accepted (and
3063 failed) connections may be logged in the server process's buffer.
3065 The original argument list, modified with the actual connection
3066 information, is available via the `process-contact' function.
3068 usage: (make-network-process &rest ARGS) */)
3069 (ptrdiff_t nargs, Lisp_Object *args)
3071 Lisp_Object proc;
3072 Lisp_Object contact;
3073 struct Lisp_Process *p;
3074 #ifdef HAVE_GETADDRINFO
3075 struct addrinfo ai, *res, *lres;
3076 struct addrinfo hints;
3077 const char *portstring;
3078 char portbuf[128];
3079 #else /* HAVE_GETADDRINFO */
3080 struct _emacs_addrinfo
3082 int ai_family;
3083 int ai_socktype;
3084 int ai_protocol;
3085 int ai_addrlen;
3086 struct sockaddr *ai_addr;
3087 struct _emacs_addrinfo *ai_next;
3088 } ai, *res, *lres;
3089 #endif /* HAVE_GETADDRINFO */
3090 struct sockaddr_in address_in;
3091 #ifdef HAVE_LOCAL_SOCKETS
3092 struct sockaddr_un address_un;
3093 #endif
3094 int port;
3095 int ret = 0;
3096 int xerrno = 0;
3097 int s = -1, outch, inch;
3098 ptrdiff_t count = SPECPDL_INDEX ();
3099 ptrdiff_t count1;
3100 Lisp_Object colon_address; /* Either QClocal or QCremote. */
3101 Lisp_Object tem;
3102 Lisp_Object name, buffer, host, service, address;
3103 Lisp_Object filter, sentinel;
3104 bool is_non_blocking_client = 0;
3105 bool is_server = 0;
3106 int backlog = 5;
3107 int socktype;
3108 int family = -1;
3110 if (nargs == 0)
3111 return Qnil;
3113 /* Save arguments for process-contact and clone-process. */
3114 contact = Flist (nargs, args);
3116 #ifdef WINDOWSNT
3117 /* Ensure socket support is loaded if available. */
3118 init_winsock (TRUE);
3119 #endif
3121 /* :type TYPE (nil: stream, datagram */
3122 tem = Fplist_get (contact, QCtype);
3123 if (NILP (tem))
3124 socktype = SOCK_STREAM;
3125 #ifdef DATAGRAM_SOCKETS
3126 else if (EQ (tem, Qdatagram))
3127 socktype = SOCK_DGRAM;
3128 #endif
3129 #ifdef HAVE_SEQPACKET
3130 else if (EQ (tem, Qseqpacket))
3131 socktype = SOCK_SEQPACKET;
3132 #endif
3133 else
3134 error ("Unsupported connection type");
3136 /* :server BOOL */
3137 tem = Fplist_get (contact, QCserver);
3138 if (!NILP (tem))
3140 /* Don't support network sockets when non-blocking mode is
3141 not available, since a blocked Emacs is not useful. */
3142 is_server = 1;
3143 if (TYPE_RANGED_INTEGERP (int, tem))
3144 backlog = XINT (tem);
3147 /* Make colon_address an alias for :local (server) or :remote (client). */
3148 colon_address = is_server ? QClocal : QCremote;
3150 /* :nowait BOOL */
3151 if (!is_server && socktype != SOCK_DGRAM
3152 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3154 #ifndef NON_BLOCKING_CONNECT
3155 error ("Non-blocking connect not supported");
3156 #else
3157 is_non_blocking_client = 1;
3158 #endif
3161 name = Fplist_get (contact, QCname);
3162 buffer = Fplist_get (contact, QCbuffer);
3163 filter = Fplist_get (contact, QCfilter);
3164 sentinel = Fplist_get (contact, QCsentinel);
3166 CHECK_STRING (name);
3168 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3169 ai.ai_socktype = socktype;
3170 ai.ai_protocol = 0;
3171 ai.ai_next = NULL;
3172 res = &ai;
3174 /* :local ADDRESS or :remote ADDRESS */
3175 address = Fplist_get (contact, colon_address);
3176 if (!NILP (address))
3178 host = service = Qnil;
3180 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3181 error ("Malformed :address");
3182 ai.ai_family = family;
3183 ai.ai_addr = alloca (ai.ai_addrlen);
3184 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3185 goto open_socket;
3188 /* :family FAMILY -- nil (for Inet), local, or integer. */
3189 tem = Fplist_get (contact, QCfamily);
3190 if (NILP (tem))
3192 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3193 family = AF_UNSPEC;
3194 #else
3195 family = AF_INET;
3196 #endif
3198 #ifdef HAVE_LOCAL_SOCKETS
3199 else if (EQ (tem, Qlocal))
3200 family = AF_LOCAL;
3201 #endif
3202 #ifdef AF_INET6
3203 else if (EQ (tem, Qipv6))
3204 family = AF_INET6;
3205 #endif
3206 else if (EQ (tem, Qipv4))
3207 family = AF_INET;
3208 else if (TYPE_RANGED_INTEGERP (int, tem))
3209 family = XINT (tem);
3210 else
3211 error ("Unknown address family");
3213 ai.ai_family = family;
3215 /* :service SERVICE -- string, integer (port number), or t (random port). */
3216 service = Fplist_get (contact, QCservice);
3218 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3219 host = Fplist_get (contact, QChost);
3220 if (!NILP (host))
3222 if (EQ (host, Qlocal))
3223 /* Depending on setup, "localhost" may map to different IPv4 and/or
3224 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3225 host = build_string ("127.0.0.1");
3226 CHECK_STRING (host);
3229 #ifdef HAVE_LOCAL_SOCKETS
3230 if (family == AF_LOCAL)
3232 if (!NILP (host))
3234 message (":family local ignores the :host property");
3235 contact = Fplist_put (contact, QChost, Qnil);
3236 host = Qnil;
3238 CHECK_STRING (service);
3239 memset (&address_un, 0, sizeof address_un);
3240 address_un.sun_family = AF_LOCAL;
3241 if (sizeof address_un.sun_path <= SBYTES (service))
3242 error ("Service name too long");
3243 lispstpcpy (address_un.sun_path, service);
3244 ai.ai_addr = (struct sockaddr *) &address_un;
3245 ai.ai_addrlen = sizeof address_un;
3246 goto open_socket;
3248 #endif
3250 /* Slow down polling to every ten seconds.
3251 Some kernels have a bug which causes retrying connect to fail
3252 after a connect. Polling can interfere with gethostbyname too. */
3253 #ifdef POLL_FOR_INPUT
3254 if (socktype != SOCK_DGRAM)
3256 record_unwind_protect_void (run_all_atimers);
3257 bind_polling_period (10);
3259 #endif
3261 #ifdef HAVE_GETADDRINFO
3262 /* If we have a host, use getaddrinfo to resolve both host and service.
3263 Otherwise, use getservbyname to lookup the service. */
3264 if (!NILP (host))
3267 /* SERVICE can either be a string or int.
3268 Convert to a C string for later use by getaddrinfo. */
3269 if (EQ (service, Qt))
3270 portstring = "0";
3271 else if (INTEGERP (service))
3273 sprintf (portbuf, "%"pI"d", XINT (service));
3274 portstring = portbuf;
3276 else
3278 CHECK_STRING (service);
3279 portstring = SSDATA (service);
3282 immediate_quit = 1;
3283 QUIT;
3284 memset (&hints, 0, sizeof (hints));
3285 hints.ai_flags = 0;
3286 hints.ai_family = family;
3287 hints.ai_socktype = socktype;
3288 hints.ai_protocol = 0;
3290 #ifdef HAVE_RES_INIT
3291 res_init ();
3292 #endif
3294 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3295 if (ret)
3296 #ifdef HAVE_GAI_STRERROR
3297 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3298 #else
3299 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3300 #endif
3301 immediate_quit = 0;
3303 goto open_socket;
3305 #endif /* HAVE_GETADDRINFO */
3307 /* We end up here if getaddrinfo is not defined, or in case no hostname
3308 has been specified (e.g. for a local server process). */
3310 if (EQ (service, Qt))
3311 port = 0;
3312 else if (INTEGERP (service))
3313 port = htons ((unsigned short) XINT (service));
3314 else
3316 struct servent *svc_info;
3317 CHECK_STRING (service);
3318 svc_info = getservbyname (SSDATA (service),
3319 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3320 if (svc_info == 0)
3321 error ("Unknown service: %s", SDATA (service));
3322 port = svc_info->s_port;
3325 memset (&address_in, 0, sizeof address_in);
3326 address_in.sin_family = family;
3327 address_in.sin_addr.s_addr = INADDR_ANY;
3328 address_in.sin_port = port;
3330 #ifndef HAVE_GETADDRINFO
3331 if (!NILP (host))
3333 struct hostent *host_info_ptr;
3335 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3336 as it may `hang' Emacs for a very long time. */
3337 immediate_quit = 1;
3338 QUIT;
3340 #ifdef HAVE_RES_INIT
3341 res_init ();
3342 #endif
3344 host_info_ptr = gethostbyname (SDATA (host));
3345 immediate_quit = 0;
3347 if (host_info_ptr)
3349 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3350 host_info_ptr->h_length);
3351 family = host_info_ptr->h_addrtype;
3352 address_in.sin_family = family;
3354 else
3355 /* Attempt to interpret host as numeric inet address. */
3357 unsigned long numeric_addr;
3358 numeric_addr = inet_addr (SSDATA (host));
3359 if (numeric_addr == -1)
3360 error ("Unknown host \"%s\"", SDATA (host));
3362 memcpy (&address_in.sin_addr, &numeric_addr,
3363 sizeof (address_in.sin_addr));
3367 #endif /* not HAVE_GETADDRINFO */
3369 ai.ai_family = family;
3370 ai.ai_addr = (struct sockaddr *) &address_in;
3371 ai.ai_addrlen = sizeof address_in;
3373 open_socket:
3375 /* Do this in case we never enter the for-loop below. */
3376 count1 = SPECPDL_INDEX ();
3377 s = -1;
3379 for (lres = res; lres; lres = lres->ai_next)
3381 ptrdiff_t optn;
3382 int optbits;
3384 #ifdef WINDOWSNT
3385 retry_connect:
3386 #endif
3388 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3389 lres->ai_protocol);
3390 if (s < 0)
3392 xerrno = errno;
3393 continue;
3396 #ifdef DATAGRAM_SOCKETS
3397 if (!is_server && socktype == SOCK_DGRAM)
3398 break;
3399 #endif /* DATAGRAM_SOCKETS */
3401 #ifdef NON_BLOCKING_CONNECT
3402 if (is_non_blocking_client)
3404 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3405 if (ret < 0)
3407 xerrno = errno;
3408 emacs_close (s);
3409 s = -1;
3410 continue;
3413 #endif
3415 /* Make us close S if quit. */
3416 record_unwind_protect_int (close_file_unwind, s);
3418 /* Parse network options in the arg list.
3419 We simply ignore anything which isn't a known option (including other keywords).
3420 An error is signaled if setting a known option fails. */
3421 for (optn = optbits = 0; optn < nargs - 1; optn += 2)
3422 optbits |= set_socket_option (s, args[optn], args[optn + 1]);
3424 if (is_server)
3426 /* Configure as a server socket. */
3428 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3429 explicit :reuseaddr key to override this. */
3430 #ifdef HAVE_LOCAL_SOCKETS
3431 if (family != AF_LOCAL)
3432 #endif
3433 if (!(optbits & (1 << OPIX_REUSEADDR)))
3435 int optval = 1;
3436 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3437 report_file_error ("Cannot set reuse option on server socket", Qnil);
3440 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3441 report_file_error ("Cannot bind server socket", Qnil);
3443 #ifdef HAVE_GETSOCKNAME
3444 if (EQ (service, Qt))
3446 struct sockaddr_in sa1;
3447 socklen_t len1 = sizeof (sa1);
3448 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3450 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3451 service = make_number (ntohs (sa1.sin_port));
3452 contact = Fplist_put (contact, QCservice, service);
3455 #endif
3457 if (socktype != SOCK_DGRAM && listen (s, backlog))
3458 report_file_error ("Cannot listen on server socket", Qnil);
3460 break;
3463 immediate_quit = 1;
3464 QUIT;
3466 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3467 xerrno = errno;
3469 if (ret == 0 || xerrno == EISCONN)
3471 /* The unwind-protect will be discarded afterwards.
3472 Likewise for immediate_quit. */
3473 break;
3476 #ifdef NON_BLOCKING_CONNECT
3477 #ifdef EINPROGRESS
3478 if (is_non_blocking_client && xerrno == EINPROGRESS)
3479 break;
3480 #else
3481 #ifdef EWOULDBLOCK
3482 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3483 break;
3484 #endif
3485 #endif
3486 #endif
3488 #ifndef WINDOWSNT
3489 if (xerrno == EINTR)
3491 /* Unlike most other syscalls connect() cannot be called
3492 again. (That would return EALREADY.) The proper way to
3493 wait for completion is pselect(). */
3494 int sc;
3495 socklen_t len;
3496 fd_set fdset;
3497 retry_select:
3498 FD_ZERO (&fdset);
3499 FD_SET (s, &fdset);
3500 QUIT;
3501 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3502 if (sc == -1)
3504 if (errno == EINTR)
3505 goto retry_select;
3506 else
3507 report_file_error ("Failed select", Qnil);
3509 eassert (sc > 0);
3511 len = sizeof xerrno;
3512 eassert (FD_ISSET (s, &fdset));
3513 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3514 report_file_error ("Failed getsockopt", Qnil);
3515 if (xerrno)
3516 report_file_errno ("Failed connect", Qnil, xerrno);
3517 break;
3519 #endif /* !WINDOWSNT */
3521 immediate_quit = 0;
3523 /* Discard the unwind protect closing S. */
3524 specpdl_ptr = specpdl + count1;
3525 emacs_close (s);
3526 s = -1;
3528 #ifdef WINDOWSNT
3529 if (xerrno == EINTR)
3530 goto retry_connect;
3531 #endif
3534 if (s >= 0)
3536 #ifdef DATAGRAM_SOCKETS
3537 if (socktype == SOCK_DGRAM)
3539 if (datagram_address[s].sa)
3540 emacs_abort ();
3541 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3542 datagram_address[s].len = lres->ai_addrlen;
3543 if (is_server)
3545 Lisp_Object remote;
3546 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3547 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3549 int rfamily, rlen;
3550 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3551 if (rlen != 0 && rfamily == lres->ai_family
3552 && rlen == lres->ai_addrlen)
3553 conv_lisp_to_sockaddr (rfamily, remote,
3554 datagram_address[s].sa, rlen);
3557 else
3558 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3560 #endif
3561 contact = Fplist_put (contact, colon_address,
3562 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3563 #ifdef HAVE_GETSOCKNAME
3564 if (!is_server)
3566 struct sockaddr_in sa1;
3567 socklen_t len1 = sizeof (sa1);
3568 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3569 contact = Fplist_put (contact, QClocal,
3570 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3572 #endif
3575 immediate_quit = 0;
3577 #ifdef HAVE_GETADDRINFO
3578 if (res != &ai)
3580 block_input ();
3581 freeaddrinfo (res);
3582 unblock_input ();
3584 #endif
3586 if (s < 0)
3588 /* If non-blocking got this far - and failed - assume non-blocking is
3589 not supported after all. This is probably a wrong assumption, but
3590 the normal blocking calls to open-network-stream handles this error
3591 better. */
3592 if (is_non_blocking_client)
3593 return Qnil;
3595 report_file_errno ((is_server
3596 ? "make server process failed"
3597 : "make client process failed"),
3598 contact, xerrno);
3601 inch = s;
3602 outch = s;
3604 if (!NILP (buffer))
3605 buffer = Fget_buffer_create (buffer);
3606 proc = make_process (name);
3608 chan_process[inch] = proc;
3610 fcntl (inch, F_SETFL, O_NONBLOCK);
3612 p = XPROCESS (proc);
3614 pset_childp (p, contact);
3615 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3616 pset_type (p, Qnetwork);
3618 pset_buffer (p, buffer);
3619 pset_sentinel (p, sentinel);
3620 pset_filter (p, filter);
3621 pset_log (p, Fplist_get (contact, QClog));
3622 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3623 p->kill_without_query = 1;
3624 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3625 pset_command (p, Qt);
3626 p->pid = 0;
3628 p->open_fd[SUBPROCESS_STDIN] = inch;
3629 p->infd = inch;
3630 p->outfd = outch;
3632 /* Discard the unwind protect for closing S, if any. */
3633 specpdl_ptr = specpdl + count1;
3635 /* Unwind bind_polling_period and request_sigio. */
3636 unbind_to (count, Qnil);
3638 if (is_server && socktype != SOCK_DGRAM)
3639 pset_status (p, Qlisten);
3641 /* Make the process marker point into the process buffer (if any). */
3642 if (BUFFERP (buffer))
3643 set_marker_both (p->mark, buffer,
3644 BUF_ZV (XBUFFER (buffer)),
3645 BUF_ZV_BYTE (XBUFFER (buffer)));
3647 #ifdef NON_BLOCKING_CONNECT
3648 if (is_non_blocking_client)
3650 /* We may get here if connect did succeed immediately. However,
3651 in that case, we still need to signal this like a non-blocking
3652 connection. */
3653 pset_status (p, Qconnect);
3654 if (!FD_ISSET (inch, &connect_wait_mask))
3656 FD_SET (inch, &connect_wait_mask);
3657 FD_SET (inch, &write_mask);
3658 num_pending_connects++;
3661 else
3662 #endif
3663 /* A server may have a client filter setting of Qt, but it must
3664 still listen for incoming connects unless it is stopped. */
3665 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3666 || (EQ (p->status, Qlisten) && NILP (p->command)))
3668 FD_SET (inch, &input_wait_mask);
3669 FD_SET (inch, &non_keyboard_wait_mask);
3672 if (inch > max_process_desc)
3673 max_process_desc = inch;
3675 tem = Fplist_member (contact, QCcoding);
3676 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3677 tem = Qnil; /* No error message (too late!). */
3680 /* Setup coding systems for communicating with the network stream. */
3681 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3682 Lisp_Object coding_systems = Qt;
3683 Lisp_Object val;
3685 if (!NILP (tem))
3687 val = XCAR (XCDR (tem));
3688 if (CONSP (val))
3689 val = XCAR (val);
3691 else if (!NILP (Vcoding_system_for_read))
3692 val = Vcoding_system_for_read;
3693 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3694 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3695 /* We dare not decode end-of-line format by setting VAL to
3696 Qraw_text, because the existing Emacs Lisp libraries
3697 assume that they receive bare code including a sequence of
3698 CR LF. */
3699 val = Qnil;
3700 else
3702 if (NILP (host) || NILP (service))
3703 coding_systems = Qnil;
3704 else
3705 coding_systems = CALLN (Ffind_operation_coding_system,
3706 Qopen_network_stream, name, buffer,
3707 host, service);
3708 if (CONSP (coding_systems))
3709 val = XCAR (coding_systems);
3710 else if (CONSP (Vdefault_process_coding_system))
3711 val = XCAR (Vdefault_process_coding_system);
3712 else
3713 val = Qnil;
3715 pset_decode_coding_system (p, val);
3717 if (!NILP (tem))
3719 val = XCAR (XCDR (tem));
3720 if (CONSP (val))
3721 val = XCDR (val);
3723 else if (!NILP (Vcoding_system_for_write))
3724 val = Vcoding_system_for_write;
3725 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3726 val = Qnil;
3727 else
3729 if (EQ (coding_systems, Qt))
3731 if (NILP (host) || NILP (service))
3732 coding_systems = Qnil;
3733 else
3734 coding_systems = CALLN (Ffind_operation_coding_system,
3735 Qopen_network_stream, name, buffer,
3736 host, service);
3738 if (CONSP (coding_systems))
3739 val = XCDR (coding_systems);
3740 else if (CONSP (Vdefault_process_coding_system))
3741 val = XCDR (Vdefault_process_coding_system);
3742 else
3743 val = Qnil;
3745 pset_encode_coding_system (p, val);
3747 setup_process_coding_systems (proc);
3749 pset_decoding_buf (p, empty_unibyte_string);
3750 p->decoding_carryover = 0;
3751 pset_encoding_buf (p, empty_unibyte_string);
3753 p->inherit_coding_system_flag
3754 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3756 return proc;
3760 #ifdef HAVE_NET_IF_H
3762 #ifdef SIOCGIFCONF
3763 static Lisp_Object
3764 network_interface_list (void)
3766 struct ifconf ifconf;
3767 struct ifreq *ifreq;
3768 void *buf = NULL;
3769 ptrdiff_t buf_size = 512;
3770 int s;
3771 Lisp_Object res;
3772 ptrdiff_t count;
3774 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3775 if (s < 0)
3776 return Qnil;
3777 count = SPECPDL_INDEX ();
3778 record_unwind_protect_int (close_file_unwind, s);
3782 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3783 ifconf.ifc_buf = buf;
3784 ifconf.ifc_len = buf_size;
3785 if (ioctl (s, SIOCGIFCONF, &ifconf))
3787 emacs_close (s);
3788 xfree (buf);
3789 return Qnil;
3792 while (ifconf.ifc_len == buf_size);
3794 res = unbind_to (count, Qnil);
3795 ifreq = ifconf.ifc_req;
3796 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3798 struct ifreq *ifq = ifreq;
3799 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3800 #define SIZEOF_IFREQ(sif) \
3801 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3802 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3804 int len = SIZEOF_IFREQ (ifq);
3805 #else
3806 int len = sizeof (*ifreq);
3807 #endif
3808 char namebuf[sizeof (ifq->ifr_name) + 1];
3809 ifreq = (struct ifreq *) ((char *) ifreq + len);
3811 if (ifq->ifr_addr.sa_family != AF_INET)
3812 continue;
3814 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3815 namebuf[sizeof (ifq->ifr_name)] = 0;
3816 res = Fcons (Fcons (build_string (namebuf),
3817 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3818 sizeof (struct sockaddr))),
3819 res);
3822 xfree (buf);
3823 return res;
3825 #endif /* SIOCGIFCONF */
3827 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3829 struct ifflag_def {
3830 int flag_bit;
3831 const char *flag_sym;
3834 static const struct ifflag_def ifflag_table[] = {
3835 #ifdef IFF_UP
3836 { IFF_UP, "up" },
3837 #endif
3838 #ifdef IFF_BROADCAST
3839 { IFF_BROADCAST, "broadcast" },
3840 #endif
3841 #ifdef IFF_DEBUG
3842 { IFF_DEBUG, "debug" },
3843 #endif
3844 #ifdef IFF_LOOPBACK
3845 { IFF_LOOPBACK, "loopback" },
3846 #endif
3847 #ifdef IFF_POINTOPOINT
3848 { IFF_POINTOPOINT, "pointopoint" },
3849 #endif
3850 #ifdef IFF_RUNNING
3851 { IFF_RUNNING, "running" },
3852 #endif
3853 #ifdef IFF_NOARP
3854 { IFF_NOARP, "noarp" },
3855 #endif
3856 #ifdef IFF_PROMISC
3857 { IFF_PROMISC, "promisc" },
3858 #endif
3859 #ifdef IFF_NOTRAILERS
3860 #ifdef NS_IMPL_COCOA
3861 /* Really means smart, notrailers is obsolete. */
3862 { IFF_NOTRAILERS, "smart" },
3863 #else
3864 { IFF_NOTRAILERS, "notrailers" },
3865 #endif
3866 #endif
3867 #ifdef IFF_ALLMULTI
3868 { IFF_ALLMULTI, "allmulti" },
3869 #endif
3870 #ifdef IFF_MASTER
3871 { IFF_MASTER, "master" },
3872 #endif
3873 #ifdef IFF_SLAVE
3874 { IFF_SLAVE, "slave" },
3875 #endif
3876 #ifdef IFF_MULTICAST
3877 { IFF_MULTICAST, "multicast" },
3878 #endif
3879 #ifdef IFF_PORTSEL
3880 { IFF_PORTSEL, "portsel" },
3881 #endif
3882 #ifdef IFF_AUTOMEDIA
3883 { IFF_AUTOMEDIA, "automedia" },
3884 #endif
3885 #ifdef IFF_DYNAMIC
3886 { IFF_DYNAMIC, "dynamic" },
3887 #endif
3888 #ifdef IFF_OACTIVE
3889 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
3890 #endif
3891 #ifdef IFF_SIMPLEX
3892 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
3893 #endif
3894 #ifdef IFF_LINK0
3895 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
3896 #endif
3897 #ifdef IFF_LINK1
3898 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
3899 #endif
3900 #ifdef IFF_LINK2
3901 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
3902 #endif
3903 { 0, 0 }
3906 static Lisp_Object
3907 network_interface_info (Lisp_Object ifname)
3909 struct ifreq rq;
3910 Lisp_Object res = Qnil;
3911 Lisp_Object elt;
3912 int s;
3913 bool any = 0;
3914 ptrdiff_t count;
3915 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3916 && defined HAVE_GETIFADDRS && defined LLADDR)
3917 struct ifaddrs *ifap;
3918 #endif
3920 CHECK_STRING (ifname);
3922 if (sizeof rq.ifr_name <= SBYTES (ifname))
3923 error ("interface name too long");
3924 lispstpcpy (rq.ifr_name, ifname);
3926 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3927 if (s < 0)
3928 return Qnil;
3929 count = SPECPDL_INDEX ();
3930 record_unwind_protect_int (close_file_unwind, s);
3932 elt = Qnil;
3933 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3934 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3936 int flags = rq.ifr_flags;
3937 const struct ifflag_def *fp;
3938 int fnum;
3940 /* If flags is smaller than int (i.e. short) it may have the high bit set
3941 due to IFF_MULTICAST. In that case, sign extending it into
3942 an int is wrong. */
3943 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3944 flags = (unsigned short) rq.ifr_flags;
3946 any = 1;
3947 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3949 if (flags & fp->flag_bit)
3951 elt = Fcons (intern (fp->flag_sym), elt);
3952 flags -= fp->flag_bit;
3955 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3957 if (flags & 1)
3959 elt = Fcons (make_number (fnum), elt);
3963 #endif
3964 res = Fcons (elt, res);
3966 elt = Qnil;
3967 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3968 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3970 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3971 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3972 int n;
3974 any = 1;
3975 for (n = 0; n < 6; n++)
3976 p->contents[n] = make_number (((unsigned char *)
3977 &rq.ifr_hwaddr.sa_data[0])
3978 [n]);
3979 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3981 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3982 if (getifaddrs (&ifap) != -1)
3984 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3985 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3986 struct ifaddrs *it;
3988 for (it = ifap; it != NULL; it = it->ifa_next)
3990 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3991 unsigned char linkaddr[6];
3992 int n;
3994 if (it->ifa_addr->sa_family != AF_LINK
3995 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3996 || sdl->sdl_alen != 6)
3997 continue;
3999 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4000 for (n = 0; n < 6; n++)
4001 p->contents[n] = make_number (linkaddr[n]);
4003 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4004 break;
4007 #ifdef HAVE_FREEIFADDRS
4008 freeifaddrs (ifap);
4009 #endif
4011 #endif /* HAVE_GETIFADDRS && LLADDR */
4013 res = Fcons (elt, res);
4015 elt = Qnil;
4016 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4017 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4019 any = 1;
4020 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4021 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4022 #else
4023 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4024 #endif
4026 #endif
4027 res = Fcons (elt, res);
4029 elt = Qnil;
4030 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4031 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4033 any = 1;
4034 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4036 #endif
4037 res = Fcons (elt, res);
4039 elt = Qnil;
4040 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4041 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4043 any = 1;
4044 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4046 #endif
4047 res = Fcons (elt, res);
4049 return unbind_to (count, any ? res : Qnil);
4051 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4052 #endif /* defined (HAVE_NET_IF_H) */
4054 DEFUN ("network-interface-list", Fnetwork_interface_list,
4055 Snetwork_interface_list, 0, 0, 0,
4056 doc: /* Return an alist of all network interfaces and their network address.
4057 Each element is a cons, the car of which is a string containing the
4058 interface name, and the cdr is the network address in internal
4059 format; see the description of ADDRESS in `make-network-process'.
4061 If the information is not available, return nil. */)
4062 (void)
4064 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4065 return network_interface_list ();
4066 #else
4067 return Qnil;
4068 #endif
4071 DEFUN ("network-interface-info", Fnetwork_interface_info,
4072 Snetwork_interface_info, 1, 1, 0,
4073 doc: /* Return information about network interface named IFNAME.
4074 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4075 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4076 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4077 FLAGS is the current flags of the interface.
4079 Data that is unavailable is returned as nil. */)
4080 (Lisp_Object ifname)
4082 #if ((defined HAVE_NET_IF_H \
4083 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4084 || defined SIOCGIFFLAGS)) \
4085 || defined WINDOWSNT)
4086 return network_interface_info (ifname);
4087 #else
4088 return Qnil;
4089 #endif
4092 /* If program file NAME starts with /: for quoting a magic
4093 name, remove that, preserving the multibyteness of NAME. */
4095 Lisp_Object
4096 remove_slash_colon (Lisp_Object name)
4098 return
4099 ((SBYTES (name) > 2 && SREF (name, 0) == '/' && SREF (name, 1) == ':')
4100 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
4101 SBYTES (name) - 2, STRING_MULTIBYTE (name))
4102 : name);
4105 /* Turn off input and output for process PROC. */
4107 static void
4108 deactivate_process (Lisp_Object proc)
4110 int inchannel;
4111 struct Lisp_Process *p = XPROCESS (proc);
4112 int i;
4114 #ifdef HAVE_GNUTLS
4115 /* Delete GnuTLS structures in PROC, if any. */
4116 emacs_gnutls_deinit (proc);
4117 #endif /* HAVE_GNUTLS */
4119 if (p->read_output_delay > 0)
4121 if (--process_output_delay_count < 0)
4122 process_output_delay_count = 0;
4123 p->read_output_delay = 0;
4124 p->read_output_skip = 0;
4127 /* Beware SIGCHLD hereabouts. */
4129 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4130 close_process_fd (&p->open_fd[i]);
4132 inchannel = p->infd;
4133 if (inchannel >= 0)
4135 p->infd = -1;
4136 p->outfd = -1;
4137 #ifdef DATAGRAM_SOCKETS
4138 if (DATAGRAM_CHAN_P (inchannel))
4140 xfree (datagram_address[inchannel].sa);
4141 datagram_address[inchannel].sa = 0;
4142 datagram_address[inchannel].len = 0;
4144 #endif
4145 chan_process[inchannel] = Qnil;
4146 FD_CLR (inchannel, &input_wait_mask);
4147 FD_CLR (inchannel, &non_keyboard_wait_mask);
4148 #ifdef NON_BLOCKING_CONNECT
4149 if (FD_ISSET (inchannel, &connect_wait_mask))
4151 FD_CLR (inchannel, &connect_wait_mask);
4152 FD_CLR (inchannel, &write_mask);
4153 if (--num_pending_connects < 0)
4154 emacs_abort ();
4156 #endif
4157 if (inchannel == max_process_desc)
4159 /* We just closed the highest-numbered process input descriptor,
4160 so recompute the highest-numbered one now. */
4161 int i = inchannel;
4163 i--;
4164 while (0 <= i && NILP (chan_process[i]));
4166 max_process_desc = i;
4172 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4173 0, 4, 0,
4174 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4175 It is given to their filter functions.
4176 Optional argument PROCESS means do not return until output has been
4177 received from PROCESS.
4179 Optional second argument SECONDS and third argument MILLISEC
4180 specify a timeout; return after that much time even if there is
4181 no subprocess output. If SECONDS is a floating point number,
4182 it specifies a fractional number of seconds to wait.
4183 The MILLISEC argument is obsolete and should be avoided.
4185 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4186 from PROCESS only, suspending reading output from other processes.
4187 If JUST-THIS-ONE is an integer, don't run any timers either.
4188 Return non-nil if we received any output from PROCESS (or, if PROCESS
4189 is nil, from any process) before the timeout expired. */)
4190 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4192 intmax_t secs;
4193 int nsecs;
4195 if (! NILP (process))
4196 CHECK_PROCESS (process);
4197 else
4198 just_this_one = Qnil;
4200 if (!NILP (millisec))
4201 { /* Obsolete calling convention using integers rather than floats. */
4202 CHECK_NUMBER (millisec);
4203 if (NILP (seconds))
4204 seconds = make_float (XINT (millisec) / 1000.0);
4205 else
4207 CHECK_NUMBER (seconds);
4208 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4212 secs = 0;
4213 nsecs = -1;
4215 if (!NILP (seconds))
4217 if (INTEGERP (seconds))
4219 if (XINT (seconds) > 0)
4221 secs = XINT (seconds);
4222 nsecs = 0;
4225 else if (FLOATP (seconds))
4227 if (XFLOAT_DATA (seconds) > 0)
4229 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4230 secs = min (t.tv_sec, WAIT_READING_MAX);
4231 nsecs = t.tv_nsec;
4234 else
4235 wrong_type_argument (Qnumberp, seconds);
4237 else if (! NILP (process))
4238 nsecs = 0;
4240 return
4241 ((wait_reading_process_output (secs, nsecs, 0, 0,
4242 Qnil,
4243 !NILP (process) ? XPROCESS (process) : NULL,
4244 (NILP (just_this_one) ? 0
4245 : !INTEGERP (just_this_one) ? 1 : -1))
4246 <= 0)
4247 ? Qnil : Qt);
4250 /* Accept a connection for server process SERVER on CHANNEL. */
4252 static EMACS_INT connect_counter = 0;
4254 static void
4255 server_accept_connection (Lisp_Object server, int channel)
4257 Lisp_Object proc, caller, name, buffer;
4258 Lisp_Object contact, host, service;
4259 struct Lisp_Process *ps = XPROCESS (server);
4260 struct Lisp_Process *p;
4261 int s;
4262 union u_sockaddr {
4263 struct sockaddr sa;
4264 struct sockaddr_in in;
4265 #ifdef AF_INET6
4266 struct sockaddr_in6 in6;
4267 #endif
4268 #ifdef HAVE_LOCAL_SOCKETS
4269 struct sockaddr_un un;
4270 #endif
4271 } saddr;
4272 socklen_t len = sizeof saddr;
4273 ptrdiff_t count;
4275 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4277 if (s < 0)
4279 int code = errno;
4281 if (code == EAGAIN)
4282 return;
4283 #ifdef EWOULDBLOCK
4284 if (code == EWOULDBLOCK)
4285 return;
4286 #endif
4288 if (!NILP (ps->log))
4289 call3 (ps->log, server, Qnil,
4290 concat3 (build_string ("accept failed with code"),
4291 Fnumber_to_string (make_number (code)),
4292 build_string ("\n")));
4293 return;
4296 count = SPECPDL_INDEX ();
4297 record_unwind_protect_int (close_file_unwind, s);
4299 connect_counter++;
4301 /* Setup a new process to handle the connection. */
4303 /* Generate a unique identification of the caller, and build contact
4304 information for this process. */
4305 host = Qt;
4306 service = Qnil;
4307 switch (saddr.sa.sa_family)
4309 case AF_INET:
4311 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4313 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4314 host = CALLN (Fformat, ipv4_format,
4315 make_number (ip[0]), make_number (ip[1]),
4316 make_number (ip[2]), make_number (ip[3]));
4317 service = make_number (ntohs (saddr.in.sin_port));
4318 AUTO_STRING (caller_format, " <%s:%d>");
4319 caller = CALLN (Fformat, caller_format, host, service);
4321 break;
4323 #ifdef AF_INET6
4324 case AF_INET6:
4326 Lisp_Object args[9];
4327 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4328 int i;
4330 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4331 args[0] = ipv6_format;
4332 for (i = 0; i < 8; i++)
4333 args[i + 1] = make_number (ntohs (ip6[i]));
4334 host = CALLMANY (Fformat, args);
4335 service = make_number (ntohs (saddr.in.sin_port));
4336 AUTO_STRING (caller_format, " <[%s]:%d>");
4337 caller = CALLN (Fformat, caller_format, host, service);
4339 break;
4340 #endif
4342 #ifdef HAVE_LOCAL_SOCKETS
4343 case AF_LOCAL:
4344 #endif
4345 default:
4346 caller = Fnumber_to_string (make_number (connect_counter));
4347 AUTO_STRING (space_less_than, " <");
4348 AUTO_STRING (greater_than, ">");
4349 caller = concat3 (space_less_than, caller, greater_than);
4350 break;
4353 /* Create a new buffer name for this process if it doesn't have a
4354 filter. The new buffer name is based on the buffer name or
4355 process name of the server process concatenated with the caller
4356 identification. */
4358 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4359 || EQ (ps->filter, Qt)))
4360 buffer = Qnil;
4361 else
4363 buffer = ps->buffer;
4364 if (!NILP (buffer))
4365 buffer = Fbuffer_name (buffer);
4366 else
4367 buffer = ps->name;
4368 if (!NILP (buffer))
4370 buffer = concat2 (buffer, caller);
4371 buffer = Fget_buffer_create (buffer);
4375 /* Generate a unique name for the new server process. Combine the
4376 server process name with the caller identification. */
4378 name = concat2 (ps->name, caller);
4379 proc = make_process (name);
4381 chan_process[s] = proc;
4383 fcntl (s, F_SETFL, O_NONBLOCK);
4385 p = XPROCESS (proc);
4387 /* Build new contact information for this setup. */
4388 contact = Fcopy_sequence (ps->childp);
4389 contact = Fplist_put (contact, QCserver, Qnil);
4390 contact = Fplist_put (contact, QChost, host);
4391 if (!NILP (service))
4392 contact = Fplist_put (contact, QCservice, service);
4393 contact = Fplist_put (contact, QCremote,
4394 conv_sockaddr_to_lisp (&saddr.sa, len));
4395 #ifdef HAVE_GETSOCKNAME
4396 len = sizeof saddr;
4397 if (getsockname (s, &saddr.sa, &len) == 0)
4398 contact = Fplist_put (contact, QClocal,
4399 conv_sockaddr_to_lisp (&saddr.sa, len));
4400 #endif
4402 pset_childp (p, contact);
4403 pset_plist (p, Fcopy_sequence (ps->plist));
4404 pset_type (p, Qnetwork);
4406 pset_buffer (p, buffer);
4407 pset_sentinel (p, ps->sentinel);
4408 pset_filter (p, ps->filter);
4409 pset_command (p, Qnil);
4410 p->pid = 0;
4412 /* Discard the unwind protect for closing S. */
4413 specpdl_ptr = specpdl + count;
4415 p->open_fd[SUBPROCESS_STDIN] = s;
4416 p->infd = s;
4417 p->outfd = s;
4418 pset_status (p, Qrun);
4420 /* Client processes for accepted connections are not stopped initially. */
4421 if (!EQ (p->filter, Qt))
4423 FD_SET (s, &input_wait_mask);
4424 FD_SET (s, &non_keyboard_wait_mask);
4427 if (s > max_process_desc)
4428 max_process_desc = s;
4430 /* Setup coding system for new process based on server process.
4431 This seems to be the proper thing to do, as the coding system
4432 of the new process should reflect the settings at the time the
4433 server socket was opened; not the current settings. */
4435 pset_decode_coding_system (p, ps->decode_coding_system);
4436 pset_encode_coding_system (p, ps->encode_coding_system);
4437 setup_process_coding_systems (proc);
4439 pset_decoding_buf (p, empty_unibyte_string);
4440 p->decoding_carryover = 0;
4441 pset_encoding_buf (p, empty_unibyte_string);
4443 p->inherit_coding_system_flag
4444 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4446 AUTO_STRING (dash, "-");
4447 AUTO_STRING (nl, "\n");
4448 Lisp_Object host_string = STRINGP (host) ? host : dash;
4450 if (!NILP (ps->log))
4452 AUTO_STRING (accept_from, "accept from ");
4453 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4456 AUTO_STRING (open_from, "open from ");
4457 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4460 /* This variable is different from waiting_for_input in keyboard.c.
4461 It is used to communicate to a lisp process-filter/sentinel (via the
4462 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4463 for user-input when that process-filter was called.
4464 waiting_for_input cannot be used as that is by definition 0 when
4465 lisp code is being evalled.
4466 This is also used in record_asynch_buffer_change.
4467 For that purpose, this must be 0
4468 when not inside wait_reading_process_output. */
4469 static int waiting_for_user_input_p;
4471 static void
4472 wait_reading_process_output_unwind (int data)
4474 waiting_for_user_input_p = data;
4477 /* This is here so breakpoints can be put on it. */
4478 static void
4479 wait_reading_process_output_1 (void)
4483 /* Read and dispose of subprocess output while waiting for timeout to
4484 elapse and/or keyboard input to be available.
4486 TIME_LIMIT is:
4487 timeout in seconds
4488 If negative, gobble data immediately available but don't wait for any.
4490 NSECS is:
4491 an additional duration to wait, measured in nanoseconds
4492 If TIME_LIMIT is zero, then:
4493 If NSECS == 0, there is no limit.
4494 If NSECS > 0, the timeout consists of NSECS only.
4495 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4497 READ_KBD is:
4498 0 to ignore keyboard input, or
4499 1 to return when input is available, or
4500 -1 meaning caller will actually read the input, so don't throw to
4501 the quit handler, or
4503 DO_DISPLAY means redisplay should be done to show subprocess
4504 output that arrives.
4506 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4507 (and gobble terminal input into the buffer if any arrives).
4509 If WAIT_PROC is specified, wait until something arrives from that
4510 process.
4512 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4513 (suspending output from other processes). A negative value
4514 means don't run any timers either.
4516 Return positive if we received input from WAIT_PROC (or from any
4517 process if WAIT_PROC is null), zero if we attempted to receive
4518 input but got none, and negative if we didn't even try. */
4521 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4522 bool do_display,
4523 Lisp_Object wait_for_cell,
4524 struct Lisp_Process *wait_proc, int just_wait_proc)
4526 int channel, nfds;
4527 fd_set Available;
4528 fd_set Writeok;
4529 bool check_write;
4530 int check_delay;
4531 bool no_avail;
4532 int xerrno;
4533 Lisp_Object proc;
4534 struct timespec timeout, end_time, timer_delay;
4535 struct timespec got_output_end_time = invalid_timespec ();
4536 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
4537 int got_some_output = -1;
4538 ptrdiff_t count = SPECPDL_INDEX ();
4540 /* Close to the current time if known, an invalid timespec otherwise. */
4541 struct timespec now = invalid_timespec ();
4543 FD_ZERO (&Available);
4544 FD_ZERO (&Writeok);
4546 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4547 && !(CONSP (wait_proc->status)
4548 && EQ (XCAR (wait_proc->status), Qexit)))
4549 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4551 record_unwind_protect_int (wait_reading_process_output_unwind,
4552 waiting_for_user_input_p);
4553 waiting_for_user_input_p = read_kbd;
4555 if (TYPE_MAXIMUM (time_t) < time_limit)
4556 time_limit = TYPE_MAXIMUM (time_t);
4558 if (time_limit < 0 || nsecs < 0)
4559 wait = MINIMUM;
4560 else if (time_limit > 0 || nsecs > 0)
4562 wait = TIMEOUT;
4563 now = current_timespec ();
4564 end_time = timespec_add (now, make_timespec (time_limit, nsecs));
4566 else
4567 wait = INFINITY;
4569 while (1)
4571 bool process_skipped = false;
4573 /* If calling from keyboard input, do not quit
4574 since we want to return C-g as an input character.
4575 Otherwise, do pending quit if requested. */
4576 if (read_kbd >= 0)
4577 QUIT;
4578 else if (pending_signals)
4579 process_pending_signals ();
4581 /* Exit now if the cell we're waiting for became non-nil. */
4582 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4583 break;
4585 /* Compute time from now till when time limit is up. */
4586 /* Exit if already run out. */
4587 if (wait == TIMEOUT)
4589 if (!timespec_valid_p (now))
4590 now = current_timespec ();
4591 if (timespec_cmp (end_time, now) <= 0)
4592 break;
4593 timeout = timespec_sub (end_time, now);
4595 else
4596 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
4598 /* Normally we run timers here.
4599 But not if wait_for_cell; in those cases,
4600 the wait is supposed to be short,
4601 and those callers cannot handle running arbitrary Lisp code here. */
4602 if (NILP (wait_for_cell)
4603 && just_wait_proc >= 0)
4607 unsigned old_timers_run = timers_run;
4608 struct buffer *old_buffer = current_buffer;
4609 Lisp_Object old_window = selected_window;
4611 timer_delay = timer_check ();
4613 /* If a timer has run, this might have changed buffers
4614 an alike. Make read_key_sequence aware of that. */
4615 if (timers_run != old_timers_run
4616 && (old_buffer != current_buffer
4617 || !EQ (old_window, selected_window))
4618 && waiting_for_user_input_p == -1)
4619 record_asynch_buffer_change ();
4621 if (timers_run != old_timers_run && do_display)
4622 /* We must retry, since a timer may have requeued itself
4623 and that could alter the time_delay. */
4624 redisplay_preserve_echo_area (9);
4625 else
4626 break;
4628 while (!detect_input_pending ());
4630 /* If there is unread keyboard input, also return. */
4631 if (read_kbd != 0
4632 && requeued_events_pending_p ())
4633 break;
4635 /* This is so a breakpoint can be put here. */
4636 if (!timespec_valid_p (timer_delay))
4637 wait_reading_process_output_1 ();
4640 /* Cause C-g and alarm signals to take immediate action,
4641 and cause input available signals to zero out timeout.
4643 It is important that we do this before checking for process
4644 activity. If we get a SIGCHLD after the explicit checks for
4645 process activity, timeout is the only way we will know. */
4646 if (read_kbd < 0)
4647 set_waiting_for_input (&timeout);
4649 /* If status of something has changed, and no input is
4650 available, notify the user of the change right away. After
4651 this explicit check, we'll let the SIGCHLD handler zap
4652 timeout to get our attention. */
4653 if (update_tick != process_tick)
4655 fd_set Atemp;
4656 fd_set Ctemp;
4658 if (kbd_on_hold_p ())
4659 FD_ZERO (&Atemp);
4660 else
4661 Atemp = input_wait_mask;
4662 Ctemp = write_mask;
4664 timeout = make_timespec (0, 0);
4665 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4666 &Atemp,
4667 #ifdef NON_BLOCKING_CONNECT
4668 (num_pending_connects > 0 ? &Ctemp : NULL),
4669 #else
4670 NULL,
4671 #endif
4672 NULL, &timeout, NULL)
4673 <= 0))
4675 /* It's okay for us to do this and then continue with
4676 the loop, since timeout has already been zeroed out. */
4677 clear_waiting_for_input ();
4678 got_some_output = status_notify (NULL, wait_proc);
4679 if (do_display) redisplay_preserve_echo_area (13);
4683 /* Don't wait for output from a non-running process. Just
4684 read whatever data has already been received. */
4685 if (wait_proc && wait_proc->raw_status_new)
4686 update_status (wait_proc);
4687 if (wait_proc
4688 && ! EQ (wait_proc->status, Qrun)
4689 && ! EQ (wait_proc->status, Qconnect))
4691 bool read_some_bytes = false;
4693 clear_waiting_for_input ();
4695 /* If data can be read from the process, do so until exhausted. */
4696 if (wait_proc->infd >= 0)
4698 XSETPROCESS (proc, wait_proc);
4700 while (true)
4702 int nread = read_process_output (proc, wait_proc->infd);
4703 if (nread < 0)
4705 if (errno == EIO || errno == EAGAIN)
4706 break;
4707 #ifdef EWOULDBLOCK
4708 if (errno == EWOULDBLOCK)
4709 break;
4710 #endif
4712 else
4714 if (got_some_output < nread)
4715 got_some_output = nread;
4716 if (nread == 0)
4717 break;
4718 read_some_bytes = true;
4723 if (read_some_bytes && do_display)
4724 redisplay_preserve_echo_area (10);
4726 break;
4729 /* Wait till there is something to do. */
4731 if (wait_proc && just_wait_proc)
4733 if (wait_proc->infd < 0) /* Terminated. */
4734 break;
4735 FD_SET (wait_proc->infd, &Available);
4736 check_delay = 0;
4737 check_write = 0;
4739 else if (!NILP (wait_for_cell))
4741 Available = non_process_wait_mask;
4742 check_delay = 0;
4743 check_write = 0;
4745 else
4747 if (! read_kbd)
4748 Available = non_keyboard_wait_mask;
4749 else
4750 Available = input_wait_mask;
4751 Writeok = write_mask;
4752 check_delay = wait_proc ? 0 : process_output_delay_count;
4753 check_write = true;
4756 /* If frame size has changed or the window is newly mapped,
4757 redisplay now, before we start to wait. There is a race
4758 condition here; if a SIGIO arrives between now and the select
4759 and indicates that a frame is trashed, the select may block
4760 displaying a trashed screen. */
4761 if (frame_garbaged && do_display)
4763 clear_waiting_for_input ();
4764 redisplay_preserve_echo_area (11);
4765 if (read_kbd < 0)
4766 set_waiting_for_input (&timeout);
4769 /* Skip the `select' call if input is available and we're
4770 waiting for keyboard input or a cell change (which can be
4771 triggered by processing X events). In the latter case, set
4772 nfds to 1 to avoid breaking the loop. */
4773 no_avail = 0;
4774 if ((read_kbd || !NILP (wait_for_cell))
4775 && detect_input_pending ())
4777 nfds = read_kbd ? 0 : 1;
4778 no_avail = 1;
4779 FD_ZERO (&Available);
4781 else
4783 /* Set the timeout for adaptive read buffering if any
4784 process has non-zero read_output_skip and non-zero
4785 read_output_delay, and we are not reading output for a
4786 specific process. It is not executed if
4787 Vprocess_adaptive_read_buffering is nil. */
4788 if (process_output_skip && check_delay > 0)
4790 int adaptive_nsecs = timeout.tv_nsec;
4791 if (timeout.tv_sec > 0 || adaptive_nsecs > READ_OUTPUT_DELAY_MAX)
4792 adaptive_nsecs = READ_OUTPUT_DELAY_MAX;
4793 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4795 proc = chan_process[channel];
4796 if (NILP (proc))
4797 continue;
4798 /* Find minimum non-zero read_output_delay among the
4799 processes with non-zero read_output_skip. */
4800 if (XPROCESS (proc)->read_output_delay > 0)
4802 check_delay--;
4803 if (!XPROCESS (proc)->read_output_skip)
4804 continue;
4805 FD_CLR (channel, &Available);
4806 process_skipped = true;
4807 XPROCESS (proc)->read_output_skip = 0;
4808 if (XPROCESS (proc)->read_output_delay < adaptive_nsecs)
4809 adaptive_nsecs = XPROCESS (proc)->read_output_delay;
4812 timeout = make_timespec (0, adaptive_nsecs);
4813 process_output_skip = 0;
4816 /* If we've got some output and haven't limited our timeout
4817 with adaptive read buffering, limit it. */
4818 if (got_some_output > 0 && !process_skipped
4819 && (timeout.tv_sec
4820 || timeout.tv_nsec > READ_OUTPUT_DELAY_INCREMENT))
4821 timeout = make_timespec (0, READ_OUTPUT_DELAY_INCREMENT);
4824 if (NILP (wait_for_cell) && just_wait_proc >= 0
4825 && timespec_valid_p (timer_delay)
4826 && timespec_cmp (timer_delay, timeout) < 0)
4828 if (!timespec_valid_p (now))
4829 now = current_timespec ();
4830 struct timespec timeout_abs = timespec_add (now, timeout);
4831 if (!timespec_valid_p (got_output_end_time)
4832 || timespec_cmp (timeout_abs, got_output_end_time) < 0)
4833 got_output_end_time = timeout_abs;
4834 timeout = timer_delay;
4836 else
4837 got_output_end_time = invalid_timespec ();
4839 /* NOW can become inaccurate if time can pass during pselect. */
4840 if (timeout.tv_sec > 0 || timeout.tv_nsec > 0)
4841 now = invalid_timespec ();
4843 #if defined (HAVE_NS)
4844 nfds = ns_select
4845 #elif defined (HAVE_GLIB)
4846 nfds = xg_select
4847 #else
4848 nfds = pselect
4849 #endif
4850 (max (max_process_desc, max_input_desc) + 1,
4851 &Available,
4852 (check_write ? &Writeok : 0),
4853 NULL, &timeout, NULL);
4855 #ifdef HAVE_GNUTLS
4856 /* GnuTLS buffers data internally. In lowat mode it leaves
4857 some data in the TCP buffers so that select works, but
4858 with custom pull/push functions we need to check if some
4859 data is available in the buffers manually. */
4860 if (nfds == 0)
4862 fd_set tls_available;
4863 int set = 0;
4865 FD_ZERO (&tls_available);
4866 if (! wait_proc)
4868 /* We're not waiting on a specific process, so loop
4869 through all the channels and check for data.
4870 This is a workaround needed for some versions of
4871 the gnutls library -- 2.12.14 has been confirmed
4872 to need it. See
4873 http://comments.gmane.org/gmane.emacs.devel/145074 */
4874 for (channel = 0; channel < FD_SETSIZE; ++channel)
4875 if (! NILP (chan_process[channel]))
4877 struct Lisp_Process *p =
4878 XPROCESS (chan_process[channel]);
4879 if (p && p->gnutls_p && p->gnutls_state
4880 && ((emacs_gnutls_record_check_pending
4881 (p->gnutls_state))
4882 > 0))
4884 nfds++;
4885 eassert (p->infd == channel);
4886 FD_SET (p->infd, &tls_available);
4887 set++;
4891 else
4893 /* Check this specific channel. */
4894 if (wait_proc->gnutls_p /* Check for valid process. */
4895 && wait_proc->gnutls_state
4896 /* Do we have pending data? */
4897 && ((emacs_gnutls_record_check_pending
4898 (wait_proc->gnutls_state))
4899 > 0))
4901 nfds = 1;
4902 eassert (0 <= wait_proc->infd);
4903 /* Set to Available. */
4904 FD_SET (wait_proc->infd, &tls_available);
4905 set++;
4908 if (set)
4909 Available = tls_available;
4911 #endif
4914 xerrno = errno;
4916 /* Make C-g and alarm signals set flags again. */
4917 clear_waiting_for_input ();
4919 /* If we woke up due to SIGWINCH, actually change size now. */
4920 do_pending_window_change (0);
4922 if (nfds == 0)
4924 /* Exit the main loop if we've passed the requested timeout,
4925 or aren't skipping processes and got some output and
4926 haven't lowered our timeout due to timers or SIGIO and
4927 have waited a long amount of time due to repeated
4928 timers. */
4929 if (wait < TIMEOUT)
4930 break;
4931 struct timespec cmp_time
4932 = (wait == TIMEOUT
4933 ? end_time
4934 : (!process_skipped && got_some_output > 0
4935 && (timeout.tv_sec > 0 || timeout.tv_nsec > 0))
4936 ? got_output_end_time
4937 : invalid_timespec ());
4938 if (timespec_valid_p (cmp_time))
4940 now = current_timespec ();
4941 if (timespec_cmp (cmp_time, now) <= 0)
4942 break;
4946 if (nfds < 0)
4948 if (xerrno == EINTR)
4949 no_avail = 1;
4950 else if (xerrno == EBADF)
4951 emacs_abort ();
4952 else
4953 report_file_errno ("Failed select", Qnil, xerrno);
4956 /* Check for keyboard input. */
4957 /* If there is any, return immediately
4958 to give it higher priority than subprocesses. */
4960 if (read_kbd != 0)
4962 unsigned old_timers_run = timers_run;
4963 struct buffer *old_buffer = current_buffer;
4964 Lisp_Object old_window = selected_window;
4965 bool leave = false;
4967 if (detect_input_pending_run_timers (do_display))
4969 swallow_events (do_display);
4970 if (detect_input_pending_run_timers (do_display))
4971 leave = true;
4974 /* If a timer has run, this might have changed buffers
4975 an alike. Make read_key_sequence aware of that. */
4976 if (timers_run != old_timers_run
4977 && waiting_for_user_input_p == -1
4978 && (old_buffer != current_buffer
4979 || !EQ (old_window, selected_window)))
4980 record_asynch_buffer_change ();
4982 if (leave)
4983 break;
4986 /* If there is unread keyboard input, also return. */
4987 if (read_kbd != 0
4988 && requeued_events_pending_p ())
4989 break;
4991 /* If we are not checking for keyboard input now,
4992 do process events (but don't run any timers).
4993 This is so that X events will be processed.
4994 Otherwise they may have to wait until polling takes place.
4995 That would causes delays in pasting selections, for example.
4997 (We used to do this only if wait_for_cell.) */
4998 if (read_kbd == 0 && detect_input_pending ())
5000 swallow_events (do_display);
5001 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5002 if (detect_input_pending ())
5003 break;
5004 #endif
5007 /* Exit now if the cell we're waiting for became non-nil. */
5008 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5009 break;
5011 #ifdef USABLE_SIGIO
5012 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5013 go read it. This can happen with X on BSD after logging out.
5014 In that case, there really is no input and no SIGIO,
5015 but select says there is input. */
5017 if (read_kbd && interrupt_input
5018 && keyboard_bit_set (&Available) && ! noninteractive)
5019 handle_input_available_signal (SIGIO);
5020 #endif
5022 /* If checking input just got us a size-change event from X,
5023 obey it now if we should. */
5024 if (read_kbd || ! NILP (wait_for_cell))
5025 do_pending_window_change (0);
5027 /* Check for data from a process. */
5028 if (no_avail || nfds == 0)
5029 continue;
5031 for (channel = 0; channel <= max_input_desc; ++channel)
5033 struct fd_callback_data *d = &fd_callback_info[channel];
5034 if (d->func
5035 && ((d->condition & FOR_READ
5036 && FD_ISSET (channel, &Available))
5037 || (d->condition & FOR_WRITE
5038 && FD_ISSET (channel, &write_mask))))
5039 d->func (channel, d->data);
5042 for (channel = 0; channel <= max_process_desc; channel++)
5044 if (FD_ISSET (channel, &Available)
5045 && FD_ISSET (channel, &non_keyboard_wait_mask)
5046 && !FD_ISSET (channel, &non_process_wait_mask))
5048 int nread;
5050 /* If waiting for this channel, arrange to return as
5051 soon as no more input to be processed. No more
5052 waiting. */
5053 proc = chan_process[channel];
5054 if (NILP (proc))
5055 continue;
5057 /* If this is a server stream socket, accept connection. */
5058 if (EQ (XPROCESS (proc)->status, Qlisten))
5060 server_accept_connection (proc, channel);
5061 continue;
5064 /* Read data from the process, starting with our
5065 buffered-ahead character if we have one. */
5067 nread = read_process_output (proc, channel);
5068 if ((!wait_proc || wait_proc == XPROCESS (proc))
5069 && got_some_output < nread)
5070 got_some_output = nread;
5071 if (nread > 0)
5073 /* Vacuum up any leftovers without waiting. */
5074 if (wait_proc == XPROCESS (proc))
5075 wait = MINIMUM;
5076 /* Since read_process_output can run a filter,
5077 which can call accept-process-output,
5078 don't try to read from any other processes
5079 before doing the select again. */
5080 FD_ZERO (&Available);
5082 if (do_display)
5083 redisplay_preserve_echo_area (12);
5085 #ifdef EWOULDBLOCK
5086 else if (nread == -1 && errno == EWOULDBLOCK)
5088 #endif
5089 else if (nread == -1 && errno == EAGAIN)
5091 #ifdef WINDOWSNT
5092 /* FIXME: Is this special case still needed? */
5093 /* Note that we cannot distinguish between no input
5094 available now and a closed pipe.
5095 With luck, a closed pipe will be accompanied by
5096 subprocess termination and SIGCHLD. */
5097 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5098 && !PIPECONN_P (proc))
5100 #endif
5101 #ifdef HAVE_PTYS
5102 /* On some OSs with ptys, when the process on one end of
5103 a pty exits, the other end gets an error reading with
5104 errno = EIO instead of getting an EOF (0 bytes read).
5105 Therefore, if we get an error reading and errno =
5106 EIO, just continue, because the child process has
5107 exited and should clean itself up soon (e.g. when we
5108 get a SIGCHLD). */
5109 else if (nread == -1 && errno == EIO)
5111 struct Lisp_Process *p = XPROCESS (proc);
5113 /* Clear the descriptor now, so we only raise the
5114 signal once. */
5115 FD_CLR (channel, &input_wait_mask);
5116 FD_CLR (channel, &non_keyboard_wait_mask);
5118 if (p->pid == -2)
5120 /* If the EIO occurs on a pty, the SIGCHLD handler's
5121 waitpid call will not find the process object to
5122 delete. Do it here. */
5123 p->tick = ++process_tick;
5124 pset_status (p, Qfailed);
5127 #endif /* HAVE_PTYS */
5128 /* If we can detect process termination, don't consider the
5129 process gone just because its pipe is closed. */
5130 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5131 && !PIPECONN_P (proc))
5133 else if (nread == 0 && PIPECONN_P (proc))
5135 /* Preserve status of processes already terminated. */
5136 XPROCESS (proc)->tick = ++process_tick;
5137 deactivate_process (proc);
5138 if (EQ (XPROCESS (proc)->status, Qrun))
5139 pset_status (XPROCESS (proc),
5140 list2 (Qexit, make_number (0)));
5142 else
5144 /* Preserve status of processes already terminated. */
5145 XPROCESS (proc)->tick = ++process_tick;
5146 deactivate_process (proc);
5147 if (XPROCESS (proc)->raw_status_new)
5148 update_status (XPROCESS (proc));
5149 if (EQ (XPROCESS (proc)->status, Qrun))
5150 pset_status (XPROCESS (proc),
5151 list2 (Qexit, make_number (256)));
5154 #ifdef NON_BLOCKING_CONNECT
5155 if (FD_ISSET (channel, &Writeok)
5156 && FD_ISSET (channel, &connect_wait_mask))
5158 struct Lisp_Process *p;
5160 FD_CLR (channel, &connect_wait_mask);
5161 FD_CLR (channel, &write_mask);
5162 if (--num_pending_connects < 0)
5163 emacs_abort ();
5165 proc = chan_process[channel];
5166 if (NILP (proc))
5167 continue;
5169 p = XPROCESS (proc);
5171 #ifdef GNU_LINUX
5172 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5173 So only use it on systems where it is known to work. */
5175 socklen_t xlen = sizeof (xerrno);
5176 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5177 xerrno = errno;
5179 #else
5181 struct sockaddr pname;
5182 socklen_t pnamelen = sizeof (pname);
5184 /* If connection failed, getpeername will fail. */
5185 xerrno = 0;
5186 if (getpeername (channel, &pname, &pnamelen) < 0)
5188 /* Obtain connect failure code through error slippage. */
5189 char dummy;
5190 xerrno = errno;
5191 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5192 xerrno = errno;
5195 #endif
5196 if (xerrno)
5198 p->tick = ++process_tick;
5199 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5200 deactivate_process (proc);
5202 else
5204 pset_status (p, Qrun);
5205 /* Execute the sentinel here. If we had relied on
5206 status_notify to do it later, it will read input
5207 from the process before calling the sentinel. */
5208 exec_sentinel (proc, build_string ("open\n"));
5209 if (0 <= p->infd && !EQ (p->filter, Qt)
5210 && !EQ (p->command, Qt))
5212 FD_SET (p->infd, &input_wait_mask);
5213 FD_SET (p->infd, &non_keyboard_wait_mask);
5217 #endif /* NON_BLOCKING_CONNECT */
5218 } /* End for each file descriptor. */
5219 } /* End while exit conditions not met. */
5221 unbind_to (count, Qnil);
5223 /* If calling from keyboard input, do not quit
5224 since we want to return C-g as an input character.
5225 Otherwise, do pending quit if requested. */
5226 if (read_kbd >= 0)
5228 /* Prevent input_pending from remaining set if we quit. */
5229 clear_input_pending ();
5230 QUIT;
5233 return got_some_output;
5236 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5238 static Lisp_Object
5239 read_process_output_call (Lisp_Object fun_and_args)
5241 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5244 static Lisp_Object
5245 read_process_output_error_handler (Lisp_Object error_val)
5247 cmd_error_internal (error_val, "error in process filter: ");
5248 Vinhibit_quit = Qt;
5249 update_echo_area ();
5250 Fsleep_for (make_number (2), Qnil);
5251 return Qt;
5254 static void
5255 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5256 ssize_t nbytes,
5257 struct coding_system *coding);
5259 /* Read pending output from the process channel,
5260 starting with our buffered-ahead character if we have one.
5261 Yield number of decoded characters read.
5263 This function reads at most 4096 characters.
5264 If you want to read all available subprocess output,
5265 you must call it repeatedly until it returns zero.
5267 The characters read are decoded according to PROC's coding-system
5268 for decoding. */
5270 static int
5271 read_process_output (Lisp_Object proc, int channel)
5273 ssize_t nbytes;
5274 struct Lisp_Process *p = XPROCESS (proc);
5275 struct coding_system *coding = proc_decode_coding_system[channel];
5276 int carryover = p->decoding_carryover;
5277 enum { readmax = 4096 };
5278 ptrdiff_t count = SPECPDL_INDEX ();
5279 Lisp_Object odeactivate;
5280 char chars[sizeof coding->carryover + readmax];
5282 if (carryover)
5283 /* See the comment above. */
5284 memcpy (chars, SDATA (p->decoding_buf), carryover);
5286 #ifdef DATAGRAM_SOCKETS
5287 /* We have a working select, so proc_buffered_char is always -1. */
5288 if (DATAGRAM_CHAN_P (channel))
5290 socklen_t len = datagram_address[channel].len;
5291 nbytes = recvfrom (channel, chars + carryover, readmax,
5292 0, datagram_address[channel].sa, &len);
5294 else
5295 #endif
5297 bool buffered = proc_buffered_char[channel] >= 0;
5298 if (buffered)
5300 chars[carryover] = proc_buffered_char[channel];
5301 proc_buffered_char[channel] = -1;
5303 #ifdef HAVE_GNUTLS
5304 if (p->gnutls_p && p->gnutls_state)
5305 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5306 readmax - buffered);
5307 else
5308 #endif
5309 nbytes = emacs_read (channel, chars + carryover + buffered,
5310 readmax - buffered);
5311 if (nbytes > 0 && p->adaptive_read_buffering)
5313 int delay = p->read_output_delay;
5314 if (nbytes < 256)
5316 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5318 if (delay == 0)
5319 process_output_delay_count++;
5320 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5323 else if (delay > 0 && nbytes == readmax - buffered)
5325 delay -= READ_OUTPUT_DELAY_INCREMENT;
5326 if (delay == 0)
5327 process_output_delay_count--;
5329 p->read_output_delay = delay;
5330 if (delay)
5332 p->read_output_skip = 1;
5333 process_output_skip = 1;
5336 nbytes += buffered;
5337 nbytes += buffered && nbytes <= 0;
5340 p->decoding_carryover = 0;
5342 /* At this point, NBYTES holds number of bytes just received
5343 (including the one in proc_buffered_char[channel]). */
5344 if (nbytes <= 0)
5346 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5347 return nbytes;
5348 coding->mode |= CODING_MODE_LAST_BLOCK;
5351 /* Now set NBYTES how many bytes we must decode. */
5352 nbytes += carryover;
5354 odeactivate = Vdeactivate_mark;
5355 /* There's no good reason to let process filters change the current
5356 buffer, and many callers of accept-process-output, sit-for, and
5357 friends don't expect current-buffer to be changed from under them. */
5358 record_unwind_current_buffer ();
5360 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5362 /* Handling the process output should not deactivate the mark. */
5363 Vdeactivate_mark = odeactivate;
5365 unbind_to (count, Qnil);
5366 return nbytes;
5369 static void
5370 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5371 ssize_t nbytes,
5372 struct coding_system *coding)
5374 Lisp_Object outstream = p->filter;
5375 Lisp_Object text;
5376 bool outer_running_asynch_code = running_asynch_code;
5377 int waiting = waiting_for_user_input_p;
5379 #if 0
5380 Lisp_Object obuffer, okeymap;
5381 XSETBUFFER (obuffer, current_buffer);
5382 okeymap = BVAR (current_buffer, keymap);
5383 #endif
5385 /* We inhibit quit here instead of just catching it so that
5386 hitting ^G when a filter happens to be running won't screw
5387 it up. */
5388 specbind (Qinhibit_quit, Qt);
5389 specbind (Qlast_nonmenu_event, Qt);
5391 /* In case we get recursively called,
5392 and we already saved the match data nonrecursively,
5393 save the same match data in safely recursive fashion. */
5394 if (outer_running_asynch_code)
5396 Lisp_Object tem;
5397 /* Don't clobber the CURRENT match data, either! */
5398 tem = Fmatch_data (Qnil, Qnil, Qnil);
5399 restore_search_regs ();
5400 record_unwind_save_match_data ();
5401 Fset_match_data (tem, Qt);
5404 /* For speed, if a search happens within this code,
5405 save the match data in a special nonrecursive fashion. */
5406 running_asynch_code = 1;
5408 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5409 text = coding->dst_object;
5410 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5411 /* A new coding system might be found. */
5412 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5414 pset_decode_coding_system (p, Vlast_coding_system_used);
5416 /* Don't call setup_coding_system for
5417 proc_decode_coding_system[channel] here. It is done in
5418 detect_coding called via decode_coding above. */
5420 /* If a coding system for encoding is not yet decided, we set
5421 it as the same as coding-system for decoding.
5423 But, before doing that we must check if
5424 proc_encode_coding_system[p->outfd] surely points to a
5425 valid memory because p->outfd will be changed once EOF is
5426 sent to the process. */
5427 if (NILP (p->encode_coding_system) && p->outfd >= 0
5428 && proc_encode_coding_system[p->outfd])
5430 pset_encode_coding_system
5431 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5432 setup_coding_system (p->encode_coding_system,
5433 proc_encode_coding_system[p->outfd]);
5437 if (coding->carryover_bytes > 0)
5439 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5440 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5441 memcpy (SDATA (p->decoding_buf), coding->carryover,
5442 coding->carryover_bytes);
5443 p->decoding_carryover = coding->carryover_bytes;
5445 if (SBYTES (text) > 0)
5446 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5447 sometimes it's simply wrong to wrap (e.g. when called from
5448 accept-process-output). */
5449 internal_condition_case_1 (read_process_output_call,
5450 list3 (outstream, make_lisp_proc (p), text),
5451 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5452 read_process_output_error_handler);
5454 /* If we saved the match data nonrecursively, restore it now. */
5455 restore_search_regs ();
5456 running_asynch_code = outer_running_asynch_code;
5458 /* Restore waiting_for_user_input_p as it was
5459 when we were called, in case the filter clobbered it. */
5460 waiting_for_user_input_p = waiting;
5462 #if 0 /* Call record_asynch_buffer_change unconditionally,
5463 because we might have changed minor modes or other things
5464 that affect key bindings. */
5465 if (! EQ (Fcurrent_buffer (), obuffer)
5466 || ! EQ (current_buffer->keymap, okeymap))
5467 #endif
5468 /* But do it only if the caller is actually going to read events.
5469 Otherwise there's no need to make him wake up, and it could
5470 cause trouble (for example it would make sit_for return). */
5471 if (waiting_for_user_input_p == -1)
5472 record_asynch_buffer_change ();
5475 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5476 Sinternal_default_process_filter, 2, 2, 0,
5477 doc: /* Function used as default process filter.
5478 This inserts the process's output into its buffer, if there is one.
5479 Otherwise it discards the output. */)
5480 (Lisp_Object proc, Lisp_Object text)
5482 struct Lisp_Process *p;
5483 ptrdiff_t opoint;
5485 CHECK_PROCESS (proc);
5486 p = XPROCESS (proc);
5487 CHECK_STRING (text);
5489 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5491 Lisp_Object old_read_only;
5492 ptrdiff_t old_begv, old_zv;
5493 ptrdiff_t old_begv_byte, old_zv_byte;
5494 ptrdiff_t before, before_byte;
5495 ptrdiff_t opoint_byte;
5496 struct buffer *b;
5498 Fset_buffer (p->buffer);
5499 opoint = PT;
5500 opoint_byte = PT_BYTE;
5501 old_read_only = BVAR (current_buffer, read_only);
5502 old_begv = BEGV;
5503 old_zv = ZV;
5504 old_begv_byte = BEGV_BYTE;
5505 old_zv_byte = ZV_BYTE;
5507 bset_read_only (current_buffer, Qnil);
5509 /* Insert new output into buffer at the current end-of-output
5510 marker, thus preserving logical ordering of input and output. */
5511 if (XMARKER (p->mark)->buffer)
5512 set_point_from_marker (p->mark);
5513 else
5514 SET_PT_BOTH (ZV, ZV_BYTE);
5515 before = PT;
5516 before_byte = PT_BYTE;
5518 /* If the output marker is outside of the visible region, save
5519 the restriction and widen. */
5520 if (! (BEGV <= PT && PT <= ZV))
5521 Fwiden ();
5523 /* Adjust the multibyteness of TEXT to that of the buffer. */
5524 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5525 != ! STRING_MULTIBYTE (text))
5526 text = (STRING_MULTIBYTE (text)
5527 ? Fstring_as_unibyte (text)
5528 : Fstring_to_multibyte (text));
5529 /* Insert before markers in case we are inserting where
5530 the buffer's mark is, and the user's next command is Meta-y. */
5531 insert_from_string_before_markers (text, 0, 0,
5532 SCHARS (text), SBYTES (text), 0);
5534 /* Make sure the process marker's position is valid when the
5535 process buffer is changed in the signal_after_change above.
5536 W3 is known to do that. */
5537 if (BUFFERP (p->buffer)
5538 && (b = XBUFFER (p->buffer), b != current_buffer))
5539 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5540 else
5541 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5543 update_mode_lines = 23;
5545 /* Make sure opoint and the old restrictions
5546 float ahead of any new text just as point would. */
5547 if (opoint >= before)
5549 opoint += PT - before;
5550 opoint_byte += PT_BYTE - before_byte;
5552 if (old_begv > before)
5554 old_begv += PT - before;
5555 old_begv_byte += PT_BYTE - before_byte;
5557 if (old_zv >= before)
5559 old_zv += PT - before;
5560 old_zv_byte += PT_BYTE - before_byte;
5563 /* If the restriction isn't what it should be, set it. */
5564 if (old_begv != BEGV || old_zv != ZV)
5565 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5567 bset_read_only (current_buffer, old_read_only);
5568 SET_PT_BOTH (opoint, opoint_byte);
5570 return Qnil;
5573 /* Sending data to subprocess. */
5575 /* In send_process, when a write fails temporarily,
5576 wait_reading_process_output is called. It may execute user code,
5577 e.g. timers, that attempts to write new data to the same process.
5578 We must ensure that data is sent in the right order, and not
5579 interspersed half-completed with other writes (Bug#10815). This is
5580 handled by the write_queue element of struct process. It is a list
5581 with each entry having the form
5583 (string . (offset . length))
5585 where STRING is a lisp string, OFFSET is the offset into the
5586 string's byte sequence from which we should begin to send, and
5587 LENGTH is the number of bytes left to send. */
5589 /* Create a new entry in write_queue.
5590 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5591 BUF is a pointer to the string sequence of the input_obj or a C
5592 string in case of Qt or Qnil. */
5594 static void
5595 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5596 const char *buf, ptrdiff_t len, bool front)
5598 ptrdiff_t offset;
5599 Lisp_Object entry, obj;
5601 if (STRINGP (input_obj))
5603 offset = buf - SSDATA (input_obj);
5604 obj = input_obj;
5606 else
5608 offset = 0;
5609 obj = make_unibyte_string (buf, len);
5612 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5614 if (front)
5615 pset_write_queue (p, Fcons (entry, p->write_queue));
5616 else
5617 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5620 /* Remove the first element in the write_queue of process P, put its
5621 contents in OBJ, BUF and LEN, and return true. If the
5622 write_queue is empty, return false. */
5624 static bool
5625 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5626 const char **buf, ptrdiff_t *len)
5628 Lisp_Object entry, offset_length;
5629 ptrdiff_t offset;
5631 if (NILP (p->write_queue))
5632 return 0;
5634 entry = XCAR (p->write_queue);
5635 pset_write_queue (p, XCDR (p->write_queue));
5637 *obj = XCAR (entry);
5638 offset_length = XCDR (entry);
5640 *len = XINT (XCDR (offset_length));
5641 offset = XINT (XCAR (offset_length));
5642 *buf = SSDATA (*obj) + offset;
5644 return 1;
5647 /* Send some data to process PROC.
5648 BUF is the beginning of the data; LEN is the number of characters.
5649 OBJECT is the Lisp object that the data comes from. If OBJECT is
5650 nil or t, it means that the data comes from C string.
5652 If OBJECT is not nil, the data is encoded by PROC's coding-system
5653 for encoding before it is sent.
5655 This function can evaluate Lisp code and can garbage collect. */
5657 static void
5658 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5659 Lisp_Object object)
5661 struct Lisp_Process *p = XPROCESS (proc);
5662 ssize_t rv;
5663 struct coding_system *coding;
5665 if (p->raw_status_new)
5666 update_status (p);
5667 if (! EQ (p->status, Qrun))
5668 error ("Process %s not running", SDATA (p->name));
5669 if (p->outfd < 0)
5670 error ("Output file descriptor of %s is closed", SDATA (p->name));
5672 coding = proc_encode_coding_system[p->outfd];
5673 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5675 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5676 || (BUFFERP (object)
5677 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5678 || EQ (object, Qt))
5680 pset_encode_coding_system
5681 (p, complement_process_encoding_system (p->encode_coding_system));
5682 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5684 /* The coding system for encoding was changed to raw-text
5685 because we sent a unibyte text previously. Now we are
5686 sending a multibyte text, thus we must encode it by the
5687 original coding system specified for the current process.
5689 Another reason we come here is that the coding system
5690 was just complemented and a new one was returned by
5691 complement_process_encoding_system. */
5692 setup_coding_system (p->encode_coding_system, coding);
5693 Vlast_coding_system_used = p->encode_coding_system;
5695 coding->src_multibyte = 1;
5697 else
5699 coding->src_multibyte = 0;
5700 /* For sending a unibyte text, character code conversion should
5701 not take place but EOL conversion should. So, setup raw-text
5702 or one of the subsidiary if we have not yet done it. */
5703 if (CODING_REQUIRE_ENCODING (coding))
5705 if (CODING_REQUIRE_FLUSHING (coding))
5707 /* But, before changing the coding, we must flush out data. */
5708 coding->mode |= CODING_MODE_LAST_BLOCK;
5709 send_process (proc, "", 0, Qt);
5710 coding->mode &= CODING_MODE_LAST_BLOCK;
5712 setup_coding_system (raw_text_coding_system
5713 (Vlast_coding_system_used),
5714 coding);
5715 coding->src_multibyte = 0;
5718 coding->dst_multibyte = 0;
5720 if (CODING_REQUIRE_ENCODING (coding))
5722 coding->dst_object = Qt;
5723 if (BUFFERP (object))
5725 ptrdiff_t from_byte, from, to;
5726 ptrdiff_t save_pt, save_pt_byte;
5727 struct buffer *cur = current_buffer;
5729 set_buffer_internal (XBUFFER (object));
5730 save_pt = PT, save_pt_byte = PT_BYTE;
5732 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5733 from = BYTE_TO_CHAR (from_byte);
5734 to = BYTE_TO_CHAR (from_byte + len);
5735 TEMP_SET_PT_BOTH (from, from_byte);
5736 encode_coding_object (coding, object, from, from_byte,
5737 to, from_byte + len, Qt);
5738 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5739 set_buffer_internal (cur);
5741 else if (STRINGP (object))
5743 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5744 SBYTES (object), Qt);
5746 else
5748 coding->dst_object = make_unibyte_string (buf, len);
5749 coding->produced = len;
5752 len = coding->produced;
5753 object = coding->dst_object;
5754 buf = SSDATA (object);
5757 /* If there is already data in the write_queue, put the new data
5758 in the back of queue. Otherwise, ignore it. */
5759 if (!NILP (p->write_queue))
5760 write_queue_push (p, object, buf, len, 0);
5762 do /* while !NILP (p->write_queue) */
5764 ptrdiff_t cur_len = -1;
5765 const char *cur_buf;
5766 Lisp_Object cur_object;
5768 /* If write_queue is empty, ignore it. */
5769 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5771 cur_len = len;
5772 cur_buf = buf;
5773 cur_object = object;
5776 while (cur_len > 0)
5778 /* Send this batch, using one or more write calls. */
5779 ptrdiff_t written = 0;
5780 int outfd = p->outfd;
5781 #ifdef DATAGRAM_SOCKETS
5782 if (DATAGRAM_CHAN_P (outfd))
5784 rv = sendto (outfd, cur_buf, cur_len,
5785 0, datagram_address[outfd].sa,
5786 datagram_address[outfd].len);
5787 if (rv >= 0)
5788 written = rv;
5789 else if (errno == EMSGSIZE)
5790 report_file_error ("Sending datagram", proc);
5792 else
5793 #endif
5795 #ifdef HAVE_GNUTLS
5796 if (p->gnutls_p && p->gnutls_state)
5797 written = emacs_gnutls_write (p, cur_buf, cur_len);
5798 else
5799 #endif
5800 written = emacs_write_sig (outfd, cur_buf, cur_len);
5801 rv = (written ? 0 : -1);
5802 if (p->read_output_delay > 0
5803 && p->adaptive_read_buffering == 1)
5805 p->read_output_delay = 0;
5806 process_output_delay_count--;
5807 p->read_output_skip = 0;
5811 if (rv < 0)
5813 if (errno == EAGAIN
5814 #ifdef EWOULDBLOCK
5815 || errno == EWOULDBLOCK
5816 #endif
5818 /* Buffer is full. Wait, accepting input;
5819 that may allow the program
5820 to finish doing output and read more. */
5822 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5823 /* A gross hack to work around a bug in FreeBSD.
5824 In the following sequence, read(2) returns
5825 bogus data:
5827 write(2) 1022 bytes
5828 write(2) 954 bytes, get EAGAIN
5829 read(2) 1024 bytes in process_read_output
5830 read(2) 11 bytes in process_read_output
5832 That is, read(2) returns more bytes than have
5833 ever been written successfully. The 1033 bytes
5834 read are the 1022 bytes written successfully
5835 after processing (for example with CRs added if
5836 the terminal is set up that way which it is
5837 here). The same bytes will be seen again in a
5838 later read(2), without the CRs. */
5840 if (errno == EAGAIN)
5842 int flags = FWRITE;
5843 ioctl (p->outfd, TIOCFLUSH, &flags);
5845 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5847 /* Put what we should have written in wait_queue. */
5848 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5849 wait_reading_process_output (0, 20 * 1000 * 1000,
5850 0, 0, Qnil, NULL, 0);
5851 /* Reread queue, to see what is left. */
5852 break;
5854 else if (errno == EPIPE)
5856 p->raw_status_new = 0;
5857 pset_status (p, list2 (Qexit, make_number (256)));
5858 p->tick = ++process_tick;
5859 deactivate_process (proc);
5860 error ("process %s no longer connected to pipe; closed it",
5861 SDATA (p->name));
5863 else
5864 /* This is a real error. */
5865 report_file_error ("Writing to process", proc);
5867 cur_buf += written;
5868 cur_len -= written;
5871 while (!NILP (p->write_queue));
5874 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5875 3, 3, 0,
5876 doc: /* Send current contents of region as input to PROCESS.
5877 PROCESS may be a process, a buffer, the name of a process or buffer, or
5878 nil, indicating the current buffer's process.
5879 Called from program, takes three arguments, PROCESS, START and END.
5880 If the region is more than 500 characters long,
5881 it is sent in several bunches. This may happen even for shorter regions.
5882 Output from processes can arrive in between bunches. */)
5883 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5885 Lisp_Object proc = get_process (process);
5886 ptrdiff_t start_byte, end_byte;
5888 validate_region (&start, &end);
5890 start_byte = CHAR_TO_BYTE (XINT (start));
5891 end_byte = CHAR_TO_BYTE (XINT (end));
5893 if (XINT (start) < GPT && XINT (end) > GPT)
5894 move_gap_both (XINT (start), start_byte);
5896 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5897 end_byte - start_byte, Fcurrent_buffer ());
5899 return Qnil;
5902 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5903 2, 2, 0,
5904 doc: /* Send PROCESS the contents of STRING as input.
5905 PROCESS may be a process, a buffer, the name of a process or buffer, or
5906 nil, indicating the current buffer's process.
5907 If STRING is more than 500 characters long,
5908 it is sent in several bunches. This may happen even for shorter strings.
5909 Output from processes can arrive in between bunches. */)
5910 (Lisp_Object process, Lisp_Object string)
5912 Lisp_Object proc;
5913 CHECK_STRING (string);
5914 proc = get_process (process);
5915 send_process (proc, SSDATA (string),
5916 SBYTES (string), string);
5917 return Qnil;
5920 /* Return the foreground process group for the tty/pty that
5921 the process P uses. */
5922 static pid_t
5923 emacs_get_tty_pgrp (struct Lisp_Process *p)
5925 pid_t gid = -1;
5927 #ifdef TIOCGPGRP
5928 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5930 int fd;
5931 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5932 master side. Try the slave side. */
5933 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5935 if (fd != -1)
5937 ioctl (fd, TIOCGPGRP, &gid);
5938 emacs_close (fd);
5941 #endif /* defined (TIOCGPGRP ) */
5943 return gid;
5946 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5947 Sprocess_running_child_p, 0, 1, 0,
5948 doc: /* Return non-nil if PROCESS has given the terminal to a
5949 child. If the operating system does not make it possible to find out,
5950 return t. If we can find out, return the numeric ID of the foreground
5951 process group. */)
5952 (Lisp_Object process)
5954 /* Initialize in case ioctl doesn't exist or gives an error,
5955 in a way that will cause returning t. */
5956 pid_t gid;
5957 Lisp_Object proc;
5958 struct Lisp_Process *p;
5960 proc = get_process (process);
5961 p = XPROCESS (proc);
5963 if (!EQ (p->type, Qreal))
5964 error ("Process %s is not a subprocess",
5965 SDATA (p->name));
5966 if (p->infd < 0)
5967 error ("Process %s is not active",
5968 SDATA (p->name));
5970 gid = emacs_get_tty_pgrp (p);
5972 if (gid == p->pid)
5973 return Qnil;
5974 if (gid != -1)
5975 return make_number (gid);
5976 return Qt;
5979 /* Send a signal number SIGNO to PROCESS.
5980 If CURRENT_GROUP is t, that means send to the process group
5981 that currently owns the terminal being used to communicate with PROCESS.
5982 This is used for various commands in shell mode.
5983 If CURRENT_GROUP is lambda, that means send to the process group
5984 that currently owns the terminal, but only if it is NOT the shell itself.
5986 If NOMSG is false, insert signal-announcements into process's buffers
5987 right away.
5989 If we can, we try to signal PROCESS by sending control characters
5990 down the pty. This allows us to signal inferiors who have changed
5991 their uid, for which kill would return an EPERM error. */
5993 static void
5994 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5995 bool nomsg)
5997 Lisp_Object proc;
5998 struct Lisp_Process *p;
5999 pid_t gid;
6000 bool no_pgrp = 0;
6002 proc = get_process (process);
6003 p = XPROCESS (proc);
6005 if (!EQ (p->type, Qreal))
6006 error ("Process %s is not a subprocess",
6007 SDATA (p->name));
6008 if (p->infd < 0)
6009 error ("Process %s is not active",
6010 SDATA (p->name));
6012 if (!p->pty_flag)
6013 current_group = Qnil;
6015 /* If we are using pgrps, get a pgrp number and make it negative. */
6016 if (NILP (current_group))
6017 /* Send the signal to the shell's process group. */
6018 gid = p->pid;
6019 else
6021 #ifdef SIGNALS_VIA_CHARACTERS
6022 /* If possible, send signals to the entire pgrp
6023 by sending an input character to it. */
6025 struct termios t;
6026 cc_t *sig_char = NULL;
6028 tcgetattr (p->infd, &t);
6030 switch (signo)
6032 case SIGINT:
6033 sig_char = &t.c_cc[VINTR];
6034 break;
6036 case SIGQUIT:
6037 sig_char = &t.c_cc[VQUIT];
6038 break;
6040 case SIGTSTP:
6041 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6042 sig_char = &t.c_cc[VSWTCH];
6043 #else
6044 sig_char = &t.c_cc[VSUSP];
6045 #endif
6046 break;
6049 if (sig_char && *sig_char != CDISABLE)
6051 send_process (proc, (char *) sig_char, 1, Qnil);
6052 return;
6054 /* If we can't send the signal with a character,
6055 fall through and send it another way. */
6057 /* The code above may fall through if it can't
6058 handle the signal. */
6059 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6061 #ifdef TIOCGPGRP
6062 /* Get the current pgrp using the tty itself, if we have that.
6063 Otherwise, use the pty to get the pgrp.
6064 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6065 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6066 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6067 His patch indicates that if TIOCGPGRP returns an error, then
6068 we should just assume that p->pid is also the process group id. */
6070 gid = emacs_get_tty_pgrp (p);
6072 if (gid == -1)
6073 /* If we can't get the information, assume
6074 the shell owns the tty. */
6075 gid = p->pid;
6077 /* It is not clear whether anything really can set GID to -1.
6078 Perhaps on some system one of those ioctls can or could do so.
6079 Or perhaps this is vestigial. */
6080 if (gid == -1)
6081 no_pgrp = 1;
6082 #else /* ! defined (TIOCGPGRP) */
6083 /* Can't select pgrps on this system, so we know that
6084 the child itself heads the pgrp. */
6085 gid = p->pid;
6086 #endif /* ! defined (TIOCGPGRP) */
6088 /* If current_group is lambda, and the shell owns the terminal,
6089 don't send any signal. */
6090 if (EQ (current_group, Qlambda) && gid == p->pid)
6091 return;
6094 #ifdef SIGCONT
6095 if (signo == SIGCONT)
6097 p->raw_status_new = 0;
6098 pset_status (p, Qrun);
6099 p->tick = ++process_tick;
6100 if (!nomsg)
6102 status_notify (NULL, NULL);
6103 redisplay_preserve_echo_area (13);
6106 #endif
6108 #ifdef TIOCSIGSEND
6109 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6110 We don't know whether the bug is fixed in later HP-UX versions. */
6111 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6112 return;
6113 #endif
6115 /* If we don't have process groups, send the signal to the immediate
6116 subprocess. That isn't really right, but it's better than any
6117 obvious alternative. */
6118 pid_t pid = no_pgrp ? gid : - gid;
6120 /* Do not kill an already-reaped process, as that could kill an
6121 innocent bystander that happens to have the same process ID. */
6122 sigset_t oldset;
6123 block_child_signal (&oldset);
6124 if (p->alive)
6125 kill (pid, signo);
6126 unblock_child_signal (&oldset);
6129 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6130 doc: /* Interrupt process PROCESS.
6131 PROCESS may be a process, a buffer, or the name of a process or buffer.
6132 No arg or nil means current buffer's process.
6133 Second arg CURRENT-GROUP non-nil means send signal to
6134 the current process-group of the process's controlling terminal
6135 rather than to the process's own process group.
6136 If the process is a shell, this means interrupt current subjob
6137 rather than the shell.
6139 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6140 don't send the signal. */)
6141 (Lisp_Object process, Lisp_Object current_group)
6143 process_send_signal (process, SIGINT, current_group, 0);
6144 return process;
6147 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6148 doc: /* Kill process PROCESS. May be process or name of one.
6149 See function `interrupt-process' for more details on usage. */)
6150 (Lisp_Object process, Lisp_Object current_group)
6152 process_send_signal (process, SIGKILL, current_group, 0);
6153 return process;
6156 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6157 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6158 See function `interrupt-process' for more details on usage. */)
6159 (Lisp_Object process, Lisp_Object current_group)
6161 process_send_signal (process, SIGQUIT, current_group, 0);
6162 return process;
6165 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6166 doc: /* Stop process PROCESS. May be process or name of one.
6167 See function `interrupt-process' for more details on usage.
6168 If PROCESS is a network or serial process, inhibit handling of incoming
6169 traffic. */)
6170 (Lisp_Object process, Lisp_Object current_group)
6172 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6173 || PIPECONN_P (process)))
6175 struct Lisp_Process *p;
6177 p = XPROCESS (process);
6178 if (NILP (p->command)
6179 && p->infd >= 0)
6181 FD_CLR (p->infd, &input_wait_mask);
6182 FD_CLR (p->infd, &non_keyboard_wait_mask);
6184 pset_command (p, Qt);
6185 return process;
6187 #ifndef SIGTSTP
6188 error ("No SIGTSTP support");
6189 #else
6190 process_send_signal (process, SIGTSTP, current_group, 0);
6191 #endif
6192 return process;
6195 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6196 doc: /* Continue process PROCESS. May be process or name of one.
6197 See function `interrupt-process' for more details on usage.
6198 If PROCESS is a network or serial process, resume handling of incoming
6199 traffic. */)
6200 (Lisp_Object process, Lisp_Object current_group)
6202 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6203 || PIPECONN_P (process)))
6205 struct Lisp_Process *p;
6207 p = XPROCESS (process);
6208 if (EQ (p->command, Qt)
6209 && p->infd >= 0
6210 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6212 FD_SET (p->infd, &input_wait_mask);
6213 FD_SET (p->infd, &non_keyboard_wait_mask);
6214 #ifdef WINDOWSNT
6215 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6216 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6217 #else /* not WINDOWSNT */
6218 tcflush (p->infd, TCIFLUSH);
6219 #endif /* not WINDOWSNT */
6221 pset_command (p, Qnil);
6222 return process;
6224 #ifdef SIGCONT
6225 process_send_signal (process, SIGCONT, current_group, 0);
6226 #else
6227 error ("No SIGCONT support");
6228 #endif
6229 return process;
6232 /* Return the integer value of the signal whose abbreviation is ABBR,
6233 or a negative number if there is no such signal. */
6234 static int
6235 abbr_to_signal (char const *name)
6237 int i, signo;
6238 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6240 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6241 name += 3;
6243 for (i = 0; i < sizeof sigbuf; i++)
6245 sigbuf[i] = c_toupper (name[i]);
6246 if (! sigbuf[i])
6247 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6250 return -1;
6253 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6254 2, 2, "sProcess (name or number): \nnSignal code: ",
6255 doc: /* Send PROCESS the signal with code SIGCODE.
6256 PROCESS may also be a number specifying the process id of the
6257 process to signal; in this case, the process need not be a child of
6258 this Emacs.
6259 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6260 (Lisp_Object process, Lisp_Object sigcode)
6262 pid_t pid;
6263 int signo;
6265 if (STRINGP (process))
6267 Lisp_Object tem = Fget_process (process);
6268 if (NILP (tem))
6270 Lisp_Object process_number
6271 = string_to_number (SSDATA (process), 10, 1);
6272 if (INTEGERP (process_number) || FLOATP (process_number))
6273 tem = process_number;
6275 process = tem;
6277 else if (!NUMBERP (process))
6278 process = get_process (process);
6280 if (NILP (process))
6281 return process;
6283 if (NUMBERP (process))
6284 CONS_TO_INTEGER (process, pid_t, pid);
6285 else
6287 CHECK_PROCESS (process);
6288 pid = XPROCESS (process)->pid;
6289 if (pid <= 0)
6290 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6293 if (INTEGERP (sigcode))
6295 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6296 signo = XINT (sigcode);
6298 else
6300 char *name;
6302 CHECK_SYMBOL (sigcode);
6303 name = SSDATA (SYMBOL_NAME (sigcode));
6305 signo = abbr_to_signal (name);
6306 if (signo < 0)
6307 error ("Undefined signal name %s", name);
6310 return make_number (kill (pid, signo));
6313 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6314 doc: /* Make PROCESS see end-of-file in its input.
6315 EOF comes after any text already sent to it.
6316 PROCESS may be a process, a buffer, the name of a process or buffer, or
6317 nil, indicating the current buffer's process.
6318 If PROCESS is a network connection, or is a process communicating
6319 through a pipe (as opposed to a pty), then you cannot send any more
6320 text to PROCESS after you call this function.
6321 If PROCESS is a serial process, wait until all output written to the
6322 process has been transmitted to the serial port. */)
6323 (Lisp_Object process)
6325 Lisp_Object proc;
6326 struct coding_system *coding = NULL;
6327 int outfd;
6329 if (DATAGRAM_CONN_P (process))
6330 return process;
6332 proc = get_process (process);
6333 outfd = XPROCESS (proc)->outfd;
6334 if (outfd >= 0)
6335 coding = proc_encode_coding_system[outfd];
6337 /* Make sure the process is really alive. */
6338 if (XPROCESS (proc)->raw_status_new)
6339 update_status (XPROCESS (proc));
6340 if (! EQ (XPROCESS (proc)->status, Qrun))
6341 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6343 if (coding && CODING_REQUIRE_FLUSHING (coding))
6345 coding->mode |= CODING_MODE_LAST_BLOCK;
6346 send_process (proc, "", 0, Qnil);
6349 if (XPROCESS (proc)->pty_flag)
6350 send_process (proc, "\004", 1, Qnil);
6351 else if (EQ (XPROCESS (proc)->type, Qserial))
6353 #ifndef WINDOWSNT
6354 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6355 report_file_error ("Failed tcdrain", Qnil);
6356 #endif /* not WINDOWSNT */
6357 /* Do nothing on Windows because writes are blocking. */
6359 else
6361 struct Lisp_Process *p = XPROCESS (proc);
6362 int old_outfd = p->outfd;
6363 int new_outfd;
6365 #ifdef HAVE_SHUTDOWN
6366 /* If this is a network connection, or socketpair is used
6367 for communication with the subprocess, call shutdown to cause EOF.
6368 (In some old system, shutdown to socketpair doesn't work.
6369 Then we just can't win.) */
6370 if (0 <= old_outfd
6371 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6372 shutdown (old_outfd, 1);
6373 #endif
6374 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6375 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6376 if (new_outfd < 0)
6377 report_file_error ("Opening null device", Qnil);
6378 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6379 p->outfd = new_outfd;
6381 if (!proc_encode_coding_system[new_outfd])
6382 proc_encode_coding_system[new_outfd]
6383 = xmalloc (sizeof (struct coding_system));
6384 if (old_outfd >= 0)
6386 *proc_encode_coding_system[new_outfd]
6387 = *proc_encode_coding_system[old_outfd];
6388 memset (proc_encode_coding_system[old_outfd], 0,
6389 sizeof (struct coding_system));
6391 else
6392 setup_coding_system (p->encode_coding_system,
6393 proc_encode_coding_system[new_outfd]);
6395 return process;
6398 /* The main Emacs thread records child processes in three places:
6400 - Vprocess_alist, for asynchronous subprocesses, which are child
6401 processes visible to Lisp.
6403 - deleted_pid_list, for child processes invisible to Lisp,
6404 typically because of delete-process. These are recorded so that
6405 the processes can be reaped when they exit, so that the operating
6406 system's process table is not cluttered by zombies.
6408 - the local variable PID in Fcall_process, call_process_cleanup and
6409 call_process_kill, for synchronous subprocesses.
6410 record_unwind_protect is used to make sure this process is not
6411 forgotten: if the user interrupts call-process and the child
6412 process refuses to exit immediately even with two C-g's,
6413 call_process_kill adds PID's contents to deleted_pid_list before
6414 returning.
6416 The main Emacs thread invokes waitpid only on child processes that
6417 it creates and that have not been reaped. This avoid races on
6418 platforms such as GTK, where other threads create their own
6419 subprocesses which the main thread should not reap. For example,
6420 if the main thread attempted to reap an already-reaped child, it
6421 might inadvertently reap a GTK-created process that happened to
6422 have the same process ID. */
6424 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6425 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6426 keep track of its own children. GNUstep is similar. */
6428 static void dummy_handler (int sig) {}
6429 static signal_handler_t volatile lib_child_handler;
6431 /* Handle a SIGCHLD signal by looking for known child processes of
6432 Emacs whose status have changed. For each one found, record its
6433 new status.
6435 All we do is change the status; we do not run sentinels or print
6436 notifications. That is saved for the next time keyboard input is
6437 done, in order to avoid timing errors.
6439 ** WARNING: this can be called during garbage collection.
6440 Therefore, it must not be fooled by the presence of mark bits in
6441 Lisp objects.
6443 ** USG WARNING: Although it is not obvious from the documentation
6444 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6445 signal() before executing at least one wait(), otherwise the
6446 handler will be called again, resulting in an infinite loop. The
6447 relevant portion of the documentation reads "SIGCLD signals will be
6448 queued and the signal-catching function will be continually
6449 reentered until the queue is empty". Invoking signal() causes the
6450 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6451 Inc.
6453 ** Malloc WARNING: This should never call malloc either directly or
6454 indirectly; if it does, that is a bug. */
6456 static void
6457 handle_child_signal (int sig)
6459 Lisp_Object tail, proc;
6461 /* Find the process that signaled us, and record its status. */
6463 /* The process can have been deleted by Fdelete_process, or have
6464 been started asynchronously by Fcall_process. */
6465 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6467 bool all_pids_are_fixnums
6468 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6469 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6470 Lisp_Object head = XCAR (tail);
6471 Lisp_Object xpid;
6472 if (! CONSP (head))
6473 continue;
6474 xpid = XCAR (head);
6475 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6477 pid_t deleted_pid;
6478 if (INTEGERP (xpid))
6479 deleted_pid = XINT (xpid);
6480 else
6481 deleted_pid = XFLOAT_DATA (xpid);
6482 if (child_status_changed (deleted_pid, 0, 0))
6484 if (STRINGP (XCDR (head)))
6485 unlink (SSDATA (XCDR (head)));
6486 XSETCAR (tail, Qnil);
6491 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6492 FOR_EACH_PROCESS (tail, proc)
6494 struct Lisp_Process *p = XPROCESS (proc);
6495 int status;
6497 if (p->alive
6498 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6500 /* Change the status of the process that was found. */
6501 p->tick = ++process_tick;
6502 p->raw_status = status;
6503 p->raw_status_new = 1;
6505 /* If process has terminated, stop waiting for its output. */
6506 if (WIFSIGNALED (status) || WIFEXITED (status))
6508 bool clear_desc_flag = 0;
6509 p->alive = 0;
6510 if (p->infd >= 0)
6511 clear_desc_flag = 1;
6513 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6514 if (clear_desc_flag)
6516 FD_CLR (p->infd, &input_wait_mask);
6517 FD_CLR (p->infd, &non_keyboard_wait_mask);
6523 lib_child_handler (sig);
6524 #ifdef NS_IMPL_GNUSTEP
6525 /* NSTask in GNUstep sets its child handler each time it is called.
6526 So we must re-set ours. */
6527 catch_child_signal ();
6528 #endif
6531 static void
6532 deliver_child_signal (int sig)
6534 deliver_process_signal (sig, handle_child_signal);
6538 static Lisp_Object
6539 exec_sentinel_error_handler (Lisp_Object error_val)
6541 cmd_error_internal (error_val, "error in process sentinel: ");
6542 Vinhibit_quit = Qt;
6543 update_echo_area ();
6544 Fsleep_for (make_number (2), Qnil);
6545 return Qt;
6548 static void
6549 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6551 Lisp_Object sentinel, odeactivate;
6552 struct Lisp_Process *p = XPROCESS (proc);
6553 ptrdiff_t count = SPECPDL_INDEX ();
6554 bool outer_running_asynch_code = running_asynch_code;
6555 int waiting = waiting_for_user_input_p;
6557 if (inhibit_sentinels)
6558 return;
6560 odeactivate = Vdeactivate_mark;
6561 #if 0
6562 Lisp_Object obuffer, okeymap;
6563 XSETBUFFER (obuffer, current_buffer);
6564 okeymap = BVAR (current_buffer, keymap);
6565 #endif
6567 /* There's no good reason to let sentinels change the current
6568 buffer, and many callers of accept-process-output, sit-for, and
6569 friends don't expect current-buffer to be changed from under them. */
6570 record_unwind_current_buffer ();
6572 sentinel = p->sentinel;
6574 /* Inhibit quit so that random quits don't screw up a running filter. */
6575 specbind (Qinhibit_quit, Qt);
6576 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6578 /* In case we get recursively called,
6579 and we already saved the match data nonrecursively,
6580 save the same match data in safely recursive fashion. */
6581 if (outer_running_asynch_code)
6583 Lisp_Object tem;
6584 tem = Fmatch_data (Qnil, Qnil, Qnil);
6585 restore_search_regs ();
6586 record_unwind_save_match_data ();
6587 Fset_match_data (tem, Qt);
6590 /* For speed, if a search happens within this code,
6591 save the match data in a special nonrecursive fashion. */
6592 running_asynch_code = 1;
6594 internal_condition_case_1 (read_process_output_call,
6595 list3 (sentinel, proc, reason),
6596 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6597 exec_sentinel_error_handler);
6599 /* If we saved the match data nonrecursively, restore it now. */
6600 restore_search_regs ();
6601 running_asynch_code = outer_running_asynch_code;
6603 Vdeactivate_mark = odeactivate;
6605 /* Restore waiting_for_user_input_p as it was
6606 when we were called, in case the filter clobbered it. */
6607 waiting_for_user_input_p = waiting;
6609 #if 0
6610 if (! EQ (Fcurrent_buffer (), obuffer)
6611 || ! EQ (current_buffer->keymap, okeymap))
6612 #endif
6613 /* But do it only if the caller is actually going to read events.
6614 Otherwise there's no need to make him wake up, and it could
6615 cause trouble (for example it would make sit_for return). */
6616 if (waiting_for_user_input_p == -1)
6617 record_asynch_buffer_change ();
6619 unbind_to (count, Qnil);
6622 /* Report all recent events of a change in process status
6623 (either run the sentinel or output a message).
6624 This is usually done while Emacs is waiting for keyboard input
6625 but can be done at other times.
6627 Return positive if any input was received from WAIT_PROC (or from
6628 any process if WAIT_PROC is null), zero if input was attempted but
6629 none received, and negative if we didn't even try. */
6631 static int
6632 status_notify (struct Lisp_Process *deleting_process,
6633 struct Lisp_Process *wait_proc)
6635 Lisp_Object proc;
6636 Lisp_Object tail, msg;
6637 int got_some_output = -1;
6639 tail = Qnil;
6640 msg = Qnil;
6642 /* Set this now, so that if new processes are created by sentinels
6643 that we run, we get called again to handle their status changes. */
6644 update_tick = process_tick;
6646 FOR_EACH_PROCESS (tail, proc)
6648 Lisp_Object symbol;
6649 register struct Lisp_Process *p = XPROCESS (proc);
6651 if (p->tick != p->update_tick)
6653 p->update_tick = p->tick;
6655 /* If process is still active, read any output that remains. */
6656 while (! EQ (p->filter, Qt)
6657 && ! EQ (p->status, Qconnect)
6658 && ! EQ (p->status, Qlisten)
6659 /* Network or serial process not stopped: */
6660 && ! EQ (p->command, Qt)
6661 && p->infd >= 0
6662 && p != deleting_process)
6664 int nread = read_process_output (proc, p->infd);
6665 if ((!wait_proc || wait_proc == XPROCESS (proc))
6666 && got_some_output < nread)
6667 got_some_output = nread;
6668 if (nread <= 0)
6669 break;
6672 /* Get the text to use for the message. */
6673 if (p->raw_status_new)
6674 update_status (p);
6675 msg = status_message (p);
6677 /* If process is terminated, deactivate it or delete it. */
6678 symbol = p->status;
6679 if (CONSP (p->status))
6680 symbol = XCAR (p->status);
6682 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6683 || EQ (symbol, Qclosed))
6685 if (delete_exited_processes)
6686 remove_process (proc);
6687 else
6688 deactivate_process (proc);
6691 /* The actions above may have further incremented p->tick.
6692 So set p->update_tick again so that an error in the sentinel will
6693 not cause this code to be run again. */
6694 p->update_tick = p->tick;
6695 /* Now output the message suitably. */
6696 exec_sentinel (proc, msg);
6698 } /* end for */
6700 update_mode_lines = 24; /* In case buffers use %s in mode-line-format. */
6701 return got_some_output;
6704 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6705 Sinternal_default_process_sentinel, 2, 2, 0,
6706 doc: /* Function used as default sentinel for processes.
6707 This inserts a status message into the process's buffer, if there is one. */)
6708 (Lisp_Object proc, Lisp_Object msg)
6710 Lisp_Object buffer, symbol;
6711 struct Lisp_Process *p;
6712 CHECK_PROCESS (proc);
6713 p = XPROCESS (proc);
6714 buffer = p->buffer;
6715 symbol = p->status;
6716 if (CONSP (symbol))
6717 symbol = XCAR (symbol);
6719 if (!EQ (symbol, Qrun) && !NILP (buffer))
6721 Lisp_Object tem;
6722 struct buffer *old = current_buffer;
6723 ptrdiff_t opoint, opoint_byte;
6724 ptrdiff_t before, before_byte;
6726 /* Avoid error if buffer is deleted
6727 (probably that's why the process is dead, too). */
6728 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6729 return Qnil;
6730 Fset_buffer (buffer);
6732 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6733 msg = (code_convert_string_norecord
6734 (msg, Vlocale_coding_system, 1));
6736 opoint = PT;
6737 opoint_byte = PT_BYTE;
6738 /* Insert new output into buffer
6739 at the current end-of-output marker,
6740 thus preserving logical ordering of input and output. */
6741 if (XMARKER (p->mark)->buffer)
6742 Fgoto_char (p->mark);
6743 else
6744 SET_PT_BOTH (ZV, ZV_BYTE);
6746 before = PT;
6747 before_byte = PT_BYTE;
6749 tem = BVAR (current_buffer, read_only);
6750 bset_read_only (current_buffer, Qnil);
6751 insert_string ("\nProcess ");
6752 { /* FIXME: temporary kludge. */
6753 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6754 insert_string (" ");
6755 Finsert (1, &msg);
6756 bset_read_only (current_buffer, tem);
6757 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6759 if (opoint >= before)
6760 SET_PT_BOTH (opoint + (PT - before),
6761 opoint_byte + (PT_BYTE - before_byte));
6762 else
6763 SET_PT_BOTH (opoint, opoint_byte);
6765 set_buffer_internal (old);
6767 return Qnil;
6771 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6772 Sset_process_coding_system, 1, 3, 0,
6773 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6774 DECODING will be used to decode subprocess output and ENCODING to
6775 encode subprocess input. */)
6776 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6778 register struct Lisp_Process *p;
6780 CHECK_PROCESS (process);
6781 p = XPROCESS (process);
6782 if (p->infd < 0)
6783 error ("Input file descriptor of %s closed", SDATA (p->name));
6784 if (p->outfd < 0)
6785 error ("Output file descriptor of %s closed", SDATA (p->name));
6786 Fcheck_coding_system (decoding);
6787 Fcheck_coding_system (encoding);
6788 encoding = coding_inherit_eol_type (encoding, Qnil);
6789 pset_decode_coding_system (p, decoding);
6790 pset_encode_coding_system (p, encoding);
6791 setup_process_coding_systems (process);
6793 return Qnil;
6796 DEFUN ("process-coding-system",
6797 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6798 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6799 (register Lisp_Object process)
6801 CHECK_PROCESS (process);
6802 return Fcons (XPROCESS (process)->decode_coding_system,
6803 XPROCESS (process)->encode_coding_system);
6806 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6807 Sset_process_filter_multibyte, 2, 2, 0,
6808 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6809 If FLAG is non-nil, the filter is given multibyte strings.
6810 If FLAG is nil, the filter is given unibyte strings. In this case,
6811 all character code conversion except for end-of-line conversion is
6812 suppressed. */)
6813 (Lisp_Object process, Lisp_Object flag)
6815 register struct Lisp_Process *p;
6817 CHECK_PROCESS (process);
6818 p = XPROCESS (process);
6819 if (NILP (flag))
6820 pset_decode_coding_system
6821 (p, raw_text_coding_system (p->decode_coding_system));
6822 setup_process_coding_systems (process);
6824 return Qnil;
6827 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6828 Sprocess_filter_multibyte_p, 1, 1, 0,
6829 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6830 (Lisp_Object process)
6832 register struct Lisp_Process *p;
6833 struct coding_system *coding;
6835 CHECK_PROCESS (process);
6836 p = XPROCESS (process);
6837 if (p->infd < 0)
6838 return Qnil;
6839 coding = proc_decode_coding_system[p->infd];
6840 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6846 # ifdef HAVE_GPM
6848 void
6849 add_gpm_wait_descriptor (int desc)
6851 add_keyboard_wait_descriptor (desc);
6854 void
6855 delete_gpm_wait_descriptor (int desc)
6857 delete_keyboard_wait_descriptor (desc);
6860 # endif
6862 # ifdef USABLE_SIGIO
6864 /* Return true if *MASK has a bit set
6865 that corresponds to one of the keyboard input descriptors. */
6867 static bool
6868 keyboard_bit_set (fd_set *mask)
6870 int fd;
6872 for (fd = 0; fd <= max_input_desc; fd++)
6873 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6874 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6875 return 1;
6877 return 0;
6879 # endif
6881 #else /* not subprocesses */
6883 /* Defined in msdos.c. */
6884 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6885 struct timespec *, void *);
6887 /* Implementation of wait_reading_process_output, assuming that there
6888 are no subprocesses. Used only by the MS-DOS build.
6890 Wait for timeout to elapse and/or keyboard input to be available.
6892 TIME_LIMIT is:
6893 timeout in seconds
6894 If negative, gobble data immediately available but don't wait for any.
6896 NSECS is:
6897 an additional duration to wait, measured in nanoseconds
6898 If TIME_LIMIT is zero, then:
6899 If NSECS == 0, there is no limit.
6900 If NSECS > 0, the timeout consists of NSECS only.
6901 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6903 READ_KBD is:
6904 0 to ignore keyboard input, or
6905 1 to return when input is available, or
6906 -1 means caller will actually read the input, so don't throw to
6907 the quit handler.
6909 see full version for other parameters. We know that wait_proc will
6910 always be NULL, since `subprocesses' isn't defined.
6912 DO_DISPLAY means redisplay should be done to show subprocess
6913 output that arrives.
6915 Return -1 signifying we got no output and did not try. */
6918 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6919 bool do_display,
6920 Lisp_Object wait_for_cell,
6921 struct Lisp_Process *wait_proc, int just_wait_proc)
6923 register int nfds;
6924 struct timespec end_time, timeout;
6925 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
6927 if (TYPE_MAXIMUM (time_t) < time_limit)
6928 time_limit = TYPE_MAXIMUM (time_t);
6930 if (time_limit < 0 || nsecs < 0)
6931 wait = MINIMUM;
6932 else if (time_limit > 0 || nsecs > 0)
6934 wait = TIMEOUT;
6935 end_time = timespec_add (current_timespec (),
6936 make_timespec (time_limit, nsecs));
6938 else
6939 wait = INFINITY;
6941 /* Turn off periodic alarms (in case they are in use)
6942 and then turn off any other atimers,
6943 because the select emulator uses alarms. */
6944 stop_polling ();
6945 turn_on_atimers (0);
6947 while (1)
6949 bool timeout_reduced_for_timers = false;
6950 fd_set waitchannels;
6951 int xerrno;
6953 /* If calling from keyboard input, do not quit
6954 since we want to return C-g as an input character.
6955 Otherwise, do pending quit if requested. */
6956 if (read_kbd >= 0)
6957 QUIT;
6959 /* Exit now if the cell we're waiting for became non-nil. */
6960 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6961 break;
6963 /* Compute time from now till when time limit is up. */
6964 /* Exit if already run out. */
6965 if (wait == TIMEOUT)
6967 struct timespec now = current_timespec ();
6968 if (timespec_cmp (end_time, now) <= 0)
6969 break;
6970 timeout = timespec_sub (end_time, now);
6972 else
6973 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
6975 /* If our caller will not immediately handle keyboard events,
6976 run timer events directly.
6977 (Callers that will immediately read keyboard events
6978 call timer_delay on their own.) */
6979 if (NILP (wait_for_cell))
6981 struct timespec timer_delay;
6985 unsigned old_timers_run = timers_run;
6986 timer_delay = timer_check ();
6987 if (timers_run != old_timers_run && do_display)
6988 /* We must retry, since a timer may have requeued itself
6989 and that could alter the time delay. */
6990 redisplay_preserve_echo_area (14);
6991 else
6992 break;
6994 while (!detect_input_pending ());
6996 /* If there is unread keyboard input, also return. */
6997 if (read_kbd != 0
6998 && requeued_events_pending_p ())
6999 break;
7001 if (timespec_valid_p (timer_delay))
7003 if (timespec_cmp (timer_delay, timeout) < 0)
7005 timeout = timer_delay;
7006 timeout_reduced_for_timers = true;
7011 /* Cause C-g and alarm signals to take immediate action,
7012 and cause input available signals to zero out timeout. */
7013 if (read_kbd < 0)
7014 set_waiting_for_input (&timeout);
7016 /* If a frame has been newly mapped and needs updating,
7017 reprocess its display stuff. */
7018 if (frame_garbaged && do_display)
7020 clear_waiting_for_input ();
7021 redisplay_preserve_echo_area (15);
7022 if (read_kbd < 0)
7023 set_waiting_for_input (&timeout);
7026 /* Wait till there is something to do. */
7027 FD_ZERO (&waitchannels);
7028 if (read_kbd && detect_input_pending ())
7029 nfds = 0;
7030 else
7032 if (read_kbd || !NILP (wait_for_cell))
7033 FD_SET (0, &waitchannels);
7034 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7037 xerrno = errno;
7039 /* Make C-g and alarm signals set flags again. */
7040 clear_waiting_for_input ();
7042 /* If we woke up due to SIGWINCH, actually change size now. */
7043 do_pending_window_change (0);
7045 if (wait < INFINITY && nfds == 0 && ! timeout_reduced_for_timers)
7046 /* We waited the full specified time, so return now. */
7047 break;
7049 if (nfds == -1)
7051 /* If the system call was interrupted, then go around the
7052 loop again. */
7053 if (xerrno == EINTR)
7054 FD_ZERO (&waitchannels);
7055 else
7056 report_file_errno ("Failed select", Qnil, xerrno);
7059 /* Check for keyboard input. */
7061 if (read_kbd
7062 && detect_input_pending_run_timers (do_display))
7064 swallow_events (do_display);
7065 if (detect_input_pending_run_timers (do_display))
7066 break;
7069 /* If there is unread keyboard input, also return. */
7070 if (read_kbd
7071 && requeued_events_pending_p ())
7072 break;
7074 /* If wait_for_cell. check for keyboard input
7075 but don't run any timers.
7076 ??? (It seems wrong to me to check for keyboard
7077 input at all when wait_for_cell, but the code
7078 has been this way since July 1994.
7079 Try changing this after version 19.31.) */
7080 if (! NILP (wait_for_cell)
7081 && detect_input_pending ())
7083 swallow_events (do_display);
7084 if (detect_input_pending ())
7085 break;
7088 /* Exit now if the cell we're waiting for became non-nil. */
7089 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7090 break;
7093 start_polling ();
7095 return -1;
7098 #endif /* not subprocesses */
7100 /* The following functions are needed even if async subprocesses are
7101 not supported. Some of them are no-op stubs in that case. */
7103 #ifdef HAVE_TIMERFD
7105 /* Add FD, which is a descriptor returned by timerfd_create,
7106 to the set of non-keyboard input descriptors. */
7108 void
7109 add_timer_wait_descriptor (int fd)
7111 FD_SET (fd, &input_wait_mask);
7112 FD_SET (fd, &non_keyboard_wait_mask);
7113 FD_SET (fd, &non_process_wait_mask);
7114 fd_callback_info[fd].func = timerfd_callback;
7115 fd_callback_info[fd].data = NULL;
7116 fd_callback_info[fd].condition |= FOR_READ;
7117 if (fd > max_input_desc)
7118 max_input_desc = fd;
7121 #endif /* HAVE_TIMERFD */
7123 /* Add DESC to the set of keyboard input descriptors. */
7125 void
7126 add_keyboard_wait_descriptor (int desc)
7128 #ifdef subprocesses /* Actually means "not MSDOS". */
7129 FD_SET (desc, &input_wait_mask);
7130 FD_SET (desc, &non_process_wait_mask);
7131 if (desc > max_input_desc)
7132 max_input_desc = desc;
7133 #endif
7136 /* From now on, do not expect DESC to give keyboard input. */
7138 void
7139 delete_keyboard_wait_descriptor (int desc)
7141 #ifdef subprocesses
7142 FD_CLR (desc, &input_wait_mask);
7143 FD_CLR (desc, &non_process_wait_mask);
7144 delete_input_desc (desc);
7145 #endif
7148 /* Setup coding systems of PROCESS. */
7150 void
7151 setup_process_coding_systems (Lisp_Object process)
7153 #ifdef subprocesses
7154 struct Lisp_Process *p = XPROCESS (process);
7155 int inch = p->infd;
7156 int outch = p->outfd;
7157 Lisp_Object coding_system;
7159 if (inch < 0 || outch < 0)
7160 return;
7162 if (!proc_decode_coding_system[inch])
7163 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7164 coding_system = p->decode_coding_system;
7165 if (EQ (p->filter, Qinternal_default_process_filter)
7166 && BUFFERP (p->buffer))
7168 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7169 coding_system = raw_text_coding_system (coding_system);
7171 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7173 if (!proc_encode_coding_system[outch])
7174 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7175 setup_coding_system (p->encode_coding_system,
7176 proc_encode_coding_system[outch]);
7177 #endif
7180 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7181 doc: /* Return the (or a) process associated with BUFFER.
7182 BUFFER may be a buffer or the name of one. */)
7183 (register Lisp_Object buffer)
7185 #ifdef subprocesses
7186 register Lisp_Object buf, tail, proc;
7188 if (NILP (buffer)) return Qnil;
7189 buf = Fget_buffer (buffer);
7190 if (NILP (buf)) return Qnil;
7192 FOR_EACH_PROCESS (tail, proc)
7193 if (EQ (XPROCESS (proc)->buffer, buf))
7194 return proc;
7195 #endif /* subprocesses */
7196 return Qnil;
7199 DEFUN ("process-inherit-coding-system-flag",
7200 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7201 1, 1, 0,
7202 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7203 If this flag is t, `buffer-file-coding-system' of the buffer
7204 associated with PROCESS will inherit the coding system used to decode
7205 the process output. */)
7206 (register Lisp_Object process)
7208 #ifdef subprocesses
7209 CHECK_PROCESS (process);
7210 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7211 #else
7212 /* Ignore the argument and return the value of
7213 inherit-process-coding-system. */
7214 return inherit_process_coding_system ? Qt : Qnil;
7215 #endif
7218 /* Kill all processes associated with `buffer'.
7219 If `buffer' is nil, kill all processes. */
7221 void
7222 kill_buffer_processes (Lisp_Object buffer)
7224 #ifdef subprocesses
7225 Lisp_Object tail, proc;
7227 FOR_EACH_PROCESS (tail, proc)
7228 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7230 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7231 Fdelete_process (proc);
7232 else if (XPROCESS (proc)->infd >= 0)
7233 process_send_signal (proc, SIGHUP, Qnil, 1);
7235 #else /* subprocesses */
7236 /* Since we have no subprocesses, this does nothing. */
7237 #endif /* subprocesses */
7240 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7241 Swaiting_for_user_input_p, 0, 0, 0,
7242 doc: /* Return non-nil if Emacs is waiting for input from the user.
7243 This is intended for use by asynchronous process output filters and sentinels. */)
7244 (void)
7246 #ifdef subprocesses
7247 return (waiting_for_user_input_p ? Qt : Qnil);
7248 #else
7249 return Qnil;
7250 #endif
7253 /* Stop reading input from keyboard sources. */
7255 void
7256 hold_keyboard_input (void)
7258 kbd_is_on_hold = 1;
7261 /* Resume reading input from keyboard sources. */
7263 void
7264 unhold_keyboard_input (void)
7266 kbd_is_on_hold = 0;
7269 /* Return true if keyboard input is on hold, zero otherwise. */
7271 bool
7272 kbd_on_hold_p (void)
7274 return kbd_is_on_hold;
7278 /* Enumeration of and access to system processes a-la ps(1). */
7280 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7281 0, 0, 0,
7282 doc: /* Return a list of numerical process IDs of all running processes.
7283 If this functionality is unsupported, return nil.
7285 See `process-attributes' for getting attributes of a process given its ID. */)
7286 (void)
7288 return list_system_processes ();
7291 DEFUN ("process-attributes", Fprocess_attributes,
7292 Sprocess_attributes, 1, 1, 0,
7293 doc: /* Return attributes of the process given by its PID, a number.
7295 Value is an alist where each element is a cons cell of the form
7297 \(KEY . VALUE)
7299 If this functionality is unsupported, the value is nil.
7301 See `list-system-processes' for getting a list of all process IDs.
7303 The KEYs of the attributes that this function may return are listed
7304 below, together with the type of the associated VALUE (in parentheses).
7305 Not all platforms support all of these attributes; unsupported
7306 attributes will not appear in the returned alist.
7307 Unless explicitly indicated otherwise, numbers can have either
7308 integer or floating point values.
7310 euid -- Effective user User ID of the process (number)
7311 user -- User name corresponding to euid (string)
7312 egid -- Effective user Group ID of the process (number)
7313 group -- Group name corresponding to egid (string)
7314 comm -- Command name (executable name only) (string)
7315 state -- Process state code, such as "S", "R", or "T" (string)
7316 ppid -- Parent process ID (number)
7317 pgrp -- Process group ID (number)
7318 sess -- Session ID, i.e. process ID of session leader (number)
7319 ttname -- Controlling tty name (string)
7320 tpgid -- ID of foreground process group on the process's tty (number)
7321 minflt -- number of minor page faults (number)
7322 majflt -- number of major page faults (number)
7323 cminflt -- cumulative number of minor page faults (number)
7324 cmajflt -- cumulative number of major page faults (number)
7325 utime -- user time used by the process, in (current-time) format,
7326 which is a list of integers (HIGH LOW USEC PSEC)
7327 stime -- system time used by the process (current-time)
7328 time -- sum of utime and stime (current-time)
7329 cutime -- user time used by the process and its children (current-time)
7330 cstime -- system time used by the process and its children (current-time)
7331 ctime -- sum of cutime and cstime (current-time)
7332 pri -- priority of the process (number)
7333 nice -- nice value of the process (number)
7334 thcount -- process thread count (number)
7335 start -- time the process started (current-time)
7336 vsize -- virtual memory size of the process in KB's (number)
7337 rss -- resident set size of the process in KB's (number)
7338 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7339 pcpu -- percents of CPU time used by the process (floating-point number)
7340 pmem -- percents of total physical memory used by process's resident set
7341 (floating-point number)
7342 args -- command line which invoked the process (string). */)
7343 ( Lisp_Object pid)
7345 return system_process_attributes (pid);
7348 #ifdef subprocesses
7349 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7350 Invoke this after init_process_emacs, and after glib and/or GNUstep
7351 futz with the SIGCHLD handler, but before Emacs forks any children.
7352 This function's caller should block SIGCHLD. */
7354 void
7355 catch_child_signal (void)
7357 struct sigaction action, old_action;
7358 sigset_t oldset;
7359 emacs_sigaction_init (&action, deliver_child_signal);
7360 block_child_signal (&oldset);
7361 sigaction (SIGCHLD, &action, &old_action);
7362 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7363 || ! (old_action.sa_flags & SA_SIGINFO));
7365 if (old_action.sa_handler != deliver_child_signal)
7366 lib_child_handler
7367 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7368 ? dummy_handler
7369 : old_action.sa_handler);
7370 unblock_child_signal (&oldset);
7372 #endif /* subprocesses */
7375 /* This is not called "init_process" because that is the name of a
7376 Mach system call, so it would cause problems on Darwin systems. */
7377 void
7378 init_process_emacs (void)
7380 #ifdef subprocesses
7381 register int i;
7383 inhibit_sentinels = 0;
7385 #ifndef CANNOT_DUMP
7386 if (! noninteractive || initialized)
7387 #endif
7389 #if defined HAVE_GLIB && !defined WINDOWSNT
7390 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7391 this should always fail, but is enough to initialize glib's
7392 private SIGCHLD handler, allowing catch_child_signal to copy
7393 it into lib_child_handler. */
7394 g_source_unref (g_child_watch_source_new (getpid ()));
7395 #endif
7396 catch_child_signal ();
7399 FD_ZERO (&input_wait_mask);
7400 FD_ZERO (&non_keyboard_wait_mask);
7401 FD_ZERO (&non_process_wait_mask);
7402 FD_ZERO (&write_mask);
7403 max_process_desc = max_input_desc = -1;
7404 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7406 #ifdef NON_BLOCKING_CONNECT
7407 FD_ZERO (&connect_wait_mask);
7408 num_pending_connects = 0;
7409 #endif
7411 process_output_delay_count = 0;
7412 process_output_skip = 0;
7414 /* Don't do this, it caused infinite select loops. The display
7415 method should call add_keyboard_wait_descriptor on stdin if it
7416 needs that. */
7417 #if 0
7418 FD_SET (0, &input_wait_mask);
7419 #endif
7421 Vprocess_alist = Qnil;
7422 deleted_pid_list = Qnil;
7423 for (i = 0; i < FD_SETSIZE; i++)
7425 chan_process[i] = Qnil;
7426 proc_buffered_char[i] = -1;
7428 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7429 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7430 #ifdef DATAGRAM_SOCKETS
7431 memset (datagram_address, 0, sizeof datagram_address);
7432 #endif
7434 #if defined (DARWIN_OS)
7435 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7436 processes. As such, we only change the default value. */
7437 if (initialized)
7439 char const *release = (STRINGP (Voperating_system_release)
7440 ? SSDATA (Voperating_system_release)
7441 : 0);
7442 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7443 Vprocess_connection_type = Qnil;
7446 #endif
7447 #endif /* subprocesses */
7448 kbd_is_on_hold = 0;
7451 void
7452 syms_of_process (void)
7454 #ifdef subprocesses
7456 DEFSYM (Qprocessp, "processp");
7457 DEFSYM (Qrun, "run");
7458 DEFSYM (Qstop, "stop");
7459 DEFSYM (Qsignal, "signal");
7461 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7462 here again. */
7464 DEFSYM (Qopen, "open");
7465 DEFSYM (Qclosed, "closed");
7466 DEFSYM (Qconnect, "connect");
7467 DEFSYM (Qfailed, "failed");
7468 DEFSYM (Qlisten, "listen");
7469 DEFSYM (Qlocal, "local");
7470 DEFSYM (Qipv4, "ipv4");
7471 #ifdef AF_INET6
7472 DEFSYM (Qipv6, "ipv6");
7473 #endif
7474 DEFSYM (Qdatagram, "datagram");
7475 DEFSYM (Qseqpacket, "seqpacket");
7477 DEFSYM (QCport, ":port");
7478 DEFSYM (QCspeed, ":speed");
7479 DEFSYM (QCprocess, ":process");
7481 DEFSYM (QCbytesize, ":bytesize");
7482 DEFSYM (QCstopbits, ":stopbits");
7483 DEFSYM (QCparity, ":parity");
7484 DEFSYM (Qodd, "odd");
7485 DEFSYM (Qeven, "even");
7486 DEFSYM (QCflowcontrol, ":flowcontrol");
7487 DEFSYM (Qhw, "hw");
7488 DEFSYM (Qsw, "sw");
7489 DEFSYM (QCsummary, ":summary");
7491 DEFSYM (Qreal, "real");
7492 DEFSYM (Qnetwork, "network");
7493 DEFSYM (Qserial, "serial");
7494 DEFSYM (Qpipe, "pipe");
7495 DEFSYM (QCbuffer, ":buffer");
7496 DEFSYM (QChost, ":host");
7497 DEFSYM (QCservice, ":service");
7498 DEFSYM (QClocal, ":local");
7499 DEFSYM (QCremote, ":remote");
7500 DEFSYM (QCcoding, ":coding");
7501 DEFSYM (QCserver, ":server");
7502 DEFSYM (QCnowait, ":nowait");
7503 DEFSYM (QCsentinel, ":sentinel");
7504 DEFSYM (QClog, ":log");
7505 DEFSYM (QCnoquery, ":noquery");
7506 DEFSYM (QCstop, ":stop");
7507 DEFSYM (QCplist, ":plist");
7508 DEFSYM (QCcommand, ":command");
7509 DEFSYM (QCconnection_type, ":connection-type");
7510 DEFSYM (QCstderr, ":stderr");
7511 DEFSYM (Qpty, "pty");
7512 DEFSYM (Qpipe, "pipe");
7514 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7516 staticpro (&Vprocess_alist);
7517 staticpro (&deleted_pid_list);
7519 #endif /* subprocesses */
7521 DEFSYM (QCname, ":name");
7522 DEFSYM (QCtype, ":type");
7524 DEFSYM (Qeuid, "euid");
7525 DEFSYM (Qegid, "egid");
7526 DEFSYM (Quser, "user");
7527 DEFSYM (Qgroup, "group");
7528 DEFSYM (Qcomm, "comm");
7529 DEFSYM (Qstate, "state");
7530 DEFSYM (Qppid, "ppid");
7531 DEFSYM (Qpgrp, "pgrp");
7532 DEFSYM (Qsess, "sess");
7533 DEFSYM (Qttname, "ttname");
7534 DEFSYM (Qtpgid, "tpgid");
7535 DEFSYM (Qminflt, "minflt");
7536 DEFSYM (Qmajflt, "majflt");
7537 DEFSYM (Qcminflt, "cminflt");
7538 DEFSYM (Qcmajflt, "cmajflt");
7539 DEFSYM (Qutime, "utime");
7540 DEFSYM (Qstime, "stime");
7541 DEFSYM (Qtime, "time");
7542 DEFSYM (Qcutime, "cutime");
7543 DEFSYM (Qcstime, "cstime");
7544 DEFSYM (Qctime, "ctime");
7545 #ifdef subprocesses
7546 DEFSYM (Qinternal_default_process_sentinel,
7547 "internal-default-process-sentinel");
7548 DEFSYM (Qinternal_default_process_filter,
7549 "internal-default-process-filter");
7550 #endif
7551 DEFSYM (Qpri, "pri");
7552 DEFSYM (Qnice, "nice");
7553 DEFSYM (Qthcount, "thcount");
7554 DEFSYM (Qstart, "start");
7555 DEFSYM (Qvsize, "vsize");
7556 DEFSYM (Qrss, "rss");
7557 DEFSYM (Qetime, "etime");
7558 DEFSYM (Qpcpu, "pcpu");
7559 DEFSYM (Qpmem, "pmem");
7560 DEFSYM (Qargs, "args");
7562 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7563 doc: /* Non-nil means delete processes immediately when they exit.
7564 A value of nil means don't delete them until `list-processes' is run. */);
7566 delete_exited_processes = 1;
7568 #ifdef subprocesses
7569 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7570 doc: /* Control type of device used to communicate with subprocesses.
7571 Values are nil to use a pipe, or t or `pty' to use a pty.
7572 The value has no effect if the system has no ptys or if all ptys are busy:
7573 then a pipe is used in any case.
7574 The value takes effect when `start-process' is called. */);
7575 Vprocess_connection_type = Qt;
7577 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7578 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7579 On some systems, when Emacs reads the output from a subprocess, the output data
7580 is read in very small blocks, potentially resulting in very poor performance.
7581 This behavior can be remedied to some extent by setting this variable to a
7582 non-nil value, as it will automatically delay reading from such processes, to
7583 allow them to produce more output before Emacs tries to read it.
7584 If the value is t, the delay is reset after each write to the process; any other
7585 non-nil value means that the delay is not reset on write.
7586 The variable takes effect when `start-process' is called. */);
7587 Vprocess_adaptive_read_buffering = Qt;
7589 defsubr (&Sprocessp);
7590 defsubr (&Sget_process);
7591 defsubr (&Sdelete_process);
7592 defsubr (&Sprocess_status);
7593 defsubr (&Sprocess_exit_status);
7594 defsubr (&Sprocess_id);
7595 defsubr (&Sprocess_name);
7596 defsubr (&Sprocess_tty_name);
7597 defsubr (&Sprocess_command);
7598 defsubr (&Sset_process_buffer);
7599 defsubr (&Sprocess_buffer);
7600 defsubr (&Sprocess_mark);
7601 defsubr (&Sset_process_filter);
7602 defsubr (&Sprocess_filter);
7603 defsubr (&Sset_process_sentinel);
7604 defsubr (&Sprocess_sentinel);
7605 defsubr (&Sset_process_window_size);
7606 defsubr (&Sset_process_inherit_coding_system_flag);
7607 defsubr (&Sset_process_query_on_exit_flag);
7608 defsubr (&Sprocess_query_on_exit_flag);
7609 defsubr (&Sprocess_contact);
7610 defsubr (&Sprocess_plist);
7611 defsubr (&Sset_process_plist);
7612 defsubr (&Sprocess_list);
7613 defsubr (&Smake_process);
7614 defsubr (&Smake_pipe_process);
7615 defsubr (&Sserial_process_configure);
7616 defsubr (&Smake_serial_process);
7617 defsubr (&Sset_network_process_option);
7618 defsubr (&Smake_network_process);
7619 defsubr (&Sformat_network_address);
7620 defsubr (&Snetwork_interface_list);
7621 defsubr (&Snetwork_interface_info);
7622 #ifdef DATAGRAM_SOCKETS
7623 defsubr (&Sprocess_datagram_address);
7624 defsubr (&Sset_process_datagram_address);
7625 #endif
7626 defsubr (&Saccept_process_output);
7627 defsubr (&Sprocess_send_region);
7628 defsubr (&Sprocess_send_string);
7629 defsubr (&Sinterrupt_process);
7630 defsubr (&Skill_process);
7631 defsubr (&Squit_process);
7632 defsubr (&Sstop_process);
7633 defsubr (&Scontinue_process);
7634 defsubr (&Sprocess_running_child_p);
7635 defsubr (&Sprocess_send_eof);
7636 defsubr (&Ssignal_process);
7637 defsubr (&Swaiting_for_user_input_p);
7638 defsubr (&Sprocess_type);
7639 defsubr (&Sinternal_default_process_sentinel);
7640 defsubr (&Sinternal_default_process_filter);
7641 defsubr (&Sset_process_coding_system);
7642 defsubr (&Sprocess_coding_system);
7643 defsubr (&Sset_process_filter_multibyte);
7644 defsubr (&Sprocess_filter_multibyte_p);
7646 #endif /* subprocesses */
7648 defsubr (&Sget_buffer_process);
7649 defsubr (&Sprocess_inherit_coding_system_flag);
7650 defsubr (&Slist_system_processes);
7651 defsubr (&Sprocess_attributes);
7654 Lisp_Object subfeatures = Qnil;
7655 const struct socket_options *sopt;
7657 #define ADD_SUBFEATURE(key, val) \
7658 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7660 #ifdef NON_BLOCKING_CONNECT
7661 ADD_SUBFEATURE (QCnowait, Qt);
7662 #endif
7663 #ifdef DATAGRAM_SOCKETS
7664 ADD_SUBFEATURE (QCtype, Qdatagram);
7665 #endif
7666 #ifdef HAVE_SEQPACKET
7667 ADD_SUBFEATURE (QCtype, Qseqpacket);
7668 #endif
7669 #ifdef HAVE_LOCAL_SOCKETS
7670 ADD_SUBFEATURE (QCfamily, Qlocal);
7671 #endif
7672 ADD_SUBFEATURE (QCfamily, Qipv4);
7673 #ifdef AF_INET6
7674 ADD_SUBFEATURE (QCfamily, Qipv6);
7675 #endif
7676 #ifdef HAVE_GETSOCKNAME
7677 ADD_SUBFEATURE (QCservice, Qt);
7678 #endif
7679 ADD_SUBFEATURE (QCserver, Qt);
7681 for (sopt = socket_options; sopt->name; sopt++)
7682 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7684 Fprovide (intern_c_string ("make-network-process"), subfeatures);