Docstring fixes re quotes in C code
[emacs.git] / src / process.c
blob1ab837809148a1d5144f14635f08fcbaf9948553
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 if (! wait_proc)
4864 /* We're not waiting on a specific process, so loop
4865 through all the channels and check for data.
4866 This is a workaround needed for some versions of
4867 the gnutls library -- 2.12.14 has been confirmed
4868 to need it. See
4869 http://comments.gmane.org/gmane.emacs.devel/145074 */
4870 for (channel = 0; channel < FD_SETSIZE; ++channel)
4871 if (! NILP (chan_process[channel]))
4873 struct Lisp_Process *p =
4874 XPROCESS (chan_process[channel]);
4875 if (p && p->gnutls_p && p->gnutls_state
4876 && ((emacs_gnutls_record_check_pending
4877 (p->gnutls_state))
4878 > 0))
4880 nfds++;
4881 eassert (p->infd == channel);
4882 FD_SET (p->infd, &Available);
4886 else
4888 /* Check this specific channel. */
4889 if (wait_proc->gnutls_p /* Check for valid process. */
4890 && wait_proc->gnutls_state
4891 /* Do we have pending data? */
4892 && ((emacs_gnutls_record_check_pending
4893 (wait_proc->gnutls_state))
4894 > 0))
4896 nfds = 1;
4897 eassert (0 <= wait_proc->infd);
4898 /* Set to Available. */
4899 FD_SET (wait_proc->infd, &Available);
4903 #endif
4906 xerrno = errno;
4908 /* Make C-g and alarm signals set flags again. */
4909 clear_waiting_for_input ();
4911 /* If we woke up due to SIGWINCH, actually change size now. */
4912 do_pending_window_change (0);
4914 if (nfds == 0)
4916 /* Exit the main loop if we've passed the requested timeout,
4917 or aren't skipping processes and got some output and
4918 haven't lowered our timeout due to timers or SIGIO and
4919 have waited a long amount of time due to repeated
4920 timers. */
4921 if (wait < TIMEOUT)
4922 break;
4923 struct timespec cmp_time
4924 = (wait == TIMEOUT
4925 ? end_time
4926 : (!process_skipped && got_some_output > 0
4927 && (timeout.tv_sec > 0 || timeout.tv_nsec > 0))
4928 ? got_output_end_time
4929 : invalid_timespec ());
4930 if (timespec_valid_p (cmp_time))
4932 now = current_timespec ();
4933 if (timespec_cmp (cmp_time, now) <= 0)
4934 break;
4938 if (nfds < 0)
4940 if (xerrno == EINTR)
4941 no_avail = 1;
4942 else if (xerrno == EBADF)
4943 emacs_abort ();
4944 else
4945 report_file_errno ("Failed select", Qnil, xerrno);
4948 /* Check for keyboard input. */
4949 /* If there is any, return immediately
4950 to give it higher priority than subprocesses. */
4952 if (read_kbd != 0)
4954 unsigned old_timers_run = timers_run;
4955 struct buffer *old_buffer = current_buffer;
4956 Lisp_Object old_window = selected_window;
4957 bool leave = false;
4959 if (detect_input_pending_run_timers (do_display))
4961 swallow_events (do_display);
4962 if (detect_input_pending_run_timers (do_display))
4963 leave = true;
4966 /* If a timer has run, this might have changed buffers
4967 an alike. Make read_key_sequence aware of that. */
4968 if (timers_run != old_timers_run
4969 && waiting_for_user_input_p == -1
4970 && (old_buffer != current_buffer
4971 || !EQ (old_window, selected_window)))
4972 record_asynch_buffer_change ();
4974 if (leave)
4975 break;
4978 /* If there is unread keyboard input, also return. */
4979 if (read_kbd != 0
4980 && requeued_events_pending_p ())
4981 break;
4983 /* If we are not checking for keyboard input now,
4984 do process events (but don't run any timers).
4985 This is so that X events will be processed.
4986 Otherwise they may have to wait until polling takes place.
4987 That would causes delays in pasting selections, for example.
4989 (We used to do this only if wait_for_cell.) */
4990 if (read_kbd == 0 && detect_input_pending ())
4992 swallow_events (do_display);
4993 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4994 if (detect_input_pending ())
4995 break;
4996 #endif
4999 /* Exit now if the cell we're waiting for became non-nil. */
5000 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5001 break;
5003 #ifdef USABLE_SIGIO
5004 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5005 go read it. This can happen with X on BSD after logging out.
5006 In that case, there really is no input and no SIGIO,
5007 but select says there is input. */
5009 if (read_kbd && interrupt_input
5010 && keyboard_bit_set (&Available) && ! noninteractive)
5011 handle_input_available_signal (SIGIO);
5012 #endif
5014 /* If checking input just got us a size-change event from X,
5015 obey it now if we should. */
5016 if (read_kbd || ! NILP (wait_for_cell))
5017 do_pending_window_change (0);
5019 /* Check for data from a process. */
5020 if (no_avail || nfds == 0)
5021 continue;
5023 for (channel = 0; channel <= max_input_desc; ++channel)
5025 struct fd_callback_data *d = &fd_callback_info[channel];
5026 if (d->func
5027 && ((d->condition & FOR_READ
5028 && FD_ISSET (channel, &Available))
5029 || (d->condition & FOR_WRITE
5030 && FD_ISSET (channel, &write_mask))))
5031 d->func (channel, d->data);
5034 for (channel = 0; channel <= max_process_desc; channel++)
5036 if (FD_ISSET (channel, &Available)
5037 && FD_ISSET (channel, &non_keyboard_wait_mask)
5038 && !FD_ISSET (channel, &non_process_wait_mask))
5040 int nread;
5042 /* If waiting for this channel, arrange to return as
5043 soon as no more input to be processed. No more
5044 waiting. */
5045 proc = chan_process[channel];
5046 if (NILP (proc))
5047 continue;
5049 /* If this is a server stream socket, accept connection. */
5050 if (EQ (XPROCESS (proc)->status, Qlisten))
5052 server_accept_connection (proc, channel);
5053 continue;
5056 /* Read data from the process, starting with our
5057 buffered-ahead character if we have one. */
5059 nread = read_process_output (proc, channel);
5060 if ((!wait_proc || wait_proc == XPROCESS (proc))
5061 && got_some_output < nread)
5062 got_some_output = nread;
5063 if (nread > 0)
5065 /* Vacuum up any leftovers without waiting. */
5066 if (wait_proc == XPROCESS (proc))
5067 wait = MINIMUM;
5068 /* Since read_process_output can run a filter,
5069 which can call accept-process-output,
5070 don't try to read from any other processes
5071 before doing the select again. */
5072 FD_ZERO (&Available);
5074 if (do_display)
5075 redisplay_preserve_echo_area (12);
5077 #ifdef EWOULDBLOCK
5078 else if (nread == -1 && errno == EWOULDBLOCK)
5080 #endif
5081 else if (nread == -1 && errno == EAGAIN)
5083 #ifdef WINDOWSNT
5084 /* FIXME: Is this special case still needed? */
5085 /* Note that we cannot distinguish between no input
5086 available now and a closed pipe.
5087 With luck, a closed pipe will be accompanied by
5088 subprocess termination and SIGCHLD. */
5089 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5090 && !PIPECONN_P (proc))
5092 #endif
5093 #ifdef HAVE_PTYS
5094 /* On some OSs with ptys, when the process on one end of
5095 a pty exits, the other end gets an error reading with
5096 errno = EIO instead of getting an EOF (0 bytes read).
5097 Therefore, if we get an error reading and errno =
5098 EIO, just continue, because the child process has
5099 exited and should clean itself up soon (e.g. when we
5100 get a SIGCHLD). */
5101 else if (nread == -1 && errno == EIO)
5103 struct Lisp_Process *p = XPROCESS (proc);
5105 /* Clear the descriptor now, so we only raise the
5106 signal once. */
5107 FD_CLR (channel, &input_wait_mask);
5108 FD_CLR (channel, &non_keyboard_wait_mask);
5110 if (p->pid == -2)
5112 /* If the EIO occurs on a pty, the SIGCHLD handler's
5113 waitpid call will not find the process object to
5114 delete. Do it here. */
5115 p->tick = ++process_tick;
5116 pset_status (p, Qfailed);
5119 #endif /* HAVE_PTYS */
5120 /* If we can detect process termination, don't consider the
5121 process gone just because its pipe is closed. */
5122 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5123 && !PIPECONN_P (proc))
5125 else if (nread == 0 && PIPECONN_P (proc))
5127 /* Preserve status of processes already terminated. */
5128 XPROCESS (proc)->tick = ++process_tick;
5129 deactivate_process (proc);
5130 if (EQ (XPROCESS (proc)->status, Qrun))
5131 pset_status (XPROCESS (proc),
5132 list2 (Qexit, make_number (0)));
5134 else
5136 /* Preserve status of processes already terminated. */
5137 XPROCESS (proc)->tick = ++process_tick;
5138 deactivate_process (proc);
5139 if (XPROCESS (proc)->raw_status_new)
5140 update_status (XPROCESS (proc));
5141 if (EQ (XPROCESS (proc)->status, Qrun))
5142 pset_status (XPROCESS (proc),
5143 list2 (Qexit, make_number (256)));
5146 #ifdef NON_BLOCKING_CONNECT
5147 if (FD_ISSET (channel, &Writeok)
5148 && FD_ISSET (channel, &connect_wait_mask))
5150 struct Lisp_Process *p;
5152 FD_CLR (channel, &connect_wait_mask);
5153 FD_CLR (channel, &write_mask);
5154 if (--num_pending_connects < 0)
5155 emacs_abort ();
5157 proc = chan_process[channel];
5158 if (NILP (proc))
5159 continue;
5161 p = XPROCESS (proc);
5163 #ifdef GNU_LINUX
5164 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5165 So only use it on systems where it is known to work. */
5167 socklen_t xlen = sizeof (xerrno);
5168 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5169 xerrno = errno;
5171 #else
5173 struct sockaddr pname;
5174 socklen_t pnamelen = sizeof (pname);
5176 /* If connection failed, getpeername will fail. */
5177 xerrno = 0;
5178 if (getpeername (channel, &pname, &pnamelen) < 0)
5180 /* Obtain connect failure code through error slippage. */
5181 char dummy;
5182 xerrno = errno;
5183 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5184 xerrno = errno;
5187 #endif
5188 if (xerrno)
5190 p->tick = ++process_tick;
5191 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5192 deactivate_process (proc);
5194 else
5196 pset_status (p, Qrun);
5197 /* Execute the sentinel here. If we had relied on
5198 status_notify to do it later, it will read input
5199 from the process before calling the sentinel. */
5200 exec_sentinel (proc, build_string ("open\n"));
5201 if (0 <= p->infd && !EQ (p->filter, Qt)
5202 && !EQ (p->command, Qt))
5204 FD_SET (p->infd, &input_wait_mask);
5205 FD_SET (p->infd, &non_keyboard_wait_mask);
5209 #endif /* NON_BLOCKING_CONNECT */
5210 } /* End for each file descriptor. */
5211 } /* End while exit conditions not met. */
5213 unbind_to (count, Qnil);
5215 /* If calling from keyboard input, do not quit
5216 since we want to return C-g as an input character.
5217 Otherwise, do pending quit if requested. */
5218 if (read_kbd >= 0)
5220 /* Prevent input_pending from remaining set if we quit. */
5221 clear_input_pending ();
5222 QUIT;
5225 return got_some_output;
5228 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5230 static Lisp_Object
5231 read_process_output_call (Lisp_Object fun_and_args)
5233 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5236 static Lisp_Object
5237 read_process_output_error_handler (Lisp_Object error_val)
5239 cmd_error_internal (error_val, "error in process filter: ");
5240 Vinhibit_quit = Qt;
5241 update_echo_area ();
5242 Fsleep_for (make_number (2), Qnil);
5243 return Qt;
5246 static void
5247 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5248 ssize_t nbytes,
5249 struct coding_system *coding);
5251 /* Read pending output from the process channel,
5252 starting with our buffered-ahead character if we have one.
5253 Yield number of decoded characters read.
5255 This function reads at most 4096 characters.
5256 If you want to read all available subprocess output,
5257 you must call it repeatedly until it returns zero.
5259 The characters read are decoded according to PROC's coding-system
5260 for decoding. */
5262 static int
5263 read_process_output (Lisp_Object proc, int channel)
5265 ssize_t nbytes;
5266 struct Lisp_Process *p = XPROCESS (proc);
5267 struct coding_system *coding = proc_decode_coding_system[channel];
5268 int carryover = p->decoding_carryover;
5269 enum { readmax = 4096 };
5270 ptrdiff_t count = SPECPDL_INDEX ();
5271 Lisp_Object odeactivate;
5272 char chars[sizeof coding->carryover + readmax];
5274 if (carryover)
5275 /* See the comment above. */
5276 memcpy (chars, SDATA (p->decoding_buf), carryover);
5278 #ifdef DATAGRAM_SOCKETS
5279 /* We have a working select, so proc_buffered_char is always -1. */
5280 if (DATAGRAM_CHAN_P (channel))
5282 socklen_t len = datagram_address[channel].len;
5283 nbytes = recvfrom (channel, chars + carryover, readmax,
5284 0, datagram_address[channel].sa, &len);
5286 else
5287 #endif
5289 bool buffered = proc_buffered_char[channel] >= 0;
5290 if (buffered)
5292 chars[carryover] = proc_buffered_char[channel];
5293 proc_buffered_char[channel] = -1;
5295 #ifdef HAVE_GNUTLS
5296 if (p->gnutls_p && p->gnutls_state)
5297 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5298 readmax - buffered);
5299 else
5300 #endif
5301 nbytes = emacs_read (channel, chars + carryover + buffered,
5302 readmax - buffered);
5303 if (nbytes > 0 && p->adaptive_read_buffering)
5305 int delay = p->read_output_delay;
5306 if (nbytes < 256)
5308 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5310 if (delay == 0)
5311 process_output_delay_count++;
5312 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5315 else if (delay > 0 && nbytes == readmax - buffered)
5317 delay -= READ_OUTPUT_DELAY_INCREMENT;
5318 if (delay == 0)
5319 process_output_delay_count--;
5321 p->read_output_delay = delay;
5322 if (delay)
5324 p->read_output_skip = 1;
5325 process_output_skip = 1;
5328 nbytes += buffered;
5329 nbytes += buffered && nbytes <= 0;
5332 p->decoding_carryover = 0;
5334 /* At this point, NBYTES holds number of bytes just received
5335 (including the one in proc_buffered_char[channel]). */
5336 if (nbytes <= 0)
5338 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5339 return nbytes;
5340 coding->mode |= CODING_MODE_LAST_BLOCK;
5343 /* Now set NBYTES how many bytes we must decode. */
5344 nbytes += carryover;
5346 odeactivate = Vdeactivate_mark;
5347 /* There's no good reason to let process filters change the current
5348 buffer, and many callers of accept-process-output, sit-for, and
5349 friends don't expect current-buffer to be changed from under them. */
5350 record_unwind_current_buffer ();
5352 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5354 /* Handling the process output should not deactivate the mark. */
5355 Vdeactivate_mark = odeactivate;
5357 unbind_to (count, Qnil);
5358 return nbytes;
5361 static void
5362 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5363 ssize_t nbytes,
5364 struct coding_system *coding)
5366 Lisp_Object outstream = p->filter;
5367 Lisp_Object text;
5368 bool outer_running_asynch_code = running_asynch_code;
5369 int waiting = waiting_for_user_input_p;
5371 #if 0
5372 Lisp_Object obuffer, okeymap;
5373 XSETBUFFER (obuffer, current_buffer);
5374 okeymap = BVAR (current_buffer, keymap);
5375 #endif
5377 /* We inhibit quit here instead of just catching it so that
5378 hitting ^G when a filter happens to be running won't screw
5379 it up. */
5380 specbind (Qinhibit_quit, Qt);
5381 specbind (Qlast_nonmenu_event, Qt);
5383 /* In case we get recursively called,
5384 and we already saved the match data nonrecursively,
5385 save the same match data in safely recursive fashion. */
5386 if (outer_running_asynch_code)
5388 Lisp_Object tem;
5389 /* Don't clobber the CURRENT match data, either! */
5390 tem = Fmatch_data (Qnil, Qnil, Qnil);
5391 restore_search_regs ();
5392 record_unwind_save_match_data ();
5393 Fset_match_data (tem, Qt);
5396 /* For speed, if a search happens within this code,
5397 save the match data in a special nonrecursive fashion. */
5398 running_asynch_code = 1;
5400 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5401 text = coding->dst_object;
5402 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5403 /* A new coding system might be found. */
5404 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5406 pset_decode_coding_system (p, Vlast_coding_system_used);
5408 /* Don't call setup_coding_system for
5409 proc_decode_coding_system[channel] here. It is done in
5410 detect_coding called via decode_coding above. */
5412 /* If a coding system for encoding is not yet decided, we set
5413 it as the same as coding-system for decoding.
5415 But, before doing that we must check if
5416 proc_encode_coding_system[p->outfd] surely points to a
5417 valid memory because p->outfd will be changed once EOF is
5418 sent to the process. */
5419 if (NILP (p->encode_coding_system) && p->outfd >= 0
5420 && proc_encode_coding_system[p->outfd])
5422 pset_encode_coding_system
5423 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5424 setup_coding_system (p->encode_coding_system,
5425 proc_encode_coding_system[p->outfd]);
5429 if (coding->carryover_bytes > 0)
5431 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5432 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5433 memcpy (SDATA (p->decoding_buf), coding->carryover,
5434 coding->carryover_bytes);
5435 p->decoding_carryover = coding->carryover_bytes;
5437 if (SBYTES (text) > 0)
5438 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5439 sometimes it's simply wrong to wrap (e.g. when called from
5440 accept-process-output). */
5441 internal_condition_case_1 (read_process_output_call,
5442 list3 (outstream, make_lisp_proc (p), text),
5443 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5444 read_process_output_error_handler);
5446 /* If we saved the match data nonrecursively, restore it now. */
5447 restore_search_regs ();
5448 running_asynch_code = outer_running_asynch_code;
5450 /* Restore waiting_for_user_input_p as it was
5451 when we were called, in case the filter clobbered it. */
5452 waiting_for_user_input_p = waiting;
5454 #if 0 /* Call record_asynch_buffer_change unconditionally,
5455 because we might have changed minor modes or other things
5456 that affect key bindings. */
5457 if (! EQ (Fcurrent_buffer (), obuffer)
5458 || ! EQ (current_buffer->keymap, okeymap))
5459 #endif
5460 /* But do it only if the caller is actually going to read events.
5461 Otherwise there's no need to make him wake up, and it could
5462 cause trouble (for example it would make sit_for return). */
5463 if (waiting_for_user_input_p == -1)
5464 record_asynch_buffer_change ();
5467 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5468 Sinternal_default_process_filter, 2, 2, 0,
5469 doc: /* Function used as default process filter.
5470 This inserts the process's output into its buffer, if there is one.
5471 Otherwise it discards the output. */)
5472 (Lisp_Object proc, Lisp_Object text)
5474 struct Lisp_Process *p;
5475 ptrdiff_t opoint;
5477 CHECK_PROCESS (proc);
5478 p = XPROCESS (proc);
5479 CHECK_STRING (text);
5481 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5483 Lisp_Object old_read_only;
5484 ptrdiff_t old_begv, old_zv;
5485 ptrdiff_t old_begv_byte, old_zv_byte;
5486 ptrdiff_t before, before_byte;
5487 ptrdiff_t opoint_byte;
5488 struct buffer *b;
5490 Fset_buffer (p->buffer);
5491 opoint = PT;
5492 opoint_byte = PT_BYTE;
5493 old_read_only = BVAR (current_buffer, read_only);
5494 old_begv = BEGV;
5495 old_zv = ZV;
5496 old_begv_byte = BEGV_BYTE;
5497 old_zv_byte = ZV_BYTE;
5499 bset_read_only (current_buffer, Qnil);
5501 /* Insert new output into buffer at the current end-of-output
5502 marker, thus preserving logical ordering of input and output. */
5503 if (XMARKER (p->mark)->buffer)
5504 set_point_from_marker (p->mark);
5505 else
5506 SET_PT_BOTH (ZV, ZV_BYTE);
5507 before = PT;
5508 before_byte = PT_BYTE;
5510 /* If the output marker is outside of the visible region, save
5511 the restriction and widen. */
5512 if (! (BEGV <= PT && PT <= ZV))
5513 Fwiden ();
5515 /* Adjust the multibyteness of TEXT to that of the buffer. */
5516 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5517 != ! STRING_MULTIBYTE (text))
5518 text = (STRING_MULTIBYTE (text)
5519 ? Fstring_as_unibyte (text)
5520 : Fstring_to_multibyte (text));
5521 /* Insert before markers in case we are inserting where
5522 the buffer's mark is, and the user's next command is Meta-y. */
5523 insert_from_string_before_markers (text, 0, 0,
5524 SCHARS (text), SBYTES (text), 0);
5526 /* Make sure the process marker's position is valid when the
5527 process buffer is changed in the signal_after_change above.
5528 W3 is known to do that. */
5529 if (BUFFERP (p->buffer)
5530 && (b = XBUFFER (p->buffer), b != current_buffer))
5531 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5532 else
5533 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5535 update_mode_lines = 23;
5537 /* Make sure opoint and the old restrictions
5538 float ahead of any new text just as point would. */
5539 if (opoint >= before)
5541 opoint += PT - before;
5542 opoint_byte += PT_BYTE - before_byte;
5544 if (old_begv > before)
5546 old_begv += PT - before;
5547 old_begv_byte += PT_BYTE - before_byte;
5549 if (old_zv >= before)
5551 old_zv += PT - before;
5552 old_zv_byte += PT_BYTE - before_byte;
5555 /* If the restriction isn't what it should be, set it. */
5556 if (old_begv != BEGV || old_zv != ZV)
5557 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5559 bset_read_only (current_buffer, old_read_only);
5560 SET_PT_BOTH (opoint, opoint_byte);
5562 return Qnil;
5565 /* Sending data to subprocess. */
5567 /* In send_process, when a write fails temporarily,
5568 wait_reading_process_output is called. It may execute user code,
5569 e.g. timers, that attempts to write new data to the same process.
5570 We must ensure that data is sent in the right order, and not
5571 interspersed half-completed with other writes (Bug#10815). This is
5572 handled by the write_queue element of struct process. It is a list
5573 with each entry having the form
5575 (string . (offset . length))
5577 where STRING is a lisp string, OFFSET is the offset into the
5578 string's byte sequence from which we should begin to send, and
5579 LENGTH is the number of bytes left to send. */
5581 /* Create a new entry in write_queue.
5582 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5583 BUF is a pointer to the string sequence of the input_obj or a C
5584 string in case of Qt or Qnil. */
5586 static void
5587 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5588 const char *buf, ptrdiff_t len, bool front)
5590 ptrdiff_t offset;
5591 Lisp_Object entry, obj;
5593 if (STRINGP (input_obj))
5595 offset = buf - SSDATA (input_obj);
5596 obj = input_obj;
5598 else
5600 offset = 0;
5601 obj = make_unibyte_string (buf, len);
5604 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5606 if (front)
5607 pset_write_queue (p, Fcons (entry, p->write_queue));
5608 else
5609 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5612 /* Remove the first element in the write_queue of process P, put its
5613 contents in OBJ, BUF and LEN, and return true. If the
5614 write_queue is empty, return false. */
5616 static bool
5617 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5618 const char **buf, ptrdiff_t *len)
5620 Lisp_Object entry, offset_length;
5621 ptrdiff_t offset;
5623 if (NILP (p->write_queue))
5624 return 0;
5626 entry = XCAR (p->write_queue);
5627 pset_write_queue (p, XCDR (p->write_queue));
5629 *obj = XCAR (entry);
5630 offset_length = XCDR (entry);
5632 *len = XINT (XCDR (offset_length));
5633 offset = XINT (XCAR (offset_length));
5634 *buf = SSDATA (*obj) + offset;
5636 return 1;
5639 /* Send some data to process PROC.
5640 BUF is the beginning of the data; LEN is the number of characters.
5641 OBJECT is the Lisp object that the data comes from. If OBJECT is
5642 nil or t, it means that the data comes from C string.
5644 If OBJECT is not nil, the data is encoded by PROC's coding-system
5645 for encoding before it is sent.
5647 This function can evaluate Lisp code and can garbage collect. */
5649 static void
5650 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5651 Lisp_Object object)
5653 struct Lisp_Process *p = XPROCESS (proc);
5654 ssize_t rv;
5655 struct coding_system *coding;
5657 if (p->raw_status_new)
5658 update_status (p);
5659 if (! EQ (p->status, Qrun))
5660 error ("Process %s not running", SDATA (p->name));
5661 if (p->outfd < 0)
5662 error ("Output file descriptor of %s is closed", SDATA (p->name));
5664 coding = proc_encode_coding_system[p->outfd];
5665 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5667 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5668 || (BUFFERP (object)
5669 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5670 || EQ (object, Qt))
5672 pset_encode_coding_system
5673 (p, complement_process_encoding_system (p->encode_coding_system));
5674 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5676 /* The coding system for encoding was changed to raw-text
5677 because we sent a unibyte text previously. Now we are
5678 sending a multibyte text, thus we must encode it by the
5679 original coding system specified for the current process.
5681 Another reason we come here is that the coding system
5682 was just complemented and a new one was returned by
5683 complement_process_encoding_system. */
5684 setup_coding_system (p->encode_coding_system, coding);
5685 Vlast_coding_system_used = p->encode_coding_system;
5687 coding->src_multibyte = 1;
5689 else
5691 coding->src_multibyte = 0;
5692 /* For sending a unibyte text, character code conversion should
5693 not take place but EOL conversion should. So, setup raw-text
5694 or one of the subsidiary if we have not yet done it. */
5695 if (CODING_REQUIRE_ENCODING (coding))
5697 if (CODING_REQUIRE_FLUSHING (coding))
5699 /* But, before changing the coding, we must flush out data. */
5700 coding->mode |= CODING_MODE_LAST_BLOCK;
5701 send_process (proc, "", 0, Qt);
5702 coding->mode &= CODING_MODE_LAST_BLOCK;
5704 setup_coding_system (raw_text_coding_system
5705 (Vlast_coding_system_used),
5706 coding);
5707 coding->src_multibyte = 0;
5710 coding->dst_multibyte = 0;
5712 if (CODING_REQUIRE_ENCODING (coding))
5714 coding->dst_object = Qt;
5715 if (BUFFERP (object))
5717 ptrdiff_t from_byte, from, to;
5718 ptrdiff_t save_pt, save_pt_byte;
5719 struct buffer *cur = current_buffer;
5721 set_buffer_internal (XBUFFER (object));
5722 save_pt = PT, save_pt_byte = PT_BYTE;
5724 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5725 from = BYTE_TO_CHAR (from_byte);
5726 to = BYTE_TO_CHAR (from_byte + len);
5727 TEMP_SET_PT_BOTH (from, from_byte);
5728 encode_coding_object (coding, object, from, from_byte,
5729 to, from_byte + len, Qt);
5730 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5731 set_buffer_internal (cur);
5733 else if (STRINGP (object))
5735 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5736 SBYTES (object), Qt);
5738 else
5740 coding->dst_object = make_unibyte_string (buf, len);
5741 coding->produced = len;
5744 len = coding->produced;
5745 object = coding->dst_object;
5746 buf = SSDATA (object);
5749 /* If there is already data in the write_queue, put the new data
5750 in the back of queue. Otherwise, ignore it. */
5751 if (!NILP (p->write_queue))
5752 write_queue_push (p, object, buf, len, 0);
5754 do /* while !NILP (p->write_queue) */
5756 ptrdiff_t cur_len = -1;
5757 const char *cur_buf;
5758 Lisp_Object cur_object;
5760 /* If write_queue is empty, ignore it. */
5761 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5763 cur_len = len;
5764 cur_buf = buf;
5765 cur_object = object;
5768 while (cur_len > 0)
5770 /* Send this batch, using one or more write calls. */
5771 ptrdiff_t written = 0;
5772 int outfd = p->outfd;
5773 #ifdef DATAGRAM_SOCKETS
5774 if (DATAGRAM_CHAN_P (outfd))
5776 rv = sendto (outfd, cur_buf, cur_len,
5777 0, datagram_address[outfd].sa,
5778 datagram_address[outfd].len);
5779 if (rv >= 0)
5780 written = rv;
5781 else if (errno == EMSGSIZE)
5782 report_file_error ("Sending datagram", proc);
5784 else
5785 #endif
5787 #ifdef HAVE_GNUTLS
5788 if (p->gnutls_p && p->gnutls_state)
5789 written = emacs_gnutls_write (p, cur_buf, cur_len);
5790 else
5791 #endif
5792 written = emacs_write_sig (outfd, cur_buf, cur_len);
5793 rv = (written ? 0 : -1);
5794 if (p->read_output_delay > 0
5795 && p->adaptive_read_buffering == 1)
5797 p->read_output_delay = 0;
5798 process_output_delay_count--;
5799 p->read_output_skip = 0;
5803 if (rv < 0)
5805 if (errno == EAGAIN
5806 #ifdef EWOULDBLOCK
5807 || errno == EWOULDBLOCK
5808 #endif
5810 /* Buffer is full. Wait, accepting input;
5811 that may allow the program
5812 to finish doing output and read more. */
5814 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5815 /* A gross hack to work around a bug in FreeBSD.
5816 In the following sequence, read(2) returns
5817 bogus data:
5819 write(2) 1022 bytes
5820 write(2) 954 bytes, get EAGAIN
5821 read(2) 1024 bytes in process_read_output
5822 read(2) 11 bytes in process_read_output
5824 That is, read(2) returns more bytes than have
5825 ever been written successfully. The 1033 bytes
5826 read are the 1022 bytes written successfully
5827 after processing (for example with CRs added if
5828 the terminal is set up that way which it is
5829 here). The same bytes will be seen again in a
5830 later read(2), without the CRs. */
5832 if (errno == EAGAIN)
5834 int flags = FWRITE;
5835 ioctl (p->outfd, TIOCFLUSH, &flags);
5837 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5839 /* Put what we should have written in wait_queue. */
5840 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5841 wait_reading_process_output (0, 20 * 1000 * 1000,
5842 0, 0, Qnil, NULL, 0);
5843 /* Reread queue, to see what is left. */
5844 break;
5846 else if (errno == EPIPE)
5848 p->raw_status_new = 0;
5849 pset_status (p, list2 (Qexit, make_number (256)));
5850 p->tick = ++process_tick;
5851 deactivate_process (proc);
5852 error ("process %s no longer connected to pipe; closed it",
5853 SDATA (p->name));
5855 else
5856 /* This is a real error. */
5857 report_file_error ("Writing to process", proc);
5859 cur_buf += written;
5860 cur_len -= written;
5863 while (!NILP (p->write_queue));
5866 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5867 3, 3, 0,
5868 doc: /* Send current contents of region as input to PROCESS.
5869 PROCESS may be a process, a buffer, the name of a process or buffer, or
5870 nil, indicating the current buffer's process.
5871 Called from program, takes three arguments, PROCESS, START and END.
5872 If the region is more than 500 characters long,
5873 it is sent in several bunches. This may happen even for shorter regions.
5874 Output from processes can arrive in between bunches. */)
5875 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5877 Lisp_Object proc = get_process (process);
5878 ptrdiff_t start_byte, end_byte;
5880 validate_region (&start, &end);
5882 start_byte = CHAR_TO_BYTE (XINT (start));
5883 end_byte = CHAR_TO_BYTE (XINT (end));
5885 if (XINT (start) < GPT && XINT (end) > GPT)
5886 move_gap_both (XINT (start), start_byte);
5888 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5889 end_byte - start_byte, Fcurrent_buffer ());
5891 return Qnil;
5894 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5895 2, 2, 0,
5896 doc: /* Send PROCESS the contents of STRING as input.
5897 PROCESS may be a process, a buffer, the name of a process or buffer, or
5898 nil, indicating the current buffer's process.
5899 If STRING is more than 500 characters long,
5900 it is sent in several bunches. This may happen even for shorter strings.
5901 Output from processes can arrive in between bunches. */)
5902 (Lisp_Object process, Lisp_Object string)
5904 Lisp_Object proc;
5905 CHECK_STRING (string);
5906 proc = get_process (process);
5907 send_process (proc, SSDATA (string),
5908 SBYTES (string), string);
5909 return Qnil;
5912 /* Return the foreground process group for the tty/pty that
5913 the process P uses. */
5914 static pid_t
5915 emacs_get_tty_pgrp (struct Lisp_Process *p)
5917 pid_t gid = -1;
5919 #ifdef TIOCGPGRP
5920 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5922 int fd;
5923 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5924 master side. Try the slave side. */
5925 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5927 if (fd != -1)
5929 ioctl (fd, TIOCGPGRP, &gid);
5930 emacs_close (fd);
5933 #endif /* defined (TIOCGPGRP ) */
5935 return gid;
5938 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5939 Sprocess_running_child_p, 0, 1, 0,
5940 doc: /* Return non-nil if PROCESS has given the terminal to a
5941 child. If the operating system does not make it possible to find out,
5942 return t. If we can find out, return the numeric ID of the foreground
5943 process group. */)
5944 (Lisp_Object process)
5946 /* Initialize in case ioctl doesn't exist or gives an error,
5947 in a way that will cause returning t. */
5948 pid_t gid;
5949 Lisp_Object proc;
5950 struct Lisp_Process *p;
5952 proc = get_process (process);
5953 p = XPROCESS (proc);
5955 if (!EQ (p->type, Qreal))
5956 error ("Process %s is not a subprocess",
5957 SDATA (p->name));
5958 if (p->infd < 0)
5959 error ("Process %s is not active",
5960 SDATA (p->name));
5962 gid = emacs_get_tty_pgrp (p);
5964 if (gid == p->pid)
5965 return Qnil;
5966 if (gid != -1)
5967 return make_number (gid);
5968 return Qt;
5971 /* Send a signal number SIGNO to PROCESS.
5972 If CURRENT_GROUP is t, that means send to the process group
5973 that currently owns the terminal being used to communicate with PROCESS.
5974 This is used for various commands in shell mode.
5975 If CURRENT_GROUP is lambda, that means send to the process group
5976 that currently owns the terminal, but only if it is NOT the shell itself.
5978 If NOMSG is false, insert signal-announcements into process's buffers
5979 right away.
5981 If we can, we try to signal PROCESS by sending control characters
5982 down the pty. This allows us to signal inferiors who have changed
5983 their uid, for which kill would return an EPERM error. */
5985 static void
5986 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5987 bool nomsg)
5989 Lisp_Object proc;
5990 struct Lisp_Process *p;
5991 pid_t gid;
5992 bool no_pgrp = 0;
5994 proc = get_process (process);
5995 p = XPROCESS (proc);
5997 if (!EQ (p->type, Qreal))
5998 error ("Process %s is not a subprocess",
5999 SDATA (p->name));
6000 if (p->infd < 0)
6001 error ("Process %s is not active",
6002 SDATA (p->name));
6004 if (!p->pty_flag)
6005 current_group = Qnil;
6007 /* If we are using pgrps, get a pgrp number and make it negative. */
6008 if (NILP (current_group))
6009 /* Send the signal to the shell's process group. */
6010 gid = p->pid;
6011 else
6013 #ifdef SIGNALS_VIA_CHARACTERS
6014 /* If possible, send signals to the entire pgrp
6015 by sending an input character to it. */
6017 struct termios t;
6018 cc_t *sig_char = NULL;
6020 tcgetattr (p->infd, &t);
6022 switch (signo)
6024 case SIGINT:
6025 sig_char = &t.c_cc[VINTR];
6026 break;
6028 case SIGQUIT:
6029 sig_char = &t.c_cc[VQUIT];
6030 break;
6032 case SIGTSTP:
6033 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6034 sig_char = &t.c_cc[VSWTCH];
6035 #else
6036 sig_char = &t.c_cc[VSUSP];
6037 #endif
6038 break;
6041 if (sig_char && *sig_char != CDISABLE)
6043 send_process (proc, (char *) sig_char, 1, Qnil);
6044 return;
6046 /* If we can't send the signal with a character,
6047 fall through and send it another way. */
6049 /* The code above may fall through if it can't
6050 handle the signal. */
6051 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6053 #ifdef TIOCGPGRP
6054 /* Get the current pgrp using the tty itself, if we have that.
6055 Otherwise, use the pty to get the pgrp.
6056 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6057 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6058 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6059 His patch indicates that if TIOCGPGRP returns an error, then
6060 we should just assume that p->pid is also the process group id. */
6062 gid = emacs_get_tty_pgrp (p);
6064 if (gid == -1)
6065 /* If we can't get the information, assume
6066 the shell owns the tty. */
6067 gid = p->pid;
6069 /* It is not clear whether anything really can set GID to -1.
6070 Perhaps on some system one of those ioctls can or could do so.
6071 Or perhaps this is vestigial. */
6072 if (gid == -1)
6073 no_pgrp = 1;
6074 #else /* ! defined (TIOCGPGRP) */
6075 /* Can't select pgrps on this system, so we know that
6076 the child itself heads the pgrp. */
6077 gid = p->pid;
6078 #endif /* ! defined (TIOCGPGRP) */
6080 /* If current_group is lambda, and the shell owns the terminal,
6081 don't send any signal. */
6082 if (EQ (current_group, Qlambda) && gid == p->pid)
6083 return;
6086 #ifdef SIGCONT
6087 if (signo == SIGCONT)
6089 p->raw_status_new = 0;
6090 pset_status (p, Qrun);
6091 p->tick = ++process_tick;
6092 if (!nomsg)
6094 status_notify (NULL, NULL);
6095 redisplay_preserve_echo_area (13);
6098 #endif
6100 #ifdef TIOCSIGSEND
6101 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6102 We don't know whether the bug is fixed in later HP-UX versions. */
6103 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6104 return;
6105 #endif
6107 /* If we don't have process groups, send the signal to the immediate
6108 subprocess. That isn't really right, but it's better than any
6109 obvious alternative. */
6110 pid_t pid = no_pgrp ? gid : - gid;
6112 /* Do not kill an already-reaped process, as that could kill an
6113 innocent bystander that happens to have the same process ID. */
6114 sigset_t oldset;
6115 block_child_signal (&oldset);
6116 if (p->alive)
6117 kill (pid, signo);
6118 unblock_child_signal (&oldset);
6121 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6122 doc: /* Interrupt process PROCESS.
6123 PROCESS may be a process, a buffer, or the name of a process or buffer.
6124 No arg or nil means current buffer's process.
6125 Second arg CURRENT-GROUP non-nil means send signal to
6126 the current process-group of the process's controlling terminal
6127 rather than to the process's own process group.
6128 If the process is a shell, this means interrupt current subjob
6129 rather than the shell.
6131 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6132 don't send the signal. */)
6133 (Lisp_Object process, Lisp_Object current_group)
6135 process_send_signal (process, SIGINT, current_group, 0);
6136 return process;
6139 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6140 doc: /* Kill process PROCESS. May be process or name of one.
6141 See function `interrupt-process' for more details on usage. */)
6142 (Lisp_Object process, Lisp_Object current_group)
6144 process_send_signal (process, SIGKILL, current_group, 0);
6145 return process;
6148 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6149 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6150 See function `interrupt-process' for more details on usage. */)
6151 (Lisp_Object process, Lisp_Object current_group)
6153 process_send_signal (process, SIGQUIT, current_group, 0);
6154 return process;
6157 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6158 doc: /* Stop process PROCESS. May be process or name of one.
6159 See function `interrupt-process' for more details on usage.
6160 If PROCESS is a network or serial process, inhibit handling of incoming
6161 traffic. */)
6162 (Lisp_Object process, Lisp_Object current_group)
6164 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6165 || PIPECONN_P (process)))
6167 struct Lisp_Process *p;
6169 p = XPROCESS (process);
6170 if (NILP (p->command)
6171 && p->infd >= 0)
6173 FD_CLR (p->infd, &input_wait_mask);
6174 FD_CLR (p->infd, &non_keyboard_wait_mask);
6176 pset_command (p, Qt);
6177 return process;
6179 #ifndef SIGTSTP
6180 error ("No SIGTSTP support");
6181 #else
6182 process_send_signal (process, SIGTSTP, current_group, 0);
6183 #endif
6184 return process;
6187 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6188 doc: /* Continue process PROCESS. May be process or name of one.
6189 See function `interrupt-process' for more details on usage.
6190 If PROCESS is a network or serial process, resume handling of incoming
6191 traffic. */)
6192 (Lisp_Object process, Lisp_Object current_group)
6194 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6195 || PIPECONN_P (process)))
6197 struct Lisp_Process *p;
6199 p = XPROCESS (process);
6200 if (EQ (p->command, Qt)
6201 && p->infd >= 0
6202 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6204 FD_SET (p->infd, &input_wait_mask);
6205 FD_SET (p->infd, &non_keyboard_wait_mask);
6206 #ifdef WINDOWSNT
6207 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6208 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6209 #else /* not WINDOWSNT */
6210 tcflush (p->infd, TCIFLUSH);
6211 #endif /* not WINDOWSNT */
6213 pset_command (p, Qnil);
6214 return process;
6216 #ifdef SIGCONT
6217 process_send_signal (process, SIGCONT, current_group, 0);
6218 #else
6219 error ("No SIGCONT support");
6220 #endif
6221 return process;
6224 /* Return the integer value of the signal whose abbreviation is ABBR,
6225 or a negative number if there is no such signal. */
6226 static int
6227 abbr_to_signal (char const *name)
6229 int i, signo;
6230 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6232 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6233 name += 3;
6235 for (i = 0; i < sizeof sigbuf; i++)
6237 sigbuf[i] = c_toupper (name[i]);
6238 if (! sigbuf[i])
6239 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6242 return -1;
6245 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6246 2, 2, "sProcess (name or number): \nnSignal code: ",
6247 doc: /* Send PROCESS the signal with code SIGCODE.
6248 PROCESS may also be a number specifying the process id of the
6249 process to signal; in this case, the process need not be a child of
6250 this Emacs.
6251 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6252 (Lisp_Object process, Lisp_Object sigcode)
6254 pid_t pid;
6255 int signo;
6257 if (STRINGP (process))
6259 Lisp_Object tem = Fget_process (process);
6260 if (NILP (tem))
6262 Lisp_Object process_number
6263 = string_to_number (SSDATA (process), 10, 1);
6264 if (INTEGERP (process_number) || FLOATP (process_number))
6265 tem = process_number;
6267 process = tem;
6269 else if (!NUMBERP (process))
6270 process = get_process (process);
6272 if (NILP (process))
6273 return process;
6275 if (NUMBERP (process))
6276 CONS_TO_INTEGER (process, pid_t, pid);
6277 else
6279 CHECK_PROCESS (process);
6280 pid = XPROCESS (process)->pid;
6281 if (pid <= 0)
6282 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6285 if (INTEGERP (sigcode))
6287 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6288 signo = XINT (sigcode);
6290 else
6292 char *name;
6294 CHECK_SYMBOL (sigcode);
6295 name = SSDATA (SYMBOL_NAME (sigcode));
6297 signo = abbr_to_signal (name);
6298 if (signo < 0)
6299 error ("Undefined signal name %s", name);
6302 return make_number (kill (pid, signo));
6305 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6306 doc: /* Make PROCESS see end-of-file in its input.
6307 EOF comes after any text already sent to it.
6308 PROCESS may be a process, a buffer, the name of a process or buffer, or
6309 nil, indicating the current buffer's process.
6310 If PROCESS is a network connection, or is a process communicating
6311 through a pipe (as opposed to a pty), then you cannot send any more
6312 text to PROCESS after you call this function.
6313 If PROCESS is a serial process, wait until all output written to the
6314 process has been transmitted to the serial port. */)
6315 (Lisp_Object process)
6317 Lisp_Object proc;
6318 struct coding_system *coding = NULL;
6319 int outfd;
6321 if (DATAGRAM_CONN_P (process))
6322 return process;
6324 proc = get_process (process);
6325 outfd = XPROCESS (proc)->outfd;
6326 if (outfd >= 0)
6327 coding = proc_encode_coding_system[outfd];
6329 /* Make sure the process is really alive. */
6330 if (XPROCESS (proc)->raw_status_new)
6331 update_status (XPROCESS (proc));
6332 if (! EQ (XPROCESS (proc)->status, Qrun))
6333 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6335 if (coding && CODING_REQUIRE_FLUSHING (coding))
6337 coding->mode |= CODING_MODE_LAST_BLOCK;
6338 send_process (proc, "", 0, Qnil);
6341 if (XPROCESS (proc)->pty_flag)
6342 send_process (proc, "\004", 1, Qnil);
6343 else if (EQ (XPROCESS (proc)->type, Qserial))
6345 #ifndef WINDOWSNT
6346 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6347 report_file_error ("Failed tcdrain", Qnil);
6348 #endif /* not WINDOWSNT */
6349 /* Do nothing on Windows because writes are blocking. */
6351 else
6353 struct Lisp_Process *p = XPROCESS (proc);
6354 int old_outfd = p->outfd;
6355 int new_outfd;
6357 #ifdef HAVE_SHUTDOWN
6358 /* If this is a network connection, or socketpair is used
6359 for communication with the subprocess, call shutdown to cause EOF.
6360 (In some old system, shutdown to socketpair doesn't work.
6361 Then we just can't win.) */
6362 if (0 <= old_outfd
6363 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6364 shutdown (old_outfd, 1);
6365 #endif
6366 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6367 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6368 if (new_outfd < 0)
6369 report_file_error ("Opening null device", Qnil);
6370 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6371 p->outfd = new_outfd;
6373 if (!proc_encode_coding_system[new_outfd])
6374 proc_encode_coding_system[new_outfd]
6375 = xmalloc (sizeof (struct coding_system));
6376 if (old_outfd >= 0)
6378 *proc_encode_coding_system[new_outfd]
6379 = *proc_encode_coding_system[old_outfd];
6380 memset (proc_encode_coding_system[old_outfd], 0,
6381 sizeof (struct coding_system));
6383 else
6384 setup_coding_system (p->encode_coding_system,
6385 proc_encode_coding_system[new_outfd]);
6387 return process;
6390 /* The main Emacs thread records child processes in three places:
6392 - Vprocess_alist, for asynchronous subprocesses, which are child
6393 processes visible to Lisp.
6395 - deleted_pid_list, for child processes invisible to Lisp,
6396 typically because of delete-process. These are recorded so that
6397 the processes can be reaped when they exit, so that the operating
6398 system's process table is not cluttered by zombies.
6400 - the local variable PID in Fcall_process, call_process_cleanup and
6401 call_process_kill, for synchronous subprocesses.
6402 record_unwind_protect is used to make sure this process is not
6403 forgotten: if the user interrupts call-process and the child
6404 process refuses to exit immediately even with two C-g's,
6405 call_process_kill adds PID's contents to deleted_pid_list before
6406 returning.
6408 The main Emacs thread invokes waitpid only on child processes that
6409 it creates and that have not been reaped. This avoid races on
6410 platforms such as GTK, where other threads create their own
6411 subprocesses which the main thread should not reap. For example,
6412 if the main thread attempted to reap an already-reaped child, it
6413 might inadvertently reap a GTK-created process that happened to
6414 have the same process ID. */
6416 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6417 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6418 keep track of its own children. GNUstep is similar. */
6420 static void dummy_handler (int sig) {}
6421 static signal_handler_t volatile lib_child_handler;
6423 /* Handle a SIGCHLD signal by looking for known child processes of
6424 Emacs whose status have changed. For each one found, record its
6425 new status.
6427 All we do is change the status; we do not run sentinels or print
6428 notifications. That is saved for the next time keyboard input is
6429 done, in order to avoid timing errors.
6431 ** WARNING: this can be called during garbage collection.
6432 Therefore, it must not be fooled by the presence of mark bits in
6433 Lisp objects.
6435 ** USG WARNING: Although it is not obvious from the documentation
6436 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6437 signal() before executing at least one wait(), otherwise the
6438 handler will be called again, resulting in an infinite loop. The
6439 relevant portion of the documentation reads "SIGCLD signals will be
6440 queued and the signal-catching function will be continually
6441 reentered until the queue is empty". Invoking signal() causes the
6442 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6443 Inc.
6445 ** Malloc WARNING: This should never call malloc either directly or
6446 indirectly; if it does, that is a bug. */
6448 static void
6449 handle_child_signal (int sig)
6451 Lisp_Object tail, proc;
6453 /* Find the process that signaled us, and record its status. */
6455 /* The process can have been deleted by Fdelete_process, or have
6456 been started asynchronously by Fcall_process. */
6457 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6459 bool all_pids_are_fixnums
6460 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6461 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6462 Lisp_Object head = XCAR (tail);
6463 Lisp_Object xpid;
6464 if (! CONSP (head))
6465 continue;
6466 xpid = XCAR (head);
6467 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6469 pid_t deleted_pid;
6470 if (INTEGERP (xpid))
6471 deleted_pid = XINT (xpid);
6472 else
6473 deleted_pid = XFLOAT_DATA (xpid);
6474 if (child_status_changed (deleted_pid, 0, 0))
6476 if (STRINGP (XCDR (head)))
6477 unlink (SSDATA (XCDR (head)));
6478 XSETCAR (tail, Qnil);
6483 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6484 FOR_EACH_PROCESS (tail, proc)
6486 struct Lisp_Process *p = XPROCESS (proc);
6487 int status;
6489 if (p->alive
6490 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6492 /* Change the status of the process that was found. */
6493 p->tick = ++process_tick;
6494 p->raw_status = status;
6495 p->raw_status_new = 1;
6497 /* If process has terminated, stop waiting for its output. */
6498 if (WIFSIGNALED (status) || WIFEXITED (status))
6500 bool clear_desc_flag = 0;
6501 p->alive = 0;
6502 if (p->infd >= 0)
6503 clear_desc_flag = 1;
6505 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6506 if (clear_desc_flag)
6508 FD_CLR (p->infd, &input_wait_mask);
6509 FD_CLR (p->infd, &non_keyboard_wait_mask);
6515 lib_child_handler (sig);
6516 #ifdef NS_IMPL_GNUSTEP
6517 /* NSTask in GNUstep sets its child handler each time it is called.
6518 So we must re-set ours. */
6519 catch_child_signal ();
6520 #endif
6523 static void
6524 deliver_child_signal (int sig)
6526 deliver_process_signal (sig, handle_child_signal);
6530 static Lisp_Object
6531 exec_sentinel_error_handler (Lisp_Object error_val)
6533 cmd_error_internal (error_val, "error in process sentinel: ");
6534 Vinhibit_quit = Qt;
6535 update_echo_area ();
6536 Fsleep_for (make_number (2), Qnil);
6537 return Qt;
6540 static void
6541 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6543 Lisp_Object sentinel, odeactivate;
6544 struct Lisp_Process *p = XPROCESS (proc);
6545 ptrdiff_t count = SPECPDL_INDEX ();
6546 bool outer_running_asynch_code = running_asynch_code;
6547 int waiting = waiting_for_user_input_p;
6549 if (inhibit_sentinels)
6550 return;
6552 odeactivate = Vdeactivate_mark;
6553 #if 0
6554 Lisp_Object obuffer, okeymap;
6555 XSETBUFFER (obuffer, current_buffer);
6556 okeymap = BVAR (current_buffer, keymap);
6557 #endif
6559 /* There's no good reason to let sentinels change the current
6560 buffer, and many callers of accept-process-output, sit-for, and
6561 friends don't expect current-buffer to be changed from under them. */
6562 record_unwind_current_buffer ();
6564 sentinel = p->sentinel;
6566 /* Inhibit quit so that random quits don't screw up a running filter. */
6567 specbind (Qinhibit_quit, Qt);
6568 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6570 /* In case we get recursively called,
6571 and we already saved the match data nonrecursively,
6572 save the same match data in safely recursive fashion. */
6573 if (outer_running_asynch_code)
6575 Lisp_Object tem;
6576 tem = Fmatch_data (Qnil, Qnil, Qnil);
6577 restore_search_regs ();
6578 record_unwind_save_match_data ();
6579 Fset_match_data (tem, Qt);
6582 /* For speed, if a search happens within this code,
6583 save the match data in a special nonrecursive fashion. */
6584 running_asynch_code = 1;
6586 internal_condition_case_1 (read_process_output_call,
6587 list3 (sentinel, proc, reason),
6588 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6589 exec_sentinel_error_handler);
6591 /* If we saved the match data nonrecursively, restore it now. */
6592 restore_search_regs ();
6593 running_asynch_code = outer_running_asynch_code;
6595 Vdeactivate_mark = odeactivate;
6597 /* Restore waiting_for_user_input_p as it was
6598 when we were called, in case the filter clobbered it. */
6599 waiting_for_user_input_p = waiting;
6601 #if 0
6602 if (! EQ (Fcurrent_buffer (), obuffer)
6603 || ! EQ (current_buffer->keymap, okeymap))
6604 #endif
6605 /* But do it only if the caller is actually going to read events.
6606 Otherwise there's no need to make him wake up, and it could
6607 cause trouble (for example it would make sit_for return). */
6608 if (waiting_for_user_input_p == -1)
6609 record_asynch_buffer_change ();
6611 unbind_to (count, Qnil);
6614 /* Report all recent events of a change in process status
6615 (either run the sentinel or output a message).
6616 This is usually done while Emacs is waiting for keyboard input
6617 but can be done at other times.
6619 Return positive if any input was received from WAIT_PROC (or from
6620 any process if WAIT_PROC is null), zero if input was attempted but
6621 none received, and negative if we didn't even try. */
6623 static int
6624 status_notify (struct Lisp_Process *deleting_process,
6625 struct Lisp_Process *wait_proc)
6627 Lisp_Object proc;
6628 Lisp_Object tail, msg;
6629 int got_some_output = -1;
6631 tail = Qnil;
6632 msg = Qnil;
6634 /* Set this now, so that if new processes are created by sentinels
6635 that we run, we get called again to handle their status changes. */
6636 update_tick = process_tick;
6638 FOR_EACH_PROCESS (tail, proc)
6640 Lisp_Object symbol;
6641 register struct Lisp_Process *p = XPROCESS (proc);
6643 if (p->tick != p->update_tick)
6645 p->update_tick = p->tick;
6647 /* If process is still active, read any output that remains. */
6648 while (! EQ (p->filter, Qt)
6649 && ! EQ (p->status, Qconnect)
6650 && ! EQ (p->status, Qlisten)
6651 /* Network or serial process not stopped: */
6652 && ! EQ (p->command, Qt)
6653 && p->infd >= 0
6654 && p != deleting_process)
6656 int nread = read_process_output (proc, p->infd);
6657 if ((!wait_proc || wait_proc == XPROCESS (proc))
6658 && got_some_output < nread)
6659 got_some_output = nread;
6660 if (nread <= 0)
6661 break;
6664 /* Get the text to use for the message. */
6665 if (p->raw_status_new)
6666 update_status (p);
6667 msg = status_message (p);
6669 /* If process is terminated, deactivate it or delete it. */
6670 symbol = p->status;
6671 if (CONSP (p->status))
6672 symbol = XCAR (p->status);
6674 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6675 || EQ (symbol, Qclosed))
6677 if (delete_exited_processes)
6678 remove_process (proc);
6679 else
6680 deactivate_process (proc);
6683 /* The actions above may have further incremented p->tick.
6684 So set p->update_tick again so that an error in the sentinel will
6685 not cause this code to be run again. */
6686 p->update_tick = p->tick;
6687 /* Now output the message suitably. */
6688 exec_sentinel (proc, msg);
6690 } /* end for */
6692 update_mode_lines = 24; /* In case buffers use %s in mode-line-format. */
6693 return got_some_output;
6696 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6697 Sinternal_default_process_sentinel, 2, 2, 0,
6698 doc: /* Function used as default sentinel for processes.
6699 This inserts a status message into the process's buffer, if there is one. */)
6700 (Lisp_Object proc, Lisp_Object msg)
6702 Lisp_Object buffer, symbol;
6703 struct Lisp_Process *p;
6704 CHECK_PROCESS (proc);
6705 p = XPROCESS (proc);
6706 buffer = p->buffer;
6707 symbol = p->status;
6708 if (CONSP (symbol))
6709 symbol = XCAR (symbol);
6711 if (!EQ (symbol, Qrun) && !NILP (buffer))
6713 Lisp_Object tem;
6714 struct buffer *old = current_buffer;
6715 ptrdiff_t opoint, opoint_byte;
6716 ptrdiff_t before, before_byte;
6718 /* Avoid error if buffer is deleted
6719 (probably that's why the process is dead, too). */
6720 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6721 return Qnil;
6722 Fset_buffer (buffer);
6724 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6725 msg = (code_convert_string_norecord
6726 (msg, Vlocale_coding_system, 1));
6728 opoint = PT;
6729 opoint_byte = PT_BYTE;
6730 /* Insert new output into buffer
6731 at the current end-of-output marker,
6732 thus preserving logical ordering of input and output. */
6733 if (XMARKER (p->mark)->buffer)
6734 Fgoto_char (p->mark);
6735 else
6736 SET_PT_BOTH (ZV, ZV_BYTE);
6738 before = PT;
6739 before_byte = PT_BYTE;
6741 tem = BVAR (current_buffer, read_only);
6742 bset_read_only (current_buffer, Qnil);
6743 insert_string ("\nProcess ");
6744 { /* FIXME: temporary kludge. */
6745 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6746 insert_string (" ");
6747 Finsert (1, &msg);
6748 bset_read_only (current_buffer, tem);
6749 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6751 if (opoint >= before)
6752 SET_PT_BOTH (opoint + (PT - before),
6753 opoint_byte + (PT_BYTE - before_byte));
6754 else
6755 SET_PT_BOTH (opoint, opoint_byte);
6757 set_buffer_internal (old);
6759 return Qnil;
6763 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6764 Sset_process_coding_system, 1, 3, 0,
6765 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6766 DECODING will be used to decode subprocess output and ENCODING to
6767 encode subprocess input. */)
6768 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6770 register struct Lisp_Process *p;
6772 CHECK_PROCESS (process);
6773 p = XPROCESS (process);
6774 if (p->infd < 0)
6775 error ("Input file descriptor of %s closed", SDATA (p->name));
6776 if (p->outfd < 0)
6777 error ("Output file descriptor of %s closed", SDATA (p->name));
6778 Fcheck_coding_system (decoding);
6779 Fcheck_coding_system (encoding);
6780 encoding = coding_inherit_eol_type (encoding, Qnil);
6781 pset_decode_coding_system (p, decoding);
6782 pset_encode_coding_system (p, encoding);
6783 setup_process_coding_systems (process);
6785 return Qnil;
6788 DEFUN ("process-coding-system",
6789 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6790 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6791 (register Lisp_Object process)
6793 CHECK_PROCESS (process);
6794 return Fcons (XPROCESS (process)->decode_coding_system,
6795 XPROCESS (process)->encode_coding_system);
6798 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6799 Sset_process_filter_multibyte, 2, 2, 0,
6800 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6801 If FLAG is non-nil, the filter is given multibyte strings.
6802 If FLAG is nil, the filter is given unibyte strings. In this case,
6803 all character code conversion except for end-of-line conversion is
6804 suppressed. */)
6805 (Lisp_Object process, Lisp_Object flag)
6807 register struct Lisp_Process *p;
6809 CHECK_PROCESS (process);
6810 p = XPROCESS (process);
6811 if (NILP (flag))
6812 pset_decode_coding_system
6813 (p, raw_text_coding_system (p->decode_coding_system));
6814 setup_process_coding_systems (process);
6816 return Qnil;
6819 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6820 Sprocess_filter_multibyte_p, 1, 1, 0,
6821 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6822 (Lisp_Object process)
6824 register struct Lisp_Process *p;
6825 struct coding_system *coding;
6827 CHECK_PROCESS (process);
6828 p = XPROCESS (process);
6829 if (p->infd < 0)
6830 return Qnil;
6831 coding = proc_decode_coding_system[p->infd];
6832 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6838 # ifdef HAVE_GPM
6840 void
6841 add_gpm_wait_descriptor (int desc)
6843 add_keyboard_wait_descriptor (desc);
6846 void
6847 delete_gpm_wait_descriptor (int desc)
6849 delete_keyboard_wait_descriptor (desc);
6852 # endif
6854 # ifdef USABLE_SIGIO
6856 /* Return true if *MASK has a bit set
6857 that corresponds to one of the keyboard input descriptors. */
6859 static bool
6860 keyboard_bit_set (fd_set *mask)
6862 int fd;
6864 for (fd = 0; fd <= max_input_desc; fd++)
6865 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6866 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6867 return 1;
6869 return 0;
6871 # endif
6873 #else /* not subprocesses */
6875 /* Defined in msdos.c. */
6876 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6877 struct timespec *, void *);
6879 /* Implementation of wait_reading_process_output, assuming that there
6880 are no subprocesses. Used only by the MS-DOS build.
6882 Wait for timeout to elapse and/or keyboard input to be available.
6884 TIME_LIMIT is:
6885 timeout in seconds
6886 If negative, gobble data immediately available but don't wait for any.
6888 NSECS is:
6889 an additional duration to wait, measured in nanoseconds
6890 If TIME_LIMIT is zero, then:
6891 If NSECS == 0, there is no limit.
6892 If NSECS > 0, the timeout consists of NSECS only.
6893 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6895 READ_KBD is:
6896 0 to ignore keyboard input, or
6897 1 to return when input is available, or
6898 -1 means caller will actually read the input, so don't throw to
6899 the quit handler.
6901 see full version for other parameters. We know that wait_proc will
6902 always be NULL, since `subprocesses' isn't defined.
6904 DO_DISPLAY means redisplay should be done to show subprocess
6905 output that arrives.
6907 Return -1 signifying we got no output and did not try. */
6910 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6911 bool do_display,
6912 Lisp_Object wait_for_cell,
6913 struct Lisp_Process *wait_proc, int just_wait_proc)
6915 register int nfds;
6916 struct timespec end_time, timeout;
6917 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
6919 if (TYPE_MAXIMUM (time_t) < time_limit)
6920 time_limit = TYPE_MAXIMUM (time_t);
6922 if (time_limit < 0 || nsecs < 0)
6923 wait = MINIMUM;
6924 else if (time_limit > 0 || nsecs > 0)
6926 wait = TIMEOUT;
6927 end_time = timespec_add (current_timespec (),
6928 make_timespec (time_limit, nsecs));
6930 else
6931 wait = INFINITY;
6933 /* Turn off periodic alarms (in case they are in use)
6934 and then turn off any other atimers,
6935 because the select emulator uses alarms. */
6936 stop_polling ();
6937 turn_on_atimers (0);
6939 while (1)
6941 bool timeout_reduced_for_timers = false;
6942 fd_set waitchannels;
6943 int xerrno;
6945 /* If calling from keyboard input, do not quit
6946 since we want to return C-g as an input character.
6947 Otherwise, do pending quit if requested. */
6948 if (read_kbd >= 0)
6949 QUIT;
6951 /* Exit now if the cell we're waiting for became non-nil. */
6952 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6953 break;
6955 /* Compute time from now till when time limit is up. */
6956 /* Exit if already run out. */
6957 if (wait == TIMEOUT)
6959 struct timespec now = current_timespec ();
6960 if (timespec_cmp (end_time, now) <= 0)
6961 break;
6962 timeout = timespec_sub (end_time, now);
6964 else
6965 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
6967 /* If our caller will not immediately handle keyboard events,
6968 run timer events directly.
6969 (Callers that will immediately read keyboard events
6970 call timer_delay on their own.) */
6971 if (NILP (wait_for_cell))
6973 struct timespec timer_delay;
6977 unsigned old_timers_run = timers_run;
6978 timer_delay = timer_check ();
6979 if (timers_run != old_timers_run && do_display)
6980 /* We must retry, since a timer may have requeued itself
6981 and that could alter the time delay. */
6982 redisplay_preserve_echo_area (14);
6983 else
6984 break;
6986 while (!detect_input_pending ());
6988 /* If there is unread keyboard input, also return. */
6989 if (read_kbd != 0
6990 && requeued_events_pending_p ())
6991 break;
6993 if (timespec_valid_p (timer_delay))
6995 if (timespec_cmp (timer_delay, timeout) < 0)
6997 timeout = timer_delay;
6998 timeout_reduced_for_timers = true;
7003 /* Cause C-g and alarm signals to take immediate action,
7004 and cause input available signals to zero out timeout. */
7005 if (read_kbd < 0)
7006 set_waiting_for_input (&timeout);
7008 /* If a frame has been newly mapped and needs updating,
7009 reprocess its display stuff. */
7010 if (frame_garbaged && do_display)
7012 clear_waiting_for_input ();
7013 redisplay_preserve_echo_area (15);
7014 if (read_kbd < 0)
7015 set_waiting_for_input (&timeout);
7018 /* Wait till there is something to do. */
7019 FD_ZERO (&waitchannels);
7020 if (read_kbd && detect_input_pending ())
7021 nfds = 0;
7022 else
7024 if (read_kbd || !NILP (wait_for_cell))
7025 FD_SET (0, &waitchannels);
7026 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7029 xerrno = errno;
7031 /* Make C-g and alarm signals set flags again. */
7032 clear_waiting_for_input ();
7034 /* If we woke up due to SIGWINCH, actually change size now. */
7035 do_pending_window_change (0);
7037 if (wait < INFINITY && nfds == 0 && ! timeout_reduced_for_timers)
7038 /* We waited the full specified time, so return now. */
7039 break;
7041 if (nfds == -1)
7043 /* If the system call was interrupted, then go around the
7044 loop again. */
7045 if (xerrno == EINTR)
7046 FD_ZERO (&waitchannels);
7047 else
7048 report_file_errno ("Failed select", Qnil, xerrno);
7051 /* Check for keyboard input. */
7053 if (read_kbd
7054 && detect_input_pending_run_timers (do_display))
7056 swallow_events (do_display);
7057 if (detect_input_pending_run_timers (do_display))
7058 break;
7061 /* If there is unread keyboard input, also return. */
7062 if (read_kbd
7063 && requeued_events_pending_p ())
7064 break;
7066 /* If wait_for_cell. check for keyboard input
7067 but don't run any timers.
7068 ??? (It seems wrong to me to check for keyboard
7069 input at all when wait_for_cell, but the code
7070 has been this way since July 1994.
7071 Try changing this after version 19.31.) */
7072 if (! NILP (wait_for_cell)
7073 && detect_input_pending ())
7075 swallow_events (do_display);
7076 if (detect_input_pending ())
7077 break;
7080 /* Exit now if the cell we're waiting for became non-nil. */
7081 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7082 break;
7085 start_polling ();
7087 return -1;
7090 #endif /* not subprocesses */
7092 /* The following functions are needed even if async subprocesses are
7093 not supported. Some of them are no-op stubs in that case. */
7095 #ifdef HAVE_TIMERFD
7097 /* Add FD, which is a descriptor returned by timerfd_create,
7098 to the set of non-keyboard input descriptors. */
7100 void
7101 add_timer_wait_descriptor (int fd)
7103 FD_SET (fd, &input_wait_mask);
7104 FD_SET (fd, &non_keyboard_wait_mask);
7105 FD_SET (fd, &non_process_wait_mask);
7106 fd_callback_info[fd].func = timerfd_callback;
7107 fd_callback_info[fd].data = NULL;
7108 fd_callback_info[fd].condition |= FOR_READ;
7109 if (fd > max_input_desc)
7110 max_input_desc = fd;
7113 #endif /* HAVE_TIMERFD */
7115 /* Add DESC to the set of keyboard input descriptors. */
7117 void
7118 add_keyboard_wait_descriptor (int desc)
7120 #ifdef subprocesses /* Actually means "not MSDOS". */
7121 FD_SET (desc, &input_wait_mask);
7122 FD_SET (desc, &non_process_wait_mask);
7123 if (desc > max_input_desc)
7124 max_input_desc = desc;
7125 #endif
7128 /* From now on, do not expect DESC to give keyboard input. */
7130 void
7131 delete_keyboard_wait_descriptor (int desc)
7133 #ifdef subprocesses
7134 FD_CLR (desc, &input_wait_mask);
7135 FD_CLR (desc, &non_process_wait_mask);
7136 delete_input_desc (desc);
7137 #endif
7140 /* Setup coding systems of PROCESS. */
7142 void
7143 setup_process_coding_systems (Lisp_Object process)
7145 #ifdef subprocesses
7146 struct Lisp_Process *p = XPROCESS (process);
7147 int inch = p->infd;
7148 int outch = p->outfd;
7149 Lisp_Object coding_system;
7151 if (inch < 0 || outch < 0)
7152 return;
7154 if (!proc_decode_coding_system[inch])
7155 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7156 coding_system = p->decode_coding_system;
7157 if (EQ (p->filter, Qinternal_default_process_filter)
7158 && BUFFERP (p->buffer))
7160 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7161 coding_system = raw_text_coding_system (coding_system);
7163 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7165 if (!proc_encode_coding_system[outch])
7166 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7167 setup_coding_system (p->encode_coding_system,
7168 proc_encode_coding_system[outch]);
7169 #endif
7172 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7173 doc: /* Return the (or a) process associated with BUFFER.
7174 BUFFER may be a buffer or the name of one. */)
7175 (register Lisp_Object buffer)
7177 #ifdef subprocesses
7178 register Lisp_Object buf, tail, proc;
7180 if (NILP (buffer)) return Qnil;
7181 buf = Fget_buffer (buffer);
7182 if (NILP (buf)) return Qnil;
7184 FOR_EACH_PROCESS (tail, proc)
7185 if (EQ (XPROCESS (proc)->buffer, buf))
7186 return proc;
7187 #endif /* subprocesses */
7188 return Qnil;
7191 DEFUN ("process-inherit-coding-system-flag",
7192 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7193 1, 1, 0,
7194 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7195 If this flag is t, `buffer-file-coding-system' of the buffer
7196 associated with PROCESS will inherit the coding system used to decode
7197 the process output. */)
7198 (register Lisp_Object process)
7200 #ifdef subprocesses
7201 CHECK_PROCESS (process);
7202 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7203 #else
7204 /* Ignore the argument and return the value of
7205 inherit-process-coding-system. */
7206 return inherit_process_coding_system ? Qt : Qnil;
7207 #endif
7210 /* Kill all processes associated with `buffer'.
7211 If `buffer' is nil, kill all processes. */
7213 void
7214 kill_buffer_processes (Lisp_Object buffer)
7216 #ifdef subprocesses
7217 Lisp_Object tail, proc;
7219 FOR_EACH_PROCESS (tail, proc)
7220 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7222 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7223 Fdelete_process (proc);
7224 else if (XPROCESS (proc)->infd >= 0)
7225 process_send_signal (proc, SIGHUP, Qnil, 1);
7227 #else /* subprocesses */
7228 /* Since we have no subprocesses, this does nothing. */
7229 #endif /* subprocesses */
7232 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7233 Swaiting_for_user_input_p, 0, 0, 0,
7234 doc: /* Return non-nil if Emacs is waiting for input from the user.
7235 This is intended for use by asynchronous process output filters and sentinels. */)
7236 (void)
7238 #ifdef subprocesses
7239 return (waiting_for_user_input_p ? Qt : Qnil);
7240 #else
7241 return Qnil;
7242 #endif
7245 /* Stop reading input from keyboard sources. */
7247 void
7248 hold_keyboard_input (void)
7250 kbd_is_on_hold = 1;
7253 /* Resume reading input from keyboard sources. */
7255 void
7256 unhold_keyboard_input (void)
7258 kbd_is_on_hold = 0;
7261 /* Return true if keyboard input is on hold, zero otherwise. */
7263 bool
7264 kbd_on_hold_p (void)
7266 return kbd_is_on_hold;
7270 /* Enumeration of and access to system processes a-la ps(1). */
7272 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7273 0, 0, 0,
7274 doc: /* Return a list of numerical process IDs of all running processes.
7275 If this functionality is unsupported, return nil.
7277 See `process-attributes' for getting attributes of a process given its ID. */)
7278 (void)
7280 return list_system_processes ();
7283 DEFUN ("process-attributes", Fprocess_attributes,
7284 Sprocess_attributes, 1, 1, 0,
7285 doc: /* Return attributes of the process given by its PID, a number.
7287 Value is an alist where each element is a cons cell of the form
7289 \(KEY . VALUE)
7291 If this functionality is unsupported, the value is nil.
7293 See `list-system-processes' for getting a list of all process IDs.
7295 The KEYs of the attributes that this function may return are listed
7296 below, together with the type of the associated VALUE (in parentheses).
7297 Not all platforms support all of these attributes; unsupported
7298 attributes will not appear in the returned alist.
7299 Unless explicitly indicated otherwise, numbers can have either
7300 integer or floating point values.
7302 euid -- Effective user User ID of the process (number)
7303 user -- User name corresponding to euid (string)
7304 egid -- Effective user Group ID of the process (number)
7305 group -- Group name corresponding to egid (string)
7306 comm -- Command name (executable name only) (string)
7307 state -- Process state code, such as "S", "R", or "T" (string)
7308 ppid -- Parent process ID (number)
7309 pgrp -- Process group ID (number)
7310 sess -- Session ID, i.e. process ID of session leader (number)
7311 ttname -- Controlling tty name (string)
7312 tpgid -- ID of foreground process group on the process's tty (number)
7313 minflt -- number of minor page faults (number)
7314 majflt -- number of major page faults (number)
7315 cminflt -- cumulative number of minor page faults (number)
7316 cmajflt -- cumulative number of major page faults (number)
7317 utime -- user time used by the process, in (current-time) format,
7318 which is a list of integers (HIGH LOW USEC PSEC)
7319 stime -- system time used by the process (current-time)
7320 time -- sum of utime and stime (current-time)
7321 cutime -- user time used by the process and its children (current-time)
7322 cstime -- system time used by the process and its children (current-time)
7323 ctime -- sum of cutime and cstime (current-time)
7324 pri -- priority of the process (number)
7325 nice -- nice value of the process (number)
7326 thcount -- process thread count (number)
7327 start -- time the process started (current-time)
7328 vsize -- virtual memory size of the process in KB's (number)
7329 rss -- resident set size of the process in KB's (number)
7330 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7331 pcpu -- percents of CPU time used by the process (floating-point number)
7332 pmem -- percents of total physical memory used by process's resident set
7333 (floating-point number)
7334 args -- command line which invoked the process (string). */)
7335 ( Lisp_Object pid)
7337 return system_process_attributes (pid);
7340 #ifdef subprocesses
7341 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7342 Invoke this after init_process_emacs, and after glib and/or GNUstep
7343 futz with the SIGCHLD handler, but before Emacs forks any children.
7344 This function's caller should block SIGCHLD. */
7346 void
7347 catch_child_signal (void)
7349 struct sigaction action, old_action;
7350 sigset_t oldset;
7351 emacs_sigaction_init (&action, deliver_child_signal);
7352 block_child_signal (&oldset);
7353 sigaction (SIGCHLD, &action, &old_action);
7354 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7355 || ! (old_action.sa_flags & SA_SIGINFO));
7357 if (old_action.sa_handler != deliver_child_signal)
7358 lib_child_handler
7359 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7360 ? dummy_handler
7361 : old_action.sa_handler);
7362 unblock_child_signal (&oldset);
7364 #endif /* subprocesses */
7367 /* This is not called "init_process" because that is the name of a
7368 Mach system call, so it would cause problems on Darwin systems. */
7369 void
7370 init_process_emacs (void)
7372 #ifdef subprocesses
7373 register int i;
7375 inhibit_sentinels = 0;
7377 #ifndef CANNOT_DUMP
7378 if (! noninteractive || initialized)
7379 #endif
7381 #if defined HAVE_GLIB && !defined WINDOWSNT
7382 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7383 this should always fail, but is enough to initialize glib's
7384 private SIGCHLD handler, allowing catch_child_signal to copy
7385 it into lib_child_handler. */
7386 g_source_unref (g_child_watch_source_new (getpid ()));
7387 #endif
7388 catch_child_signal ();
7391 FD_ZERO (&input_wait_mask);
7392 FD_ZERO (&non_keyboard_wait_mask);
7393 FD_ZERO (&non_process_wait_mask);
7394 FD_ZERO (&write_mask);
7395 max_process_desc = max_input_desc = -1;
7396 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7398 #ifdef NON_BLOCKING_CONNECT
7399 FD_ZERO (&connect_wait_mask);
7400 num_pending_connects = 0;
7401 #endif
7403 process_output_delay_count = 0;
7404 process_output_skip = 0;
7406 /* Don't do this, it caused infinite select loops. The display
7407 method should call add_keyboard_wait_descriptor on stdin if it
7408 needs that. */
7409 #if 0
7410 FD_SET (0, &input_wait_mask);
7411 #endif
7413 Vprocess_alist = Qnil;
7414 deleted_pid_list = Qnil;
7415 for (i = 0; i < FD_SETSIZE; i++)
7417 chan_process[i] = Qnil;
7418 proc_buffered_char[i] = -1;
7420 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7421 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7422 #ifdef DATAGRAM_SOCKETS
7423 memset (datagram_address, 0, sizeof datagram_address);
7424 #endif
7426 #if defined (DARWIN_OS)
7427 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7428 processes. As such, we only change the default value. */
7429 if (initialized)
7431 char const *release = (STRINGP (Voperating_system_release)
7432 ? SSDATA (Voperating_system_release)
7433 : 0);
7434 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7435 Vprocess_connection_type = Qnil;
7438 #endif
7439 #endif /* subprocesses */
7440 kbd_is_on_hold = 0;
7443 void
7444 syms_of_process (void)
7446 #ifdef subprocesses
7448 DEFSYM (Qprocessp, "processp");
7449 DEFSYM (Qrun, "run");
7450 DEFSYM (Qstop, "stop");
7451 DEFSYM (Qsignal, "signal");
7453 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7454 here again. */
7456 DEFSYM (Qopen, "open");
7457 DEFSYM (Qclosed, "closed");
7458 DEFSYM (Qconnect, "connect");
7459 DEFSYM (Qfailed, "failed");
7460 DEFSYM (Qlisten, "listen");
7461 DEFSYM (Qlocal, "local");
7462 DEFSYM (Qipv4, "ipv4");
7463 #ifdef AF_INET6
7464 DEFSYM (Qipv6, "ipv6");
7465 #endif
7466 DEFSYM (Qdatagram, "datagram");
7467 DEFSYM (Qseqpacket, "seqpacket");
7469 DEFSYM (QCport, ":port");
7470 DEFSYM (QCspeed, ":speed");
7471 DEFSYM (QCprocess, ":process");
7473 DEFSYM (QCbytesize, ":bytesize");
7474 DEFSYM (QCstopbits, ":stopbits");
7475 DEFSYM (QCparity, ":parity");
7476 DEFSYM (Qodd, "odd");
7477 DEFSYM (Qeven, "even");
7478 DEFSYM (QCflowcontrol, ":flowcontrol");
7479 DEFSYM (Qhw, "hw");
7480 DEFSYM (Qsw, "sw");
7481 DEFSYM (QCsummary, ":summary");
7483 DEFSYM (Qreal, "real");
7484 DEFSYM (Qnetwork, "network");
7485 DEFSYM (Qserial, "serial");
7486 DEFSYM (Qpipe, "pipe");
7487 DEFSYM (QCbuffer, ":buffer");
7488 DEFSYM (QChost, ":host");
7489 DEFSYM (QCservice, ":service");
7490 DEFSYM (QClocal, ":local");
7491 DEFSYM (QCremote, ":remote");
7492 DEFSYM (QCcoding, ":coding");
7493 DEFSYM (QCserver, ":server");
7494 DEFSYM (QCnowait, ":nowait");
7495 DEFSYM (QCsentinel, ":sentinel");
7496 DEFSYM (QClog, ":log");
7497 DEFSYM (QCnoquery, ":noquery");
7498 DEFSYM (QCstop, ":stop");
7499 DEFSYM (QCplist, ":plist");
7500 DEFSYM (QCcommand, ":command");
7501 DEFSYM (QCconnection_type, ":connection-type");
7502 DEFSYM (QCstderr, ":stderr");
7503 DEFSYM (Qpty, "pty");
7504 DEFSYM (Qpipe, "pipe");
7506 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7508 staticpro (&Vprocess_alist);
7509 staticpro (&deleted_pid_list);
7511 #endif /* subprocesses */
7513 DEFSYM (QCname, ":name");
7514 DEFSYM (QCtype, ":type");
7516 DEFSYM (Qeuid, "euid");
7517 DEFSYM (Qegid, "egid");
7518 DEFSYM (Quser, "user");
7519 DEFSYM (Qgroup, "group");
7520 DEFSYM (Qcomm, "comm");
7521 DEFSYM (Qstate, "state");
7522 DEFSYM (Qppid, "ppid");
7523 DEFSYM (Qpgrp, "pgrp");
7524 DEFSYM (Qsess, "sess");
7525 DEFSYM (Qttname, "ttname");
7526 DEFSYM (Qtpgid, "tpgid");
7527 DEFSYM (Qminflt, "minflt");
7528 DEFSYM (Qmajflt, "majflt");
7529 DEFSYM (Qcminflt, "cminflt");
7530 DEFSYM (Qcmajflt, "cmajflt");
7531 DEFSYM (Qutime, "utime");
7532 DEFSYM (Qstime, "stime");
7533 DEFSYM (Qtime, "time");
7534 DEFSYM (Qcutime, "cutime");
7535 DEFSYM (Qcstime, "cstime");
7536 DEFSYM (Qctime, "ctime");
7537 #ifdef subprocesses
7538 DEFSYM (Qinternal_default_process_sentinel,
7539 "internal-default-process-sentinel");
7540 DEFSYM (Qinternal_default_process_filter,
7541 "internal-default-process-filter");
7542 #endif
7543 DEFSYM (Qpri, "pri");
7544 DEFSYM (Qnice, "nice");
7545 DEFSYM (Qthcount, "thcount");
7546 DEFSYM (Qstart, "start");
7547 DEFSYM (Qvsize, "vsize");
7548 DEFSYM (Qrss, "rss");
7549 DEFSYM (Qetime, "etime");
7550 DEFSYM (Qpcpu, "pcpu");
7551 DEFSYM (Qpmem, "pmem");
7552 DEFSYM (Qargs, "args");
7554 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7555 doc: /* Non-nil means delete processes immediately when they exit.
7556 A value of nil means don't delete them until `list-processes' is run. */);
7558 delete_exited_processes = 1;
7560 #ifdef subprocesses
7561 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7562 doc: /* Control type of device used to communicate with subprocesses.
7563 Values are nil to use a pipe, or t or `pty' to use a pty.
7564 The value has no effect if the system has no ptys or if all ptys are busy:
7565 then a pipe is used in any case.
7566 The value takes effect when `start-process' is called. */);
7567 Vprocess_connection_type = Qt;
7569 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7570 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7571 On some systems, when Emacs reads the output from a subprocess, the output data
7572 is read in very small blocks, potentially resulting in very poor performance.
7573 This behavior can be remedied to some extent by setting this variable to a
7574 non-nil value, as it will automatically delay reading from such processes, to
7575 allow them to produce more output before Emacs tries to read it.
7576 If the value is t, the delay is reset after each write to the process; any other
7577 non-nil value means that the delay is not reset on write.
7578 The variable takes effect when `start-process' is called. */);
7579 Vprocess_adaptive_read_buffering = Qt;
7581 defsubr (&Sprocessp);
7582 defsubr (&Sget_process);
7583 defsubr (&Sdelete_process);
7584 defsubr (&Sprocess_status);
7585 defsubr (&Sprocess_exit_status);
7586 defsubr (&Sprocess_id);
7587 defsubr (&Sprocess_name);
7588 defsubr (&Sprocess_tty_name);
7589 defsubr (&Sprocess_command);
7590 defsubr (&Sset_process_buffer);
7591 defsubr (&Sprocess_buffer);
7592 defsubr (&Sprocess_mark);
7593 defsubr (&Sset_process_filter);
7594 defsubr (&Sprocess_filter);
7595 defsubr (&Sset_process_sentinel);
7596 defsubr (&Sprocess_sentinel);
7597 defsubr (&Sset_process_window_size);
7598 defsubr (&Sset_process_inherit_coding_system_flag);
7599 defsubr (&Sset_process_query_on_exit_flag);
7600 defsubr (&Sprocess_query_on_exit_flag);
7601 defsubr (&Sprocess_contact);
7602 defsubr (&Sprocess_plist);
7603 defsubr (&Sset_process_plist);
7604 defsubr (&Sprocess_list);
7605 defsubr (&Smake_process);
7606 defsubr (&Smake_pipe_process);
7607 defsubr (&Sserial_process_configure);
7608 defsubr (&Smake_serial_process);
7609 defsubr (&Sset_network_process_option);
7610 defsubr (&Smake_network_process);
7611 defsubr (&Sformat_network_address);
7612 defsubr (&Snetwork_interface_list);
7613 defsubr (&Snetwork_interface_info);
7614 #ifdef DATAGRAM_SOCKETS
7615 defsubr (&Sprocess_datagram_address);
7616 defsubr (&Sset_process_datagram_address);
7617 #endif
7618 defsubr (&Saccept_process_output);
7619 defsubr (&Sprocess_send_region);
7620 defsubr (&Sprocess_send_string);
7621 defsubr (&Sinterrupt_process);
7622 defsubr (&Skill_process);
7623 defsubr (&Squit_process);
7624 defsubr (&Sstop_process);
7625 defsubr (&Scontinue_process);
7626 defsubr (&Sprocess_running_child_p);
7627 defsubr (&Sprocess_send_eof);
7628 defsubr (&Ssignal_process);
7629 defsubr (&Swaiting_for_user_input_p);
7630 defsubr (&Sprocess_type);
7631 defsubr (&Sinternal_default_process_sentinel);
7632 defsubr (&Sinternal_default_process_filter);
7633 defsubr (&Sset_process_coding_system);
7634 defsubr (&Sprocess_coding_system);
7635 defsubr (&Sset_process_filter_multibyte);
7636 defsubr (&Sprocess_filter_multibyte_p);
7638 #endif /* subprocesses */
7640 defsubr (&Sget_buffer_process);
7641 defsubr (&Sprocess_inherit_coding_system_flag);
7642 defsubr (&Slist_system_processes);
7643 defsubr (&Sprocess_attributes);
7646 Lisp_Object subfeatures = Qnil;
7647 const struct socket_options *sopt;
7649 #define ADD_SUBFEATURE(key, val) \
7650 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7652 #ifdef NON_BLOCKING_CONNECT
7653 ADD_SUBFEATURE (QCnowait, Qt);
7654 #endif
7655 #ifdef DATAGRAM_SOCKETS
7656 ADD_SUBFEATURE (QCtype, Qdatagram);
7657 #endif
7658 #ifdef HAVE_SEQPACKET
7659 ADD_SUBFEATURE (QCtype, Qseqpacket);
7660 #endif
7661 #ifdef HAVE_LOCAL_SOCKETS
7662 ADD_SUBFEATURE (QCfamily, Qlocal);
7663 #endif
7664 ADD_SUBFEATURE (QCfamily, Qipv4);
7665 #ifdef AF_INET6
7666 ADD_SUBFEATURE (QCfamily, Qipv6);
7667 #endif
7668 #ifdef HAVE_GETSOCKNAME
7669 ADD_SUBFEATURE (QCservice, Qt);
7670 #endif
7671 ADD_SUBFEATURE (QCserver, Qt);
7673 for (sopt = socket_options; sopt->name; sopt++)
7674 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7676 Fprovide (intern_c_string ("make-network-process"), subfeatures);