lisp/gnus/nnimap.el (nnimap-request-group-scan): Further `M-g' group fixes
[emacs.git] / src / process.c
blob1d935ba8a3ec853ffc75ae53259b1aa862e6360d
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 These lines can be removed once the GCC bug is fixed. */
140 #if __GNUC__ > 4 || (__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))
193 /* Number of events of change of status of a process. */
194 static EMACS_INT process_tick;
195 /* Number of events for which the user or sentinel has been notified. */
196 static EMACS_INT update_tick;
198 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
200 /* Only W32 has this, it really means that select can't take write mask. */
201 #ifdef BROKEN_NON_BLOCKING_CONNECT
202 #undef NON_BLOCKING_CONNECT
203 enum { SELECT_CAN_DO_WRITE_MASK = false };
204 #else
205 enum { SELECT_CAN_DO_WRITE_MASK = true };
206 #ifndef NON_BLOCKING_CONNECT
207 #ifdef HAVE_SELECT
208 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
209 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
210 #define NON_BLOCKING_CONNECT
211 #endif /* EWOULDBLOCK || EINPROGRESS */
212 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
213 #endif /* HAVE_SELECT */
214 #endif /* NON_BLOCKING_CONNECT */
215 #endif /* BROKEN_NON_BLOCKING_CONNECT */
217 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
218 this system. We need to read full packets, so we need a
219 "non-destructive" select. So we require either native select,
220 or emulation of select using FIONREAD. */
222 #ifndef BROKEN_DATAGRAM_SOCKETS
223 # if defined HAVE_SELECT || defined USABLE_FIONREAD
224 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
225 # define DATAGRAM_SOCKETS
226 # endif
227 # endif
228 #endif
230 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
231 # define HAVE_SEQPACKET
232 #endif
234 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
235 #define ADAPTIVE_READ_BUFFERING
236 #endif
238 #ifdef ADAPTIVE_READ_BUFFERING
239 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
240 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
241 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
243 /* Number of processes which have a non-zero read_output_delay,
244 and therefore might be delayed for adaptive read buffering. */
246 static int process_output_delay_count;
248 /* True if any process has non-nil read_output_skip. */
250 static bool process_output_skip;
252 #else
253 #define process_output_delay_count 0
254 #endif
256 static void create_process (Lisp_Object, char **, Lisp_Object);
257 #ifdef USABLE_SIGIO
258 static bool keyboard_bit_set (fd_set *);
259 #endif
260 static void deactivate_process (Lisp_Object);
261 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
262 static int read_process_output (Lisp_Object, int);
263 static void handle_child_signal (int);
264 static void create_pty (Lisp_Object);
266 static Lisp_Object get_process (register Lisp_Object name);
267 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
269 /* Mask of bits indicating the descriptors that we wait for input on. */
271 static fd_set input_wait_mask;
273 /* Mask that excludes keyboard input descriptor(s). */
275 static fd_set non_keyboard_wait_mask;
277 /* Mask that excludes process input descriptor(s). */
279 static fd_set non_process_wait_mask;
281 /* Mask for selecting for write. */
283 static fd_set write_mask;
285 #ifdef NON_BLOCKING_CONNECT
286 /* Mask of bits indicating the descriptors that we wait for connect to
287 complete on. Once they complete, they are removed from this mask
288 and added to the input_wait_mask and non_keyboard_wait_mask. */
290 static fd_set connect_wait_mask;
292 /* Number of bits set in connect_wait_mask. */
293 static int num_pending_connects;
294 #endif /* NON_BLOCKING_CONNECT */
296 /* The largest descriptor currently in use for a process object; -1 if none. */
297 static int max_process_desc;
299 /* The largest descriptor currently in use for input; -1 if none. */
300 static int max_input_desc;
302 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
303 static Lisp_Object chan_process[FD_SETSIZE];
305 /* Alist of elements (NAME . PROCESS). */
306 static Lisp_Object Vprocess_alist;
308 /* Buffered-ahead input char from process, indexed by channel.
309 -1 means empty (no char is buffered).
310 Used on sys V where the only way to tell if there is any
311 output from the process is to read at least one char.
312 Always -1 on systems that support FIONREAD. */
314 static int proc_buffered_char[FD_SETSIZE];
316 /* Table of `struct coding-system' for each process. */
317 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
318 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
320 #ifdef DATAGRAM_SOCKETS
321 /* Table of `partner address' for datagram sockets. */
322 static struct sockaddr_and_len {
323 struct sockaddr *sa;
324 int len;
325 } datagram_address[FD_SETSIZE];
326 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
327 #define DATAGRAM_CONN_P(proc) \
328 (PROCESSP (proc) && \
329 XPROCESS (proc)->infd >= 0 && \
330 datagram_address[XPROCESS (proc)->infd].sa != 0)
331 #else
332 #define DATAGRAM_CHAN_P(chan) (0)
333 #define DATAGRAM_CONN_P(proc) (0)
334 #endif
336 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
337 a `for' loop which iterates over processes from Vprocess_alist. */
339 #define FOR_EACH_PROCESS(list_var, proc_var) \
340 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
342 /* These setters are used only in this file, so they can be private. */
343 static void
344 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
346 p->buffer = val;
348 static void
349 pset_command (struct Lisp_Process *p, Lisp_Object val)
351 p->command = val;
353 static void
354 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
356 p->decode_coding_system = val;
358 static void
359 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
361 p->decoding_buf = val;
363 static void
364 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
366 p->encode_coding_system = val;
368 static void
369 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
371 p->encoding_buf = val;
373 static void
374 pset_filter (struct Lisp_Process *p, Lisp_Object val)
376 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
378 static void
379 pset_log (struct Lisp_Process *p, Lisp_Object val)
381 p->log = val;
383 static void
384 pset_mark (struct Lisp_Process *p, Lisp_Object val)
386 p->mark = val;
388 static void
389 pset_name (struct Lisp_Process *p, Lisp_Object val)
391 p->name = val;
393 static void
394 pset_plist (struct Lisp_Process *p, Lisp_Object val)
396 p->plist = val;
398 static void
399 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
401 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
403 static void
404 pset_status (struct Lisp_Process *p, Lisp_Object val)
406 p->status = val;
408 static void
409 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
411 p->tty_name = val;
413 static void
414 pset_type (struct Lisp_Process *p, Lisp_Object val)
416 p->type = val;
418 static void
419 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
421 p->write_queue = val;
425 static Lisp_Object
426 make_lisp_proc (struct Lisp_Process *p)
428 return make_lisp_ptr (p, Lisp_Vectorlike);
431 static struct fd_callback_data
433 fd_callback func;
434 void *data;
435 #define FOR_READ 1
436 #define FOR_WRITE 2
437 int condition; /* Mask of the defines above. */
438 } fd_callback_info[FD_SETSIZE];
441 /* Add a file descriptor FD to be monitored for when read is possible.
442 When read is possible, call FUNC with argument DATA. */
444 void
445 add_read_fd (int fd, fd_callback func, void *data)
447 add_keyboard_wait_descriptor (fd);
449 fd_callback_info[fd].func = func;
450 fd_callback_info[fd].data = data;
451 fd_callback_info[fd].condition |= FOR_READ;
454 /* Stop monitoring file descriptor FD for when read is possible. */
456 void
457 delete_read_fd (int fd)
459 delete_keyboard_wait_descriptor (fd);
461 fd_callback_info[fd].condition &= ~FOR_READ;
462 if (fd_callback_info[fd].condition == 0)
464 fd_callback_info[fd].func = 0;
465 fd_callback_info[fd].data = 0;
469 /* Add a file descriptor FD to be monitored for when write is possible.
470 When write is possible, call FUNC with argument DATA. */
472 void
473 add_write_fd (int fd, fd_callback func, void *data)
475 FD_SET (fd, &write_mask);
476 if (fd > max_input_desc)
477 max_input_desc = fd;
479 fd_callback_info[fd].func = func;
480 fd_callback_info[fd].data = data;
481 fd_callback_info[fd].condition |= FOR_WRITE;
484 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
486 static void
487 delete_input_desc (int fd)
489 if (fd == max_input_desc)
492 fd--;
493 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
494 || FD_ISSET (fd, &write_mask)));
496 max_input_desc = fd;
500 /* Stop monitoring file descriptor FD for when write is possible. */
502 void
503 delete_write_fd (int fd)
505 FD_CLR (fd, &write_mask);
506 fd_callback_info[fd].condition &= ~FOR_WRITE;
507 if (fd_callback_info[fd].condition == 0)
509 fd_callback_info[fd].func = 0;
510 fd_callback_info[fd].data = 0;
511 delete_input_desc (fd);
516 /* Compute the Lisp form of the process status, p->status, from
517 the numeric status that was returned by `wait'. */
519 static Lisp_Object status_convert (int);
521 static void
522 update_status (struct Lisp_Process *p)
524 eassert (p->raw_status_new);
525 pset_status (p, status_convert (p->raw_status));
526 p->raw_status_new = 0;
529 /* Convert a process status word in Unix format to
530 the list that we use internally. */
532 static Lisp_Object
533 status_convert (int w)
535 if (WIFSTOPPED (w))
536 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
537 else if (WIFEXITED (w))
538 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
539 WCOREDUMP (w) ? Qt : Qnil));
540 else if (WIFSIGNALED (w))
541 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
542 WCOREDUMP (w) ? Qt : Qnil));
543 else
544 return Qrun;
547 /* Given a status-list, extract the three pieces of information
548 and store them individually through the three pointers. */
550 static void
551 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
553 Lisp_Object tem;
555 if (SYMBOLP (l))
557 *symbol = l;
558 *code = 0;
559 *coredump = 0;
561 else
563 *symbol = XCAR (l);
564 tem = XCDR (l);
565 *code = XFASTINT (XCAR (tem));
566 tem = XCDR (tem);
567 *coredump = !NILP (tem);
571 /* Return a string describing a process status list. */
573 static Lisp_Object
574 status_message (struct Lisp_Process *p)
576 Lisp_Object status = p->status;
577 Lisp_Object symbol;
578 int code;
579 bool coredump;
580 Lisp_Object string;
582 decode_status (status, &symbol, &code, &coredump);
584 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
586 char const *signame;
587 synchronize_system_messages_locale ();
588 signame = strsignal (code);
589 if (signame == 0)
590 string = build_string ("unknown");
591 else
593 int c1, c2;
595 string = build_unibyte_string (signame);
596 if (! NILP (Vlocale_coding_system))
597 string = (code_convert_string_norecord
598 (string, Vlocale_coding_system, 0));
599 c1 = STRING_CHAR (SDATA (string));
600 c2 = downcase (c1);
601 if (c1 != c2)
602 Faset (string, make_number (0), make_number (c2));
604 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
605 return concat2 (string, suffix);
607 else if (EQ (symbol, Qexit))
609 if (NETCONN1_P (p))
610 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
611 if (code == 0)
612 return build_string ("finished\n");
613 AUTO_STRING (prefix, "exited abnormally with code ");
614 string = Fnumber_to_string (make_number (code));
615 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
616 return concat3 (prefix, string, suffix);
618 else if (EQ (symbol, Qfailed))
620 AUTO_STRING (prefix, "failed with code ");
621 string = Fnumber_to_string (make_number (code));
622 AUTO_STRING (suffix, "\n");
623 return concat3 (prefix, string, suffix);
625 else
626 return Fcopy_sequence (Fsymbol_name (symbol));
629 enum { PTY_NAME_SIZE = 24 };
631 /* Open an available pty, returning a file descriptor.
632 Store into PTY_NAME the file name of the terminal corresponding to the pty.
633 Return -1 on failure. */
635 static int
636 allocate_pty (char pty_name[PTY_NAME_SIZE])
638 #ifdef HAVE_PTYS
639 int fd;
641 #ifdef PTY_ITERATION
642 PTY_ITERATION
643 #else
644 register int c, i;
645 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
646 for (i = 0; i < 16; i++)
647 #endif
649 #ifdef PTY_NAME_SPRINTF
650 PTY_NAME_SPRINTF
651 #else
652 sprintf (pty_name, "/dev/pty%c%x", c, i);
653 #endif /* no PTY_NAME_SPRINTF */
655 #ifdef PTY_OPEN
656 PTY_OPEN;
657 #else /* no PTY_OPEN */
658 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
659 #endif /* no PTY_OPEN */
661 if (fd >= 0)
663 #ifdef PTY_OPEN
664 /* Set FD's close-on-exec flag. This is needed even if
665 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
666 doesn't require support for that combination.
667 Multithreaded platforms where posix_openpt ignores
668 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
669 have a race condition between the PTY_OPEN and here. */
670 fcntl (fd, F_SETFD, FD_CLOEXEC);
671 #endif
672 /* Check to make certain that both sides are available
673 this avoids a nasty yet stupid bug in rlogins. */
674 #ifdef PTY_TTY_NAME_SPRINTF
675 PTY_TTY_NAME_SPRINTF
676 #else
677 sprintf (pty_name, "/dev/tty%c%x", c, i);
678 #endif /* no PTY_TTY_NAME_SPRINTF */
679 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
681 emacs_close (fd);
682 # ifndef __sgi
683 continue;
684 # else
685 return -1;
686 # endif /* __sgi */
688 setup_pty (fd);
689 return fd;
692 #endif /* HAVE_PTYS */
693 return -1;
696 /* Allocate basically initialized process. */
698 static struct Lisp_Process *
699 allocate_process (void)
701 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
704 static Lisp_Object
705 make_process (Lisp_Object name)
707 register Lisp_Object val, tem, name1;
708 register struct Lisp_Process *p;
709 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
710 printmax_t i;
712 p = allocate_process ();
713 /* Initialize Lisp data. Note that allocate_process initializes all
714 Lisp data to nil, so do it only for slots which should not be nil. */
715 pset_status (p, Qrun);
716 pset_mark (p, Fmake_marker ());
718 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
719 non-Lisp data, so do it only for slots which should not be zero. */
720 p->infd = -1;
721 p->outfd = -1;
722 for (i = 0; i < PROCESS_OPEN_FDS; i++)
723 p->open_fd[i] = -1;
725 #ifdef HAVE_GNUTLS
726 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
727 #endif
729 /* If name is already in use, modify it until it is unused. */
731 name1 = name;
732 for (i = 1; ; i++)
734 tem = Fget_process (name1);
735 if (NILP (tem)) break;
736 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
738 name = name1;
739 pset_name (p, name);
740 pset_sentinel (p, Qinternal_default_process_sentinel);
741 pset_filter (p, Qinternal_default_process_filter);
742 XSETPROCESS (val, p);
743 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
744 return val;
747 static void
748 remove_process (register Lisp_Object proc)
750 register Lisp_Object pair;
752 pair = Frassq (proc, Vprocess_alist);
753 Vprocess_alist = Fdelq (pair, Vprocess_alist);
755 deactivate_process (proc);
759 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
760 doc: /* Return t if OBJECT is a process. */)
761 (Lisp_Object object)
763 return PROCESSP (object) ? Qt : Qnil;
766 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
767 doc: /* Return the process named NAME, or nil if there is none. */)
768 (register Lisp_Object name)
770 if (PROCESSP (name))
771 return name;
772 CHECK_STRING (name);
773 return Fcdr (Fassoc (name, Vprocess_alist));
776 /* This is how commands for the user decode process arguments. It
777 accepts a process, a process name, a buffer, a buffer name, or nil.
778 Buffers denote the first process in the buffer, and nil denotes the
779 current buffer. */
781 static Lisp_Object
782 get_process (register Lisp_Object name)
784 register Lisp_Object proc, obj;
785 if (STRINGP (name))
787 obj = Fget_process (name);
788 if (NILP (obj))
789 obj = Fget_buffer (name);
790 if (NILP (obj))
791 error ("Process %s does not exist", SDATA (name));
793 else if (NILP (name))
794 obj = Fcurrent_buffer ();
795 else
796 obj = name;
798 /* Now obj should be either a buffer object or a process object. */
799 if (BUFFERP (obj))
801 if (NILP (BVAR (XBUFFER (obj), name)))
802 error ("Attempt to get process for a dead buffer");
803 proc = Fget_buffer_process (obj);
804 if (NILP (proc))
805 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
807 else
809 CHECK_PROCESS (obj);
810 proc = obj;
812 return proc;
816 /* Fdelete_process promises to immediately forget about the process, but in
817 reality, Emacs needs to remember those processes until they have been
818 treated by the SIGCHLD handler and waitpid has been invoked on them;
819 otherwise they might fill up the kernel's process table.
821 Some processes created by call-process are also put onto this list.
823 Members of this list are (process-ID . filename) pairs. The
824 process-ID is a number; the filename, if a string, is a file that
825 needs to be removed after the process exits. */
826 static Lisp_Object deleted_pid_list;
828 void
829 record_deleted_pid (pid_t pid, Lisp_Object filename)
831 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
832 /* GC treated elements set to nil. */
833 Fdelq (Qnil, deleted_pid_list));
837 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
838 doc: /* Delete PROCESS: kill it and forget about it immediately.
839 PROCESS may be a process, a buffer, the name of a process or buffer, or
840 nil, indicating the current buffer's process. */)
841 (register Lisp_Object process)
843 register struct Lisp_Process *p;
845 process = get_process (process);
846 p = XPROCESS (process);
848 p->raw_status_new = 0;
849 if (NETCONN1_P (p) || SERIALCONN1_P (p))
851 pset_status (p, list2 (Qexit, make_number (0)));
852 p->tick = ++process_tick;
853 status_notify (p, NULL);
854 redisplay_preserve_echo_area (13);
856 else
858 if (p->alive)
859 record_kill_process (p, Qnil);
861 if (p->infd >= 0)
863 /* Update P's status, since record_kill_process will make the
864 SIGCHLD handler update deleted_pid_list, not *P. */
865 Lisp_Object symbol;
866 if (p->raw_status_new)
867 update_status (p);
868 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
869 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
870 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
872 p->tick = ++process_tick;
873 status_notify (p, NULL);
874 redisplay_preserve_echo_area (13);
877 remove_process (process);
878 return Qnil;
881 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
882 doc: /* Return the status of PROCESS.
883 The returned value is one of the following symbols:
884 run -- for a process that is running.
885 stop -- for a process stopped but continuable.
886 exit -- for a process that has exited.
887 signal -- for a process that has got a fatal signal.
888 open -- for a network stream connection that is open.
889 listen -- for a network stream server that is listening.
890 closed -- for a network stream connection that is closed.
891 connect -- when waiting for a non-blocking connection to complete.
892 failed -- when a non-blocking connection has failed.
893 nil -- if arg is a process name and no such process exists.
894 PROCESS may be a process, a buffer, the name of a process, or
895 nil, indicating the current buffer's process. */)
896 (register Lisp_Object process)
898 register struct Lisp_Process *p;
899 register Lisp_Object status;
901 if (STRINGP (process))
902 process = Fget_process (process);
903 else
904 process = get_process (process);
906 if (NILP (process))
907 return process;
909 p = XPROCESS (process);
910 if (p->raw_status_new)
911 update_status (p);
912 status = p->status;
913 if (CONSP (status))
914 status = XCAR (status);
915 if (NETCONN1_P (p) || SERIALCONN1_P (p))
917 if (EQ (status, Qexit))
918 status = Qclosed;
919 else if (EQ (p->command, Qt))
920 status = Qstop;
921 else if (EQ (status, Qrun))
922 status = Qopen;
924 return status;
927 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
928 1, 1, 0,
929 doc: /* Return the exit status of PROCESS or the signal number that killed it.
930 If PROCESS has not yet exited or died, return 0. */)
931 (register Lisp_Object process)
933 CHECK_PROCESS (process);
934 if (XPROCESS (process)->raw_status_new)
935 update_status (XPROCESS (process));
936 if (CONSP (XPROCESS (process)->status))
937 return XCAR (XCDR (XPROCESS (process)->status));
938 return make_number (0);
941 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
942 doc: /* Return the process id of PROCESS.
943 This is the pid of the external process which PROCESS uses or talks to.
944 For a network connection, this value is nil. */)
945 (register Lisp_Object process)
947 pid_t pid;
949 CHECK_PROCESS (process);
950 pid = XPROCESS (process)->pid;
951 return (pid ? make_fixnum_or_float (pid) : Qnil);
954 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
955 doc: /* Return the name of PROCESS, as a string.
956 This is the name of the program invoked in PROCESS,
957 possibly modified to make it unique among process names. */)
958 (register Lisp_Object process)
960 CHECK_PROCESS (process);
961 return XPROCESS (process)->name;
964 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
965 doc: /* Return the command that was executed to start PROCESS.
966 This is a list of strings, the first string being the program executed
967 and the rest of the strings being the arguments given to it.
968 For a network or serial process, this is nil (process is running) or t
969 \(process is stopped). */)
970 (register Lisp_Object process)
972 CHECK_PROCESS (process);
973 return XPROCESS (process)->command;
976 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
977 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
978 This is the terminal that the process itself reads and writes on,
979 not the name of the pty that Emacs uses to talk with that terminal. */)
980 (register Lisp_Object process)
982 CHECK_PROCESS (process);
983 return XPROCESS (process)->tty_name;
986 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
987 2, 2, 0,
988 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
989 Return BUFFER. */)
990 (register Lisp_Object process, Lisp_Object buffer)
992 struct Lisp_Process *p;
994 CHECK_PROCESS (process);
995 if (!NILP (buffer))
996 CHECK_BUFFER (buffer);
997 p = XPROCESS (process);
998 pset_buffer (p, buffer);
999 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1000 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1001 setup_process_coding_systems (process);
1002 return buffer;
1005 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1006 1, 1, 0,
1007 doc: /* Return the buffer PROCESS is associated with.
1008 The default process filter inserts output from PROCESS into this buffer. */)
1009 (register Lisp_Object process)
1011 CHECK_PROCESS (process);
1012 return XPROCESS (process)->buffer;
1015 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1016 1, 1, 0,
1017 doc: /* Return the marker for the end of the last output from PROCESS. */)
1018 (register Lisp_Object process)
1020 CHECK_PROCESS (process);
1021 return XPROCESS (process)->mark;
1024 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1025 2, 2, 0,
1026 doc: /* Give PROCESS the filter function FILTER; nil means default.
1027 A value of t means stop accepting output from the process.
1029 When a process has a non-default filter, its buffer is not used for output.
1030 Instead, each time it does output, the entire string of output is
1031 passed to the filter.
1033 The filter gets two arguments: the process and the string of output.
1034 The string argument is normally a multibyte string, except:
1035 - if the process's input coding system is no-conversion or raw-text,
1036 it is a unibyte string (the non-converted input), or else
1037 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1038 string (the result of converting the decoded input multibyte
1039 string to unibyte with `string-make-unibyte'). */)
1040 (register Lisp_Object process, Lisp_Object filter)
1042 struct Lisp_Process *p;
1044 CHECK_PROCESS (process);
1045 p = XPROCESS (process);
1047 /* Don't signal an error if the process's input file descriptor
1048 is closed. This could make debugging Lisp more difficult,
1049 for example when doing something like
1051 (setq process (start-process ...))
1052 (debug)
1053 (set-process-filter process ...) */
1055 if (NILP (filter))
1056 filter = Qinternal_default_process_filter;
1058 if (p->infd >= 0)
1060 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1062 FD_CLR (p->infd, &input_wait_mask);
1063 FD_CLR (p->infd, &non_keyboard_wait_mask);
1065 else if (EQ (p->filter, Qt)
1066 /* Network or serial process not stopped: */
1067 && !EQ (p->command, Qt))
1069 FD_SET (p->infd, &input_wait_mask);
1070 FD_SET (p->infd, &non_keyboard_wait_mask);
1074 pset_filter (p, filter);
1075 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1076 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1077 setup_process_coding_systems (process);
1078 return filter;
1081 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1082 1, 1, 0,
1083 doc: /* Return the filter function of PROCESS.
1084 See `set-process-filter' for more info on filter functions. */)
1085 (register Lisp_Object process)
1087 CHECK_PROCESS (process);
1088 return XPROCESS (process)->filter;
1091 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1092 2, 2, 0,
1093 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1094 The sentinel is called as a function when the process changes state.
1095 It gets two arguments: the process, and a string describing the change. */)
1096 (register Lisp_Object process, Lisp_Object sentinel)
1098 struct Lisp_Process *p;
1100 CHECK_PROCESS (process);
1101 p = XPROCESS (process);
1103 if (NILP (sentinel))
1104 sentinel = Qinternal_default_process_sentinel;
1106 pset_sentinel (p, sentinel);
1107 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1108 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1109 return sentinel;
1112 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1113 1, 1, 0,
1114 doc: /* Return the sentinel of PROCESS.
1115 See `set-process-sentinel' for more info on sentinels. */)
1116 (register Lisp_Object process)
1118 CHECK_PROCESS (process);
1119 return XPROCESS (process)->sentinel;
1122 DEFUN ("set-process-window-size", Fset_process_window_size,
1123 Sset_process_window_size, 3, 3, 0,
1124 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1125 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1127 CHECK_PROCESS (process);
1129 /* All known platforms store window sizes as 'unsigned short'. */
1130 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1131 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1133 if (XPROCESS (process)->infd < 0
1134 || (set_window_size (XPROCESS (process)->infd,
1135 XINT (height), XINT (width))
1136 < 0))
1137 return Qnil;
1138 else
1139 return Qt;
1142 DEFUN ("set-process-inherit-coding-system-flag",
1143 Fset_process_inherit_coding_system_flag,
1144 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1145 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1146 If the second argument FLAG is non-nil, then the variable
1147 `buffer-file-coding-system' of the buffer associated with PROCESS
1148 will be bound to the value of the coding system used to decode
1149 the process output.
1151 This is useful when the coding system specified for the process buffer
1152 leaves either the character code conversion or the end-of-line conversion
1153 unspecified, or if the coding system used to decode the process output
1154 is more appropriate for saving the process buffer.
1156 Binding the variable `inherit-process-coding-system' to non-nil before
1157 starting the process is an alternative way of setting the inherit flag
1158 for the process which will run.
1160 This function returns FLAG. */)
1161 (register Lisp_Object process, Lisp_Object flag)
1163 CHECK_PROCESS (process);
1164 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1165 return flag;
1168 DEFUN ("set-process-query-on-exit-flag",
1169 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1170 2, 2, 0,
1171 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1172 If the second argument FLAG is non-nil, Emacs will query the user before
1173 exiting or killing a buffer if PROCESS is running. This function
1174 returns FLAG. */)
1175 (register Lisp_Object process, Lisp_Object flag)
1177 CHECK_PROCESS (process);
1178 XPROCESS (process)->kill_without_query = NILP (flag);
1179 return flag;
1182 DEFUN ("process-query-on-exit-flag",
1183 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1184 1, 1, 0,
1185 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1186 (register Lisp_Object process)
1188 CHECK_PROCESS (process);
1189 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1192 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1193 1, 2, 0,
1194 doc: /* Return the contact info of PROCESS; t for a real child.
1195 For a network or serial connection, the value depends on the optional
1196 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1197 SERVICE) for a network connection or (PORT SPEED) for a serial
1198 connection. If KEY is t, the complete contact information for the
1199 connection is returned, else the specific value for the keyword KEY is
1200 returned. See `make-network-process' or `make-serial-process' for a
1201 list of keywords. */)
1202 (register Lisp_Object process, Lisp_Object key)
1204 Lisp_Object contact;
1206 CHECK_PROCESS (process);
1207 contact = XPROCESS (process)->childp;
1209 #ifdef DATAGRAM_SOCKETS
1210 if (DATAGRAM_CONN_P (process)
1211 && (EQ (key, Qt) || EQ (key, QCremote)))
1212 contact = Fplist_put (contact, QCremote,
1213 Fprocess_datagram_address (process));
1214 #endif
1216 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1217 return contact;
1218 if (NILP (key) && NETCONN_P (process))
1219 return list2 (Fplist_get (contact, QChost),
1220 Fplist_get (contact, QCservice));
1221 if (NILP (key) && SERIALCONN_P (process))
1222 return list2 (Fplist_get (contact, QCport),
1223 Fplist_get (contact, QCspeed));
1224 return Fplist_get (contact, key);
1227 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1228 1, 1, 0,
1229 doc: /* Return the plist of PROCESS. */)
1230 (register Lisp_Object process)
1232 CHECK_PROCESS (process);
1233 return XPROCESS (process)->plist;
1236 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1237 2, 2, 0,
1238 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1239 (register Lisp_Object process, Lisp_Object plist)
1241 CHECK_PROCESS (process);
1242 CHECK_LIST (plist);
1244 pset_plist (XPROCESS (process), plist);
1245 return plist;
1248 #if 0 /* Turned off because we don't currently record this info
1249 in the process. Perhaps add it. */
1250 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1251 doc: /* Return the connection type of PROCESS.
1252 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1253 a socket connection. */)
1254 (Lisp_Object process)
1256 return XPROCESS (process)->type;
1258 #endif
1260 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1261 doc: /* Return the connection type of PROCESS.
1262 The value is either the symbol `real', `network', or `serial'.
1263 PROCESS may be a process, a buffer, the name of a process or buffer, or
1264 nil, indicating the current buffer's process. */)
1265 (Lisp_Object process)
1267 Lisp_Object proc;
1268 proc = get_process (process);
1269 return XPROCESS (proc)->type;
1272 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1273 1, 2, 0,
1274 doc: /* Convert network ADDRESS from internal format to a string.
1275 A 4 or 5 element vector represents an IPv4 address (with port number).
1276 An 8 or 9 element vector represents an IPv6 address (with port number).
1277 If optional second argument OMIT-PORT is non-nil, don't include a port
1278 number in the string, even when present in ADDRESS.
1279 Returns nil if format of ADDRESS is invalid. */)
1280 (Lisp_Object address, Lisp_Object omit_port)
1282 if (NILP (address))
1283 return Qnil;
1285 if (STRINGP (address)) /* AF_LOCAL */
1286 return address;
1288 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1290 register struct Lisp_Vector *p = XVECTOR (address);
1291 ptrdiff_t size = p->header.size;
1292 Lisp_Object args[10];
1293 int nargs, i;
1294 char const *format;
1296 if (size == 4 || (size == 5 && !NILP (omit_port)))
1298 format = "%d.%d.%d.%d";
1299 nargs = 4;
1301 else if (size == 5)
1303 format = "%d.%d.%d.%d:%d";
1304 nargs = 5;
1306 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1308 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1309 nargs = 8;
1311 else if (size == 9)
1313 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1314 nargs = 9;
1316 else
1317 return Qnil;
1319 AUTO_STRING (format_obj, format);
1320 args[0] = format_obj;
1322 for (i = 0; i < nargs; i++)
1324 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1325 return Qnil;
1327 if (nargs <= 5 /* IPv4 */
1328 && i < 4 /* host, not port */
1329 && XINT (p->contents[i]) > 255)
1330 return Qnil;
1332 args[i + 1] = p->contents[i];
1335 return Fformat (nargs + 1, args);
1338 if (CONSP (address))
1340 AUTO_STRING (format, "<Family %d>");
1341 return CALLN (Fformat, format, Fcar (address));
1344 return Qnil;
1347 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1348 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1349 (void)
1351 return Fmapcar (Qcdr, Vprocess_alist);
1354 /* Starting asynchronous inferior processes. */
1356 static void start_process_unwind (Lisp_Object proc);
1358 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1359 doc: /* Start a program in a subprocess. Return the process object for it.
1360 NAME is name for process. It is modified if necessary to make it unique.
1361 BUFFER is the buffer (or buffer name) to associate with the process.
1363 Process output (both standard output and standard error streams) goes
1364 at end of BUFFER, unless you specify an output stream or filter
1365 function to handle the output. BUFFER may also be nil, meaning that
1366 this process is not associated with any buffer.
1368 PROGRAM is the program file name. It is searched for in `exec-path'
1369 (which see). If nil, just associate a pty with the buffer. Remaining
1370 arguments are strings to give program as arguments.
1372 If you want to separate standard output from standard error, invoke
1373 the command through a shell and redirect one of them using the shell
1374 syntax.
1376 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1377 (ptrdiff_t nargs, Lisp_Object *args)
1379 Lisp_Object buffer, name, program, proc, current_dir, tem;
1380 unsigned char **new_argv;
1381 ptrdiff_t i;
1382 ptrdiff_t count = SPECPDL_INDEX ();
1383 USE_SAFE_ALLOCA;
1385 buffer = args[1];
1386 if (!NILP (buffer))
1387 buffer = Fget_buffer_create (buffer);
1389 /* Make sure that the child will be able to chdir to the current
1390 buffer's current directory, or its unhandled equivalent. We
1391 can't just have the child check for an error when it does the
1392 chdir, since it's in a vfork.
1394 We have to GCPRO around this because Fexpand_file_name and
1395 Funhandled_file_name_directory might call a file name handling
1396 function. The argument list is protected by the caller, so all
1397 we really have to worry about is buffer. */
1399 struct gcpro gcpro1;
1400 GCPRO1 (buffer);
1401 current_dir = encode_current_directory ();
1402 UNGCPRO;
1405 name = args[0];
1406 CHECK_STRING (name);
1408 program = args[2];
1410 if (!NILP (program))
1411 CHECK_STRING (program);
1413 proc = make_process (name);
1414 /* If an error occurs and we can't start the process, we want to
1415 remove it from the process list. This means that each error
1416 check in create_process doesn't need to call remove_process
1417 itself; it's all taken care of here. */
1418 record_unwind_protect (start_process_unwind, proc);
1420 pset_childp (XPROCESS (proc), Qt);
1421 pset_plist (XPROCESS (proc), Qnil);
1422 pset_type (XPROCESS (proc), Qreal);
1423 pset_buffer (XPROCESS (proc), buffer);
1424 pset_sentinel (XPROCESS (proc), Qinternal_default_process_sentinel);
1425 pset_filter (XPROCESS (proc), Qinternal_default_process_filter);
1426 pset_command (XPROCESS (proc), Flist (nargs - 2, args + 2));
1428 #ifdef HAVE_GNUTLS
1429 /* AKA GNUTLS_INITSTAGE(proc). */
1430 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1431 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1432 #endif
1434 #ifdef ADAPTIVE_READ_BUFFERING
1435 XPROCESS (proc)->adaptive_read_buffering
1436 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1437 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1438 #endif
1440 /* Make the process marker point into the process buffer (if any). */
1441 if (BUFFERP (buffer))
1442 set_marker_both (XPROCESS (proc)->mark, buffer,
1443 BUF_ZV (XBUFFER (buffer)),
1444 BUF_ZV_BYTE (XBUFFER (buffer)));
1447 /* Decide coding systems for communicating with the process. Here
1448 we don't setup the structure coding_system nor pay attention to
1449 unibyte mode. They are done in create_process. */
1451 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1452 Lisp_Object coding_systems = Qt;
1453 Lisp_Object val, *args2;
1454 struct gcpro gcpro1, gcpro2;
1456 val = Vcoding_system_for_read;
1457 if (NILP (val))
1459 SAFE_ALLOCA_LISP (args2, nargs + 1);
1460 args2[0] = Qstart_process;
1461 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1462 GCPRO2 (proc, current_dir);
1463 if (!NILP (program))
1464 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1465 UNGCPRO;
1466 if (CONSP (coding_systems))
1467 val = XCAR (coding_systems);
1468 else if (CONSP (Vdefault_process_coding_system))
1469 val = XCAR (Vdefault_process_coding_system);
1471 pset_decode_coding_system (XPROCESS (proc), val);
1473 val = Vcoding_system_for_write;
1474 if (NILP (val))
1476 if (EQ (coding_systems, Qt))
1478 SAFE_ALLOCA_LISP (args2, nargs + 1);
1479 args2[0] = Qstart_process;
1480 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1481 GCPRO2 (proc, current_dir);
1482 if (!NILP (program))
1483 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1484 UNGCPRO;
1486 if (CONSP (coding_systems))
1487 val = XCDR (coding_systems);
1488 else if (CONSP (Vdefault_process_coding_system))
1489 val = XCDR (Vdefault_process_coding_system);
1491 pset_encode_coding_system (XPROCESS (proc), val);
1492 /* Note: At this moment, the above coding system may leave
1493 text-conversion or eol-conversion unspecified. They will be
1494 decided after we read output from the process and decode it by
1495 some coding system, or just before we actually send a text to
1496 the process. */
1500 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1501 XPROCESS (proc)->decoding_carryover = 0;
1502 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1504 XPROCESS (proc)->inherit_coding_system_flag
1505 = !(NILP (buffer) || !inherit_process_coding_system);
1507 if (!NILP (program))
1509 /* If program file name is not absolute, search our path for it.
1510 Put the name we will really use in TEM. */
1511 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1512 && !(SCHARS (program) > 1
1513 && IS_DEVICE_SEP (SREF (program, 1))))
1515 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1517 tem = Qnil;
1518 GCPRO4 (name, program, buffer, current_dir);
1519 openp (Vexec_path, program, Vexec_suffixes, &tem,
1520 make_number (X_OK), false);
1521 UNGCPRO;
1522 if (NILP (tem))
1523 report_file_error ("Searching for program", program);
1524 tem = Fexpand_file_name (tem, Qnil);
1526 else
1528 if (!NILP (Ffile_directory_p (program)))
1529 error ("Specified program for new process is a directory");
1530 tem = program;
1533 /* Remove "/:" from TEM. */
1534 tem = remove_slash_colon (tem);
1537 Lisp_Object arg_encoding = Qnil;
1538 struct gcpro gcpro1;
1539 GCPRO1 (tem);
1541 /* Encode the file name and put it in NEW_ARGV.
1542 That's where the child will use it to execute the program. */
1543 tem = list1 (ENCODE_FILE (tem));
1545 /* Here we encode arguments by the coding system used for sending
1546 data to the process. We don't support using different coding
1547 systems for encoding arguments and for encoding data sent to the
1548 process. */
1550 for (i = 3; i < nargs; i++)
1552 tem = Fcons (args[i], tem);
1553 CHECK_STRING (XCAR (tem));
1554 if (STRING_MULTIBYTE (XCAR (tem)))
1556 if (NILP (arg_encoding))
1557 arg_encoding = (complement_process_encoding_system
1558 (XPROCESS (proc)->encode_coding_system));
1559 XSETCAR (tem,
1560 code_convert_string_norecord
1561 (XCAR (tem), arg_encoding, 1));
1565 UNGCPRO;
1568 /* Now that everything is encoded we can collect the strings into
1569 NEW_ARGV. */
1570 SAFE_NALLOCA (new_argv, 1, nargs - 1);
1571 new_argv[nargs - 2] = 0;
1573 for (i = nargs - 2; i-- != 0; )
1575 new_argv[i] = SDATA (XCAR (tem));
1576 tem = XCDR (tem);
1579 create_process (proc, (char **) new_argv, current_dir);
1581 else
1582 create_pty (proc);
1584 SAFE_FREE ();
1585 return unbind_to (count, proc);
1588 /* This function is the unwind_protect form for Fstart_process. If
1589 PROC doesn't have its pid set, then we know someone has signaled
1590 an error and the process wasn't started successfully, so we should
1591 remove it from the process list. */
1592 static void
1593 start_process_unwind (Lisp_Object proc)
1595 if (!PROCESSP (proc))
1596 emacs_abort ();
1598 /* Was PROC started successfully?
1599 -2 is used for a pty with no process, eg for gdb. */
1600 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1601 remove_process (proc);
1604 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1606 static void
1607 close_process_fd (int *fd_addr)
1609 int fd = *fd_addr;
1610 if (0 <= fd)
1612 *fd_addr = -1;
1613 emacs_close (fd);
1617 /* Indexes of file descriptors in open_fds. */
1618 enum
1620 /* The pipe from Emacs to its subprocess. */
1621 SUBPROCESS_STDIN,
1622 WRITE_TO_SUBPROCESS,
1624 /* The main pipe from the subprocess to Emacs. */
1625 READ_FROM_SUBPROCESS,
1626 SUBPROCESS_STDOUT,
1628 /* The pipe from the subprocess to Emacs that is closed when the
1629 subprocess execs. */
1630 READ_FROM_EXEC_MONITOR,
1631 EXEC_MONITOR_OUTPUT
1634 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1636 static void
1637 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1639 struct Lisp_Process *p = XPROCESS (process);
1640 int inchannel, outchannel;
1641 pid_t pid;
1642 int vfork_errno;
1643 int forkin, forkout;
1644 bool pty_flag = 0;
1645 char pty_name[PTY_NAME_SIZE];
1646 Lisp_Object lisp_pty_name = Qnil;
1647 sigset_t oldset;
1649 inchannel = outchannel = -1;
1651 if (!NILP (Vprocess_connection_type))
1652 outchannel = inchannel = allocate_pty (pty_name);
1654 if (inchannel >= 0)
1656 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1657 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1658 /* On most USG systems it does not work to open the pty's tty here,
1659 then close it and reopen it in the child. */
1660 /* Don't let this terminal become our controlling terminal
1661 (in case we don't have one). */
1662 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1663 if (forkin < 0)
1664 report_file_error ("Opening pty", Qnil);
1665 p->open_fd[SUBPROCESS_STDIN] = forkin;
1666 #else
1667 forkin = forkout = -1;
1668 #endif /* not USG, or USG_SUBTTY_WORKS */
1669 pty_flag = 1;
1670 lisp_pty_name = build_string (pty_name);
1672 else
1674 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1675 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1676 report_file_error ("Creating pipe", Qnil);
1677 forkin = p->open_fd[SUBPROCESS_STDIN];
1678 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1679 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1680 forkout = p->open_fd[SUBPROCESS_STDOUT];
1683 #ifndef WINDOWSNT
1684 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1685 report_file_error ("Creating pipe", Qnil);
1686 #endif
1688 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1689 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1691 /* Record this as an active process, with its channels. */
1692 chan_process[inchannel] = process;
1693 p->infd = inchannel;
1694 p->outfd = outchannel;
1696 /* Previously we recorded the tty descriptor used in the subprocess.
1697 It was only used for getting the foreground tty process, so now
1698 we just reopen the device (see emacs_get_tty_pgrp) as this is
1699 more portable (see USG_SUBTTY_WORKS above). */
1701 p->pty_flag = pty_flag;
1702 pset_status (p, Qrun);
1704 FD_SET (inchannel, &input_wait_mask);
1705 FD_SET (inchannel, &non_keyboard_wait_mask);
1706 if (inchannel > max_process_desc)
1707 max_process_desc = inchannel;
1709 /* This may signal an error. */
1710 setup_process_coding_systems (process);
1712 block_input ();
1713 block_child_signal (&oldset);
1715 #ifndef WINDOWSNT
1716 /* vfork, and prevent local vars from being clobbered by the vfork. */
1718 Lisp_Object volatile current_dir_volatile = current_dir;
1719 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1720 char **volatile new_argv_volatile = new_argv;
1721 int volatile forkin_volatile = forkin;
1722 int volatile forkout_volatile = forkout;
1723 struct Lisp_Process *p_volatile = p;
1725 pid = vfork ();
1727 current_dir = current_dir_volatile;
1728 lisp_pty_name = lisp_pty_name_volatile;
1729 new_argv = new_argv_volatile;
1730 forkin = forkin_volatile;
1731 forkout = forkout_volatile;
1732 p = p_volatile;
1734 pty_flag = p->pty_flag;
1737 if (pid == 0)
1738 #endif /* not WINDOWSNT */
1740 int xforkin = forkin;
1741 int xforkout = forkout;
1743 /* Make the pty be the controlling terminal of the process. */
1744 #ifdef HAVE_PTYS
1745 /* First, disconnect its current controlling terminal. */
1746 /* We tried doing setsid only if pty_flag, but it caused
1747 process_set_signal to fail on SGI when using a pipe. */
1748 setsid ();
1749 /* Make the pty's terminal the controlling terminal. */
1750 if (pty_flag && xforkin >= 0)
1752 #ifdef TIOCSCTTY
1753 /* We ignore the return value
1754 because faith@cs.unc.edu says that is necessary on Linux. */
1755 ioctl (xforkin, TIOCSCTTY, 0);
1756 #endif
1758 #if defined (LDISC1)
1759 if (pty_flag && xforkin >= 0)
1761 struct termios t;
1762 tcgetattr (xforkin, &t);
1763 t.c_lflag = LDISC1;
1764 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1765 emacs_perror ("create_process/tcsetattr LDISC1");
1767 #else
1768 #if defined (NTTYDISC) && defined (TIOCSETD)
1769 if (pty_flag && xforkin >= 0)
1771 /* Use new line discipline. */
1772 int ldisc = NTTYDISC;
1773 ioctl (xforkin, TIOCSETD, &ldisc);
1775 #endif
1776 #endif
1777 #ifdef TIOCNOTTY
1778 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1779 can do TIOCSPGRP only to the process's controlling tty. */
1780 if (pty_flag)
1782 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1783 I can't test it since I don't have 4.3. */
1784 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1785 if (j >= 0)
1787 ioctl (j, TIOCNOTTY, 0);
1788 emacs_close (j);
1791 #endif /* TIOCNOTTY */
1793 #if !defined (DONT_REOPEN_PTY)
1794 /*** There is a suggestion that this ought to be a
1795 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1796 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1797 that system does seem to need this code, even though
1798 both TIOCSCTTY is defined. */
1799 /* Now close the pty (if we had it open) and reopen it.
1800 This makes the pty the controlling terminal of the subprocess. */
1801 if (pty_flag)
1804 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1805 would work? */
1806 if (xforkin >= 0)
1807 emacs_close (xforkin);
1808 xforkout = xforkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1810 if (xforkin < 0)
1812 emacs_perror (SSDATA (lisp_pty_name));
1813 _exit (EXIT_CANCELED);
1817 #endif /* not DONT_REOPEN_PTY */
1819 #ifdef SETUP_SLAVE_PTY
1820 if (pty_flag)
1822 SETUP_SLAVE_PTY;
1824 #endif /* SETUP_SLAVE_PTY */
1825 #endif /* HAVE_PTYS */
1827 signal (SIGINT, SIG_DFL);
1828 signal (SIGQUIT, SIG_DFL);
1829 #ifdef SIGPROF
1830 signal (SIGPROF, SIG_DFL);
1831 #endif
1833 /* Emacs ignores SIGPIPE, but the child should not. */
1834 signal (SIGPIPE, SIG_DFL);
1836 /* Stop blocking SIGCHLD in the child. */
1837 unblock_child_signal (&oldset);
1839 if (pty_flag)
1840 child_setup_tty (xforkout);
1841 #ifdef WINDOWSNT
1842 pid = child_setup (xforkin, xforkout, xforkout, new_argv, 1, current_dir);
1843 #else /* not WINDOWSNT */
1844 child_setup (xforkin, xforkout, xforkout, new_argv, 1, current_dir);
1845 #endif /* not WINDOWSNT */
1848 /* Back in the parent process. */
1850 vfork_errno = errno;
1851 p->pid = pid;
1852 if (pid >= 0)
1853 p->alive = 1;
1855 /* Stop blocking in the parent. */
1856 unblock_child_signal (&oldset);
1857 unblock_input ();
1859 if (pid < 0)
1860 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1861 else
1863 /* vfork succeeded. */
1865 /* Close the pipe ends that the child uses, or the child's pty. */
1866 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
1867 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
1869 #ifdef WINDOWSNT
1870 register_child (pid, inchannel);
1871 #endif /* WINDOWSNT */
1873 pset_tty_name (p, lisp_pty_name);
1875 #ifndef WINDOWSNT
1876 /* Wait for child_setup to complete in case that vfork is
1877 actually defined as fork. The descriptor
1878 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1879 of a pipe is closed at the child side either by close-on-exec
1880 on successful execve or the _exit call in child_setup. */
1882 char dummy;
1884 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
1885 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
1886 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
1888 #endif
1892 static void
1893 create_pty (Lisp_Object process)
1895 struct Lisp_Process *p = XPROCESS (process);
1896 char pty_name[PTY_NAME_SIZE];
1897 int pty_fd = NILP (Vprocess_connection_type) ? -1 : allocate_pty (pty_name);
1899 if (pty_fd >= 0)
1901 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
1902 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1903 /* On most USG systems it does not work to open the pty's tty here,
1904 then close it and reopen it in the child. */
1905 /* Don't let this terminal become our controlling terminal
1906 (in case we don't have one). */
1907 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1908 if (forkout < 0)
1909 report_file_error ("Opening pty", Qnil);
1910 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
1911 #if defined (DONT_REOPEN_PTY)
1912 /* In the case that vfork is defined as fork, the parent process
1913 (Emacs) may send some data before the child process completes
1914 tty options setup. So we setup tty before forking. */
1915 child_setup_tty (forkout);
1916 #endif /* DONT_REOPEN_PTY */
1917 #endif /* not USG, or USG_SUBTTY_WORKS */
1919 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
1921 /* Record this as an active process, with its channels.
1922 As a result, child_setup will close Emacs's side of the pipes. */
1923 chan_process[pty_fd] = process;
1924 p->infd = pty_fd;
1925 p->outfd = pty_fd;
1927 /* Previously we recorded the tty descriptor used in the subprocess.
1928 It was only used for getting the foreground tty process, so now
1929 we just reopen the device (see emacs_get_tty_pgrp) as this is
1930 more portable (see USG_SUBTTY_WORKS above). */
1932 p->pty_flag = 1;
1933 pset_status (p, Qrun);
1934 setup_process_coding_systems (process);
1936 FD_SET (pty_fd, &input_wait_mask);
1937 FD_SET (pty_fd, &non_keyboard_wait_mask);
1938 if (pty_fd > max_process_desc)
1939 max_process_desc = pty_fd;
1941 pset_tty_name (p, build_string (pty_name));
1944 p->pid = -2;
1948 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1949 The address family of sa is not included in the result. */
1951 Lisp_Object
1952 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
1954 Lisp_Object address;
1955 int i;
1956 unsigned char *cp;
1957 register struct Lisp_Vector *p;
1959 /* Workaround for a bug in getsockname on BSD: Names bound to
1960 sockets in the UNIX domain are inaccessible; getsockname returns
1961 a zero length name. */
1962 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
1963 return empty_unibyte_string;
1965 switch (sa->sa_family)
1967 case AF_INET:
1969 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
1970 len = sizeof (sin->sin_addr) + 1;
1971 address = Fmake_vector (make_number (len), Qnil);
1972 p = XVECTOR (address);
1973 p->contents[--len] = make_number (ntohs (sin->sin_port));
1974 cp = (unsigned char *) &sin->sin_addr;
1975 break;
1977 #ifdef AF_INET6
1978 case AF_INET6:
1980 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
1981 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
1982 len = sizeof (sin6->sin6_addr) / 2 + 1;
1983 address = Fmake_vector (make_number (len), Qnil);
1984 p = XVECTOR (address);
1985 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
1986 for (i = 0; i < len; i++)
1987 p->contents[i] = make_number (ntohs (ip6[i]));
1988 return address;
1990 #endif
1991 #ifdef HAVE_LOCAL_SOCKETS
1992 case AF_LOCAL:
1994 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
1995 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
1996 /* If the first byte is NUL, the name is a Linux abstract
1997 socket name, and the name can contain embedded NULs. If
1998 it's not, we have a NUL-terminated string. Be careful not
1999 to walk past the end of the object looking for the name
2000 terminator, however. */
2001 if (name_length > 0 && sockun->sun_path[0] != '\0')
2003 const char *terminator
2004 = memchr (sockun->sun_path, '\0', name_length);
2006 if (terminator)
2007 name_length = terminator - (const char *) sockun->sun_path;
2010 return make_unibyte_string (sockun->sun_path, name_length);
2012 #endif
2013 default:
2014 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2015 address = Fcons (make_number (sa->sa_family),
2016 Fmake_vector (make_number (len), Qnil));
2017 p = XVECTOR (XCDR (address));
2018 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2019 break;
2022 i = 0;
2023 while (i < len)
2024 p->contents[i++] = make_number (*cp++);
2026 return address;
2030 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2032 static int
2033 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2035 register struct Lisp_Vector *p;
2037 if (VECTORP (address))
2039 p = XVECTOR (address);
2040 if (p->header.size == 5)
2042 *familyp = AF_INET;
2043 return sizeof (struct sockaddr_in);
2045 #ifdef AF_INET6
2046 else if (p->header.size == 9)
2048 *familyp = AF_INET6;
2049 return sizeof (struct sockaddr_in6);
2051 #endif
2053 #ifdef HAVE_LOCAL_SOCKETS
2054 else if (STRINGP (address))
2056 *familyp = AF_LOCAL;
2057 return sizeof (struct sockaddr_un);
2059 #endif
2060 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2061 && VECTORP (XCDR (address)))
2063 struct sockaddr *sa;
2064 p = XVECTOR (XCDR (address));
2065 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2066 return 0;
2067 *familyp = XINT (XCAR (address));
2068 return p->header.size + sizeof (sa->sa_family);
2070 return 0;
2073 /* Convert an address object (vector or string) to an internal sockaddr.
2075 The address format has been basically validated by
2076 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2077 it could have come from user data. So if FAMILY is not valid,
2078 we return after zeroing *SA. */
2080 static void
2081 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2083 register struct Lisp_Vector *p;
2084 register unsigned char *cp = NULL;
2085 register int i;
2086 EMACS_INT hostport;
2088 memset (sa, 0, len);
2090 if (VECTORP (address))
2092 p = XVECTOR (address);
2093 if (family == AF_INET)
2095 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2096 len = sizeof (sin->sin_addr) + 1;
2097 hostport = XINT (p->contents[--len]);
2098 sin->sin_port = htons (hostport);
2099 cp = (unsigned char *)&sin->sin_addr;
2100 sa->sa_family = family;
2102 #ifdef AF_INET6
2103 else if (family == AF_INET6)
2105 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2106 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2107 len = sizeof (sin6->sin6_addr) + 1;
2108 hostport = XINT (p->contents[--len]);
2109 sin6->sin6_port = htons (hostport);
2110 for (i = 0; i < len; i++)
2111 if (INTEGERP (p->contents[i]))
2113 int j = XFASTINT (p->contents[i]) & 0xffff;
2114 ip6[i] = ntohs (j);
2116 sa->sa_family = family;
2117 return;
2119 #endif
2120 else
2121 return;
2123 else if (STRINGP (address))
2125 #ifdef HAVE_LOCAL_SOCKETS
2126 if (family == AF_LOCAL)
2128 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2129 cp = SDATA (address);
2130 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2131 sockun->sun_path[i] = *cp++;
2132 sa->sa_family = family;
2134 #endif
2135 return;
2137 else
2139 p = XVECTOR (XCDR (address));
2140 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2143 for (i = 0; i < len; i++)
2144 if (INTEGERP (p->contents[i]))
2145 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2148 #ifdef DATAGRAM_SOCKETS
2149 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2150 1, 1, 0,
2151 doc: /* Get the current datagram address associated with PROCESS. */)
2152 (Lisp_Object process)
2154 int channel;
2156 CHECK_PROCESS (process);
2158 if (!DATAGRAM_CONN_P (process))
2159 return Qnil;
2161 channel = XPROCESS (process)->infd;
2162 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2163 datagram_address[channel].len);
2166 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2167 2, 2, 0,
2168 doc: /* Set the datagram address for PROCESS to ADDRESS.
2169 Returns nil upon error setting address, ADDRESS otherwise. */)
2170 (Lisp_Object process, Lisp_Object address)
2172 int channel;
2173 int family, len;
2175 CHECK_PROCESS (process);
2177 if (!DATAGRAM_CONN_P (process))
2178 return Qnil;
2180 channel = XPROCESS (process)->infd;
2182 len = get_lisp_to_sockaddr_size (address, &family);
2183 if (len == 0 || datagram_address[channel].len != len)
2184 return Qnil;
2185 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2186 return address;
2188 #endif
2191 static const struct socket_options {
2192 /* The name of this option. Should be lowercase version of option
2193 name without SO_ prefix. */
2194 const char *name;
2195 /* Option level SOL_... */
2196 int optlevel;
2197 /* Option number SO_... */
2198 int optnum;
2199 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2200 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2201 } socket_options[] =
2203 #ifdef SO_BINDTODEVICE
2204 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2205 #endif
2206 #ifdef SO_BROADCAST
2207 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2208 #endif
2209 #ifdef SO_DONTROUTE
2210 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2211 #endif
2212 #ifdef SO_KEEPALIVE
2213 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2214 #endif
2215 #ifdef SO_LINGER
2216 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2217 #endif
2218 #ifdef SO_OOBINLINE
2219 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2220 #endif
2221 #ifdef SO_PRIORITY
2222 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2223 #endif
2224 #ifdef SO_REUSEADDR
2225 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2226 #endif
2227 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2230 /* Set option OPT to value VAL on socket S.
2232 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2233 Signals an error if setting a known option fails.
2236 static int
2237 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2239 char *name;
2240 const struct socket_options *sopt;
2241 int ret = 0;
2243 CHECK_SYMBOL (opt);
2245 name = SSDATA (SYMBOL_NAME (opt));
2246 for (sopt = socket_options; sopt->name; sopt++)
2247 if (strcmp (name, sopt->name) == 0)
2248 break;
2250 switch (sopt->opttype)
2252 case SOPT_BOOL:
2254 int optval;
2255 optval = NILP (val) ? 0 : 1;
2256 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2257 &optval, sizeof (optval));
2258 break;
2261 case SOPT_INT:
2263 int optval;
2264 if (TYPE_RANGED_INTEGERP (int, val))
2265 optval = XINT (val);
2266 else
2267 error ("Bad option value for %s", name);
2268 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2269 &optval, sizeof (optval));
2270 break;
2273 #ifdef SO_BINDTODEVICE
2274 case SOPT_IFNAME:
2276 char devname[IFNAMSIZ + 1];
2278 /* This is broken, at least in the Linux 2.4 kernel.
2279 To unbind, the arg must be a zero integer, not the empty string.
2280 This should work on all systems. KFS. 2003-09-23. */
2281 memset (devname, 0, sizeof devname);
2282 if (STRINGP (val))
2284 char *arg = SSDATA (val);
2285 int len = min (strlen (arg), IFNAMSIZ);
2286 memcpy (devname, arg, len);
2288 else if (!NILP (val))
2289 error ("Bad option value for %s", name);
2290 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2291 devname, IFNAMSIZ);
2292 break;
2294 #endif
2296 #ifdef SO_LINGER
2297 case SOPT_LINGER:
2299 struct linger linger;
2301 linger.l_onoff = 1;
2302 linger.l_linger = 0;
2303 if (TYPE_RANGED_INTEGERP (int, val))
2304 linger.l_linger = XINT (val);
2305 else
2306 linger.l_onoff = NILP (val) ? 0 : 1;
2307 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2308 &linger, sizeof (linger));
2309 break;
2311 #endif
2313 default:
2314 return 0;
2317 if (ret < 0)
2319 int setsockopt_errno = errno;
2320 report_file_errno ("Cannot set network option", list2 (opt, val),
2321 setsockopt_errno);
2324 return (1 << sopt->optbit);
2328 DEFUN ("set-network-process-option",
2329 Fset_network_process_option, Sset_network_process_option,
2330 3, 4, 0,
2331 doc: /* For network process PROCESS set option OPTION to value VALUE.
2332 See `make-network-process' for a list of options and values.
2333 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2334 OPTION is not a supported option, return nil instead; otherwise return t. */)
2335 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2337 int s;
2338 struct Lisp_Process *p;
2340 CHECK_PROCESS (process);
2341 p = XPROCESS (process);
2342 if (!NETCONN1_P (p))
2343 error ("Process is not a network process");
2345 s = p->infd;
2346 if (s < 0)
2347 error ("Process is not running");
2349 if (set_socket_option (s, option, value))
2351 pset_childp (p, Fplist_put (p->childp, option, value));
2352 return Qt;
2355 if (NILP (no_error))
2356 error ("Unknown or unsupported option");
2358 return Qnil;
2362 DEFUN ("serial-process-configure",
2363 Fserial_process_configure,
2364 Sserial_process_configure,
2365 0, MANY, 0,
2366 doc: /* Configure speed, bytesize, etc. of a serial process.
2368 Arguments are specified as keyword/argument pairs. Attributes that
2369 are not given are re-initialized from the process's current
2370 configuration (available via the function `process-contact') or set to
2371 reasonable default values. The following arguments are defined:
2373 :process PROCESS
2374 :name NAME
2375 :buffer BUFFER
2376 :port PORT
2377 -- Any of these arguments can be given to identify the process that is
2378 to be configured. If none of these arguments is given, the current
2379 buffer's process is used.
2381 :speed SPEED -- SPEED is the speed of the serial port in bits per
2382 second, also called baud rate. Any value can be given for SPEED, but
2383 most serial ports work only at a few defined values between 1200 and
2384 115200, with 9600 being the most common value. If SPEED is nil, the
2385 serial port is not configured any further, i.e., all other arguments
2386 are ignored. This may be useful for special serial ports such as
2387 Bluetooth-to-serial converters which can only be configured through AT
2388 commands. A value of nil for SPEED can be used only when passed
2389 through `make-serial-process' or `serial-term'.
2391 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2392 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2394 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2395 `odd' (use odd parity), or the symbol `even' (use even parity). If
2396 PARITY is not given, no parity is used.
2398 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2399 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2400 is not given or nil, 1 stopbit is used.
2402 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2403 flowcontrol to be used, which is either nil (don't use flowcontrol),
2404 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2405 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2406 flowcontrol is used.
2408 `serial-process-configure' is called by `make-serial-process' for the
2409 initial configuration of the serial port.
2411 Examples:
2413 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2415 \(serial-process-configure
2416 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2418 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2420 usage: (serial-process-configure &rest ARGS) */)
2421 (ptrdiff_t nargs, Lisp_Object *args)
2423 struct Lisp_Process *p;
2424 Lisp_Object contact = Qnil;
2425 Lisp_Object proc = Qnil;
2426 struct gcpro gcpro1;
2428 contact = Flist (nargs, args);
2429 GCPRO1 (contact);
2431 proc = Fplist_get (contact, QCprocess);
2432 if (NILP (proc))
2433 proc = Fplist_get (contact, QCname);
2434 if (NILP (proc))
2435 proc = Fplist_get (contact, QCbuffer);
2436 if (NILP (proc))
2437 proc = Fplist_get (contact, QCport);
2438 proc = get_process (proc);
2439 p = XPROCESS (proc);
2440 if (!EQ (p->type, Qserial))
2441 error ("Not a serial process");
2443 if (NILP (Fplist_get (p->childp, QCspeed)))
2445 UNGCPRO;
2446 return Qnil;
2449 serial_configure (p, contact);
2451 UNGCPRO;
2452 return Qnil;
2455 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2456 0, MANY, 0,
2457 doc: /* Create and return a serial port process.
2459 In Emacs, serial port connections are represented by process objects,
2460 so input and output work as for subprocesses, and `delete-process'
2461 closes a serial port connection. However, a serial process has no
2462 process id, it cannot be signaled, and the status codes are different
2463 from normal processes.
2465 `make-serial-process' creates a process and a buffer, on which you
2466 probably want to use `process-send-string'. Try \\[serial-term] for
2467 an interactive terminal. See below for examples.
2469 Arguments are specified as keyword/argument pairs. The following
2470 arguments are defined:
2472 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2473 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2474 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2475 the backslashes in strings).
2477 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2478 which this function calls.
2480 :name NAME -- NAME is the name of the process. If NAME is not given,
2481 the value of PORT is used.
2483 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2484 with the process. Process output goes at the end of that buffer,
2485 unless you specify an output stream or filter function to handle the
2486 output. If BUFFER is not given, the value of NAME is used.
2488 :coding CODING -- If CODING is a symbol, it specifies the coding
2489 system used for both reading and writing for this process. If CODING
2490 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2491 ENCODING is used for writing.
2493 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2494 the process is running. If BOOL is not given, query before exiting.
2496 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2497 In the stopped state, a serial process does not accept incoming data,
2498 but you can send outgoing data. The stopped state is cleared by
2499 `continue-process' and set by `stop-process'.
2501 :filter FILTER -- Install FILTER as the process filter.
2503 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2505 :plist PLIST -- Install PLIST as the initial plist of the process.
2507 :bytesize
2508 :parity
2509 :stopbits
2510 :flowcontrol
2511 -- This function calls `serial-process-configure' to handle these
2512 arguments.
2514 The original argument list, possibly modified by later configuration,
2515 is available via the function `process-contact'.
2517 Examples:
2519 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2521 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2523 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2525 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2527 usage: (make-serial-process &rest ARGS) */)
2528 (ptrdiff_t nargs, Lisp_Object *args)
2530 int fd = -1;
2531 Lisp_Object proc, contact, port;
2532 struct Lisp_Process *p;
2533 struct gcpro gcpro1;
2534 Lisp_Object name, buffer;
2535 Lisp_Object tem, val;
2536 ptrdiff_t specpdl_count;
2538 if (nargs == 0)
2539 return Qnil;
2541 contact = Flist (nargs, args);
2542 GCPRO1 (contact);
2544 port = Fplist_get (contact, QCport);
2545 if (NILP (port))
2546 error ("No port specified");
2547 CHECK_STRING (port);
2549 if (NILP (Fplist_member (contact, QCspeed)))
2550 error (":speed not specified");
2551 if (!NILP (Fplist_get (contact, QCspeed)))
2552 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2554 name = Fplist_get (contact, QCname);
2555 if (NILP (name))
2556 name = port;
2557 CHECK_STRING (name);
2558 proc = make_process (name);
2559 specpdl_count = SPECPDL_INDEX ();
2560 record_unwind_protect (remove_process, proc);
2561 p = XPROCESS (proc);
2563 fd = serial_open (port);
2564 p->open_fd[SUBPROCESS_STDIN] = fd;
2565 p->infd = fd;
2566 p->outfd = fd;
2567 if (fd > max_process_desc)
2568 max_process_desc = fd;
2569 chan_process[fd] = proc;
2571 buffer = Fplist_get (contact, QCbuffer);
2572 if (NILP (buffer))
2573 buffer = name;
2574 buffer = Fget_buffer_create (buffer);
2575 pset_buffer (p, buffer);
2577 pset_childp (p, contact);
2578 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2579 pset_type (p, Qserial);
2580 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2581 pset_filter (p, Fplist_get (contact, QCfilter));
2582 pset_log (p, Qnil);
2583 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2584 p->kill_without_query = 1;
2585 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2586 pset_command (p, Qt);
2587 eassert (! p->pty_flag);
2589 if (!EQ (p->command, Qt))
2591 FD_SET (fd, &input_wait_mask);
2592 FD_SET (fd, &non_keyboard_wait_mask);
2595 if (BUFFERP (buffer))
2597 set_marker_both (p->mark, buffer,
2598 BUF_ZV (XBUFFER (buffer)),
2599 BUF_ZV_BYTE (XBUFFER (buffer)));
2602 tem = Fplist_member (contact, QCcoding);
2603 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2604 tem = Qnil;
2606 val = Qnil;
2607 if (!NILP (tem))
2609 val = XCAR (XCDR (tem));
2610 if (CONSP (val))
2611 val = XCAR (val);
2613 else if (!NILP (Vcoding_system_for_read))
2614 val = Vcoding_system_for_read;
2615 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2616 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2617 val = Qnil;
2618 pset_decode_coding_system (p, val);
2620 val = Qnil;
2621 if (!NILP (tem))
2623 val = XCAR (XCDR (tem));
2624 if (CONSP (val))
2625 val = XCDR (val);
2627 else if (!NILP (Vcoding_system_for_write))
2628 val = Vcoding_system_for_write;
2629 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2630 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2631 val = Qnil;
2632 pset_encode_coding_system (p, val);
2634 setup_process_coding_systems (proc);
2635 pset_decoding_buf (p, empty_unibyte_string);
2636 p->decoding_carryover = 0;
2637 pset_encoding_buf (p, empty_unibyte_string);
2638 p->inherit_coding_system_flag
2639 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2641 Fserial_process_configure (nargs, args);
2643 specpdl_ptr = specpdl + specpdl_count;
2645 UNGCPRO;
2646 return proc;
2649 /* Create a network stream/datagram client/server process. Treated
2650 exactly like a normal process when reading and writing. Primary
2651 differences are in status display and process deletion. A network
2652 connection has no PID; you cannot signal it. All you can do is
2653 stop/continue it and deactivate/close it via delete-process. */
2655 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2656 0, MANY, 0,
2657 doc: /* Create and return a network server or client process.
2659 In Emacs, network connections are represented by process objects, so
2660 input and output work as for subprocesses and `delete-process' closes
2661 a network connection. However, a network process has no process id,
2662 it cannot be signaled, and the status codes are different from normal
2663 processes.
2665 Arguments are specified as keyword/argument pairs. The following
2666 arguments are defined:
2668 :name NAME -- NAME is name for process. It is modified if necessary
2669 to make it unique.
2671 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2672 with the process. Process output goes at end of that buffer, unless
2673 you specify an output stream or filter function to handle the output.
2674 BUFFER may be also nil, meaning that this process is not associated
2675 with any buffer.
2677 :host HOST -- HOST is name of the host to connect to, or its IP
2678 address. The symbol `local' specifies the local host. If specified
2679 for a server process, it must be a valid name or address for the local
2680 host, and only clients connecting to that address will be accepted.
2682 :service SERVICE -- SERVICE is name of the service desired, or an
2683 integer specifying a port number to connect to. If SERVICE is t,
2684 a random port number is selected for the server. (If Emacs was
2685 compiled with getaddrinfo, a port number can also be specified as a
2686 string, e.g. "80", as well as an integer. This is not portable.)
2688 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2689 stream type connection, `datagram' creates a datagram type connection,
2690 `seqpacket' creates a reliable datagram connection.
2692 :family FAMILY -- FAMILY is the address (and protocol) family for the
2693 service specified by HOST and SERVICE. The default (nil) is to use
2694 whatever address family (IPv4 or IPv6) that is defined for the host
2695 and port number specified by HOST and SERVICE. Other address families
2696 supported are:
2697 local -- for a local (i.e. UNIX) address specified by SERVICE.
2698 ipv4 -- use IPv4 address family only.
2699 ipv6 -- use IPv6 address family only.
2701 :local ADDRESS -- ADDRESS is the local address used for the connection.
2702 This parameter is ignored when opening a client process. When specified
2703 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2705 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2706 connection. This parameter is ignored when opening a stream server
2707 process. For a datagram server process, it specifies the initial
2708 setting of the remote datagram address. When specified for a client
2709 process, the FAMILY, HOST, and SERVICE args are ignored.
2711 The format of ADDRESS depends on the address family:
2712 - An IPv4 address is represented as an vector of integers [A B C D P]
2713 corresponding to numeric IP address A.B.C.D and port number P.
2714 - A local address is represented as a string with the address in the
2715 local address space.
2716 - An "unsupported family" address is represented by a cons (F . AV)
2717 where F is the family number and AV is a vector containing the socket
2718 address data with one element per address data byte. Do not rely on
2719 this format in portable code, as it may depend on implementation
2720 defined constants, data sizes, and data structure alignment.
2722 :coding CODING -- If CODING is a symbol, it specifies the coding
2723 system used for both reading and writing for this process. If CODING
2724 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2725 ENCODING is used for writing.
2727 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2728 return without waiting for the connection to complete; instead, the
2729 sentinel function will be called with second arg matching "open" (if
2730 successful) or "failed" when the connect completes. Default is to use
2731 a blocking connect (i.e. wait) for stream type connections.
2733 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2734 running when Emacs is exited.
2736 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2737 In the stopped state, a server process does not accept new
2738 connections, and a client process does not handle incoming traffic.
2739 The stopped state is cleared by `continue-process' and set by
2740 `stop-process'.
2742 :filter FILTER -- Install FILTER as the process filter.
2744 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2745 process filter are multibyte, otherwise they are unibyte.
2746 If this keyword is not specified, the strings are multibyte if
2747 the default value of `enable-multibyte-characters' is non-nil.
2749 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2751 :log LOG -- Install LOG as the server process log function. This
2752 function is called when the server accepts a network connection from a
2753 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2754 is the server process, CLIENT is the new process for the connection,
2755 and MESSAGE is a string.
2757 :plist PLIST -- Install PLIST as the new process's initial plist.
2759 :server QLEN -- if QLEN is non-nil, create a server process for the
2760 specified FAMILY, SERVICE, and connection type (stream or datagram).
2761 If QLEN is an integer, it is used as the max. length of the server's
2762 pending connection queue (also known as the backlog); the default
2763 queue length is 5. Default is to create a client process.
2765 The following network options can be specified for this connection:
2767 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2768 :dontroute BOOL -- Only send to directly connected hosts.
2769 :keepalive BOOL -- Send keep-alive messages on network stream.
2770 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2771 :oobinline BOOL -- Place out-of-band data in receive data stream.
2772 :priority INT -- Set protocol defined priority for sent packets.
2773 :reuseaddr BOOL -- Allow reusing a recently used local address
2774 (this is allowed by default for a server process).
2775 :bindtodevice NAME -- bind to interface NAME. Using this may require
2776 special privileges on some systems.
2778 Consult the relevant system programmer's manual pages for more
2779 information on using these options.
2782 A server process will listen for and accept connections from clients.
2783 When a client connection is accepted, a new network process is created
2784 for the connection with the following parameters:
2786 - The client's process name is constructed by concatenating the server
2787 process's NAME and a client identification string.
2788 - If the FILTER argument is non-nil, the client process will not get a
2789 separate process buffer; otherwise, the client's process buffer is a newly
2790 created buffer named after the server process's BUFFER name or process
2791 NAME concatenated with the client identification string.
2792 - The connection type and the process filter and sentinel parameters are
2793 inherited from the server process's TYPE, FILTER and SENTINEL.
2794 - The client process's contact info is set according to the client's
2795 addressing information (typically an IP address and a port number).
2796 - The client process's plist is initialized from the server's plist.
2798 Notice that the FILTER and SENTINEL args are never used directly by
2799 the server process. Also, the BUFFER argument is not used directly by
2800 the server process, but via the optional :log function, accepted (and
2801 failed) connections may be logged in the server process's buffer.
2803 The original argument list, modified with the actual connection
2804 information, is available via the `process-contact' function.
2806 usage: (make-network-process &rest ARGS) */)
2807 (ptrdiff_t nargs, Lisp_Object *args)
2809 Lisp_Object proc;
2810 Lisp_Object contact;
2811 struct Lisp_Process *p;
2812 #ifdef HAVE_GETADDRINFO
2813 struct addrinfo ai, *res, *lres;
2814 struct addrinfo hints;
2815 const char *portstring;
2816 char portbuf[128];
2817 #else /* HAVE_GETADDRINFO */
2818 struct _emacs_addrinfo
2820 int ai_family;
2821 int ai_socktype;
2822 int ai_protocol;
2823 int ai_addrlen;
2824 struct sockaddr *ai_addr;
2825 struct _emacs_addrinfo *ai_next;
2826 } ai, *res, *lres;
2827 #endif /* HAVE_GETADDRINFO */
2828 struct sockaddr_in address_in;
2829 #ifdef HAVE_LOCAL_SOCKETS
2830 struct sockaddr_un address_un;
2831 #endif
2832 int port;
2833 int ret = 0;
2834 int xerrno = 0;
2835 int s = -1, outch, inch;
2836 struct gcpro gcpro1;
2837 ptrdiff_t count = SPECPDL_INDEX ();
2838 ptrdiff_t count1;
2839 Lisp_Object colon_address; /* Either QClocal or QCremote. */
2840 Lisp_Object tem;
2841 Lisp_Object name, buffer, host, service, address;
2842 Lisp_Object filter, sentinel;
2843 bool is_non_blocking_client = 0;
2844 bool is_server = 0;
2845 int backlog = 5;
2846 int socktype;
2847 int family = -1;
2849 if (nargs == 0)
2850 return Qnil;
2852 /* Save arguments for process-contact and clone-process. */
2853 contact = Flist (nargs, args);
2854 GCPRO1 (contact);
2856 #ifdef WINDOWSNT
2857 /* Ensure socket support is loaded if available. */
2858 init_winsock (TRUE);
2859 #endif
2861 /* :type TYPE (nil: stream, datagram */
2862 tem = Fplist_get (contact, QCtype);
2863 if (NILP (tem))
2864 socktype = SOCK_STREAM;
2865 #ifdef DATAGRAM_SOCKETS
2866 else if (EQ (tem, Qdatagram))
2867 socktype = SOCK_DGRAM;
2868 #endif
2869 #ifdef HAVE_SEQPACKET
2870 else if (EQ (tem, Qseqpacket))
2871 socktype = SOCK_SEQPACKET;
2872 #endif
2873 else
2874 error ("Unsupported connection type");
2876 /* :server BOOL */
2877 tem = Fplist_get (contact, QCserver);
2878 if (!NILP (tem))
2880 /* Don't support network sockets when non-blocking mode is
2881 not available, since a blocked Emacs is not useful. */
2882 is_server = 1;
2883 if (TYPE_RANGED_INTEGERP (int, tem))
2884 backlog = XINT (tem);
2887 /* Make colon_address an alias for :local (server) or :remote (client). */
2888 colon_address = is_server ? QClocal : QCremote;
2890 /* :nowait BOOL */
2891 if (!is_server && socktype != SOCK_DGRAM
2892 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2894 #ifndef NON_BLOCKING_CONNECT
2895 error ("Non-blocking connect not supported");
2896 #else
2897 is_non_blocking_client = 1;
2898 #endif
2901 name = Fplist_get (contact, QCname);
2902 buffer = Fplist_get (contact, QCbuffer);
2903 filter = Fplist_get (contact, QCfilter);
2904 sentinel = Fplist_get (contact, QCsentinel);
2906 CHECK_STRING (name);
2908 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2909 ai.ai_socktype = socktype;
2910 ai.ai_protocol = 0;
2911 ai.ai_next = NULL;
2912 res = &ai;
2914 /* :local ADDRESS or :remote ADDRESS */
2915 address = Fplist_get (contact, colon_address);
2916 if (!NILP (address))
2918 host = service = Qnil;
2920 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2921 error ("Malformed :address");
2922 ai.ai_family = family;
2923 ai.ai_addr = alloca (ai.ai_addrlen);
2924 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
2925 goto open_socket;
2928 /* :family FAMILY -- nil (for Inet), local, or integer. */
2929 tem = Fplist_get (contact, QCfamily);
2930 if (NILP (tem))
2932 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
2933 family = AF_UNSPEC;
2934 #else
2935 family = AF_INET;
2936 #endif
2938 #ifdef HAVE_LOCAL_SOCKETS
2939 else if (EQ (tem, Qlocal))
2940 family = AF_LOCAL;
2941 #endif
2942 #ifdef AF_INET6
2943 else if (EQ (tem, Qipv6))
2944 family = AF_INET6;
2945 #endif
2946 else if (EQ (tem, Qipv4))
2947 family = AF_INET;
2948 else if (TYPE_RANGED_INTEGERP (int, tem))
2949 family = XINT (tem);
2950 else
2951 error ("Unknown address family");
2953 ai.ai_family = family;
2955 /* :service SERVICE -- string, integer (port number), or t (random port). */
2956 service = Fplist_get (contact, QCservice);
2958 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2959 host = Fplist_get (contact, QChost);
2960 if (!NILP (host))
2962 if (EQ (host, Qlocal))
2963 /* Depending on setup, "localhost" may map to different IPv4 and/or
2964 IPv6 addresses, so it's better to be explicit (Bug#6781). */
2965 host = build_string ("127.0.0.1");
2966 CHECK_STRING (host);
2969 #ifdef HAVE_LOCAL_SOCKETS
2970 if (family == AF_LOCAL)
2972 if (!NILP (host))
2974 message (":family local ignores the :host \"%s\" property",
2975 SDATA (host));
2976 contact = Fplist_put (contact, QChost, Qnil);
2977 host = Qnil;
2979 CHECK_STRING (service);
2980 memset (&address_un, 0, sizeof address_un);
2981 address_un.sun_family = AF_LOCAL;
2982 if (sizeof address_un.sun_path <= SBYTES (service))
2983 error ("Service name too long");
2984 lispstpcpy (address_un.sun_path, service);
2985 ai.ai_addr = (struct sockaddr *) &address_un;
2986 ai.ai_addrlen = sizeof address_un;
2987 goto open_socket;
2989 #endif
2991 /* Slow down polling to every ten seconds.
2992 Some kernels have a bug which causes retrying connect to fail
2993 after a connect. Polling can interfere with gethostbyname too. */
2994 #ifdef POLL_FOR_INPUT
2995 if (socktype != SOCK_DGRAM)
2997 record_unwind_protect_void (run_all_atimers);
2998 bind_polling_period (10);
3000 #endif
3002 #ifdef HAVE_GETADDRINFO
3003 /* If we have a host, use getaddrinfo to resolve both host and service.
3004 Otherwise, use getservbyname to lookup the service. */
3005 if (!NILP (host))
3008 /* SERVICE can either be a string or int.
3009 Convert to a C string for later use by getaddrinfo. */
3010 if (EQ (service, Qt))
3011 portstring = "0";
3012 else if (INTEGERP (service))
3014 sprintf (portbuf, "%"pI"d", XINT (service));
3015 portstring = portbuf;
3017 else
3019 CHECK_STRING (service);
3020 portstring = SSDATA (service);
3023 immediate_quit = 1;
3024 QUIT;
3025 memset (&hints, 0, sizeof (hints));
3026 hints.ai_flags = 0;
3027 hints.ai_family = family;
3028 hints.ai_socktype = socktype;
3029 hints.ai_protocol = 0;
3031 #ifdef HAVE_RES_INIT
3032 res_init ();
3033 #endif
3035 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3036 if (ret)
3037 #ifdef HAVE_GAI_STRERROR
3038 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3039 #else
3040 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3041 #endif
3042 immediate_quit = 0;
3044 goto open_socket;
3046 #endif /* HAVE_GETADDRINFO */
3048 /* We end up here if getaddrinfo is not defined, or in case no hostname
3049 has been specified (e.g. for a local server process). */
3051 if (EQ (service, Qt))
3052 port = 0;
3053 else if (INTEGERP (service))
3054 port = htons ((unsigned short) XINT (service));
3055 else
3057 struct servent *svc_info;
3058 CHECK_STRING (service);
3059 svc_info = getservbyname (SSDATA (service),
3060 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3061 if (svc_info == 0)
3062 error ("Unknown service: %s", SDATA (service));
3063 port = svc_info->s_port;
3066 memset (&address_in, 0, sizeof address_in);
3067 address_in.sin_family = family;
3068 address_in.sin_addr.s_addr = INADDR_ANY;
3069 address_in.sin_port = port;
3071 #ifndef HAVE_GETADDRINFO
3072 if (!NILP (host))
3074 struct hostent *host_info_ptr;
3076 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3077 as it may `hang' Emacs for a very long time. */
3078 immediate_quit = 1;
3079 QUIT;
3081 #ifdef HAVE_RES_INIT
3082 res_init ();
3083 #endif
3085 host_info_ptr = gethostbyname (SDATA (host));
3086 immediate_quit = 0;
3088 if (host_info_ptr)
3090 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3091 host_info_ptr->h_length);
3092 family = host_info_ptr->h_addrtype;
3093 address_in.sin_family = family;
3095 else
3096 /* Attempt to interpret host as numeric inet address. */
3098 unsigned long numeric_addr;
3099 numeric_addr = inet_addr (SSDATA (host));
3100 if (numeric_addr == -1)
3101 error ("Unknown host \"%s\"", SDATA (host));
3103 memcpy (&address_in.sin_addr, &numeric_addr,
3104 sizeof (address_in.sin_addr));
3108 #endif /* not HAVE_GETADDRINFO */
3110 ai.ai_family = family;
3111 ai.ai_addr = (struct sockaddr *) &address_in;
3112 ai.ai_addrlen = sizeof address_in;
3114 open_socket:
3116 /* Do this in case we never enter the for-loop below. */
3117 count1 = SPECPDL_INDEX ();
3118 s = -1;
3120 for (lres = res; lres; lres = lres->ai_next)
3122 ptrdiff_t optn;
3123 int optbits;
3125 #ifdef WINDOWSNT
3126 retry_connect:
3127 #endif
3129 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3130 lres->ai_protocol);
3131 if (s < 0)
3133 xerrno = errno;
3134 continue;
3137 #ifdef DATAGRAM_SOCKETS
3138 if (!is_server && socktype == SOCK_DGRAM)
3139 break;
3140 #endif /* DATAGRAM_SOCKETS */
3142 #ifdef NON_BLOCKING_CONNECT
3143 if (is_non_blocking_client)
3145 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3146 if (ret < 0)
3148 xerrno = errno;
3149 emacs_close (s);
3150 s = -1;
3151 continue;
3154 #endif
3156 /* Make us close S if quit. */
3157 record_unwind_protect_int (close_file_unwind, s);
3159 /* Parse network options in the arg list.
3160 We simply ignore anything which isn't a known option (including other keywords).
3161 An error is signaled if setting a known option fails. */
3162 for (optn = optbits = 0; optn < nargs - 1; optn += 2)
3163 optbits |= set_socket_option (s, args[optn], args[optn + 1]);
3165 if (is_server)
3167 /* Configure as a server socket. */
3169 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3170 explicit :reuseaddr key to override this. */
3171 #ifdef HAVE_LOCAL_SOCKETS
3172 if (family != AF_LOCAL)
3173 #endif
3174 if (!(optbits & (1 << OPIX_REUSEADDR)))
3176 int optval = 1;
3177 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3178 report_file_error ("Cannot set reuse option on server socket", Qnil);
3181 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3182 report_file_error ("Cannot bind server socket", Qnil);
3184 #ifdef HAVE_GETSOCKNAME
3185 if (EQ (service, Qt))
3187 struct sockaddr_in sa1;
3188 socklen_t len1 = sizeof (sa1);
3189 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3191 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3192 service = make_number (ntohs (sa1.sin_port));
3193 contact = Fplist_put (contact, QCservice, service);
3196 #endif
3198 if (socktype != SOCK_DGRAM && listen (s, backlog))
3199 report_file_error ("Cannot listen on server socket", Qnil);
3201 break;
3204 immediate_quit = 1;
3205 QUIT;
3207 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3208 xerrno = errno;
3210 if (ret == 0 || xerrno == EISCONN)
3212 /* The unwind-protect will be discarded afterwards.
3213 Likewise for immediate_quit. */
3214 break;
3217 #ifdef NON_BLOCKING_CONNECT
3218 #ifdef EINPROGRESS
3219 if (is_non_blocking_client && xerrno == EINPROGRESS)
3220 break;
3221 #else
3222 #ifdef EWOULDBLOCK
3223 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3224 break;
3225 #endif
3226 #endif
3227 #endif
3229 #ifndef WINDOWSNT
3230 if (xerrno == EINTR)
3232 /* Unlike most other syscalls connect() cannot be called
3233 again. (That would return EALREADY.) The proper way to
3234 wait for completion is pselect(). */
3235 int sc;
3236 socklen_t len;
3237 fd_set fdset;
3238 retry_select:
3239 FD_ZERO (&fdset);
3240 FD_SET (s, &fdset);
3241 QUIT;
3242 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3243 if (sc == -1)
3245 if (errno == EINTR)
3246 goto retry_select;
3247 else
3248 report_file_error ("Failed select", Qnil);
3250 eassert (sc > 0);
3252 len = sizeof xerrno;
3253 eassert (FD_ISSET (s, &fdset));
3254 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3255 report_file_error ("Failed getsockopt", Qnil);
3256 if (xerrno)
3257 report_file_errno ("Failed connect", Qnil, xerrno);
3258 break;
3260 #endif /* !WINDOWSNT */
3262 immediate_quit = 0;
3264 /* Discard the unwind protect closing S. */
3265 specpdl_ptr = specpdl + count1;
3266 emacs_close (s);
3267 s = -1;
3269 #ifdef WINDOWSNT
3270 if (xerrno == EINTR)
3271 goto retry_connect;
3272 #endif
3275 if (s >= 0)
3277 #ifdef DATAGRAM_SOCKETS
3278 if (socktype == SOCK_DGRAM)
3280 if (datagram_address[s].sa)
3281 emacs_abort ();
3282 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3283 datagram_address[s].len = lres->ai_addrlen;
3284 if (is_server)
3286 Lisp_Object remote;
3287 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3288 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3290 int rfamily, rlen;
3291 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3292 if (rlen != 0 && rfamily == lres->ai_family
3293 && rlen == lres->ai_addrlen)
3294 conv_lisp_to_sockaddr (rfamily, remote,
3295 datagram_address[s].sa, rlen);
3298 else
3299 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3301 #endif
3302 contact = Fplist_put (contact, colon_address,
3303 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3304 #ifdef HAVE_GETSOCKNAME
3305 if (!is_server)
3307 struct sockaddr_in sa1;
3308 socklen_t len1 = sizeof (sa1);
3309 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3310 contact = Fplist_put (contact, QClocal,
3311 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3313 #endif
3316 immediate_quit = 0;
3318 #ifdef HAVE_GETADDRINFO
3319 if (res != &ai)
3321 block_input ();
3322 freeaddrinfo (res);
3323 unblock_input ();
3325 #endif
3327 if (s < 0)
3329 /* If non-blocking got this far - and failed - assume non-blocking is
3330 not supported after all. This is probably a wrong assumption, but
3331 the normal blocking calls to open-network-stream handles this error
3332 better. */
3333 if (is_non_blocking_client)
3334 return Qnil;
3336 report_file_errno ((is_server
3337 ? "make server process failed"
3338 : "make client process failed"),
3339 contact, xerrno);
3342 inch = s;
3343 outch = s;
3345 if (!NILP (buffer))
3346 buffer = Fget_buffer_create (buffer);
3347 proc = make_process (name);
3349 chan_process[inch] = proc;
3351 fcntl (inch, F_SETFL, O_NONBLOCK);
3353 p = XPROCESS (proc);
3355 pset_childp (p, contact);
3356 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3357 pset_type (p, Qnetwork);
3359 pset_buffer (p, buffer);
3360 pset_sentinel (p, sentinel);
3361 pset_filter (p, filter);
3362 pset_log (p, Fplist_get (contact, QClog));
3363 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3364 p->kill_without_query = 1;
3365 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3366 pset_command (p, Qt);
3367 p->pid = 0;
3369 p->open_fd[SUBPROCESS_STDIN] = inch;
3370 p->infd = inch;
3371 p->outfd = outch;
3373 /* Discard the unwind protect for closing S, if any. */
3374 specpdl_ptr = specpdl + count1;
3376 /* Unwind bind_polling_period and request_sigio. */
3377 unbind_to (count, Qnil);
3379 if (is_server && socktype != SOCK_DGRAM)
3380 pset_status (p, Qlisten);
3382 /* Make the process marker point into the process buffer (if any). */
3383 if (BUFFERP (buffer))
3384 set_marker_both (p->mark, buffer,
3385 BUF_ZV (XBUFFER (buffer)),
3386 BUF_ZV_BYTE (XBUFFER (buffer)));
3388 #ifdef NON_BLOCKING_CONNECT
3389 if (is_non_blocking_client)
3391 /* We may get here if connect did succeed immediately. However,
3392 in that case, we still need to signal this like a non-blocking
3393 connection. */
3394 pset_status (p, Qconnect);
3395 if (!FD_ISSET (inch, &connect_wait_mask))
3397 FD_SET (inch, &connect_wait_mask);
3398 FD_SET (inch, &write_mask);
3399 num_pending_connects++;
3402 else
3403 #endif
3404 /* A server may have a client filter setting of Qt, but it must
3405 still listen for incoming connects unless it is stopped. */
3406 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3407 || (EQ (p->status, Qlisten) && NILP (p->command)))
3409 FD_SET (inch, &input_wait_mask);
3410 FD_SET (inch, &non_keyboard_wait_mask);
3413 if (inch > max_process_desc)
3414 max_process_desc = inch;
3416 tem = Fplist_member (contact, QCcoding);
3417 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3418 tem = Qnil; /* No error message (too late!). */
3421 /* Setup coding systems for communicating with the network stream. */
3422 struct gcpro gcpro1;
3423 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3424 Lisp_Object coding_systems = Qt;
3425 Lisp_Object val;
3427 if (!NILP (tem))
3429 val = XCAR (XCDR (tem));
3430 if (CONSP (val))
3431 val = XCAR (val);
3433 else if (!NILP (Vcoding_system_for_read))
3434 val = Vcoding_system_for_read;
3435 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3436 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3437 /* We dare not decode end-of-line format by setting VAL to
3438 Qraw_text, because the existing Emacs Lisp libraries
3439 assume that they receive bare code including a sequence of
3440 CR LF. */
3441 val = Qnil;
3442 else
3444 if (NILP (host) || NILP (service))
3445 coding_systems = Qnil;
3446 else
3448 GCPRO1 (proc);
3449 coding_systems = CALLN (Ffind_operation_coding_system,
3450 Qopen_network_stream, name, buffer,
3451 host, service);
3452 UNGCPRO;
3454 if (CONSP (coding_systems))
3455 val = XCAR (coding_systems);
3456 else if (CONSP (Vdefault_process_coding_system))
3457 val = XCAR (Vdefault_process_coding_system);
3458 else
3459 val = Qnil;
3461 pset_decode_coding_system (p, val);
3463 if (!NILP (tem))
3465 val = XCAR (XCDR (tem));
3466 if (CONSP (val))
3467 val = XCDR (val);
3469 else if (!NILP (Vcoding_system_for_write))
3470 val = Vcoding_system_for_write;
3471 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3472 val = Qnil;
3473 else
3475 if (EQ (coding_systems, Qt))
3477 if (NILP (host) || NILP (service))
3478 coding_systems = Qnil;
3479 else
3481 GCPRO1 (proc);
3482 coding_systems = CALLN (Ffind_operation_coding_system,
3483 Qopen_network_stream, name, buffer,
3484 host, service);
3485 UNGCPRO;
3488 if (CONSP (coding_systems))
3489 val = XCDR (coding_systems);
3490 else if (CONSP (Vdefault_process_coding_system))
3491 val = XCDR (Vdefault_process_coding_system);
3492 else
3493 val = Qnil;
3495 pset_encode_coding_system (p, val);
3497 setup_process_coding_systems (proc);
3499 pset_decoding_buf (p, empty_unibyte_string);
3500 p->decoding_carryover = 0;
3501 pset_encoding_buf (p, empty_unibyte_string);
3503 p->inherit_coding_system_flag
3504 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3506 UNGCPRO;
3507 return proc;
3511 #ifdef HAVE_NET_IF_H
3513 #ifdef SIOCGIFCONF
3514 static Lisp_Object
3515 network_interface_list (void)
3517 struct ifconf ifconf;
3518 struct ifreq *ifreq;
3519 void *buf = NULL;
3520 ptrdiff_t buf_size = 512;
3521 int s;
3522 Lisp_Object res;
3523 ptrdiff_t count;
3525 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3526 if (s < 0)
3527 return Qnil;
3528 count = SPECPDL_INDEX ();
3529 record_unwind_protect_int (close_file_unwind, s);
3533 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3534 ifconf.ifc_buf = buf;
3535 ifconf.ifc_len = buf_size;
3536 if (ioctl (s, SIOCGIFCONF, &ifconf))
3538 emacs_close (s);
3539 xfree (buf);
3540 return Qnil;
3543 while (ifconf.ifc_len == buf_size);
3545 res = unbind_to (count, Qnil);
3546 ifreq = ifconf.ifc_req;
3547 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3549 struct ifreq *ifq = ifreq;
3550 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3551 #define SIZEOF_IFREQ(sif) \
3552 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3553 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3555 int len = SIZEOF_IFREQ (ifq);
3556 #else
3557 int len = sizeof (*ifreq);
3558 #endif
3559 char namebuf[sizeof (ifq->ifr_name) + 1];
3560 ifreq = (struct ifreq *) ((char *) ifreq + len);
3562 if (ifq->ifr_addr.sa_family != AF_INET)
3563 continue;
3565 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3566 namebuf[sizeof (ifq->ifr_name)] = 0;
3567 res = Fcons (Fcons (build_string (namebuf),
3568 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3569 sizeof (struct sockaddr))),
3570 res);
3573 xfree (buf);
3574 return res;
3576 #endif /* SIOCGIFCONF */
3578 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3580 struct ifflag_def {
3581 int flag_bit;
3582 const char *flag_sym;
3585 static const struct ifflag_def ifflag_table[] = {
3586 #ifdef IFF_UP
3587 { IFF_UP, "up" },
3588 #endif
3589 #ifdef IFF_BROADCAST
3590 { IFF_BROADCAST, "broadcast" },
3591 #endif
3592 #ifdef IFF_DEBUG
3593 { IFF_DEBUG, "debug" },
3594 #endif
3595 #ifdef IFF_LOOPBACK
3596 { IFF_LOOPBACK, "loopback" },
3597 #endif
3598 #ifdef IFF_POINTOPOINT
3599 { IFF_POINTOPOINT, "pointopoint" },
3600 #endif
3601 #ifdef IFF_RUNNING
3602 { IFF_RUNNING, "running" },
3603 #endif
3604 #ifdef IFF_NOARP
3605 { IFF_NOARP, "noarp" },
3606 #endif
3607 #ifdef IFF_PROMISC
3608 { IFF_PROMISC, "promisc" },
3609 #endif
3610 #ifdef IFF_NOTRAILERS
3611 #ifdef NS_IMPL_COCOA
3612 /* Really means smart, notrailers is obsolete. */
3613 { IFF_NOTRAILERS, "smart" },
3614 #else
3615 { IFF_NOTRAILERS, "notrailers" },
3616 #endif
3617 #endif
3618 #ifdef IFF_ALLMULTI
3619 { IFF_ALLMULTI, "allmulti" },
3620 #endif
3621 #ifdef IFF_MASTER
3622 { IFF_MASTER, "master" },
3623 #endif
3624 #ifdef IFF_SLAVE
3625 { IFF_SLAVE, "slave" },
3626 #endif
3627 #ifdef IFF_MULTICAST
3628 { IFF_MULTICAST, "multicast" },
3629 #endif
3630 #ifdef IFF_PORTSEL
3631 { IFF_PORTSEL, "portsel" },
3632 #endif
3633 #ifdef IFF_AUTOMEDIA
3634 { IFF_AUTOMEDIA, "automedia" },
3635 #endif
3636 #ifdef IFF_DYNAMIC
3637 { IFF_DYNAMIC, "dynamic" },
3638 #endif
3639 #ifdef IFF_OACTIVE
3640 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
3641 #endif
3642 #ifdef IFF_SIMPLEX
3643 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
3644 #endif
3645 #ifdef IFF_LINK0
3646 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
3647 #endif
3648 #ifdef IFF_LINK1
3649 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
3650 #endif
3651 #ifdef IFF_LINK2
3652 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
3653 #endif
3654 { 0, 0 }
3657 static Lisp_Object
3658 network_interface_info (Lisp_Object ifname)
3660 struct ifreq rq;
3661 Lisp_Object res = Qnil;
3662 Lisp_Object elt;
3663 int s;
3664 bool any = 0;
3665 ptrdiff_t count;
3666 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3667 && defined HAVE_GETIFADDRS && defined LLADDR)
3668 struct ifaddrs *ifap;
3669 #endif
3671 CHECK_STRING (ifname);
3673 if (sizeof rq.ifr_name <= SBYTES (ifname))
3674 error ("interface name too long");
3675 lispstpcpy (rq.ifr_name, ifname);
3677 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3678 if (s < 0)
3679 return Qnil;
3680 count = SPECPDL_INDEX ();
3681 record_unwind_protect_int (close_file_unwind, s);
3683 elt = Qnil;
3684 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3685 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3687 int flags = rq.ifr_flags;
3688 const struct ifflag_def *fp;
3689 int fnum;
3691 /* If flags is smaller than int (i.e. short) it may have the high bit set
3692 due to IFF_MULTICAST. In that case, sign extending it into
3693 an int is wrong. */
3694 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3695 flags = (unsigned short) rq.ifr_flags;
3697 any = 1;
3698 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3700 if (flags & fp->flag_bit)
3702 elt = Fcons (intern (fp->flag_sym), elt);
3703 flags -= fp->flag_bit;
3706 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3708 if (flags & 1)
3710 elt = Fcons (make_number (fnum), elt);
3714 #endif
3715 res = Fcons (elt, res);
3717 elt = Qnil;
3718 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3719 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3721 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3722 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3723 int n;
3725 any = 1;
3726 for (n = 0; n < 6; n++)
3727 p->contents[n] = make_number (((unsigned char *)
3728 &rq.ifr_hwaddr.sa_data[0])
3729 [n]);
3730 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3732 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3733 if (getifaddrs (&ifap) != -1)
3735 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3736 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3737 struct ifaddrs *it;
3739 for (it = ifap; it != NULL; it = it->ifa_next)
3741 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3742 unsigned char linkaddr[6];
3743 int n;
3745 if (it->ifa_addr->sa_family != AF_LINK
3746 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3747 || sdl->sdl_alen != 6)
3748 continue;
3750 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3751 for (n = 0; n < 6; n++)
3752 p->contents[n] = make_number (linkaddr[n]);
3754 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
3755 break;
3758 #ifdef HAVE_FREEIFADDRS
3759 freeifaddrs (ifap);
3760 #endif
3762 #endif /* HAVE_GETIFADDRS && LLADDR */
3764 res = Fcons (elt, res);
3766 elt = Qnil;
3767 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3768 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3770 any = 1;
3771 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3772 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3773 #else
3774 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3775 #endif
3777 #endif
3778 res = Fcons (elt, res);
3780 elt = Qnil;
3781 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3782 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3784 any = 1;
3785 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3787 #endif
3788 res = Fcons (elt, res);
3790 elt = Qnil;
3791 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3792 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3794 any = 1;
3795 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3797 #endif
3798 res = Fcons (elt, res);
3800 return unbind_to (count, any ? res : Qnil);
3802 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
3803 #endif /* defined (HAVE_NET_IF_H) */
3805 DEFUN ("network-interface-list", Fnetwork_interface_list,
3806 Snetwork_interface_list, 0, 0, 0,
3807 doc: /* Return an alist of all network interfaces and their network address.
3808 Each element is a cons, the car of which is a string containing the
3809 interface name, and the cdr is the network address in internal
3810 format; see the description of ADDRESS in `make-network-process'.
3812 If the information is not available, return nil. */)
3813 (void)
3815 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
3816 return network_interface_list ();
3817 #else
3818 return Qnil;
3819 #endif
3822 DEFUN ("network-interface-info", Fnetwork_interface_info,
3823 Snetwork_interface_info, 1, 1, 0,
3824 doc: /* Return information about network interface named IFNAME.
3825 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3826 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3827 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3828 FLAGS is the current flags of the interface.
3830 Data that is unavailable is returned as nil. */)
3831 (Lisp_Object ifname)
3833 #if ((defined HAVE_NET_IF_H \
3834 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
3835 || defined SIOCGIFFLAGS)) \
3836 || defined WINDOWSNT)
3837 return network_interface_info (ifname);
3838 #else
3839 return Qnil;
3840 #endif
3843 /* If program file NAME starts with /: for quoting a magic
3844 name, remove that, preserving the multibyteness of NAME. */
3846 Lisp_Object
3847 remove_slash_colon (Lisp_Object name)
3849 return
3850 ((SBYTES (name) > 2 && SREF (name, 0) == '/' && SREF (name, 1) == ':')
3851 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
3852 SBYTES (name) - 2, STRING_MULTIBYTE (name))
3853 : name);
3856 /* Turn off input and output for process PROC. */
3858 static void
3859 deactivate_process (Lisp_Object proc)
3861 int inchannel;
3862 struct Lisp_Process *p = XPROCESS (proc);
3863 int i;
3865 #ifdef HAVE_GNUTLS
3866 /* Delete GnuTLS structures in PROC, if any. */
3867 emacs_gnutls_deinit (proc);
3868 #endif /* HAVE_GNUTLS */
3870 #ifdef ADAPTIVE_READ_BUFFERING
3871 if (p->read_output_delay > 0)
3873 if (--process_output_delay_count < 0)
3874 process_output_delay_count = 0;
3875 p->read_output_delay = 0;
3876 p->read_output_skip = 0;
3878 #endif
3880 /* Beware SIGCHLD hereabouts. */
3882 for (i = 0; i < PROCESS_OPEN_FDS; i++)
3883 close_process_fd (&p->open_fd[i]);
3885 inchannel = p->infd;
3886 if (inchannel >= 0)
3888 p->infd = -1;
3889 p->outfd = -1;
3890 #ifdef DATAGRAM_SOCKETS
3891 if (DATAGRAM_CHAN_P (inchannel))
3893 xfree (datagram_address[inchannel].sa);
3894 datagram_address[inchannel].sa = 0;
3895 datagram_address[inchannel].len = 0;
3897 #endif
3898 chan_process[inchannel] = Qnil;
3899 FD_CLR (inchannel, &input_wait_mask);
3900 FD_CLR (inchannel, &non_keyboard_wait_mask);
3901 #ifdef NON_BLOCKING_CONNECT
3902 if (FD_ISSET (inchannel, &connect_wait_mask))
3904 FD_CLR (inchannel, &connect_wait_mask);
3905 FD_CLR (inchannel, &write_mask);
3906 if (--num_pending_connects < 0)
3907 emacs_abort ();
3909 #endif
3910 if (inchannel == max_process_desc)
3912 /* We just closed the highest-numbered process input descriptor,
3913 so recompute the highest-numbered one now. */
3914 int i = inchannel;
3916 i--;
3917 while (0 <= i && NILP (chan_process[i]));
3919 max_process_desc = i;
3925 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3926 0, 4, 0,
3927 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3928 It is given to their filter functions.
3929 Optional argument PROCESS means do not return until output has been
3930 received from PROCESS.
3932 Optional second argument SECONDS and third argument MILLISEC
3933 specify a timeout; return after that much time even if there is
3934 no subprocess output. If SECONDS is a floating point number,
3935 it specifies a fractional number of seconds to wait.
3936 The MILLISEC argument is obsolete and should be avoided.
3938 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
3939 from PROCESS only, suspending reading output from other processes.
3940 If JUST-THIS-ONE is an integer, don't run any timers either.
3941 Return non-nil if we received any output from PROCESS (or, if PROCESS
3942 is nil, from any process) before the timeout expired. */)
3943 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
3945 intmax_t secs;
3946 int nsecs;
3948 if (! NILP (process))
3949 CHECK_PROCESS (process);
3950 else
3951 just_this_one = Qnil;
3953 if (!NILP (millisec))
3954 { /* Obsolete calling convention using integers rather than floats. */
3955 CHECK_NUMBER (millisec);
3956 if (NILP (seconds))
3957 seconds = make_float (XINT (millisec) / 1000.0);
3958 else
3960 CHECK_NUMBER (seconds);
3961 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
3965 secs = 0;
3966 nsecs = -1;
3968 if (!NILP (seconds))
3970 if (INTEGERP (seconds))
3972 if (XINT (seconds) > 0)
3974 secs = XINT (seconds);
3975 nsecs = 0;
3978 else if (FLOATP (seconds))
3980 if (XFLOAT_DATA (seconds) > 0)
3982 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
3983 secs = min (t.tv_sec, WAIT_READING_MAX);
3984 nsecs = t.tv_nsec;
3987 else
3988 wrong_type_argument (Qnumberp, seconds);
3990 else if (! NILP (process))
3991 nsecs = 0;
3993 return
3994 ((wait_reading_process_output (secs, nsecs, 0, 0,
3995 Qnil,
3996 !NILP (process) ? XPROCESS (process) : NULL,
3997 (NILP (just_this_one) ? 0
3998 : !INTEGERP (just_this_one) ? 1 : -1))
3999 <= 0)
4000 ? Qnil : Qt);
4003 /* Accept a connection for server process SERVER on CHANNEL. */
4005 static EMACS_INT connect_counter = 0;
4007 static void
4008 server_accept_connection (Lisp_Object server, int channel)
4010 Lisp_Object proc, caller, name, buffer;
4011 Lisp_Object contact, host, service;
4012 struct Lisp_Process *ps = XPROCESS (server);
4013 struct Lisp_Process *p;
4014 int s;
4015 union u_sockaddr {
4016 struct sockaddr sa;
4017 struct sockaddr_in in;
4018 #ifdef AF_INET6
4019 struct sockaddr_in6 in6;
4020 #endif
4021 #ifdef HAVE_LOCAL_SOCKETS
4022 struct sockaddr_un un;
4023 #endif
4024 } saddr;
4025 socklen_t len = sizeof saddr;
4026 ptrdiff_t count;
4028 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4030 if (s < 0)
4032 int code = errno;
4034 if (code == EAGAIN)
4035 return;
4036 #ifdef EWOULDBLOCK
4037 if (code == EWOULDBLOCK)
4038 return;
4039 #endif
4041 if (!NILP (ps->log))
4042 call3 (ps->log, server, Qnil,
4043 concat3 (build_string ("accept failed with code"),
4044 Fnumber_to_string (make_number (code)),
4045 build_string ("\n")));
4046 return;
4049 count = SPECPDL_INDEX ();
4050 record_unwind_protect_int (close_file_unwind, s);
4052 connect_counter++;
4054 /* Setup a new process to handle the connection. */
4056 /* Generate a unique identification of the caller, and build contact
4057 information for this process. */
4058 host = Qt;
4059 service = Qnil;
4060 switch (saddr.sa.sa_family)
4062 case AF_INET:
4064 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4066 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4067 host = CALLN (Fformat, ipv4_format,
4068 make_number (ip[0]), make_number (ip[1]),
4069 make_number (ip[2]), make_number (ip[3]));
4070 service = make_number (ntohs (saddr.in.sin_port));
4071 AUTO_STRING (caller_format, " <%s:%d>");
4072 caller = CALLN (Fformat, caller_format, host, service);
4074 break;
4076 #ifdef AF_INET6
4077 case AF_INET6:
4079 Lisp_Object args[9];
4080 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4081 int i;
4083 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4084 args[0] = ipv6_format;
4085 for (i = 0; i < 8; i++)
4086 args[i + 1] = make_number (ntohs (ip6[i]));
4087 host = CALLMANY (Fformat, args);
4088 service = make_number (ntohs (saddr.in.sin_port));
4089 AUTO_STRING (caller_format, " <[%s]:%d>");
4090 caller = CALLN (Fformat, caller_format, host, service);
4092 break;
4093 #endif
4095 #ifdef HAVE_LOCAL_SOCKETS
4096 case AF_LOCAL:
4097 #endif
4098 default:
4099 caller = Fnumber_to_string (make_number (connect_counter));
4100 AUTO_STRING (space_less_than, " <");
4101 AUTO_STRING (greater_than, ">");
4102 caller = concat3 (space_less_than, caller, greater_than);
4103 break;
4106 /* Create a new buffer name for this process if it doesn't have a
4107 filter. The new buffer name is based on the buffer name or
4108 process name of the server process concatenated with the caller
4109 identification. */
4111 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4112 || EQ (ps->filter, Qt)))
4113 buffer = Qnil;
4114 else
4116 buffer = ps->buffer;
4117 if (!NILP (buffer))
4118 buffer = Fbuffer_name (buffer);
4119 else
4120 buffer = ps->name;
4121 if (!NILP (buffer))
4123 buffer = concat2 (buffer, caller);
4124 buffer = Fget_buffer_create (buffer);
4128 /* Generate a unique name for the new server process. Combine the
4129 server process name with the caller identification. */
4131 name = concat2 (ps->name, caller);
4132 proc = make_process (name);
4134 chan_process[s] = proc;
4136 fcntl (s, F_SETFL, O_NONBLOCK);
4138 p = XPROCESS (proc);
4140 /* Build new contact information for this setup. */
4141 contact = Fcopy_sequence (ps->childp);
4142 contact = Fplist_put (contact, QCserver, Qnil);
4143 contact = Fplist_put (contact, QChost, host);
4144 if (!NILP (service))
4145 contact = Fplist_put (contact, QCservice, service);
4146 contact = Fplist_put (contact, QCremote,
4147 conv_sockaddr_to_lisp (&saddr.sa, len));
4148 #ifdef HAVE_GETSOCKNAME
4149 len = sizeof saddr;
4150 if (getsockname (s, &saddr.sa, &len) == 0)
4151 contact = Fplist_put (contact, QClocal,
4152 conv_sockaddr_to_lisp (&saddr.sa, len));
4153 #endif
4155 pset_childp (p, contact);
4156 pset_plist (p, Fcopy_sequence (ps->plist));
4157 pset_type (p, Qnetwork);
4159 pset_buffer (p, buffer);
4160 pset_sentinel (p, ps->sentinel);
4161 pset_filter (p, ps->filter);
4162 pset_command (p, Qnil);
4163 p->pid = 0;
4165 /* Discard the unwind protect for closing S. */
4166 specpdl_ptr = specpdl + count;
4168 p->open_fd[SUBPROCESS_STDIN] = s;
4169 p->infd = s;
4170 p->outfd = s;
4171 pset_status (p, Qrun);
4173 /* Client processes for accepted connections are not stopped initially. */
4174 if (!EQ (p->filter, Qt))
4176 FD_SET (s, &input_wait_mask);
4177 FD_SET (s, &non_keyboard_wait_mask);
4180 if (s > max_process_desc)
4181 max_process_desc = s;
4183 /* Setup coding system for new process based on server process.
4184 This seems to be the proper thing to do, as the coding system
4185 of the new process should reflect the settings at the time the
4186 server socket was opened; not the current settings. */
4188 pset_decode_coding_system (p, ps->decode_coding_system);
4189 pset_encode_coding_system (p, ps->encode_coding_system);
4190 setup_process_coding_systems (proc);
4192 pset_decoding_buf (p, empty_unibyte_string);
4193 p->decoding_carryover = 0;
4194 pset_encoding_buf (p, empty_unibyte_string);
4196 p->inherit_coding_system_flag
4197 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4199 AUTO_STRING (dash, "-");
4200 AUTO_STRING (nl, "\n");
4201 Lisp_Object host_string = STRINGP (host) ? host : dash;
4203 if (!NILP (ps->log))
4205 AUTO_STRING (accept_from, "accept from ");
4206 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4209 AUTO_STRING (open_from, "open from ");
4210 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4213 /* This variable is different from waiting_for_input in keyboard.c.
4214 It is used to communicate to a lisp process-filter/sentinel (via the
4215 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4216 for user-input when that process-filter was called.
4217 waiting_for_input cannot be used as that is by definition 0 when
4218 lisp code is being evalled.
4219 This is also used in record_asynch_buffer_change.
4220 For that purpose, this must be 0
4221 when not inside wait_reading_process_output. */
4222 static int waiting_for_user_input_p;
4224 static void
4225 wait_reading_process_output_unwind (int data)
4227 waiting_for_user_input_p = data;
4230 /* This is here so breakpoints can be put on it. */
4231 static void
4232 wait_reading_process_output_1 (void)
4236 /* Read and dispose of subprocess output while waiting for timeout to
4237 elapse and/or keyboard input to be available.
4239 TIME_LIMIT is:
4240 timeout in seconds
4241 If negative, gobble data immediately available but don't wait for any.
4243 NSECS is:
4244 an additional duration to wait, measured in nanoseconds
4245 If TIME_LIMIT is zero, then:
4246 If NSECS == 0, there is no limit.
4247 If NSECS > 0, the timeout consists of NSECS only.
4248 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4250 READ_KBD is:
4251 0 to ignore keyboard input, or
4252 1 to return when input is available, or
4253 -1 meaning caller will actually read the input, so don't throw to
4254 the quit handler, or
4256 DO_DISPLAY means redisplay should be done to show subprocess
4257 output that arrives.
4259 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4260 (and gobble terminal input into the buffer if any arrives).
4262 If WAIT_PROC is specified, wait until something arrives from that
4263 process.
4265 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4266 (suspending output from other processes). A negative value
4267 means don't run any timers either.
4269 Return positive if we received input from WAIT_PROC (or from any
4270 process if WAIT_PROC is null), zero if we attempted to receive
4271 input but got none, and negative if we didn't even try. */
4274 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4275 bool do_display,
4276 Lisp_Object wait_for_cell,
4277 struct Lisp_Process *wait_proc, int just_wait_proc)
4279 int channel, nfds;
4280 fd_set Available;
4281 fd_set Writeok;
4282 bool check_write;
4283 int check_delay;
4284 bool no_avail;
4285 int xerrno;
4286 Lisp_Object proc;
4287 struct timespec timeout, end_time;
4288 int got_some_input = -1;
4289 ptrdiff_t count = SPECPDL_INDEX ();
4291 FD_ZERO (&Available);
4292 FD_ZERO (&Writeok);
4294 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4295 && !(CONSP (wait_proc->status)
4296 && EQ (XCAR (wait_proc->status), Qexit)))
4297 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4299 record_unwind_protect_int (wait_reading_process_output_unwind,
4300 waiting_for_user_input_p);
4301 waiting_for_user_input_p = read_kbd;
4303 if (time_limit < 0)
4305 time_limit = 0;
4306 nsecs = -1;
4308 else if (TYPE_MAXIMUM (time_t) < time_limit)
4309 time_limit = TYPE_MAXIMUM (time_t);
4311 /* Since we may need to wait several times,
4312 compute the absolute time to return at. */
4313 if (time_limit || nsecs > 0)
4315 timeout = make_timespec (time_limit, nsecs);
4316 end_time = timespec_add (current_timespec (), timeout);
4319 while (1)
4321 bool timeout_reduced_for_timers = false;
4323 /* If calling from keyboard input, do not quit
4324 since we want to return C-g as an input character.
4325 Otherwise, do pending quit if requested. */
4326 if (read_kbd >= 0)
4327 QUIT;
4328 else if (pending_signals)
4329 process_pending_signals ();
4331 /* Exit now if the cell we're waiting for became non-nil. */
4332 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4333 break;
4335 /* After reading input, vacuum up any leftovers without waiting. */
4336 if (0 <= got_some_input)
4337 nsecs = -1;
4339 /* Compute time from now till when time limit is up. */
4340 /* Exit if already run out. */
4341 if (nsecs < 0)
4343 /* A negative timeout means
4344 gobble output available now
4345 but don't wait at all. */
4347 timeout = make_timespec (0, 0);
4349 else if (time_limit || nsecs > 0)
4351 struct timespec now = current_timespec ();
4352 if (timespec_cmp (end_time, now) <= 0)
4353 break;
4354 timeout = timespec_sub (end_time, now);
4356 else
4358 timeout = make_timespec (100000, 0);
4361 /* Normally we run timers here.
4362 But not if wait_for_cell; in those cases,
4363 the wait is supposed to be short,
4364 and those callers cannot handle running arbitrary Lisp code here. */
4365 if (NILP (wait_for_cell)
4366 && just_wait_proc >= 0)
4368 struct timespec timer_delay;
4372 unsigned old_timers_run = timers_run;
4373 struct buffer *old_buffer = current_buffer;
4374 Lisp_Object old_window = selected_window;
4376 timer_delay = timer_check ();
4378 /* If a timer has run, this might have changed buffers
4379 an alike. Make read_key_sequence aware of that. */
4380 if (timers_run != old_timers_run
4381 && (old_buffer != current_buffer
4382 || !EQ (old_window, selected_window))
4383 && waiting_for_user_input_p == -1)
4384 record_asynch_buffer_change ();
4386 if (timers_run != old_timers_run && do_display)
4387 /* We must retry, since a timer may have requeued itself
4388 and that could alter the time_delay. */
4389 redisplay_preserve_echo_area (9);
4390 else
4391 break;
4393 while (!detect_input_pending ());
4395 /* If there is unread keyboard input, also return. */
4396 if (read_kbd != 0
4397 && requeued_events_pending_p ())
4398 break;
4400 /* A negative timeout means do not wait at all. */
4401 if (nsecs >= 0)
4403 if (timespec_valid_p (timer_delay))
4405 if (timespec_cmp (timer_delay, timeout) < 0)
4407 timeout = timer_delay;
4408 timeout_reduced_for_timers = true;
4411 else
4413 /* This is so a breakpoint can be put here. */
4414 wait_reading_process_output_1 ();
4419 /* Cause C-g and alarm signals to take immediate action,
4420 and cause input available signals to zero out timeout.
4422 It is important that we do this before checking for process
4423 activity. If we get a SIGCHLD after the explicit checks for
4424 process activity, timeout is the only way we will know. */
4425 if (read_kbd < 0)
4426 set_waiting_for_input (&timeout);
4428 /* If status of something has changed, and no input is
4429 available, notify the user of the change right away. After
4430 this explicit check, we'll let the SIGCHLD handler zap
4431 timeout to get our attention. */
4432 if (update_tick != process_tick)
4434 fd_set Atemp;
4435 fd_set Ctemp;
4437 if (kbd_on_hold_p ())
4438 FD_ZERO (&Atemp);
4439 else
4440 Atemp = input_wait_mask;
4441 Ctemp = write_mask;
4443 timeout = make_timespec (0, 0);
4444 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4445 &Atemp,
4446 #ifdef NON_BLOCKING_CONNECT
4447 (num_pending_connects > 0 ? &Ctemp : NULL),
4448 #else
4449 NULL,
4450 #endif
4451 NULL, &timeout, NULL)
4452 <= 0))
4454 /* It's okay for us to do this and then continue with
4455 the loop, since timeout has already been zeroed out. */
4456 clear_waiting_for_input ();
4457 got_some_input = status_notify (NULL, wait_proc);
4458 if (do_display) redisplay_preserve_echo_area (13);
4462 /* Don't wait for output from a non-running process. Just
4463 read whatever data has already been received. */
4464 if (wait_proc && wait_proc->raw_status_new)
4465 update_status (wait_proc);
4466 if (wait_proc
4467 && wait_proc->infd >= 0
4468 && ! EQ (wait_proc->status, Qrun)
4469 && ! EQ (wait_proc->status, Qconnect))
4471 bool read_some_bytes = false;
4473 clear_waiting_for_input ();
4474 XSETPROCESS (proc, wait_proc);
4476 /* Read data from the process, until we exhaust it. */
4477 while (true)
4479 int nread = read_process_output (proc, wait_proc->infd);
4480 if (nread < 0)
4482 if (errno == EIO || errno == EAGAIN)
4483 break;
4484 #ifdef EWOULDBLOCK
4485 if (errno == EWOULDBLOCK)
4486 break;
4487 #endif
4489 else
4491 if (got_some_input < nread)
4492 got_some_input = nread;
4493 if (nread == 0)
4494 break;
4495 read_some_bytes = true;
4498 if (read_some_bytes && do_display)
4499 redisplay_preserve_echo_area (10);
4501 break;
4504 /* Wait till there is something to do. */
4506 if (wait_proc && just_wait_proc)
4508 if (wait_proc->infd < 0) /* Terminated. */
4509 break;
4510 FD_SET (wait_proc->infd, &Available);
4511 check_delay = 0;
4512 check_write = 0;
4514 else if (!NILP (wait_for_cell))
4516 Available = non_process_wait_mask;
4517 check_delay = 0;
4518 check_write = 0;
4520 else
4522 if (! read_kbd)
4523 Available = non_keyboard_wait_mask;
4524 else
4525 Available = input_wait_mask;
4526 Writeok = write_mask;
4527 check_delay = wait_proc ? 0 : process_output_delay_count;
4528 check_write = SELECT_CAN_DO_WRITE_MASK;
4531 /* If frame size has changed or the window is newly mapped,
4532 redisplay now, before we start to wait. There is a race
4533 condition here; if a SIGIO arrives between now and the select
4534 and indicates that a frame is trashed, the select may block
4535 displaying a trashed screen. */
4536 if (frame_garbaged && do_display)
4538 clear_waiting_for_input ();
4539 redisplay_preserve_echo_area (11);
4540 if (read_kbd < 0)
4541 set_waiting_for_input (&timeout);
4544 /* Skip the `select' call if input is available and we're
4545 waiting for keyboard input or a cell change (which can be
4546 triggered by processing X events). In the latter case, set
4547 nfds to 1 to avoid breaking the loop. */
4548 no_avail = 0;
4549 if ((read_kbd || !NILP (wait_for_cell))
4550 && detect_input_pending ())
4552 nfds = read_kbd ? 0 : 1;
4553 no_avail = 1;
4554 FD_ZERO (&Available);
4557 if (!no_avail)
4560 #ifdef ADAPTIVE_READ_BUFFERING
4561 /* Set the timeout for adaptive read buffering if any
4562 process has non-zero read_output_skip and non-zero
4563 read_output_delay, and we are not reading output for a
4564 specific process. It is not executed if
4565 Vprocess_adaptive_read_buffering is nil. */
4566 if (process_output_skip && check_delay > 0)
4568 int nsecs = timeout.tv_nsec;
4569 if (timeout.tv_sec > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4570 nsecs = READ_OUTPUT_DELAY_MAX;
4571 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4573 proc = chan_process[channel];
4574 if (NILP (proc))
4575 continue;
4576 /* Find minimum non-zero read_output_delay among the
4577 processes with non-zero read_output_skip. */
4578 if (XPROCESS (proc)->read_output_delay > 0)
4580 check_delay--;
4581 if (!XPROCESS (proc)->read_output_skip)
4582 continue;
4583 FD_CLR (channel, &Available);
4584 XPROCESS (proc)->read_output_skip = 0;
4585 if (XPROCESS (proc)->read_output_delay < nsecs)
4586 nsecs = XPROCESS (proc)->read_output_delay;
4589 timeout = make_timespec (0, nsecs);
4590 process_output_skip = 0;
4592 #endif
4594 #if defined (HAVE_NS)
4595 nfds = ns_select
4596 #elif defined (HAVE_GLIB)
4597 nfds = xg_select
4598 #else
4599 nfds = pselect
4600 #endif
4601 (max (max_process_desc, max_input_desc) + 1,
4602 &Available,
4603 (check_write ? &Writeok : 0),
4604 NULL, &timeout, NULL);
4606 #ifdef HAVE_GNUTLS
4607 /* GnuTLS buffers data internally. In lowat mode it leaves
4608 some data in the TCP buffers so that select works, but
4609 with custom pull/push functions we need to check if some
4610 data is available in the buffers manually. */
4611 if (nfds == 0)
4613 if (! wait_proc)
4615 /* We're not waiting on a specific process, so loop
4616 through all the channels and check for data.
4617 This is a workaround needed for some versions of
4618 the gnutls library -- 2.12.14 has been confirmed
4619 to need it. See
4620 http://comments.gmane.org/gmane.emacs.devel/145074 */
4621 for (channel = 0; channel < FD_SETSIZE; ++channel)
4622 if (! NILP (chan_process[channel]))
4624 struct Lisp_Process *p =
4625 XPROCESS (chan_process[channel]);
4626 if (p && p->gnutls_p && p->gnutls_state
4627 && ((emacs_gnutls_record_check_pending
4628 (p->gnutls_state))
4629 > 0))
4631 nfds++;
4632 eassert (p->infd == channel);
4633 FD_SET (p->infd, &Available);
4637 else
4639 /* Check this specific channel. */
4640 if (wait_proc->gnutls_p /* Check for valid process. */
4641 && wait_proc->gnutls_state
4642 /* Do we have pending data? */
4643 && ((emacs_gnutls_record_check_pending
4644 (wait_proc->gnutls_state))
4645 > 0))
4647 nfds = 1;
4648 eassert (0 <= wait_proc->infd);
4649 /* Set to Available. */
4650 FD_SET (wait_proc->infd, &Available);
4654 #endif
4657 xerrno = errno;
4659 /* Make C-g and alarm signals set flags again. */
4660 clear_waiting_for_input ();
4662 /* If we woke up due to SIGWINCH, actually change size now. */
4663 do_pending_window_change (0);
4665 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4666 /* We waited the full specified time, so return now. */
4667 break;
4668 if (nfds < 0)
4670 if (xerrno == EINTR)
4671 no_avail = 1;
4672 else if (xerrno == EBADF)
4673 emacs_abort ();
4674 else
4675 report_file_errno ("Failed select", Qnil, xerrno);
4678 /* Check for keyboard input. */
4679 /* If there is any, return immediately
4680 to give it higher priority than subprocesses. */
4682 if (read_kbd != 0)
4684 unsigned old_timers_run = timers_run;
4685 struct buffer *old_buffer = current_buffer;
4686 Lisp_Object old_window = selected_window;
4687 bool leave = false;
4689 if (detect_input_pending_run_timers (do_display))
4691 swallow_events (do_display);
4692 if (detect_input_pending_run_timers (do_display))
4693 leave = true;
4696 /* If a timer has run, this might have changed buffers
4697 an alike. Make read_key_sequence aware of that. */
4698 if (timers_run != old_timers_run
4699 && waiting_for_user_input_p == -1
4700 && (old_buffer != current_buffer
4701 || !EQ (old_window, selected_window)))
4702 record_asynch_buffer_change ();
4704 if (leave)
4705 break;
4708 /* If there is unread keyboard input, also return. */
4709 if (read_kbd != 0
4710 && requeued_events_pending_p ())
4711 break;
4713 /* If we are not checking for keyboard input now,
4714 do process events (but don't run any timers).
4715 This is so that X events will be processed.
4716 Otherwise they may have to wait until polling takes place.
4717 That would causes delays in pasting selections, for example.
4719 (We used to do this only if wait_for_cell.) */
4720 if (read_kbd == 0 && detect_input_pending ())
4722 swallow_events (do_display);
4723 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4724 if (detect_input_pending ())
4725 break;
4726 #endif
4729 /* Exit now if the cell we're waiting for became non-nil. */
4730 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4731 break;
4733 #ifdef USABLE_SIGIO
4734 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4735 go read it. This can happen with X on BSD after logging out.
4736 In that case, there really is no input and no SIGIO,
4737 but select says there is input. */
4739 if (read_kbd && interrupt_input
4740 && keyboard_bit_set (&Available) && ! noninteractive)
4741 handle_input_available_signal (SIGIO);
4742 #endif
4744 /* If checking input just got us a size-change event from X,
4745 obey it now if we should. */
4746 if (read_kbd || ! NILP (wait_for_cell))
4747 do_pending_window_change (0);
4749 /* Check for data from a process. */
4750 if (no_avail || nfds == 0)
4751 continue;
4753 for (channel = 0; channel <= max_input_desc; ++channel)
4755 struct fd_callback_data *d = &fd_callback_info[channel];
4756 if (d->func
4757 && ((d->condition & FOR_READ
4758 && FD_ISSET (channel, &Available))
4759 || (d->condition & FOR_WRITE
4760 && FD_ISSET (channel, &write_mask))))
4761 d->func (channel, d->data);
4764 for (channel = 0; channel <= max_process_desc; channel++)
4766 if (FD_ISSET (channel, &Available)
4767 && FD_ISSET (channel, &non_keyboard_wait_mask)
4768 && !FD_ISSET (channel, &non_process_wait_mask))
4770 int nread;
4772 /* If waiting for this channel, arrange to return as
4773 soon as no more input to be processed. No more
4774 waiting. */
4775 proc = chan_process[channel];
4776 if (NILP (proc))
4777 continue;
4779 /* If this is a server stream socket, accept connection. */
4780 if (EQ (XPROCESS (proc)->status, Qlisten))
4782 server_accept_connection (proc, channel);
4783 continue;
4786 /* Read data from the process, starting with our
4787 buffered-ahead character if we have one. */
4789 nread = read_process_output (proc, channel);
4790 if ((!wait_proc || wait_proc == XPROCESS (proc)) && got_some_input < nread)
4791 got_some_input = nread;
4792 if (nread > 0)
4794 /* Since read_process_output can run a filter,
4795 which can call accept-process-output,
4796 don't try to read from any other processes
4797 before doing the select again. */
4798 FD_ZERO (&Available);
4800 if (do_display)
4801 redisplay_preserve_echo_area (12);
4803 #ifdef EWOULDBLOCK
4804 else if (nread == -1 && errno == EWOULDBLOCK)
4806 #endif
4807 else if (nread == -1 && errno == EAGAIN)
4809 #ifdef WINDOWSNT
4810 /* FIXME: Is this special case still needed? */
4811 /* Note that we cannot distinguish between no input
4812 available now and a closed pipe.
4813 With luck, a closed pipe will be accompanied by
4814 subprocess termination and SIGCHLD. */
4815 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4817 #endif
4818 #ifdef HAVE_PTYS
4819 /* On some OSs with ptys, when the process on one end of
4820 a pty exits, the other end gets an error reading with
4821 errno = EIO instead of getting an EOF (0 bytes read).
4822 Therefore, if we get an error reading and errno =
4823 EIO, just continue, because the child process has
4824 exited and should clean itself up soon (e.g. when we
4825 get a SIGCHLD). */
4826 else if (nread == -1 && errno == EIO)
4828 struct Lisp_Process *p = XPROCESS (proc);
4830 /* Clear the descriptor now, so we only raise the
4831 signal once. */
4832 FD_CLR (channel, &input_wait_mask);
4833 FD_CLR (channel, &non_keyboard_wait_mask);
4835 if (p->pid == -2)
4837 /* If the EIO occurs on a pty, the SIGCHLD handler's
4838 waitpid call will not find the process object to
4839 delete. Do it here. */
4840 p->tick = ++process_tick;
4841 pset_status (p, Qfailed);
4844 #endif /* HAVE_PTYS */
4845 /* If we can detect process termination, don't consider the
4846 process gone just because its pipe is closed. */
4847 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4849 else
4851 /* Preserve status of processes already terminated. */
4852 XPROCESS (proc)->tick = ++process_tick;
4853 deactivate_process (proc);
4854 if (XPROCESS (proc)->raw_status_new)
4855 update_status (XPROCESS (proc));
4856 if (EQ (XPROCESS (proc)->status, Qrun))
4857 pset_status (XPROCESS (proc),
4858 list2 (Qexit, make_number (256)));
4861 #ifdef NON_BLOCKING_CONNECT
4862 if (FD_ISSET (channel, &Writeok)
4863 && FD_ISSET (channel, &connect_wait_mask))
4865 struct Lisp_Process *p;
4867 FD_CLR (channel, &connect_wait_mask);
4868 FD_CLR (channel, &write_mask);
4869 if (--num_pending_connects < 0)
4870 emacs_abort ();
4872 proc = chan_process[channel];
4873 if (NILP (proc))
4874 continue;
4876 p = XPROCESS (proc);
4878 #ifdef GNU_LINUX
4879 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4880 So only use it on systems where it is known to work. */
4882 socklen_t xlen = sizeof (xerrno);
4883 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4884 xerrno = errno;
4886 #else
4888 struct sockaddr pname;
4889 socklen_t pnamelen = sizeof (pname);
4891 /* If connection failed, getpeername will fail. */
4892 xerrno = 0;
4893 if (getpeername (channel, &pname, &pnamelen) < 0)
4895 /* Obtain connect failure code through error slippage. */
4896 char dummy;
4897 xerrno = errno;
4898 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
4899 xerrno = errno;
4902 #endif
4903 if (xerrno)
4905 p->tick = ++process_tick;
4906 pset_status (p, list2 (Qfailed, make_number (xerrno)));
4907 deactivate_process (proc);
4909 else
4911 pset_status (p, Qrun);
4912 /* Execute the sentinel here. If we had relied on
4913 status_notify to do it later, it will read input
4914 from the process before calling the sentinel. */
4915 exec_sentinel (proc, build_string ("open\n"));
4916 if (0 <= p->infd && !EQ (p->filter, Qt)
4917 && !EQ (p->command, Qt))
4919 FD_SET (p->infd, &input_wait_mask);
4920 FD_SET (p->infd, &non_keyboard_wait_mask);
4924 #endif /* NON_BLOCKING_CONNECT */
4925 } /* End for each file descriptor. */
4926 } /* End while exit conditions not met. */
4928 unbind_to (count, Qnil);
4930 /* If calling from keyboard input, do not quit
4931 since we want to return C-g as an input character.
4932 Otherwise, do pending quit if requested. */
4933 if (read_kbd >= 0)
4935 /* Prevent input_pending from remaining set if we quit. */
4936 clear_input_pending ();
4937 QUIT;
4940 return got_some_input;
4943 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4945 static Lisp_Object
4946 read_process_output_call (Lisp_Object fun_and_args)
4948 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4951 static Lisp_Object
4952 read_process_output_error_handler (Lisp_Object error_val)
4954 cmd_error_internal (error_val, "error in process filter: ");
4955 Vinhibit_quit = Qt;
4956 update_echo_area ();
4957 Fsleep_for (make_number (2), Qnil);
4958 return Qt;
4961 static void
4962 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
4963 ssize_t nbytes,
4964 struct coding_system *coding);
4966 /* Read pending output from the process channel,
4967 starting with our buffered-ahead character if we have one.
4968 Yield number of decoded characters read.
4970 This function reads at most 4096 characters.
4971 If you want to read all available subprocess output,
4972 you must call it repeatedly until it returns zero.
4974 The characters read are decoded according to PROC's coding-system
4975 for decoding. */
4977 static int
4978 read_process_output (Lisp_Object proc, int channel)
4980 ssize_t nbytes;
4981 struct Lisp_Process *p = XPROCESS (proc);
4982 struct coding_system *coding = proc_decode_coding_system[channel];
4983 int carryover = p->decoding_carryover;
4984 enum { readmax = 4096 };
4985 ptrdiff_t count = SPECPDL_INDEX ();
4986 Lisp_Object odeactivate;
4987 char chars[sizeof coding->carryover + readmax];
4989 if (carryover)
4990 /* See the comment above. */
4991 memcpy (chars, SDATA (p->decoding_buf), carryover);
4993 #ifdef DATAGRAM_SOCKETS
4994 /* We have a working select, so proc_buffered_char is always -1. */
4995 if (DATAGRAM_CHAN_P (channel))
4997 socklen_t len = datagram_address[channel].len;
4998 nbytes = recvfrom (channel, chars + carryover, readmax,
4999 0, datagram_address[channel].sa, &len);
5001 else
5002 #endif
5004 bool buffered = proc_buffered_char[channel] >= 0;
5005 if (buffered)
5007 chars[carryover] = proc_buffered_char[channel];
5008 proc_buffered_char[channel] = -1;
5010 #ifdef HAVE_GNUTLS
5011 if (p->gnutls_p && p->gnutls_state)
5012 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5013 readmax - buffered);
5014 else
5015 #endif
5016 nbytes = emacs_read (channel, chars + carryover + buffered,
5017 readmax - buffered);
5018 #ifdef ADAPTIVE_READ_BUFFERING
5019 if (nbytes > 0 && p->adaptive_read_buffering)
5021 int delay = p->read_output_delay;
5022 if (nbytes < 256)
5024 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5026 if (delay == 0)
5027 process_output_delay_count++;
5028 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5031 else if (delay > 0 && nbytes == readmax - buffered)
5033 delay -= READ_OUTPUT_DELAY_INCREMENT;
5034 if (delay == 0)
5035 process_output_delay_count--;
5037 p->read_output_delay = delay;
5038 if (delay)
5040 p->read_output_skip = 1;
5041 process_output_skip = 1;
5044 #endif
5045 nbytes += buffered;
5046 nbytes += buffered && nbytes <= 0;
5049 p->decoding_carryover = 0;
5051 /* At this point, NBYTES holds number of bytes just received
5052 (including the one in proc_buffered_char[channel]). */
5053 if (nbytes <= 0)
5055 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5056 return nbytes;
5057 coding->mode |= CODING_MODE_LAST_BLOCK;
5060 /* Now set NBYTES how many bytes we must decode. */
5061 nbytes += carryover;
5063 odeactivate = Vdeactivate_mark;
5064 /* There's no good reason to let process filters change the current
5065 buffer, and many callers of accept-process-output, sit-for, and
5066 friends don't expect current-buffer to be changed from under them. */
5067 record_unwind_current_buffer ();
5069 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5071 /* Handling the process output should not deactivate the mark. */
5072 Vdeactivate_mark = odeactivate;
5074 unbind_to (count, Qnil);
5075 return nbytes;
5078 static void
5079 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5080 ssize_t nbytes,
5081 struct coding_system *coding)
5083 Lisp_Object outstream = p->filter;
5084 Lisp_Object text;
5085 bool outer_running_asynch_code = running_asynch_code;
5086 int waiting = waiting_for_user_input_p;
5088 /* No need to gcpro these, because all we do with them later
5089 is test them for EQness, and none of them should be a string. */
5090 #if 0
5091 Lisp_Object obuffer, okeymap;
5092 XSETBUFFER (obuffer, current_buffer);
5093 okeymap = BVAR (current_buffer, keymap);
5094 #endif
5096 /* We inhibit quit here instead of just catching it so that
5097 hitting ^G when a filter happens to be running won't screw
5098 it up. */
5099 specbind (Qinhibit_quit, Qt);
5100 specbind (Qlast_nonmenu_event, Qt);
5102 /* In case we get recursively called,
5103 and we already saved the match data nonrecursively,
5104 save the same match data in safely recursive fashion. */
5105 if (outer_running_asynch_code)
5107 Lisp_Object tem;
5108 /* Don't clobber the CURRENT match data, either! */
5109 tem = Fmatch_data (Qnil, Qnil, Qnil);
5110 restore_search_regs ();
5111 record_unwind_save_match_data ();
5112 Fset_match_data (tem, Qt);
5115 /* For speed, if a search happens within this code,
5116 save the match data in a special nonrecursive fashion. */
5117 running_asynch_code = 1;
5119 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5120 text = coding->dst_object;
5121 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5122 /* A new coding system might be found. */
5123 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5125 pset_decode_coding_system (p, Vlast_coding_system_used);
5127 /* Don't call setup_coding_system for
5128 proc_decode_coding_system[channel] here. It is done in
5129 detect_coding called via decode_coding above. */
5131 /* If a coding system for encoding is not yet decided, we set
5132 it as the same as coding-system for decoding.
5134 But, before doing that we must check if
5135 proc_encode_coding_system[p->outfd] surely points to a
5136 valid memory because p->outfd will be changed once EOF is
5137 sent to the process. */
5138 if (NILP (p->encode_coding_system) && p->outfd >= 0
5139 && proc_encode_coding_system[p->outfd])
5141 pset_encode_coding_system
5142 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5143 setup_coding_system (p->encode_coding_system,
5144 proc_encode_coding_system[p->outfd]);
5148 if (coding->carryover_bytes > 0)
5150 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5151 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5152 memcpy (SDATA (p->decoding_buf), coding->carryover,
5153 coding->carryover_bytes);
5154 p->decoding_carryover = coding->carryover_bytes;
5156 if (SBYTES (text) > 0)
5157 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5158 sometimes it's simply wrong to wrap (e.g. when called from
5159 accept-process-output). */
5160 internal_condition_case_1 (read_process_output_call,
5161 list3 (outstream, make_lisp_proc (p), text),
5162 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5163 read_process_output_error_handler);
5165 /* If we saved the match data nonrecursively, restore it now. */
5166 restore_search_regs ();
5167 running_asynch_code = outer_running_asynch_code;
5169 /* Restore waiting_for_user_input_p as it was
5170 when we were called, in case the filter clobbered it. */
5171 waiting_for_user_input_p = waiting;
5173 #if 0 /* Call record_asynch_buffer_change unconditionally,
5174 because we might have changed minor modes or other things
5175 that affect key bindings. */
5176 if (! EQ (Fcurrent_buffer (), obuffer)
5177 || ! EQ (current_buffer->keymap, okeymap))
5178 #endif
5179 /* But do it only if the caller is actually going to read events.
5180 Otherwise there's no need to make him wake up, and it could
5181 cause trouble (for example it would make sit_for return). */
5182 if (waiting_for_user_input_p == -1)
5183 record_asynch_buffer_change ();
5186 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5187 Sinternal_default_process_filter, 2, 2, 0,
5188 doc: /* Function used as default process filter.
5189 This inserts the process's output into its buffer, if there is one.
5190 Otherwise it discards the output. */)
5191 (Lisp_Object proc, Lisp_Object text)
5193 struct Lisp_Process *p;
5194 ptrdiff_t opoint;
5196 CHECK_PROCESS (proc);
5197 p = XPROCESS (proc);
5198 CHECK_STRING (text);
5200 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5202 Lisp_Object old_read_only;
5203 ptrdiff_t old_begv, old_zv;
5204 ptrdiff_t old_begv_byte, old_zv_byte;
5205 ptrdiff_t before, before_byte;
5206 ptrdiff_t opoint_byte;
5207 struct buffer *b;
5209 Fset_buffer (p->buffer);
5210 opoint = PT;
5211 opoint_byte = PT_BYTE;
5212 old_read_only = BVAR (current_buffer, read_only);
5213 old_begv = BEGV;
5214 old_zv = ZV;
5215 old_begv_byte = BEGV_BYTE;
5216 old_zv_byte = ZV_BYTE;
5218 bset_read_only (current_buffer, Qnil);
5220 /* Insert new output into buffer at the current end-of-output
5221 marker, thus preserving logical ordering of input and output. */
5222 if (XMARKER (p->mark)->buffer)
5223 set_point_from_marker (p->mark);
5224 else
5225 SET_PT_BOTH (ZV, ZV_BYTE);
5226 before = PT;
5227 before_byte = PT_BYTE;
5229 /* If the output marker is outside of the visible region, save
5230 the restriction and widen. */
5231 if (! (BEGV <= PT && PT <= ZV))
5232 Fwiden ();
5234 /* Adjust the multibyteness of TEXT to that of the buffer. */
5235 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5236 != ! STRING_MULTIBYTE (text))
5237 text = (STRING_MULTIBYTE (text)
5238 ? Fstring_as_unibyte (text)
5239 : Fstring_to_multibyte (text));
5240 /* Insert before markers in case we are inserting where
5241 the buffer's mark is, and the user's next command is Meta-y. */
5242 insert_from_string_before_markers (text, 0, 0,
5243 SCHARS (text), SBYTES (text), 0);
5245 /* Make sure the process marker's position is valid when the
5246 process buffer is changed in the signal_after_change above.
5247 W3 is known to do that. */
5248 if (BUFFERP (p->buffer)
5249 && (b = XBUFFER (p->buffer), b != current_buffer))
5250 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5251 else
5252 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5254 update_mode_lines = 23;
5256 /* Make sure opoint and the old restrictions
5257 float ahead of any new text just as point would. */
5258 if (opoint >= before)
5260 opoint += PT - before;
5261 opoint_byte += PT_BYTE - before_byte;
5263 if (old_begv > before)
5265 old_begv += PT - before;
5266 old_begv_byte += PT_BYTE - before_byte;
5268 if (old_zv >= before)
5270 old_zv += PT - before;
5271 old_zv_byte += PT_BYTE - before_byte;
5274 /* If the restriction isn't what it should be, set it. */
5275 if (old_begv != BEGV || old_zv != ZV)
5276 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5278 bset_read_only (current_buffer, old_read_only);
5279 SET_PT_BOTH (opoint, opoint_byte);
5281 return Qnil;
5284 /* Sending data to subprocess. */
5286 /* In send_process, when a write fails temporarily,
5287 wait_reading_process_output is called. It may execute user code,
5288 e.g. timers, that attempts to write new data to the same process.
5289 We must ensure that data is sent in the right order, and not
5290 interspersed half-completed with other writes (Bug#10815). This is
5291 handled by the write_queue element of struct process. It is a list
5292 with each entry having the form
5294 (string . (offset . length))
5296 where STRING is a lisp string, OFFSET is the offset into the
5297 string's byte sequence from which we should begin to send, and
5298 LENGTH is the number of bytes left to send. */
5300 /* Create a new entry in write_queue.
5301 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5302 BUF is a pointer to the string sequence of the input_obj or a C
5303 string in case of Qt or Qnil. */
5305 static void
5306 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5307 const char *buf, ptrdiff_t len, bool front)
5309 ptrdiff_t offset;
5310 Lisp_Object entry, obj;
5312 if (STRINGP (input_obj))
5314 offset = buf - SSDATA (input_obj);
5315 obj = input_obj;
5317 else
5319 offset = 0;
5320 obj = make_unibyte_string (buf, len);
5323 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5325 if (front)
5326 pset_write_queue (p, Fcons (entry, p->write_queue));
5327 else
5328 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5331 /* Remove the first element in the write_queue of process P, put its
5332 contents in OBJ, BUF and LEN, and return true. If the
5333 write_queue is empty, return false. */
5335 static bool
5336 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5337 const char **buf, ptrdiff_t *len)
5339 Lisp_Object entry, offset_length;
5340 ptrdiff_t offset;
5342 if (NILP (p->write_queue))
5343 return 0;
5345 entry = XCAR (p->write_queue);
5346 pset_write_queue (p, XCDR (p->write_queue));
5348 *obj = XCAR (entry);
5349 offset_length = XCDR (entry);
5351 *len = XINT (XCDR (offset_length));
5352 offset = XINT (XCAR (offset_length));
5353 *buf = SSDATA (*obj) + offset;
5355 return 1;
5358 /* Send some data to process PROC.
5359 BUF is the beginning of the data; LEN is the number of characters.
5360 OBJECT is the Lisp object that the data comes from. If OBJECT is
5361 nil or t, it means that the data comes from C string.
5363 If OBJECT is not nil, the data is encoded by PROC's coding-system
5364 for encoding before it is sent.
5366 This function can evaluate Lisp code and can garbage collect. */
5368 static void
5369 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5370 Lisp_Object object)
5372 struct Lisp_Process *p = XPROCESS (proc);
5373 ssize_t rv;
5374 struct coding_system *coding;
5376 if (p->raw_status_new)
5377 update_status (p);
5378 if (! EQ (p->status, Qrun))
5379 error ("Process %s not running", SDATA (p->name));
5380 if (p->outfd < 0)
5381 error ("Output file descriptor of %s is closed", SDATA (p->name));
5383 coding = proc_encode_coding_system[p->outfd];
5384 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5386 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5387 || (BUFFERP (object)
5388 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5389 || EQ (object, Qt))
5391 pset_encode_coding_system
5392 (p, complement_process_encoding_system (p->encode_coding_system));
5393 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5395 /* The coding system for encoding was changed to raw-text
5396 because we sent a unibyte text previously. Now we are
5397 sending a multibyte text, thus we must encode it by the
5398 original coding system specified for the current process.
5400 Another reason we come here is that the coding system
5401 was just complemented and a new one was returned by
5402 complement_process_encoding_system. */
5403 setup_coding_system (p->encode_coding_system, coding);
5404 Vlast_coding_system_used = p->encode_coding_system;
5406 coding->src_multibyte = 1;
5408 else
5410 coding->src_multibyte = 0;
5411 /* For sending a unibyte text, character code conversion should
5412 not take place but EOL conversion should. So, setup raw-text
5413 or one of the subsidiary if we have not yet done it. */
5414 if (CODING_REQUIRE_ENCODING (coding))
5416 if (CODING_REQUIRE_FLUSHING (coding))
5418 /* But, before changing the coding, we must flush out data. */
5419 coding->mode |= CODING_MODE_LAST_BLOCK;
5420 send_process (proc, "", 0, Qt);
5421 coding->mode &= CODING_MODE_LAST_BLOCK;
5423 setup_coding_system (raw_text_coding_system
5424 (Vlast_coding_system_used),
5425 coding);
5426 coding->src_multibyte = 0;
5429 coding->dst_multibyte = 0;
5431 if (CODING_REQUIRE_ENCODING (coding))
5433 coding->dst_object = Qt;
5434 if (BUFFERP (object))
5436 ptrdiff_t from_byte, from, to;
5437 ptrdiff_t save_pt, save_pt_byte;
5438 struct buffer *cur = current_buffer;
5440 set_buffer_internal (XBUFFER (object));
5441 save_pt = PT, save_pt_byte = PT_BYTE;
5443 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5444 from = BYTE_TO_CHAR (from_byte);
5445 to = BYTE_TO_CHAR (from_byte + len);
5446 TEMP_SET_PT_BOTH (from, from_byte);
5447 encode_coding_object (coding, object, from, from_byte,
5448 to, from_byte + len, Qt);
5449 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5450 set_buffer_internal (cur);
5452 else if (STRINGP (object))
5454 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5455 SBYTES (object), Qt);
5457 else
5459 coding->dst_object = make_unibyte_string (buf, len);
5460 coding->produced = len;
5463 len = coding->produced;
5464 object = coding->dst_object;
5465 buf = SSDATA (object);
5468 /* If there is already data in the write_queue, put the new data
5469 in the back of queue. Otherwise, ignore it. */
5470 if (!NILP (p->write_queue))
5471 write_queue_push (p, object, buf, len, 0);
5473 do /* while !NILP (p->write_queue) */
5475 ptrdiff_t cur_len = -1;
5476 const char *cur_buf;
5477 Lisp_Object cur_object;
5479 /* If write_queue is empty, ignore it. */
5480 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5482 cur_len = len;
5483 cur_buf = buf;
5484 cur_object = object;
5487 while (cur_len > 0)
5489 /* Send this batch, using one or more write calls. */
5490 ptrdiff_t written = 0;
5491 int outfd = p->outfd;
5492 #ifdef DATAGRAM_SOCKETS
5493 if (DATAGRAM_CHAN_P (outfd))
5495 rv = sendto (outfd, cur_buf, cur_len,
5496 0, datagram_address[outfd].sa,
5497 datagram_address[outfd].len);
5498 if (rv >= 0)
5499 written = rv;
5500 else if (errno == EMSGSIZE)
5501 report_file_error ("Sending datagram", proc);
5503 else
5504 #endif
5506 #ifdef HAVE_GNUTLS
5507 if (p->gnutls_p && p->gnutls_state)
5508 written = emacs_gnutls_write (p, cur_buf, cur_len);
5509 else
5510 #endif
5511 written = emacs_write_sig (outfd, cur_buf, cur_len);
5512 rv = (written ? 0 : -1);
5513 #ifdef ADAPTIVE_READ_BUFFERING
5514 if (p->read_output_delay > 0
5515 && p->adaptive_read_buffering == 1)
5517 p->read_output_delay = 0;
5518 process_output_delay_count--;
5519 p->read_output_skip = 0;
5521 #endif
5524 if (rv < 0)
5526 if (errno == EAGAIN
5527 #ifdef EWOULDBLOCK
5528 || errno == EWOULDBLOCK
5529 #endif
5531 /* Buffer is full. Wait, accepting input;
5532 that may allow the program
5533 to finish doing output and read more. */
5535 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5536 /* A gross hack to work around a bug in FreeBSD.
5537 In the following sequence, read(2) returns
5538 bogus data:
5540 write(2) 1022 bytes
5541 write(2) 954 bytes, get EAGAIN
5542 read(2) 1024 bytes in process_read_output
5543 read(2) 11 bytes in process_read_output
5545 That is, read(2) returns more bytes than have
5546 ever been written successfully. The 1033 bytes
5547 read are the 1022 bytes written successfully
5548 after processing (for example with CRs added if
5549 the terminal is set up that way which it is
5550 here). The same bytes will be seen again in a
5551 later read(2), without the CRs. */
5553 if (errno == EAGAIN)
5555 int flags = FWRITE;
5556 ioctl (p->outfd, TIOCFLUSH, &flags);
5558 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5560 /* Put what we should have written in wait_queue. */
5561 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5562 wait_reading_process_output (0, 20 * 1000 * 1000,
5563 0, 0, Qnil, NULL, 0);
5564 /* Reread queue, to see what is left. */
5565 break;
5567 else if (errno == EPIPE)
5569 p->raw_status_new = 0;
5570 pset_status (p, list2 (Qexit, make_number (256)));
5571 p->tick = ++process_tick;
5572 deactivate_process (proc);
5573 error ("process %s no longer connected to pipe; closed it",
5574 SDATA (p->name));
5576 else
5577 /* This is a real error. */
5578 report_file_error ("Writing to process", proc);
5580 cur_buf += written;
5581 cur_len -= written;
5584 while (!NILP (p->write_queue));
5587 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5588 3, 3, 0,
5589 doc: /* Send current contents of region as input to PROCESS.
5590 PROCESS may be a process, a buffer, the name of a process or buffer, or
5591 nil, indicating the current buffer's process.
5592 Called from program, takes three arguments, PROCESS, START and END.
5593 If the region is more than 500 characters long,
5594 it is sent in several bunches. This may happen even for shorter regions.
5595 Output from processes can arrive in between bunches. */)
5596 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5598 Lisp_Object proc = get_process (process);
5599 ptrdiff_t start_byte, end_byte;
5601 validate_region (&start, &end);
5603 start_byte = CHAR_TO_BYTE (XINT (start));
5604 end_byte = CHAR_TO_BYTE (XINT (end));
5606 if (XINT (start) < GPT && XINT (end) > GPT)
5607 move_gap_both (XINT (start), start_byte);
5609 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5610 end_byte - start_byte, Fcurrent_buffer ());
5612 return Qnil;
5615 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5616 2, 2, 0,
5617 doc: /* Send PROCESS the contents of STRING as input.
5618 PROCESS may be a process, a buffer, the name of a process or buffer, or
5619 nil, indicating the current buffer's process.
5620 If STRING is more than 500 characters long,
5621 it is sent in several bunches. This may happen even for shorter strings.
5622 Output from processes can arrive in between bunches. */)
5623 (Lisp_Object process, Lisp_Object string)
5625 Lisp_Object proc;
5626 CHECK_STRING (string);
5627 proc = get_process (process);
5628 send_process (proc, SSDATA (string),
5629 SBYTES (string), string);
5630 return Qnil;
5633 /* Return the foreground process group for the tty/pty that
5634 the process P uses. */
5635 static pid_t
5636 emacs_get_tty_pgrp (struct Lisp_Process *p)
5638 pid_t gid = -1;
5640 #ifdef TIOCGPGRP
5641 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5643 int fd;
5644 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5645 master side. Try the slave side. */
5646 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5648 if (fd != -1)
5650 ioctl (fd, TIOCGPGRP, &gid);
5651 emacs_close (fd);
5654 #endif /* defined (TIOCGPGRP ) */
5656 return gid;
5659 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5660 Sprocess_running_child_p, 0, 1, 0,
5661 doc: /* Return t if PROCESS has given the terminal to a child.
5662 If the operating system does not make it possible to find out,
5663 return t unconditionally. */)
5664 (Lisp_Object process)
5666 /* Initialize in case ioctl doesn't exist or gives an error,
5667 in a way that will cause returning t. */
5668 pid_t gid;
5669 Lisp_Object proc;
5670 struct Lisp_Process *p;
5672 proc = get_process (process);
5673 p = XPROCESS (proc);
5675 if (!EQ (p->type, Qreal))
5676 error ("Process %s is not a subprocess",
5677 SDATA (p->name));
5678 if (p->infd < 0)
5679 error ("Process %s is not active",
5680 SDATA (p->name));
5682 gid = emacs_get_tty_pgrp (p);
5684 if (gid == p->pid)
5685 return Qnil;
5686 return Qt;
5689 /* Send a signal number SIGNO to PROCESS.
5690 If CURRENT_GROUP is t, that means send to the process group
5691 that currently owns the terminal being used to communicate with PROCESS.
5692 This is used for various commands in shell mode.
5693 If CURRENT_GROUP is lambda, that means send to the process group
5694 that currently owns the terminal, but only if it is NOT the shell itself.
5696 If NOMSG is false, insert signal-announcements into process's buffers
5697 right away.
5699 If we can, we try to signal PROCESS by sending control characters
5700 down the pty. This allows us to signal inferiors who have changed
5701 their uid, for which kill would return an EPERM error. */
5703 static void
5704 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5705 bool nomsg)
5707 Lisp_Object proc;
5708 struct Lisp_Process *p;
5709 pid_t gid;
5710 bool no_pgrp = 0;
5712 proc = get_process (process);
5713 p = XPROCESS (proc);
5715 if (!EQ (p->type, Qreal))
5716 error ("Process %s is not a subprocess",
5717 SDATA (p->name));
5718 if (p->infd < 0)
5719 error ("Process %s is not active",
5720 SDATA (p->name));
5722 if (!p->pty_flag)
5723 current_group = Qnil;
5725 /* If we are using pgrps, get a pgrp number and make it negative. */
5726 if (NILP (current_group))
5727 /* Send the signal to the shell's process group. */
5728 gid = p->pid;
5729 else
5731 #ifdef SIGNALS_VIA_CHARACTERS
5732 /* If possible, send signals to the entire pgrp
5733 by sending an input character to it. */
5735 struct termios t;
5736 cc_t *sig_char = NULL;
5738 tcgetattr (p->infd, &t);
5740 switch (signo)
5742 case SIGINT:
5743 sig_char = &t.c_cc[VINTR];
5744 break;
5746 case SIGQUIT:
5747 sig_char = &t.c_cc[VQUIT];
5748 break;
5750 case SIGTSTP:
5751 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5752 sig_char = &t.c_cc[VSWTCH];
5753 #else
5754 sig_char = &t.c_cc[VSUSP];
5755 #endif
5756 break;
5759 if (sig_char && *sig_char != CDISABLE)
5761 send_process (proc, (char *) sig_char, 1, Qnil);
5762 return;
5764 /* If we can't send the signal with a character,
5765 fall through and send it another way. */
5767 /* The code above may fall through if it can't
5768 handle the signal. */
5769 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5771 #ifdef TIOCGPGRP
5772 /* Get the current pgrp using the tty itself, if we have that.
5773 Otherwise, use the pty to get the pgrp.
5774 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5775 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5776 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5777 His patch indicates that if TIOCGPGRP returns an error, then
5778 we should just assume that p->pid is also the process group id. */
5780 gid = emacs_get_tty_pgrp (p);
5782 if (gid == -1)
5783 /* If we can't get the information, assume
5784 the shell owns the tty. */
5785 gid = p->pid;
5787 /* It is not clear whether anything really can set GID to -1.
5788 Perhaps on some system one of those ioctls can or could do so.
5789 Or perhaps this is vestigial. */
5790 if (gid == -1)
5791 no_pgrp = 1;
5792 #else /* ! defined (TIOCGPGRP) */
5793 /* Can't select pgrps on this system, so we know that
5794 the child itself heads the pgrp. */
5795 gid = p->pid;
5796 #endif /* ! defined (TIOCGPGRP) */
5798 /* If current_group is lambda, and the shell owns the terminal,
5799 don't send any signal. */
5800 if (EQ (current_group, Qlambda) && gid == p->pid)
5801 return;
5804 #ifdef SIGCONT
5805 if (signo == SIGCONT)
5807 p->raw_status_new = 0;
5808 pset_status (p, Qrun);
5809 p->tick = ++process_tick;
5810 if (!nomsg)
5812 status_notify (NULL, NULL);
5813 redisplay_preserve_echo_area (13);
5816 #endif
5818 #ifdef TIOCSIGSEND
5819 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
5820 We don't know whether the bug is fixed in later HP-UX versions. */
5821 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
5822 return;
5823 #endif
5825 /* If we don't have process groups, send the signal to the immediate
5826 subprocess. That isn't really right, but it's better than any
5827 obvious alternative. */
5828 pid_t pid = no_pgrp ? gid : - gid;
5830 /* Do not kill an already-reaped process, as that could kill an
5831 innocent bystander that happens to have the same process ID. */
5832 sigset_t oldset;
5833 block_child_signal (&oldset);
5834 if (p->alive)
5835 kill (pid, signo);
5836 unblock_child_signal (&oldset);
5839 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5840 doc: /* Interrupt process PROCESS.
5841 PROCESS may be a process, a buffer, or the name of a process or buffer.
5842 No arg or nil means current buffer's process.
5843 Second arg CURRENT-GROUP non-nil means send signal to
5844 the current process-group of the process's controlling terminal
5845 rather than to the process's own process group.
5846 If the process is a shell, this means interrupt current subjob
5847 rather than the shell.
5849 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5850 don't send the signal. */)
5851 (Lisp_Object process, Lisp_Object current_group)
5853 process_send_signal (process, SIGINT, current_group, 0);
5854 return process;
5857 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5858 doc: /* Kill process PROCESS. May be process or name of one.
5859 See function `interrupt-process' for more details on usage. */)
5860 (Lisp_Object process, Lisp_Object current_group)
5862 process_send_signal (process, SIGKILL, current_group, 0);
5863 return process;
5866 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5867 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5868 See function `interrupt-process' for more details on usage. */)
5869 (Lisp_Object process, Lisp_Object current_group)
5871 process_send_signal (process, SIGQUIT, current_group, 0);
5872 return process;
5875 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
5876 doc: /* Stop process PROCESS. May be process or name of one.
5877 See function `interrupt-process' for more details on usage.
5878 If PROCESS is a network or serial process, inhibit handling of incoming
5879 traffic. */)
5880 (Lisp_Object process, Lisp_Object current_group)
5882 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5884 struct Lisp_Process *p;
5886 p = XPROCESS (process);
5887 if (NILP (p->command)
5888 && p->infd >= 0)
5890 FD_CLR (p->infd, &input_wait_mask);
5891 FD_CLR (p->infd, &non_keyboard_wait_mask);
5893 pset_command (p, Qt);
5894 return process;
5896 #ifndef SIGTSTP
5897 error ("No SIGTSTP support");
5898 #else
5899 process_send_signal (process, SIGTSTP, current_group, 0);
5900 #endif
5901 return process;
5904 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
5905 doc: /* Continue process PROCESS. May be process or name of one.
5906 See function `interrupt-process' for more details on usage.
5907 If PROCESS is a network or serial process, resume handling of incoming
5908 traffic. */)
5909 (Lisp_Object process, Lisp_Object current_group)
5911 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5913 struct Lisp_Process *p;
5915 p = XPROCESS (process);
5916 if (EQ (p->command, Qt)
5917 && p->infd >= 0
5918 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
5920 FD_SET (p->infd, &input_wait_mask);
5921 FD_SET (p->infd, &non_keyboard_wait_mask);
5922 #ifdef WINDOWSNT
5923 if (fd_info[ p->infd ].flags & FILE_SERIAL)
5924 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
5925 #else /* not WINDOWSNT */
5926 tcflush (p->infd, TCIFLUSH);
5927 #endif /* not WINDOWSNT */
5929 pset_command (p, Qnil);
5930 return process;
5932 #ifdef SIGCONT
5933 process_send_signal (process, SIGCONT, current_group, 0);
5934 #else
5935 error ("No SIGCONT support");
5936 #endif
5937 return process;
5940 /* Return the integer value of the signal whose abbreviation is ABBR,
5941 or a negative number if there is no such signal. */
5942 static int
5943 abbr_to_signal (char const *name)
5945 int i, signo;
5946 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
5948 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
5949 name += 3;
5951 for (i = 0; i < sizeof sigbuf; i++)
5953 sigbuf[i] = c_toupper (name[i]);
5954 if (! sigbuf[i])
5955 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
5958 return -1;
5961 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
5962 2, 2, "sProcess (name or number): \nnSignal code: ",
5963 doc: /* Send PROCESS the signal with code SIGCODE.
5964 PROCESS may also be a number specifying the process id of the
5965 process to signal; in this case, the process need not be a child of
5966 this Emacs.
5967 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5968 (Lisp_Object process, Lisp_Object sigcode)
5970 pid_t pid;
5971 int signo;
5973 if (STRINGP (process))
5975 Lisp_Object tem = Fget_process (process);
5976 if (NILP (tem))
5978 Lisp_Object process_number
5979 = string_to_number (SSDATA (process), 10, 1);
5980 if (INTEGERP (process_number) || FLOATP (process_number))
5981 tem = process_number;
5983 process = tem;
5985 else if (!NUMBERP (process))
5986 process = get_process (process);
5988 if (NILP (process))
5989 return process;
5991 if (NUMBERP (process))
5992 CONS_TO_INTEGER (process, pid_t, pid);
5993 else
5995 CHECK_PROCESS (process);
5996 pid = XPROCESS (process)->pid;
5997 if (pid <= 0)
5998 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6001 if (INTEGERP (sigcode))
6003 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6004 signo = XINT (sigcode);
6006 else
6008 char *name;
6010 CHECK_SYMBOL (sigcode);
6011 name = SSDATA (SYMBOL_NAME (sigcode));
6013 signo = abbr_to_signal (name);
6014 if (signo < 0)
6015 error ("Undefined signal name %s", name);
6018 return make_number (kill (pid, signo));
6021 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6022 doc: /* Make PROCESS see end-of-file in its input.
6023 EOF comes after any text already sent to it.
6024 PROCESS may be a process, a buffer, the name of a process or buffer, or
6025 nil, indicating the current buffer's process.
6026 If PROCESS is a network connection, or is a process communicating
6027 through a pipe (as opposed to a pty), then you cannot send any more
6028 text to PROCESS after you call this function.
6029 If PROCESS is a serial process, wait until all output written to the
6030 process has been transmitted to the serial port. */)
6031 (Lisp_Object process)
6033 Lisp_Object proc;
6034 struct coding_system *coding = NULL;
6035 int outfd;
6037 if (DATAGRAM_CONN_P (process))
6038 return process;
6040 proc = get_process (process);
6041 outfd = XPROCESS (proc)->outfd;
6042 if (outfd >= 0)
6043 coding = proc_encode_coding_system[outfd];
6045 /* Make sure the process is really alive. */
6046 if (XPROCESS (proc)->raw_status_new)
6047 update_status (XPROCESS (proc));
6048 if (! EQ (XPROCESS (proc)->status, Qrun))
6049 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6051 if (coding && CODING_REQUIRE_FLUSHING (coding))
6053 coding->mode |= CODING_MODE_LAST_BLOCK;
6054 send_process (proc, "", 0, Qnil);
6057 if (XPROCESS (proc)->pty_flag)
6058 send_process (proc, "\004", 1, Qnil);
6059 else if (EQ (XPROCESS (proc)->type, Qserial))
6061 #ifndef WINDOWSNT
6062 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6063 report_file_error ("Failed tcdrain", Qnil);
6064 #endif /* not WINDOWSNT */
6065 /* Do nothing on Windows because writes are blocking. */
6067 else
6069 struct Lisp_Process *p = XPROCESS (proc);
6070 int old_outfd = p->outfd;
6071 int new_outfd;
6073 #ifdef HAVE_SHUTDOWN
6074 /* If this is a network connection, or socketpair is used
6075 for communication with the subprocess, call shutdown to cause EOF.
6076 (In some old system, shutdown to socketpair doesn't work.
6077 Then we just can't win.) */
6078 if (0 <= old_outfd
6079 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6080 shutdown (old_outfd, 1);
6081 #endif
6082 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6083 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6084 if (new_outfd < 0)
6085 report_file_error ("Opening null device", Qnil);
6086 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6087 p->outfd = new_outfd;
6089 if (!proc_encode_coding_system[new_outfd])
6090 proc_encode_coding_system[new_outfd]
6091 = xmalloc (sizeof (struct coding_system));
6092 if (old_outfd >= 0)
6094 *proc_encode_coding_system[new_outfd]
6095 = *proc_encode_coding_system[old_outfd];
6096 memset (proc_encode_coding_system[old_outfd], 0,
6097 sizeof (struct coding_system));
6099 else
6100 setup_coding_system (p->encode_coding_system,
6101 proc_encode_coding_system[new_outfd]);
6103 return process;
6106 /* The main Emacs thread records child processes in three places:
6108 - Vprocess_alist, for asynchronous subprocesses, which are child
6109 processes visible to Lisp.
6111 - deleted_pid_list, for child processes invisible to Lisp,
6112 typically because of delete-process. These are recorded so that
6113 the processes can be reaped when they exit, so that the operating
6114 system's process table is not cluttered by zombies.
6116 - the local variable PID in Fcall_process, call_process_cleanup and
6117 call_process_kill, for synchronous subprocesses.
6118 record_unwind_protect is used to make sure this process is not
6119 forgotten: if the user interrupts call-process and the child
6120 process refuses to exit immediately even with two C-g's,
6121 call_process_kill adds PID's contents to deleted_pid_list before
6122 returning.
6124 The main Emacs thread invokes waitpid only on child processes that
6125 it creates and that have not been reaped. This avoid races on
6126 platforms such as GTK, where other threads create their own
6127 subprocesses which the main thread should not reap. For example,
6128 if the main thread attempted to reap an already-reaped child, it
6129 might inadvertently reap a GTK-created process that happened to
6130 have the same process ID. */
6132 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6133 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6134 keep track of its own children. GNUstep is similar. */
6136 static void dummy_handler (int sig) {}
6137 static signal_handler_t volatile lib_child_handler;
6139 /* Handle a SIGCHLD signal by looking for known child processes of
6140 Emacs whose status have changed. For each one found, record its
6141 new status.
6143 All we do is change the status; we do not run sentinels or print
6144 notifications. That is saved for the next time keyboard input is
6145 done, in order to avoid timing errors.
6147 ** WARNING: this can be called during garbage collection.
6148 Therefore, it must not be fooled by the presence of mark bits in
6149 Lisp objects.
6151 ** USG WARNING: Although it is not obvious from the documentation
6152 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6153 signal() before executing at least one wait(), otherwise the
6154 handler will be called again, resulting in an infinite loop. The
6155 relevant portion of the documentation reads "SIGCLD signals will be
6156 queued and the signal-catching function will be continually
6157 reentered until the queue is empty". Invoking signal() causes the
6158 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6159 Inc.
6161 ** Malloc WARNING: This should never call malloc either directly or
6162 indirectly; if it does, that is a bug. */
6164 static void
6165 handle_child_signal (int sig)
6167 Lisp_Object tail, proc;
6169 /* Find the process that signaled us, and record its status. */
6171 /* The process can have been deleted by Fdelete_process, or have
6172 been started asynchronously by Fcall_process. */
6173 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6175 bool all_pids_are_fixnums
6176 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6177 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6178 Lisp_Object head = XCAR (tail);
6179 Lisp_Object xpid;
6180 if (! CONSP (head))
6181 continue;
6182 xpid = XCAR (head);
6183 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6185 pid_t deleted_pid;
6186 if (INTEGERP (xpid))
6187 deleted_pid = XINT (xpid);
6188 else
6189 deleted_pid = XFLOAT_DATA (xpid);
6190 if (child_status_changed (deleted_pid, 0, 0))
6192 if (STRINGP (XCDR (head)))
6193 unlink (SSDATA (XCDR (head)));
6194 XSETCAR (tail, Qnil);
6199 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6200 FOR_EACH_PROCESS (tail, proc)
6202 struct Lisp_Process *p = XPROCESS (proc);
6203 int status;
6205 if (p->alive
6206 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6208 /* Change the status of the process that was found. */
6209 p->tick = ++process_tick;
6210 p->raw_status = status;
6211 p->raw_status_new = 1;
6213 /* If process has terminated, stop waiting for its output. */
6214 if (WIFSIGNALED (status) || WIFEXITED (status))
6216 bool clear_desc_flag = 0;
6217 p->alive = 0;
6218 if (p->infd >= 0)
6219 clear_desc_flag = 1;
6221 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6222 if (clear_desc_flag)
6224 FD_CLR (p->infd, &input_wait_mask);
6225 FD_CLR (p->infd, &non_keyboard_wait_mask);
6231 lib_child_handler (sig);
6232 #ifdef NS_IMPL_GNUSTEP
6233 /* NSTask in GNUstep sets its child handler each time it is called.
6234 So we must re-set ours. */
6235 catch_child_signal ();
6236 #endif
6239 static void
6240 deliver_child_signal (int sig)
6242 deliver_process_signal (sig, handle_child_signal);
6246 static Lisp_Object
6247 exec_sentinel_error_handler (Lisp_Object error_val)
6249 cmd_error_internal (error_val, "error in process sentinel: ");
6250 Vinhibit_quit = Qt;
6251 update_echo_area ();
6252 Fsleep_for (make_number (2), Qnil);
6253 return Qt;
6256 static void
6257 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6259 Lisp_Object sentinel, odeactivate;
6260 struct Lisp_Process *p = XPROCESS (proc);
6261 ptrdiff_t count = SPECPDL_INDEX ();
6262 bool outer_running_asynch_code = running_asynch_code;
6263 int waiting = waiting_for_user_input_p;
6265 if (inhibit_sentinels)
6266 return;
6268 /* No need to gcpro these, because all we do with them later
6269 is test them for EQness, and none of them should be a string. */
6270 odeactivate = Vdeactivate_mark;
6271 #if 0
6272 Lisp_Object obuffer, okeymap;
6273 XSETBUFFER (obuffer, current_buffer);
6274 okeymap = BVAR (current_buffer, keymap);
6275 #endif
6277 /* There's no good reason to let sentinels change the current
6278 buffer, and many callers of accept-process-output, sit-for, and
6279 friends don't expect current-buffer to be changed from under them. */
6280 record_unwind_current_buffer ();
6282 sentinel = p->sentinel;
6284 /* Inhibit quit so that random quits don't screw up a running filter. */
6285 specbind (Qinhibit_quit, Qt);
6286 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6288 /* In case we get recursively called,
6289 and we already saved the match data nonrecursively,
6290 save the same match data in safely recursive fashion. */
6291 if (outer_running_asynch_code)
6293 Lisp_Object tem;
6294 tem = Fmatch_data (Qnil, Qnil, Qnil);
6295 restore_search_regs ();
6296 record_unwind_save_match_data ();
6297 Fset_match_data (tem, Qt);
6300 /* For speed, if a search happens within this code,
6301 save the match data in a special nonrecursive fashion. */
6302 running_asynch_code = 1;
6304 internal_condition_case_1 (read_process_output_call,
6305 list3 (sentinel, proc, reason),
6306 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6307 exec_sentinel_error_handler);
6309 /* If we saved the match data nonrecursively, restore it now. */
6310 restore_search_regs ();
6311 running_asynch_code = outer_running_asynch_code;
6313 Vdeactivate_mark = odeactivate;
6315 /* Restore waiting_for_user_input_p as it was
6316 when we were called, in case the filter clobbered it. */
6317 waiting_for_user_input_p = waiting;
6319 #if 0
6320 if (! EQ (Fcurrent_buffer (), obuffer)
6321 || ! EQ (current_buffer->keymap, okeymap))
6322 #endif
6323 /* But do it only if the caller is actually going to read events.
6324 Otherwise there's no need to make him wake up, and it could
6325 cause trouble (for example it would make sit_for return). */
6326 if (waiting_for_user_input_p == -1)
6327 record_asynch_buffer_change ();
6329 unbind_to (count, Qnil);
6332 /* Report all recent events of a change in process status
6333 (either run the sentinel or output a message).
6334 This is usually done while Emacs is waiting for keyboard input
6335 but can be done at other times.
6337 Return positive if any input was received from WAIT_PROC (or from
6338 any process if WAIT_PROC is null), zero if input was attempted but
6339 none received, and negative if we didn't even try. */
6341 static int
6342 status_notify (struct Lisp_Process *deleting_process,
6343 struct Lisp_Process *wait_proc)
6345 Lisp_Object proc;
6346 Lisp_Object tail, msg;
6347 struct gcpro gcpro1, gcpro2;
6348 int got_some_input = -1;
6350 tail = Qnil;
6351 msg = Qnil;
6352 /* We need to gcpro tail; if read_process_output calls a filter
6353 which deletes a process and removes the cons to which tail points
6354 from Vprocess_alist, and then causes a GC, tail is an unprotected
6355 reference. */
6356 GCPRO2 (tail, msg);
6358 /* Set this now, so that if new processes are created by sentinels
6359 that we run, we get called again to handle their status changes. */
6360 update_tick = process_tick;
6362 FOR_EACH_PROCESS (tail, proc)
6364 Lisp_Object symbol;
6365 register struct Lisp_Process *p = XPROCESS (proc);
6367 if (p->tick != p->update_tick)
6369 p->update_tick = p->tick;
6371 /* If process is still active, read any output that remains. */
6372 while (! EQ (p->filter, Qt)
6373 && ! EQ (p->status, Qconnect)
6374 && ! EQ (p->status, Qlisten)
6375 /* Network or serial process not stopped: */
6376 && ! EQ (p->command, Qt)
6377 && p->infd >= 0
6378 && p != deleting_process)
6380 int nread = read_process_output (proc, p->infd);
6381 if (got_some_input < nread)
6382 got_some_input = nread;
6383 if (nread <= 0)
6384 break;
6387 /* Get the text to use for the message. */
6388 if (p->raw_status_new)
6389 update_status (p);
6390 msg = status_message (p);
6392 /* If process is terminated, deactivate it or delete it. */
6393 symbol = p->status;
6394 if (CONSP (p->status))
6395 symbol = XCAR (p->status);
6397 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6398 || EQ (symbol, Qclosed))
6400 if (delete_exited_processes)
6401 remove_process (proc);
6402 else
6403 deactivate_process (proc);
6406 /* The actions above may have further incremented p->tick.
6407 So set p->update_tick again so that an error in the sentinel will
6408 not cause this code to be run again. */
6409 p->update_tick = p->tick;
6410 /* Now output the message suitably. */
6411 exec_sentinel (proc, msg);
6413 } /* end for */
6415 update_mode_lines = 24; /* In case buffers use %s in mode-line-format. */
6416 UNGCPRO;
6417 return got_some_input;
6420 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6421 Sinternal_default_process_sentinel, 2, 2, 0,
6422 doc: /* Function used as default sentinel for processes.
6423 This inserts a status message into the process's buffer, if there is one. */)
6424 (Lisp_Object proc, Lisp_Object msg)
6426 Lisp_Object buffer, symbol;
6427 struct Lisp_Process *p;
6428 CHECK_PROCESS (proc);
6429 p = XPROCESS (proc);
6430 buffer = p->buffer;
6431 symbol = p->status;
6432 if (CONSP (symbol))
6433 symbol = XCAR (symbol);
6435 if (!EQ (symbol, Qrun) && !NILP (buffer))
6437 Lisp_Object tem;
6438 struct buffer *old = current_buffer;
6439 ptrdiff_t opoint, opoint_byte;
6440 ptrdiff_t before, before_byte;
6442 /* Avoid error if buffer is deleted
6443 (probably that's why the process is dead, too). */
6444 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6445 return Qnil;
6446 Fset_buffer (buffer);
6448 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6449 msg = (code_convert_string_norecord
6450 (msg, Vlocale_coding_system, 1));
6452 opoint = PT;
6453 opoint_byte = PT_BYTE;
6454 /* Insert new output into buffer
6455 at the current end-of-output marker,
6456 thus preserving logical ordering of input and output. */
6457 if (XMARKER (p->mark)->buffer)
6458 Fgoto_char (p->mark);
6459 else
6460 SET_PT_BOTH (ZV, ZV_BYTE);
6462 before = PT;
6463 before_byte = PT_BYTE;
6465 tem = BVAR (current_buffer, read_only);
6466 bset_read_only (current_buffer, Qnil);
6467 insert_string ("\nProcess ");
6468 { /* FIXME: temporary kludge. */
6469 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6470 insert_string (" ");
6471 Finsert (1, &msg);
6472 bset_read_only (current_buffer, tem);
6473 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6475 if (opoint >= before)
6476 SET_PT_BOTH (opoint + (PT - before),
6477 opoint_byte + (PT_BYTE - before_byte));
6478 else
6479 SET_PT_BOTH (opoint, opoint_byte);
6481 set_buffer_internal (old);
6483 return Qnil;
6487 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6488 Sset_process_coding_system, 1, 3, 0,
6489 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6490 DECODING will be used to decode subprocess output and ENCODING to
6491 encode subprocess input. */)
6492 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6494 register struct Lisp_Process *p;
6496 CHECK_PROCESS (process);
6497 p = XPROCESS (process);
6498 if (p->infd < 0)
6499 error ("Input file descriptor of %s closed", SDATA (p->name));
6500 if (p->outfd < 0)
6501 error ("Output file descriptor of %s closed", SDATA (p->name));
6502 Fcheck_coding_system (decoding);
6503 Fcheck_coding_system (encoding);
6504 encoding = coding_inherit_eol_type (encoding, Qnil);
6505 pset_decode_coding_system (p, decoding);
6506 pset_encode_coding_system (p, encoding);
6507 setup_process_coding_systems (process);
6509 return Qnil;
6512 DEFUN ("process-coding-system",
6513 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6514 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6515 (register Lisp_Object process)
6517 CHECK_PROCESS (process);
6518 return Fcons (XPROCESS (process)->decode_coding_system,
6519 XPROCESS (process)->encode_coding_system);
6522 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6523 Sset_process_filter_multibyte, 2, 2, 0,
6524 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6525 If FLAG is non-nil, the filter is given multibyte strings.
6526 If FLAG is nil, the filter is given unibyte strings. In this case,
6527 all character code conversion except for end-of-line conversion is
6528 suppressed. */)
6529 (Lisp_Object process, Lisp_Object flag)
6531 register struct Lisp_Process *p;
6533 CHECK_PROCESS (process);
6534 p = XPROCESS (process);
6535 if (NILP (flag))
6536 pset_decode_coding_system
6537 (p, raw_text_coding_system (p->decode_coding_system));
6538 setup_process_coding_systems (process);
6540 return Qnil;
6543 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6544 Sprocess_filter_multibyte_p, 1, 1, 0,
6545 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6546 (Lisp_Object process)
6548 register struct Lisp_Process *p;
6549 struct coding_system *coding;
6551 CHECK_PROCESS (process);
6552 p = XPROCESS (process);
6553 if (p->infd < 0)
6554 return Qnil;
6555 coding = proc_decode_coding_system[p->infd];
6556 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6562 # ifdef HAVE_GPM
6564 void
6565 add_gpm_wait_descriptor (int desc)
6567 add_keyboard_wait_descriptor (desc);
6570 void
6571 delete_gpm_wait_descriptor (int desc)
6573 delete_keyboard_wait_descriptor (desc);
6576 # endif
6578 # ifdef USABLE_SIGIO
6580 /* Return true if *MASK has a bit set
6581 that corresponds to one of the keyboard input descriptors. */
6583 static bool
6584 keyboard_bit_set (fd_set *mask)
6586 int fd;
6588 for (fd = 0; fd <= max_input_desc; fd++)
6589 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6590 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6591 return 1;
6593 return 0;
6595 # endif
6597 #else /* not subprocesses */
6599 /* Defined in msdos.c. */
6600 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6601 struct timespec *, void *);
6603 /* Implementation of wait_reading_process_output, assuming that there
6604 are no subprocesses. Used only by the MS-DOS build.
6606 Wait for timeout to elapse and/or keyboard input to be available.
6608 TIME_LIMIT is:
6609 timeout in seconds
6610 If negative, gobble data immediately available but don't wait for any.
6612 NSECS is:
6613 an additional duration to wait, measured in nanoseconds
6614 If TIME_LIMIT is zero, then:
6615 If NSECS == 0, there is no limit.
6616 If NSECS > 0, the timeout consists of NSECS only.
6617 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6619 READ_KBD is:
6620 0 to ignore keyboard input, or
6621 1 to return when input is available, or
6622 -1 means caller will actually read the input, so don't throw to
6623 the quit handler.
6625 see full version for other parameters. We know that wait_proc will
6626 always be NULL, since `subprocesses' isn't defined.
6628 DO_DISPLAY means redisplay should be done to show subprocess
6629 output that arrives.
6631 Return positive if we received input from WAIT_PROC (or from any
6632 process if WAIT_PROC is null), zero if we attempted to receive
6633 input but got none, and negative if we didn't even try. */
6636 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6637 bool do_display,
6638 Lisp_Object wait_for_cell,
6639 struct Lisp_Process *wait_proc, int just_wait_proc)
6641 register int nfds;
6642 struct timespec end_time, timeout;
6644 if (time_limit < 0)
6646 time_limit = 0;
6647 nsecs = -1;
6649 else if (TYPE_MAXIMUM (time_t) < time_limit)
6650 time_limit = TYPE_MAXIMUM (time_t);
6652 /* What does time_limit really mean? */
6653 if (time_limit || nsecs > 0)
6655 timeout = make_timespec (time_limit, nsecs);
6656 end_time = timespec_add (current_timespec (), timeout);
6659 /* Turn off periodic alarms (in case they are in use)
6660 and then turn off any other atimers,
6661 because the select emulator uses alarms. */
6662 stop_polling ();
6663 turn_on_atimers (0);
6665 while (1)
6667 bool timeout_reduced_for_timers = false;
6668 fd_set waitchannels;
6669 int xerrno;
6671 /* If calling from keyboard input, do not quit
6672 since we want to return C-g as an input character.
6673 Otherwise, do pending quit if requested. */
6674 if (read_kbd >= 0)
6675 QUIT;
6677 /* Exit now if the cell we're waiting for became non-nil. */
6678 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6679 break;
6681 /* Compute time from now till when time limit is up. */
6682 /* Exit if already run out. */
6683 if (nsecs < 0)
6685 /* A negative timeout means
6686 gobble output available now
6687 but don't wait at all. */
6689 timeout = make_timespec (0, 0);
6691 else if (time_limit || nsecs > 0)
6693 struct timespec now = current_timespec ();
6694 if (timespec_cmp (end_time, now) <= 0)
6695 break;
6696 timeout = timespec_sub (end_time, now);
6698 else
6700 timeout = make_timespec (100000, 0);
6703 /* If our caller will not immediately handle keyboard events,
6704 run timer events directly.
6705 (Callers that will immediately read keyboard events
6706 call timer_delay on their own.) */
6707 if (NILP (wait_for_cell))
6709 struct timespec timer_delay;
6713 unsigned old_timers_run = timers_run;
6714 timer_delay = timer_check ();
6715 if (timers_run != old_timers_run && do_display)
6716 /* We must retry, since a timer may have requeued itself
6717 and that could alter the time delay. */
6718 redisplay_preserve_echo_area (14);
6719 else
6720 break;
6722 while (!detect_input_pending ());
6724 /* If there is unread keyboard input, also return. */
6725 if (read_kbd != 0
6726 && requeued_events_pending_p ())
6727 break;
6729 if (timespec_valid_p (timer_delay) && nsecs >= 0)
6731 if (timespec_cmp (timer_delay, timeout) < 0)
6733 timeout = timer_delay;
6734 timeout_reduced_for_timers = true;
6739 /* Cause C-g and alarm signals to take immediate action,
6740 and cause input available signals to zero out timeout. */
6741 if (read_kbd < 0)
6742 set_waiting_for_input (&timeout);
6744 /* If a frame has been newly mapped and needs updating,
6745 reprocess its display stuff. */
6746 if (frame_garbaged && do_display)
6748 clear_waiting_for_input ();
6749 redisplay_preserve_echo_area (15);
6750 if (read_kbd < 0)
6751 set_waiting_for_input (&timeout);
6754 /* Wait till there is something to do. */
6755 FD_ZERO (&waitchannels);
6756 if (read_kbd && detect_input_pending ())
6757 nfds = 0;
6758 else
6760 if (read_kbd || !NILP (wait_for_cell))
6761 FD_SET (0, &waitchannels);
6762 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
6765 xerrno = errno;
6767 /* Make C-g and alarm signals set flags again. */
6768 clear_waiting_for_input ();
6770 /* If we woke up due to SIGWINCH, actually change size now. */
6771 do_pending_window_change (0);
6773 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
6774 /* We waited the full specified time, so return now. */
6775 break;
6777 if (nfds == -1)
6779 /* If the system call was interrupted, then go around the
6780 loop again. */
6781 if (xerrno == EINTR)
6782 FD_ZERO (&waitchannels);
6783 else
6784 report_file_errno ("Failed select", Qnil, xerrno);
6787 /* Check for keyboard input. */
6789 if (read_kbd
6790 && detect_input_pending_run_timers (do_display))
6792 swallow_events (do_display);
6793 if (detect_input_pending_run_timers (do_display))
6794 break;
6797 /* If there is unread keyboard input, also return. */
6798 if (read_kbd
6799 && requeued_events_pending_p ())
6800 break;
6802 /* If wait_for_cell. check for keyboard input
6803 but don't run any timers.
6804 ??? (It seems wrong to me to check for keyboard
6805 input at all when wait_for_cell, but the code
6806 has been this way since July 1994.
6807 Try changing this after version 19.31.) */
6808 if (! NILP (wait_for_cell)
6809 && detect_input_pending ())
6811 swallow_events (do_display);
6812 if (detect_input_pending ())
6813 break;
6816 /* Exit now if the cell we're waiting for became non-nil. */
6817 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6818 break;
6821 start_polling ();
6823 return -1;
6826 #endif /* not subprocesses */
6828 /* The following functions are needed even if async subprocesses are
6829 not supported. Some of them are no-op stubs in that case. */
6831 #ifdef HAVE_TIMERFD
6833 /* Add FD, which is a descriptor returned by timerfd_create,
6834 to the set of non-keyboard input descriptors. */
6836 void
6837 add_timer_wait_descriptor (int fd)
6839 FD_SET (fd, &input_wait_mask);
6840 FD_SET (fd, &non_keyboard_wait_mask);
6841 FD_SET (fd, &non_process_wait_mask);
6842 fd_callback_info[fd].func = timerfd_callback;
6843 fd_callback_info[fd].data = NULL;
6844 fd_callback_info[fd].condition |= FOR_READ;
6845 if (fd > max_input_desc)
6846 max_input_desc = fd;
6849 #endif /* HAVE_TIMERFD */
6851 /* Add DESC to the set of keyboard input descriptors. */
6853 void
6854 add_keyboard_wait_descriptor (int desc)
6856 #ifdef subprocesses /* Actually means "not MSDOS". */
6857 FD_SET (desc, &input_wait_mask);
6858 FD_SET (desc, &non_process_wait_mask);
6859 if (desc > max_input_desc)
6860 max_input_desc = desc;
6861 #endif
6864 /* From now on, do not expect DESC to give keyboard input. */
6866 void
6867 delete_keyboard_wait_descriptor (int desc)
6869 #ifdef subprocesses
6870 FD_CLR (desc, &input_wait_mask);
6871 FD_CLR (desc, &non_process_wait_mask);
6872 delete_input_desc (desc);
6873 #endif
6876 /* Setup coding systems of PROCESS. */
6878 void
6879 setup_process_coding_systems (Lisp_Object process)
6881 #ifdef subprocesses
6882 struct Lisp_Process *p = XPROCESS (process);
6883 int inch = p->infd;
6884 int outch = p->outfd;
6885 Lisp_Object coding_system;
6887 if (inch < 0 || outch < 0)
6888 return;
6890 if (!proc_decode_coding_system[inch])
6891 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
6892 coding_system = p->decode_coding_system;
6893 if (EQ (p->filter, Qinternal_default_process_filter)
6894 && BUFFERP (p->buffer))
6896 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
6897 coding_system = raw_text_coding_system (coding_system);
6899 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
6901 if (!proc_encode_coding_system[outch])
6902 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
6903 setup_coding_system (p->encode_coding_system,
6904 proc_encode_coding_system[outch]);
6905 #endif
6908 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
6909 doc: /* Return the (or a) process associated with BUFFER.
6910 BUFFER may be a buffer or the name of one. */)
6911 (register Lisp_Object buffer)
6913 #ifdef subprocesses
6914 register Lisp_Object buf, tail, proc;
6916 if (NILP (buffer)) return Qnil;
6917 buf = Fget_buffer (buffer);
6918 if (NILP (buf)) return Qnil;
6920 FOR_EACH_PROCESS (tail, proc)
6921 if (EQ (XPROCESS (proc)->buffer, buf))
6922 return proc;
6923 #endif /* subprocesses */
6924 return Qnil;
6927 DEFUN ("process-inherit-coding-system-flag",
6928 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
6929 1, 1, 0,
6930 doc: /* Return the value of inherit-coding-system flag for PROCESS.
6931 If this flag is t, `buffer-file-coding-system' of the buffer
6932 associated with PROCESS will inherit the coding system used to decode
6933 the process output. */)
6934 (register Lisp_Object process)
6936 #ifdef subprocesses
6937 CHECK_PROCESS (process);
6938 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
6939 #else
6940 /* Ignore the argument and return the value of
6941 inherit-process-coding-system. */
6942 return inherit_process_coding_system ? Qt : Qnil;
6943 #endif
6946 /* Kill all processes associated with `buffer'.
6947 If `buffer' is nil, kill all processes. */
6949 void
6950 kill_buffer_processes (Lisp_Object buffer)
6952 #ifdef subprocesses
6953 Lisp_Object tail, proc;
6955 FOR_EACH_PROCESS (tail, proc)
6956 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
6958 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6959 Fdelete_process (proc);
6960 else if (XPROCESS (proc)->infd >= 0)
6961 process_send_signal (proc, SIGHUP, Qnil, 1);
6963 #else /* subprocesses */
6964 /* Since we have no subprocesses, this does nothing. */
6965 #endif /* subprocesses */
6968 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
6969 Swaiting_for_user_input_p, 0, 0, 0,
6970 doc: /* Return non-nil if Emacs is waiting for input from the user.
6971 This is intended for use by asynchronous process output filters and sentinels. */)
6972 (void)
6974 #ifdef subprocesses
6975 return (waiting_for_user_input_p ? Qt : Qnil);
6976 #else
6977 return Qnil;
6978 #endif
6981 /* Stop reading input from keyboard sources. */
6983 void
6984 hold_keyboard_input (void)
6986 kbd_is_on_hold = 1;
6989 /* Resume reading input from keyboard sources. */
6991 void
6992 unhold_keyboard_input (void)
6994 kbd_is_on_hold = 0;
6997 /* Return true if keyboard input is on hold, zero otherwise. */
6999 bool
7000 kbd_on_hold_p (void)
7002 return kbd_is_on_hold;
7006 /* Enumeration of and access to system processes a-la ps(1). */
7008 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7009 0, 0, 0,
7010 doc: /* Return a list of numerical process IDs of all running processes.
7011 If this functionality is unsupported, return nil.
7013 See `process-attributes' for getting attributes of a process given its ID. */)
7014 (void)
7016 return list_system_processes ();
7019 DEFUN ("process-attributes", Fprocess_attributes,
7020 Sprocess_attributes, 1, 1, 0,
7021 doc: /* Return attributes of the process given by its PID, a number.
7023 Value is an alist where each element is a cons cell of the form
7025 \(KEY . VALUE)
7027 If this functionality is unsupported, the value is nil.
7029 See `list-system-processes' for getting a list of all process IDs.
7031 The KEYs of the attributes that this function may return are listed
7032 below, together with the type of the associated VALUE (in parentheses).
7033 Not all platforms support all of these attributes; unsupported
7034 attributes will not appear in the returned alist.
7035 Unless explicitly indicated otherwise, numbers can have either
7036 integer or floating point values.
7038 euid -- Effective user User ID of the process (number)
7039 user -- User name corresponding to euid (string)
7040 egid -- Effective user Group ID of the process (number)
7041 group -- Group name corresponding to egid (string)
7042 comm -- Command name (executable name only) (string)
7043 state -- Process state code, such as "S", "R", or "T" (string)
7044 ppid -- Parent process ID (number)
7045 pgrp -- Process group ID (number)
7046 sess -- Session ID, i.e. process ID of session leader (number)
7047 ttname -- Controlling tty name (string)
7048 tpgid -- ID of foreground process group on the process's tty (number)
7049 minflt -- number of minor page faults (number)
7050 majflt -- number of major page faults (number)
7051 cminflt -- cumulative number of minor page faults (number)
7052 cmajflt -- cumulative number of major page faults (number)
7053 utime -- user time used by the process, in (current-time) format,
7054 which is a list of integers (HIGH LOW USEC PSEC)
7055 stime -- system time used by the process (current-time)
7056 time -- sum of utime and stime (current-time)
7057 cutime -- user time used by the process and its children (current-time)
7058 cstime -- system time used by the process and its children (current-time)
7059 ctime -- sum of cutime and cstime (current-time)
7060 pri -- priority of the process (number)
7061 nice -- nice value of the process (number)
7062 thcount -- process thread count (number)
7063 start -- time the process started (current-time)
7064 vsize -- virtual memory size of the process in KB's (number)
7065 rss -- resident set size of the process in KB's (number)
7066 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7067 pcpu -- percents of CPU time used by the process (floating-point number)
7068 pmem -- percents of total physical memory used by process's resident set
7069 (floating-point number)
7070 args -- command line which invoked the process (string). */)
7071 ( Lisp_Object pid)
7073 return system_process_attributes (pid);
7076 #ifdef subprocesses
7077 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7078 Invoke this after init_process_emacs, and after glib and/or GNUstep
7079 futz with the SIGCHLD handler, but before Emacs forks any children.
7080 This function's caller should block SIGCHLD. */
7082 void
7083 catch_child_signal (void)
7085 struct sigaction action, old_action;
7086 sigset_t oldset;
7087 emacs_sigaction_init (&action, deliver_child_signal);
7088 block_child_signal (&oldset);
7089 sigaction (SIGCHLD, &action, &old_action);
7090 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7091 || ! (old_action.sa_flags & SA_SIGINFO));
7093 if (old_action.sa_handler != deliver_child_signal)
7094 lib_child_handler
7095 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7096 ? dummy_handler
7097 : old_action.sa_handler);
7098 unblock_child_signal (&oldset);
7100 #endif /* subprocesses */
7103 /* This is not called "init_process" because that is the name of a
7104 Mach system call, so it would cause problems on Darwin systems. */
7105 void
7106 init_process_emacs (void)
7108 #ifdef subprocesses
7109 register int i;
7111 inhibit_sentinels = 0;
7113 #ifndef CANNOT_DUMP
7114 if (! noninteractive || initialized)
7115 #endif
7117 #if defined HAVE_GLIB && !defined WINDOWSNT
7118 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7119 this should always fail, but is enough to initialize glib's
7120 private SIGCHLD handler, allowing catch_child_signal to copy
7121 it into lib_child_handler. */
7122 g_source_unref (g_child_watch_source_new (getpid ()));
7123 #endif
7124 catch_child_signal ();
7127 FD_ZERO (&input_wait_mask);
7128 FD_ZERO (&non_keyboard_wait_mask);
7129 FD_ZERO (&non_process_wait_mask);
7130 FD_ZERO (&write_mask);
7131 max_process_desc = max_input_desc = -1;
7132 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7134 #ifdef NON_BLOCKING_CONNECT
7135 FD_ZERO (&connect_wait_mask);
7136 num_pending_connects = 0;
7137 #endif
7139 #ifdef ADAPTIVE_READ_BUFFERING
7140 process_output_delay_count = 0;
7141 process_output_skip = 0;
7142 #endif
7144 /* Don't do this, it caused infinite select loops. The display
7145 method should call add_keyboard_wait_descriptor on stdin if it
7146 needs that. */
7147 #if 0
7148 FD_SET (0, &input_wait_mask);
7149 #endif
7151 Vprocess_alist = Qnil;
7152 deleted_pid_list = Qnil;
7153 for (i = 0; i < FD_SETSIZE; i++)
7155 chan_process[i] = Qnil;
7156 proc_buffered_char[i] = -1;
7158 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7159 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7160 #ifdef DATAGRAM_SOCKETS
7161 memset (datagram_address, 0, sizeof datagram_address);
7162 #endif
7165 Lisp_Object subfeatures = Qnil;
7166 const struct socket_options *sopt;
7168 #define ADD_SUBFEATURE(key, val) \
7169 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7171 #ifdef NON_BLOCKING_CONNECT
7172 ADD_SUBFEATURE (QCnowait, Qt);
7173 #endif
7174 #ifdef DATAGRAM_SOCKETS
7175 ADD_SUBFEATURE (QCtype, Qdatagram);
7176 #endif
7177 #ifdef HAVE_SEQPACKET
7178 ADD_SUBFEATURE (QCtype, Qseqpacket);
7179 #endif
7180 #ifdef HAVE_LOCAL_SOCKETS
7181 ADD_SUBFEATURE (QCfamily, Qlocal);
7182 #endif
7183 ADD_SUBFEATURE (QCfamily, Qipv4);
7184 #ifdef AF_INET6
7185 ADD_SUBFEATURE (QCfamily, Qipv6);
7186 #endif
7187 #ifdef HAVE_GETSOCKNAME
7188 ADD_SUBFEATURE (QCservice, Qt);
7189 #endif
7190 ADD_SUBFEATURE (QCserver, Qt);
7192 for (sopt = socket_options; sopt->name; sopt++)
7193 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7195 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7198 #if defined (DARWIN_OS)
7199 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7200 processes. As such, we only change the default value. */
7201 if (initialized)
7203 char const *release = (STRINGP (Voperating_system_release)
7204 ? SSDATA (Voperating_system_release)
7205 : 0);
7206 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7207 Vprocess_connection_type = Qnil;
7210 #endif
7211 #endif /* subprocesses */
7212 kbd_is_on_hold = 0;
7215 void
7216 syms_of_process (void)
7218 #ifdef subprocesses
7220 DEFSYM (Qprocessp, "processp");
7221 DEFSYM (Qrun, "run");
7222 DEFSYM (Qstop, "stop");
7223 DEFSYM (Qsignal, "signal");
7225 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7226 here again. */
7228 DEFSYM (Qopen, "open");
7229 DEFSYM (Qclosed, "closed");
7230 DEFSYM (Qconnect, "connect");
7231 DEFSYM (Qfailed, "failed");
7232 DEFSYM (Qlisten, "listen");
7233 DEFSYM (Qlocal, "local");
7234 DEFSYM (Qipv4, "ipv4");
7235 #ifdef AF_INET6
7236 DEFSYM (Qipv6, "ipv6");
7237 #endif
7238 DEFSYM (Qdatagram, "datagram");
7239 DEFSYM (Qseqpacket, "seqpacket");
7241 DEFSYM (QCport, ":port");
7242 DEFSYM (QCspeed, ":speed");
7243 DEFSYM (QCprocess, ":process");
7245 DEFSYM (QCbytesize, ":bytesize");
7246 DEFSYM (QCstopbits, ":stopbits");
7247 DEFSYM (QCparity, ":parity");
7248 DEFSYM (Qodd, "odd");
7249 DEFSYM (Qeven, "even");
7250 DEFSYM (QCflowcontrol, ":flowcontrol");
7251 DEFSYM (Qhw, "hw");
7252 DEFSYM (Qsw, "sw");
7253 DEFSYM (QCsummary, ":summary");
7255 DEFSYM (Qreal, "real");
7256 DEFSYM (Qnetwork, "network");
7257 DEFSYM (Qserial, "serial");
7258 DEFSYM (QCbuffer, ":buffer");
7259 DEFSYM (QChost, ":host");
7260 DEFSYM (QCservice, ":service");
7261 DEFSYM (QClocal, ":local");
7262 DEFSYM (QCremote, ":remote");
7263 DEFSYM (QCcoding, ":coding");
7264 DEFSYM (QCserver, ":server");
7265 DEFSYM (QCnowait, ":nowait");
7266 DEFSYM (QCsentinel, ":sentinel");
7267 DEFSYM (QClog, ":log");
7268 DEFSYM (QCnoquery, ":noquery");
7269 DEFSYM (QCstop, ":stop");
7270 DEFSYM (QCoptions, ":options");
7271 DEFSYM (QCplist, ":plist");
7273 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7275 staticpro (&Vprocess_alist);
7276 staticpro (&deleted_pid_list);
7278 #endif /* subprocesses */
7280 DEFSYM (QCname, ":name");
7281 DEFSYM (QCtype, ":type");
7283 DEFSYM (Qeuid, "euid");
7284 DEFSYM (Qegid, "egid");
7285 DEFSYM (Quser, "user");
7286 DEFSYM (Qgroup, "group");
7287 DEFSYM (Qcomm, "comm");
7288 DEFSYM (Qstate, "state");
7289 DEFSYM (Qppid, "ppid");
7290 DEFSYM (Qpgrp, "pgrp");
7291 DEFSYM (Qsess, "sess");
7292 DEFSYM (Qttname, "ttname");
7293 DEFSYM (Qtpgid, "tpgid");
7294 DEFSYM (Qminflt, "minflt");
7295 DEFSYM (Qmajflt, "majflt");
7296 DEFSYM (Qcminflt, "cminflt");
7297 DEFSYM (Qcmajflt, "cmajflt");
7298 DEFSYM (Qutime, "utime");
7299 DEFSYM (Qstime, "stime");
7300 DEFSYM (Qtime, "time");
7301 DEFSYM (Qcutime, "cutime");
7302 DEFSYM (Qcstime, "cstime");
7303 DEFSYM (Qctime, "ctime");
7304 #ifdef subprocesses
7305 DEFSYM (Qinternal_default_process_sentinel,
7306 "internal-default-process-sentinel");
7307 DEFSYM (Qinternal_default_process_filter,
7308 "internal-default-process-filter");
7309 #endif
7310 DEFSYM (Qpri, "pri");
7311 DEFSYM (Qnice, "nice");
7312 DEFSYM (Qthcount, "thcount");
7313 DEFSYM (Qstart, "start");
7314 DEFSYM (Qvsize, "vsize");
7315 DEFSYM (Qrss, "rss");
7316 DEFSYM (Qetime, "etime");
7317 DEFSYM (Qpcpu, "pcpu");
7318 DEFSYM (Qpmem, "pmem");
7319 DEFSYM (Qargs, "args");
7321 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7322 doc: /* Non-nil means delete processes immediately when they exit.
7323 A value of nil means don't delete them until `list-processes' is run. */);
7325 delete_exited_processes = 1;
7327 #ifdef subprocesses
7328 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7329 doc: /* Control type of device used to communicate with subprocesses.
7330 Values are nil to use a pipe, or t or `pty' to use a pty.
7331 The value has no effect if the system has no ptys or if all ptys are busy:
7332 then a pipe is used in any case.
7333 The value takes effect when `start-process' is called. */);
7334 Vprocess_connection_type = Qt;
7336 #ifdef ADAPTIVE_READ_BUFFERING
7337 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7338 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7339 On some systems, when Emacs reads the output from a subprocess, the output data
7340 is read in very small blocks, potentially resulting in very poor performance.
7341 This behavior can be remedied to some extent by setting this variable to a
7342 non-nil value, as it will automatically delay reading from such processes, to
7343 allow them to produce more output before Emacs tries to read it.
7344 If the value is t, the delay is reset after each write to the process; any other
7345 non-nil value means that the delay is not reset on write.
7346 The variable takes effect when `start-process' is called. */);
7347 Vprocess_adaptive_read_buffering = Qt;
7348 #endif
7350 defsubr (&Sprocessp);
7351 defsubr (&Sget_process);
7352 defsubr (&Sdelete_process);
7353 defsubr (&Sprocess_status);
7354 defsubr (&Sprocess_exit_status);
7355 defsubr (&Sprocess_id);
7356 defsubr (&Sprocess_name);
7357 defsubr (&Sprocess_tty_name);
7358 defsubr (&Sprocess_command);
7359 defsubr (&Sset_process_buffer);
7360 defsubr (&Sprocess_buffer);
7361 defsubr (&Sprocess_mark);
7362 defsubr (&Sset_process_filter);
7363 defsubr (&Sprocess_filter);
7364 defsubr (&Sset_process_sentinel);
7365 defsubr (&Sprocess_sentinel);
7366 defsubr (&Sset_process_window_size);
7367 defsubr (&Sset_process_inherit_coding_system_flag);
7368 defsubr (&Sset_process_query_on_exit_flag);
7369 defsubr (&Sprocess_query_on_exit_flag);
7370 defsubr (&Sprocess_contact);
7371 defsubr (&Sprocess_plist);
7372 defsubr (&Sset_process_plist);
7373 defsubr (&Sprocess_list);
7374 defsubr (&Sstart_process);
7375 defsubr (&Sserial_process_configure);
7376 defsubr (&Smake_serial_process);
7377 defsubr (&Sset_network_process_option);
7378 defsubr (&Smake_network_process);
7379 defsubr (&Sformat_network_address);
7380 defsubr (&Snetwork_interface_list);
7381 defsubr (&Snetwork_interface_info);
7382 #ifdef DATAGRAM_SOCKETS
7383 defsubr (&Sprocess_datagram_address);
7384 defsubr (&Sset_process_datagram_address);
7385 #endif
7386 defsubr (&Saccept_process_output);
7387 defsubr (&Sprocess_send_region);
7388 defsubr (&Sprocess_send_string);
7389 defsubr (&Sinterrupt_process);
7390 defsubr (&Skill_process);
7391 defsubr (&Squit_process);
7392 defsubr (&Sstop_process);
7393 defsubr (&Scontinue_process);
7394 defsubr (&Sprocess_running_child_p);
7395 defsubr (&Sprocess_send_eof);
7396 defsubr (&Ssignal_process);
7397 defsubr (&Swaiting_for_user_input_p);
7398 defsubr (&Sprocess_type);
7399 defsubr (&Sinternal_default_process_sentinel);
7400 defsubr (&Sinternal_default_process_filter);
7401 defsubr (&Sset_process_coding_system);
7402 defsubr (&Sprocess_coding_system);
7403 defsubr (&Sset_process_filter_multibyte);
7404 defsubr (&Sprocess_filter_multibyte_p);
7406 #endif /* subprocesses */
7408 defsubr (&Sget_buffer_process);
7409 defsubr (&Sprocess_inherit_coding_system_flag);
7410 defsubr (&Slist_system_processes);
7411 defsubr (&Sprocess_attributes);