* lisp/emacs-lisp/seq.el: Documentation improvements
[emacs.git] / src / process.c
blob3fe8644b48aa9aa17d4b742770dbcb6c47312f38
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 ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1359 doc: /* Start a program in a subprocess. Return the process object for it.
1361 This is similar to `start-process', but arguments are specified as
1362 keyword/argument pairs. The following arguments are defined:
1364 :name NAME -- NAME is name for process. It is modified if necessary
1365 to make it unique.
1367 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1368 with the process. Process output goes at end of that buffer, unless
1369 you specify an output stream or filter function to handle the output.
1370 BUFFER may be also nil, meaning that this process is not associated
1371 with any buffer.
1373 :command COMMAND -- COMMAND is a list starting with the program file
1374 name, followed by strings to give to the program as arguments.
1376 :coding CODING -- If CODING is a symbol, it specifies the coding
1377 system used for both reading and writing for this process. If CODING
1378 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1379 ENCODING is used for writing.
1381 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1382 the process is running. If BOOL is not given, query before exiting.
1384 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1385 In the stopped state, a process does not accept incoming data, but you
1386 can send outgoing data. The stopped state is cleared by
1387 `continue-process' and set by `stop-process'.
1389 :connection-type TYPE -- TYPE is control type of device used to
1390 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1391 to use a pty, or nil to use the default specified through
1392 `process-connection-type'.
1394 :filter FILTER -- Install FILTER as the process filter.
1396 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1398 usage: (make-process &rest ARGS) */)
1399 (ptrdiff_t nargs, Lisp_Object *args)
1401 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1402 ptrdiff_t count = SPECPDL_INDEX ();
1403 struct gcpro gcpro1;
1404 USE_SAFE_ALLOCA;
1406 if (nargs == 0)
1407 return Qnil;
1409 /* Save arguments for process-contact and clone-process. */
1410 contact = Flist (nargs, args);
1411 GCPRO1 (contact);
1413 buffer = Fplist_get (contact, QCbuffer);
1414 if (!NILP (buffer))
1415 buffer = Fget_buffer_create (buffer);
1417 /* Make sure that the child will be able to chdir to the current
1418 buffer's current directory, or its unhandled equivalent. We
1419 can't just have the child check for an error when it does the
1420 chdir, since it's in a vfork.
1422 We have to GCPRO around this because Fexpand_file_name and
1423 Funhandled_file_name_directory might call a file name handling
1424 function. The argument list is protected by the caller, so all
1425 we really have to worry about is buffer. */
1427 struct gcpro gcpro1;
1428 GCPRO1 (buffer);
1429 current_dir = encode_current_directory ();
1430 UNGCPRO;
1433 name = Fplist_get (contact, QCname);
1434 CHECK_STRING (name);
1436 command = Fplist_get (contact, QCcommand);
1437 if (CONSP (command))
1438 program = XCAR (command);
1439 else
1440 program = Qnil;
1442 if (!NILP (program))
1443 CHECK_STRING (program);
1445 proc = make_process (name);
1446 /* If an error occurs and we can't start the process, we want to
1447 remove it from the process list. This means that each error
1448 check in create_process doesn't need to call remove_process
1449 itself; it's all taken care of here. */
1450 record_unwind_protect (start_process_unwind, proc);
1452 pset_childp (XPROCESS (proc), Qt);
1453 pset_plist (XPROCESS (proc), Qnil);
1454 pset_type (XPROCESS (proc), Qreal);
1455 pset_buffer (XPROCESS (proc), buffer);
1456 pset_sentinel (XPROCESS (proc), Qinternal_default_process_sentinel);
1457 pset_filter (XPROCESS (proc), Qinternal_default_process_filter);
1458 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1460 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
1461 XPROCESS (proc)->kill_without_query = 1;
1462 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1463 pset_command (XPROCESS (proc), Qt);
1465 tem = Fplist_get (contact, QCconnection_type);
1466 if (EQ (tem, Qpty))
1467 XPROCESS (proc)->pty_flag = true;
1468 else if (EQ (tem, Qpipe))
1469 XPROCESS (proc)->pty_flag = false;
1470 else if (NILP (tem))
1471 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1472 else
1473 report_file_error ("Unknown connection type", tem);
1475 #ifdef HAVE_GNUTLS
1476 /* AKA GNUTLS_INITSTAGE(proc). */
1477 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1478 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1479 #endif
1481 #ifdef ADAPTIVE_READ_BUFFERING
1482 XPROCESS (proc)->adaptive_read_buffering
1483 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1484 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1485 #endif
1487 /* Make the process marker point into the process buffer (if any). */
1488 if (BUFFERP (buffer))
1489 set_marker_both (XPROCESS (proc)->mark, buffer,
1490 BUF_ZV (XBUFFER (buffer)),
1491 BUF_ZV_BYTE (XBUFFER (buffer)));
1494 /* Decide coding systems for communicating with the process. Here
1495 we don't setup the structure coding_system nor pay attention to
1496 unibyte mode. They are done in create_process. */
1498 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1499 Lisp_Object coding_systems = Qt;
1500 Lisp_Object val, *args2;
1501 struct gcpro gcpro1, gcpro2;
1503 tem = Fplist_get (contact, QCcoding);
1504 if (!NILP (tem))
1506 val = tem;
1507 if (CONSP (val))
1508 val = XCAR (val);
1510 else
1511 val = Vcoding_system_for_read;
1512 if (NILP (val))
1514 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1515 Lisp_Object tem2;
1516 SAFE_ALLOCA_LISP (args2, nargs2);
1517 ptrdiff_t i = 0;
1518 args2[i++] = Qstart_process;
1519 args2[i++] = name;
1520 args2[i++] = buffer;
1521 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1522 args2[i++] = XCAR (tem2);
1523 GCPRO2 (proc, current_dir);
1524 if (!NILP (program))
1525 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1526 UNGCPRO;
1527 if (CONSP (coding_systems))
1528 val = XCAR (coding_systems);
1529 else if (CONSP (Vdefault_process_coding_system))
1530 val = XCAR (Vdefault_process_coding_system);
1532 pset_decode_coding_system (XPROCESS (proc), val);
1534 if (!NILP (tem))
1536 val = tem;
1537 if (CONSP (val))
1538 val = XCDR (val);
1540 else
1541 val = Vcoding_system_for_write;
1542 if (NILP (val))
1544 if (EQ (coding_systems, Qt))
1546 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1547 Lisp_Object tem2;
1548 SAFE_ALLOCA_LISP (args2, nargs2);
1549 ptrdiff_t i = 0;
1550 args2[i++] = Qstart_process;
1551 args2[i++] = name;
1552 args2[i++] = buffer;
1553 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1554 args2[i++] = XCAR (tem2);
1555 GCPRO2 (proc, current_dir);
1556 if (!NILP (program))
1557 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1558 UNGCPRO;
1560 if (CONSP (coding_systems))
1561 val = XCDR (coding_systems);
1562 else if (CONSP (Vdefault_process_coding_system))
1563 val = XCDR (Vdefault_process_coding_system);
1565 pset_encode_coding_system (XPROCESS (proc), val);
1566 /* Note: At this moment, the above coding system may leave
1567 text-conversion or eol-conversion unspecified. They will be
1568 decided after we read output from the process and decode it by
1569 some coding system, or just before we actually send a text to
1570 the process. */
1574 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1575 XPROCESS (proc)->decoding_carryover = 0;
1576 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1578 XPROCESS (proc)->inherit_coding_system_flag
1579 = !(NILP (buffer) || !inherit_process_coding_system);
1581 if (!NILP (program))
1583 Lisp_Object program_args = XCDR (command);
1585 /* If program file name is not absolute, search our path for it.
1586 Put the name we will really use in TEM. */
1587 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1588 && !(SCHARS (program) > 1
1589 && IS_DEVICE_SEP (SREF (program, 1))))
1591 struct gcpro gcpro1, gcpro2;
1593 tem = Qnil;
1594 GCPRO2 (buffer, current_dir);
1595 openp (Vexec_path, program, Vexec_suffixes, &tem,
1596 make_number (X_OK), false);
1597 UNGCPRO;
1598 if (NILP (tem))
1599 report_file_error ("Searching for program", program);
1600 tem = Fexpand_file_name (tem, Qnil);
1602 else
1604 if (!NILP (Ffile_directory_p (program)))
1605 error ("Specified program for new process is a directory");
1606 tem = program;
1609 /* Remove "/:" from TEM. */
1610 tem = remove_slash_colon (tem);
1612 Lisp_Object arg_encoding = Qnil;
1613 struct gcpro gcpro1;
1614 GCPRO1 (tem);
1616 /* Encode the file name and put it in NEW_ARGV.
1617 That's where the child will use it to execute the program. */
1618 tem = list1 (ENCODE_FILE (tem));
1619 ptrdiff_t new_argc = 1;
1621 /* Here we encode arguments by the coding system used for sending
1622 data to the process. We don't support using different coding
1623 systems for encoding arguments and for encoding data sent to the
1624 process. */
1626 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1628 Lisp_Object arg = XCAR (tem2);
1629 CHECK_STRING (arg);
1630 if (STRING_MULTIBYTE (arg))
1632 if (NILP (arg_encoding))
1633 arg_encoding = (complement_process_encoding_system
1634 (XPROCESS (proc)->encode_coding_system));
1635 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1637 tem = Fcons (arg, tem);
1638 new_argc++;
1641 UNGCPRO;
1643 /* Now that everything is encoded we can collect the strings into
1644 NEW_ARGV. */
1645 char **new_argv;
1646 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1647 new_argv[new_argc] = 0;
1649 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1651 new_argv[i] = SSDATA (XCAR (tem));
1652 tem = XCDR (tem);
1655 create_process (proc, new_argv, current_dir);
1657 else
1658 create_pty (proc);
1660 UNGCPRO;
1661 SAFE_FREE ();
1662 return unbind_to (count, proc);
1665 /* This function is the unwind_protect form for Fstart_process. If
1666 PROC doesn't have its pid set, then we know someone has signaled
1667 an error and the process wasn't started successfully, so we should
1668 remove it from the process list. */
1669 static void
1670 start_process_unwind (Lisp_Object proc)
1672 if (!PROCESSP (proc))
1673 emacs_abort ();
1675 /* Was PROC started successfully?
1676 -2 is used for a pty with no process, eg for gdb. */
1677 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1678 remove_process (proc);
1681 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1683 static void
1684 close_process_fd (int *fd_addr)
1686 int fd = *fd_addr;
1687 if (0 <= fd)
1689 *fd_addr = -1;
1690 emacs_close (fd);
1694 /* Indexes of file descriptors in open_fds. */
1695 enum
1697 /* The pipe from Emacs to its subprocess. */
1698 SUBPROCESS_STDIN,
1699 WRITE_TO_SUBPROCESS,
1701 /* The main pipe from the subprocess to Emacs. */
1702 READ_FROM_SUBPROCESS,
1703 SUBPROCESS_STDOUT,
1705 /* The pipe from the subprocess to Emacs that is closed when the
1706 subprocess execs. */
1707 READ_FROM_EXEC_MONITOR,
1708 EXEC_MONITOR_OUTPUT
1711 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1713 static void
1714 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1716 struct Lisp_Process *p = XPROCESS (process);
1717 int inchannel, outchannel;
1718 pid_t pid;
1719 int vfork_errno;
1720 int forkin, forkout;
1721 bool pty_flag = 0;
1722 char pty_name[PTY_NAME_SIZE];
1723 Lisp_Object lisp_pty_name = Qnil;
1724 sigset_t oldset;
1726 inchannel = outchannel = -1;
1728 if (p->pty_flag)
1729 outchannel = inchannel = allocate_pty (pty_name);
1731 if (inchannel >= 0)
1733 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1734 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1735 /* On most USG systems it does not work to open the pty's tty here,
1736 then close it and reopen it in the child. */
1737 /* Don't let this terminal become our controlling terminal
1738 (in case we don't have one). */
1739 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1740 if (forkin < 0)
1741 report_file_error ("Opening pty", Qnil);
1742 p->open_fd[SUBPROCESS_STDIN] = forkin;
1743 #else
1744 forkin = forkout = -1;
1745 #endif /* not USG, or USG_SUBTTY_WORKS */
1746 pty_flag = 1;
1747 lisp_pty_name = build_string (pty_name);
1749 else
1751 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1752 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1753 report_file_error ("Creating pipe", Qnil);
1754 forkin = p->open_fd[SUBPROCESS_STDIN];
1755 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1756 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1757 forkout = p->open_fd[SUBPROCESS_STDOUT];
1760 #ifndef WINDOWSNT
1761 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1762 report_file_error ("Creating pipe", Qnil);
1763 #endif
1765 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1766 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1768 /* Record this as an active process, with its channels. */
1769 chan_process[inchannel] = process;
1770 p->infd = inchannel;
1771 p->outfd = outchannel;
1773 /* Previously we recorded the tty descriptor used in the subprocess.
1774 It was only used for getting the foreground tty process, so now
1775 we just reopen the device (see emacs_get_tty_pgrp) as this is
1776 more portable (see USG_SUBTTY_WORKS above). */
1778 p->pty_flag = pty_flag;
1779 pset_status (p, Qrun);
1781 if (!EQ (p->command, Qt))
1783 FD_SET (inchannel, &input_wait_mask);
1784 FD_SET (inchannel, &non_keyboard_wait_mask);
1787 if (inchannel > max_process_desc)
1788 max_process_desc = inchannel;
1790 /* This may signal an error. */
1791 setup_process_coding_systems (process);
1793 block_input ();
1794 block_child_signal (&oldset);
1796 #ifndef WINDOWSNT
1797 /* vfork, and prevent local vars from being clobbered by the vfork. */
1799 Lisp_Object volatile current_dir_volatile = current_dir;
1800 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1801 char **volatile new_argv_volatile = new_argv;
1802 int volatile forkin_volatile = forkin;
1803 int volatile forkout_volatile = forkout;
1804 struct Lisp_Process *p_volatile = p;
1806 pid = vfork ();
1808 current_dir = current_dir_volatile;
1809 lisp_pty_name = lisp_pty_name_volatile;
1810 new_argv = new_argv_volatile;
1811 forkin = forkin_volatile;
1812 forkout = forkout_volatile;
1813 p = p_volatile;
1815 pty_flag = p->pty_flag;
1818 if (pid == 0)
1819 #endif /* not WINDOWSNT */
1821 int xforkin = forkin;
1822 int xforkout = forkout;
1824 /* Make the pty be the controlling terminal of the process. */
1825 #ifdef HAVE_PTYS
1826 /* First, disconnect its current controlling terminal. */
1827 /* We tried doing setsid only if pty_flag, but it caused
1828 process_set_signal to fail on SGI when using a pipe. */
1829 setsid ();
1830 /* Make the pty's terminal the controlling terminal. */
1831 if (pty_flag && xforkin >= 0)
1833 #ifdef TIOCSCTTY
1834 /* We ignore the return value
1835 because faith@cs.unc.edu says that is necessary on Linux. */
1836 ioctl (xforkin, TIOCSCTTY, 0);
1837 #endif
1839 #if defined (LDISC1)
1840 if (pty_flag && xforkin >= 0)
1842 struct termios t;
1843 tcgetattr (xforkin, &t);
1844 t.c_lflag = LDISC1;
1845 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1846 emacs_perror ("create_process/tcsetattr LDISC1");
1848 #else
1849 #if defined (NTTYDISC) && defined (TIOCSETD)
1850 if (pty_flag && xforkin >= 0)
1852 /* Use new line discipline. */
1853 int ldisc = NTTYDISC;
1854 ioctl (xforkin, TIOCSETD, &ldisc);
1856 #endif
1857 #endif
1858 #ifdef TIOCNOTTY
1859 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1860 can do TIOCSPGRP only to the process's controlling tty. */
1861 if (pty_flag)
1863 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1864 I can't test it since I don't have 4.3. */
1865 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1866 if (j >= 0)
1868 ioctl (j, TIOCNOTTY, 0);
1869 emacs_close (j);
1872 #endif /* TIOCNOTTY */
1874 #if !defined (DONT_REOPEN_PTY)
1875 /*** There is a suggestion that this ought to be a
1876 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1877 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1878 that system does seem to need this code, even though
1879 both TIOCSCTTY is defined. */
1880 /* Now close the pty (if we had it open) and reopen it.
1881 This makes the pty the controlling terminal of the subprocess. */
1882 if (pty_flag)
1885 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1886 would work? */
1887 if (xforkin >= 0)
1888 emacs_close (xforkin);
1889 xforkout = xforkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1891 if (xforkin < 0)
1893 emacs_perror (SSDATA (lisp_pty_name));
1894 _exit (EXIT_CANCELED);
1898 #endif /* not DONT_REOPEN_PTY */
1900 #ifdef SETUP_SLAVE_PTY
1901 if (pty_flag)
1903 SETUP_SLAVE_PTY;
1905 #endif /* SETUP_SLAVE_PTY */
1906 #endif /* HAVE_PTYS */
1908 signal (SIGINT, SIG_DFL);
1909 signal (SIGQUIT, SIG_DFL);
1910 #ifdef SIGPROF
1911 signal (SIGPROF, SIG_DFL);
1912 #endif
1914 /* Emacs ignores SIGPIPE, but the child should not. */
1915 signal (SIGPIPE, SIG_DFL);
1917 /* Stop blocking SIGCHLD in the child. */
1918 unblock_child_signal (&oldset);
1920 if (pty_flag)
1921 child_setup_tty (xforkout);
1922 #ifdef WINDOWSNT
1923 pid = child_setup (xforkin, xforkout, xforkout, new_argv, 1, current_dir);
1924 #else /* not WINDOWSNT */
1925 child_setup (xforkin, xforkout, xforkout, new_argv, 1, current_dir);
1926 #endif /* not WINDOWSNT */
1929 /* Back in the parent process. */
1931 vfork_errno = errno;
1932 p->pid = pid;
1933 if (pid >= 0)
1934 p->alive = 1;
1936 /* Stop blocking in the parent. */
1937 unblock_child_signal (&oldset);
1938 unblock_input ();
1940 if (pid < 0)
1941 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1942 else
1944 /* vfork succeeded. */
1946 /* Close the pipe ends that the child uses, or the child's pty. */
1947 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
1948 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
1950 #ifdef WINDOWSNT
1951 register_child (pid, inchannel);
1952 #endif /* WINDOWSNT */
1954 pset_tty_name (p, lisp_pty_name);
1956 #ifndef WINDOWSNT
1957 /* Wait for child_setup to complete in case that vfork is
1958 actually defined as fork. The descriptor
1959 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1960 of a pipe is closed at the child side either by close-on-exec
1961 on successful execve or the _exit call in child_setup. */
1963 char dummy;
1965 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
1966 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
1967 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
1969 #endif
1973 static void
1974 create_pty (Lisp_Object process)
1976 struct Lisp_Process *p = XPROCESS (process);
1977 char pty_name[PTY_NAME_SIZE];
1978 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
1980 if (pty_fd >= 0)
1982 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
1983 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1984 /* On most USG systems it does not work to open the pty's tty here,
1985 then close it and reopen it in the child. */
1986 /* Don't let this terminal become our controlling terminal
1987 (in case we don't have one). */
1988 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1989 if (forkout < 0)
1990 report_file_error ("Opening pty", Qnil);
1991 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
1992 #if defined (DONT_REOPEN_PTY)
1993 /* In the case that vfork is defined as fork, the parent process
1994 (Emacs) may send some data before the child process completes
1995 tty options setup. So we setup tty before forking. */
1996 child_setup_tty (forkout);
1997 #endif /* DONT_REOPEN_PTY */
1998 #endif /* not USG, or USG_SUBTTY_WORKS */
2000 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2002 /* Record this as an active process, with its channels.
2003 As a result, child_setup will close Emacs's side of the pipes. */
2004 chan_process[pty_fd] = process;
2005 p->infd = pty_fd;
2006 p->outfd = pty_fd;
2008 /* Previously we recorded the tty descriptor used in the subprocess.
2009 It was only used for getting the foreground tty process, so now
2010 we just reopen the device (see emacs_get_tty_pgrp) as this is
2011 more portable (see USG_SUBTTY_WORKS above). */
2013 p->pty_flag = 1;
2014 pset_status (p, Qrun);
2015 setup_process_coding_systems (process);
2017 FD_SET (pty_fd, &input_wait_mask);
2018 FD_SET (pty_fd, &non_keyboard_wait_mask);
2019 if (pty_fd > max_process_desc)
2020 max_process_desc = pty_fd;
2022 pset_tty_name (p, build_string (pty_name));
2025 p->pid = -2;
2029 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2030 The address family of sa is not included in the result. */
2032 Lisp_Object
2033 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2035 Lisp_Object address;
2036 int i;
2037 unsigned char *cp;
2038 register struct Lisp_Vector *p;
2040 /* Workaround for a bug in getsockname on BSD: Names bound to
2041 sockets in the UNIX domain are inaccessible; getsockname returns
2042 a zero length name. */
2043 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2044 return empty_unibyte_string;
2046 switch (sa->sa_family)
2048 case AF_INET:
2050 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2051 len = sizeof (sin->sin_addr) + 1;
2052 address = Fmake_vector (make_number (len), Qnil);
2053 p = XVECTOR (address);
2054 p->contents[--len] = make_number (ntohs (sin->sin_port));
2055 cp = (unsigned char *) &sin->sin_addr;
2056 break;
2058 #ifdef AF_INET6
2059 case AF_INET6:
2061 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2062 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2063 len = sizeof (sin6->sin6_addr) / 2 + 1;
2064 address = Fmake_vector (make_number (len), Qnil);
2065 p = XVECTOR (address);
2066 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2067 for (i = 0; i < len; i++)
2068 p->contents[i] = make_number (ntohs (ip6[i]));
2069 return address;
2071 #endif
2072 #ifdef HAVE_LOCAL_SOCKETS
2073 case AF_LOCAL:
2075 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2076 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2077 /* If the first byte is NUL, the name is a Linux abstract
2078 socket name, and the name can contain embedded NULs. If
2079 it's not, we have a NUL-terminated string. Be careful not
2080 to walk past the end of the object looking for the name
2081 terminator, however. */
2082 if (name_length > 0 && sockun->sun_path[0] != '\0')
2084 const char *terminator
2085 = memchr (sockun->sun_path, '\0', name_length);
2087 if (terminator)
2088 name_length = terminator - (const char *) sockun->sun_path;
2091 return make_unibyte_string (sockun->sun_path, name_length);
2093 #endif
2094 default:
2095 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2096 address = Fcons (make_number (sa->sa_family),
2097 Fmake_vector (make_number (len), Qnil));
2098 p = XVECTOR (XCDR (address));
2099 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2100 break;
2103 i = 0;
2104 while (i < len)
2105 p->contents[i++] = make_number (*cp++);
2107 return address;
2111 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2113 static int
2114 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2116 register struct Lisp_Vector *p;
2118 if (VECTORP (address))
2120 p = XVECTOR (address);
2121 if (p->header.size == 5)
2123 *familyp = AF_INET;
2124 return sizeof (struct sockaddr_in);
2126 #ifdef AF_INET6
2127 else if (p->header.size == 9)
2129 *familyp = AF_INET6;
2130 return sizeof (struct sockaddr_in6);
2132 #endif
2134 #ifdef HAVE_LOCAL_SOCKETS
2135 else if (STRINGP (address))
2137 *familyp = AF_LOCAL;
2138 return sizeof (struct sockaddr_un);
2140 #endif
2141 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2142 && VECTORP (XCDR (address)))
2144 struct sockaddr *sa;
2145 p = XVECTOR (XCDR (address));
2146 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2147 return 0;
2148 *familyp = XINT (XCAR (address));
2149 return p->header.size + sizeof (sa->sa_family);
2151 return 0;
2154 /* Convert an address object (vector or string) to an internal sockaddr.
2156 The address format has been basically validated by
2157 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2158 it could have come from user data. So if FAMILY is not valid,
2159 we return after zeroing *SA. */
2161 static void
2162 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2164 register struct Lisp_Vector *p;
2165 register unsigned char *cp = NULL;
2166 register int i;
2167 EMACS_INT hostport;
2169 memset (sa, 0, len);
2171 if (VECTORP (address))
2173 p = XVECTOR (address);
2174 if (family == AF_INET)
2176 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2177 len = sizeof (sin->sin_addr) + 1;
2178 hostport = XINT (p->contents[--len]);
2179 sin->sin_port = htons (hostport);
2180 cp = (unsigned char *)&sin->sin_addr;
2181 sa->sa_family = family;
2183 #ifdef AF_INET6
2184 else if (family == AF_INET6)
2186 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2187 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2188 len = sizeof (sin6->sin6_addr) + 1;
2189 hostport = XINT (p->contents[--len]);
2190 sin6->sin6_port = htons (hostport);
2191 for (i = 0; i < len; i++)
2192 if (INTEGERP (p->contents[i]))
2194 int j = XFASTINT (p->contents[i]) & 0xffff;
2195 ip6[i] = ntohs (j);
2197 sa->sa_family = family;
2198 return;
2200 #endif
2201 else
2202 return;
2204 else if (STRINGP (address))
2206 #ifdef HAVE_LOCAL_SOCKETS
2207 if (family == AF_LOCAL)
2209 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2210 cp = SDATA (address);
2211 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2212 sockun->sun_path[i] = *cp++;
2213 sa->sa_family = family;
2215 #endif
2216 return;
2218 else
2220 p = XVECTOR (XCDR (address));
2221 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2224 for (i = 0; i < len; i++)
2225 if (INTEGERP (p->contents[i]))
2226 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2229 #ifdef DATAGRAM_SOCKETS
2230 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2231 1, 1, 0,
2232 doc: /* Get the current datagram address associated with PROCESS. */)
2233 (Lisp_Object process)
2235 int channel;
2237 CHECK_PROCESS (process);
2239 if (!DATAGRAM_CONN_P (process))
2240 return Qnil;
2242 channel = XPROCESS (process)->infd;
2243 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2244 datagram_address[channel].len);
2247 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2248 2, 2, 0,
2249 doc: /* Set the datagram address for PROCESS to ADDRESS.
2250 Returns nil upon error setting address, ADDRESS otherwise. */)
2251 (Lisp_Object process, Lisp_Object address)
2253 int channel;
2254 int family, len;
2256 CHECK_PROCESS (process);
2258 if (!DATAGRAM_CONN_P (process))
2259 return Qnil;
2261 channel = XPROCESS (process)->infd;
2263 len = get_lisp_to_sockaddr_size (address, &family);
2264 if (len == 0 || datagram_address[channel].len != len)
2265 return Qnil;
2266 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2267 return address;
2269 #endif
2272 static const struct socket_options {
2273 /* The name of this option. Should be lowercase version of option
2274 name without SO_ prefix. */
2275 const char *name;
2276 /* Option level SOL_... */
2277 int optlevel;
2278 /* Option number SO_... */
2279 int optnum;
2280 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2281 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2282 } socket_options[] =
2284 #ifdef SO_BINDTODEVICE
2285 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2286 #endif
2287 #ifdef SO_BROADCAST
2288 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2289 #endif
2290 #ifdef SO_DONTROUTE
2291 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2292 #endif
2293 #ifdef SO_KEEPALIVE
2294 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2295 #endif
2296 #ifdef SO_LINGER
2297 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2298 #endif
2299 #ifdef SO_OOBINLINE
2300 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2301 #endif
2302 #ifdef SO_PRIORITY
2303 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2304 #endif
2305 #ifdef SO_REUSEADDR
2306 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2307 #endif
2308 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2311 /* Set option OPT to value VAL on socket S.
2313 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2314 Signals an error if setting a known option fails.
2317 static int
2318 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2320 char *name;
2321 const struct socket_options *sopt;
2322 int ret = 0;
2324 CHECK_SYMBOL (opt);
2326 name = SSDATA (SYMBOL_NAME (opt));
2327 for (sopt = socket_options; sopt->name; sopt++)
2328 if (strcmp (name, sopt->name) == 0)
2329 break;
2331 switch (sopt->opttype)
2333 case SOPT_BOOL:
2335 int optval;
2336 optval = NILP (val) ? 0 : 1;
2337 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2338 &optval, sizeof (optval));
2339 break;
2342 case SOPT_INT:
2344 int optval;
2345 if (TYPE_RANGED_INTEGERP (int, val))
2346 optval = XINT (val);
2347 else
2348 error ("Bad option value for %s", name);
2349 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2350 &optval, sizeof (optval));
2351 break;
2354 #ifdef SO_BINDTODEVICE
2355 case SOPT_IFNAME:
2357 char devname[IFNAMSIZ + 1];
2359 /* This is broken, at least in the Linux 2.4 kernel.
2360 To unbind, the arg must be a zero integer, not the empty string.
2361 This should work on all systems. KFS. 2003-09-23. */
2362 memset (devname, 0, sizeof devname);
2363 if (STRINGP (val))
2365 char *arg = SSDATA (val);
2366 int len = min (strlen (arg), IFNAMSIZ);
2367 memcpy (devname, arg, len);
2369 else if (!NILP (val))
2370 error ("Bad option value for %s", name);
2371 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2372 devname, IFNAMSIZ);
2373 break;
2375 #endif
2377 #ifdef SO_LINGER
2378 case SOPT_LINGER:
2380 struct linger linger;
2382 linger.l_onoff = 1;
2383 linger.l_linger = 0;
2384 if (TYPE_RANGED_INTEGERP (int, val))
2385 linger.l_linger = XINT (val);
2386 else
2387 linger.l_onoff = NILP (val) ? 0 : 1;
2388 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2389 &linger, sizeof (linger));
2390 break;
2392 #endif
2394 default:
2395 return 0;
2398 if (ret < 0)
2400 int setsockopt_errno = errno;
2401 report_file_errno ("Cannot set network option", list2 (opt, val),
2402 setsockopt_errno);
2405 return (1 << sopt->optbit);
2409 DEFUN ("set-network-process-option",
2410 Fset_network_process_option, Sset_network_process_option,
2411 3, 4, 0,
2412 doc: /* For network process PROCESS set option OPTION to value VALUE.
2413 See `make-network-process' for a list of options and values.
2414 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2415 OPTION is not a supported option, return nil instead; otherwise return t. */)
2416 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2418 int s;
2419 struct Lisp_Process *p;
2421 CHECK_PROCESS (process);
2422 p = XPROCESS (process);
2423 if (!NETCONN1_P (p))
2424 error ("Process is not a network process");
2426 s = p->infd;
2427 if (s < 0)
2428 error ("Process is not running");
2430 if (set_socket_option (s, option, value))
2432 pset_childp (p, Fplist_put (p->childp, option, value));
2433 return Qt;
2436 if (NILP (no_error))
2437 error ("Unknown or unsupported option");
2439 return Qnil;
2443 DEFUN ("serial-process-configure",
2444 Fserial_process_configure,
2445 Sserial_process_configure,
2446 0, MANY, 0,
2447 doc: /* Configure speed, bytesize, etc. of a serial process.
2449 Arguments are specified as keyword/argument pairs. Attributes that
2450 are not given are re-initialized from the process's current
2451 configuration (available via the function `process-contact') or set to
2452 reasonable default values. The following arguments are defined:
2454 :process PROCESS
2455 :name NAME
2456 :buffer BUFFER
2457 :port PORT
2458 -- Any of these arguments can be given to identify the process that is
2459 to be configured. If none of these arguments is given, the current
2460 buffer's process is used.
2462 :speed SPEED -- SPEED is the speed of the serial port in bits per
2463 second, also called baud rate. Any value can be given for SPEED, but
2464 most serial ports work only at a few defined values between 1200 and
2465 115200, with 9600 being the most common value. If SPEED is nil, the
2466 serial port is not configured any further, i.e., all other arguments
2467 are ignored. This may be useful for special serial ports such as
2468 Bluetooth-to-serial converters which can only be configured through AT
2469 commands. A value of nil for SPEED can be used only when passed
2470 through `make-serial-process' or `serial-term'.
2472 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2473 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2475 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2476 `odd' (use odd parity), or the symbol `even' (use even parity). If
2477 PARITY is not given, no parity is used.
2479 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2480 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2481 is not given or nil, 1 stopbit is used.
2483 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2484 flowcontrol to be used, which is either nil (don't use flowcontrol),
2485 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2486 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2487 flowcontrol is used.
2489 `serial-process-configure' is called by `make-serial-process' for the
2490 initial configuration of the serial port.
2492 Examples:
2494 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2496 \(serial-process-configure
2497 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2499 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2501 usage: (serial-process-configure &rest ARGS) */)
2502 (ptrdiff_t nargs, Lisp_Object *args)
2504 struct Lisp_Process *p;
2505 Lisp_Object contact = Qnil;
2506 Lisp_Object proc = Qnil;
2507 struct gcpro gcpro1;
2509 contact = Flist (nargs, args);
2510 GCPRO1 (contact);
2512 proc = Fplist_get (contact, QCprocess);
2513 if (NILP (proc))
2514 proc = Fplist_get (contact, QCname);
2515 if (NILP (proc))
2516 proc = Fplist_get (contact, QCbuffer);
2517 if (NILP (proc))
2518 proc = Fplist_get (contact, QCport);
2519 proc = get_process (proc);
2520 p = XPROCESS (proc);
2521 if (!EQ (p->type, Qserial))
2522 error ("Not a serial process");
2524 if (NILP (Fplist_get (p->childp, QCspeed)))
2526 UNGCPRO;
2527 return Qnil;
2530 serial_configure (p, contact);
2532 UNGCPRO;
2533 return Qnil;
2536 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2537 0, MANY, 0,
2538 doc: /* Create and return a serial port process.
2540 In Emacs, serial port connections are represented by process objects,
2541 so input and output work as for subprocesses, and `delete-process'
2542 closes a serial port connection. However, a serial process has no
2543 process id, it cannot be signaled, and the status codes are different
2544 from normal processes.
2546 `make-serial-process' creates a process and a buffer, on which you
2547 probably want to use `process-send-string'. Try \\[serial-term] for
2548 an interactive terminal. See below for examples.
2550 Arguments are specified as keyword/argument pairs. The following
2551 arguments are defined:
2553 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2554 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2555 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2556 the backslashes in strings).
2558 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2559 which this function calls.
2561 :name NAME -- NAME is the name of the process. If NAME is not given,
2562 the value of PORT is used.
2564 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2565 with the process. Process output goes at the end of that buffer,
2566 unless you specify an output stream or filter function to handle the
2567 output. If BUFFER is not given, the value of NAME is used.
2569 :coding CODING -- If CODING is a symbol, it specifies the coding
2570 system used for both reading and writing for this process. If CODING
2571 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2572 ENCODING is used for writing.
2574 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2575 the process is running. If BOOL is not given, query before exiting.
2577 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2578 In the stopped state, a serial process does not accept incoming data,
2579 but you can send outgoing data. The stopped state is cleared by
2580 `continue-process' and set by `stop-process'.
2582 :filter FILTER -- Install FILTER as the process filter.
2584 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2586 :plist PLIST -- Install PLIST as the initial plist of the process.
2588 :bytesize
2589 :parity
2590 :stopbits
2591 :flowcontrol
2592 -- This function calls `serial-process-configure' to handle these
2593 arguments.
2595 The original argument list, possibly modified by later configuration,
2596 is available via the function `process-contact'.
2598 Examples:
2600 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2602 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2604 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2606 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2608 usage: (make-serial-process &rest ARGS) */)
2609 (ptrdiff_t nargs, Lisp_Object *args)
2611 int fd = -1;
2612 Lisp_Object proc, contact, port;
2613 struct Lisp_Process *p;
2614 struct gcpro gcpro1;
2615 Lisp_Object name, buffer;
2616 Lisp_Object tem, val;
2617 ptrdiff_t specpdl_count;
2619 if (nargs == 0)
2620 return Qnil;
2622 contact = Flist (nargs, args);
2623 GCPRO1 (contact);
2625 port = Fplist_get (contact, QCport);
2626 if (NILP (port))
2627 error ("No port specified");
2628 CHECK_STRING (port);
2630 if (NILP (Fplist_member (contact, QCspeed)))
2631 error (":speed not specified");
2632 if (!NILP (Fplist_get (contact, QCspeed)))
2633 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2635 name = Fplist_get (contact, QCname);
2636 if (NILP (name))
2637 name = port;
2638 CHECK_STRING (name);
2639 proc = make_process (name);
2640 specpdl_count = SPECPDL_INDEX ();
2641 record_unwind_protect (remove_process, proc);
2642 p = XPROCESS (proc);
2644 fd = serial_open (port);
2645 p->open_fd[SUBPROCESS_STDIN] = fd;
2646 p->infd = fd;
2647 p->outfd = fd;
2648 if (fd > max_process_desc)
2649 max_process_desc = fd;
2650 chan_process[fd] = proc;
2652 buffer = Fplist_get (contact, QCbuffer);
2653 if (NILP (buffer))
2654 buffer = name;
2655 buffer = Fget_buffer_create (buffer);
2656 pset_buffer (p, buffer);
2658 pset_childp (p, contact);
2659 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2660 pset_type (p, Qserial);
2661 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2662 pset_filter (p, Fplist_get (contact, QCfilter));
2663 pset_log (p, Qnil);
2664 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2665 p->kill_without_query = 1;
2666 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2667 pset_command (p, Qt);
2668 eassert (! p->pty_flag);
2670 if (!EQ (p->command, Qt))
2672 FD_SET (fd, &input_wait_mask);
2673 FD_SET (fd, &non_keyboard_wait_mask);
2676 if (BUFFERP (buffer))
2678 set_marker_both (p->mark, buffer,
2679 BUF_ZV (XBUFFER (buffer)),
2680 BUF_ZV_BYTE (XBUFFER (buffer)));
2683 tem = Fplist_member (contact, QCcoding);
2684 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2685 tem = Qnil;
2687 val = Qnil;
2688 if (!NILP (tem))
2690 val = XCAR (XCDR (tem));
2691 if (CONSP (val))
2692 val = XCAR (val);
2694 else if (!NILP (Vcoding_system_for_read))
2695 val = Vcoding_system_for_read;
2696 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2697 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2698 val = Qnil;
2699 pset_decode_coding_system (p, val);
2701 val = Qnil;
2702 if (!NILP (tem))
2704 val = XCAR (XCDR (tem));
2705 if (CONSP (val))
2706 val = XCDR (val);
2708 else if (!NILP (Vcoding_system_for_write))
2709 val = Vcoding_system_for_write;
2710 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2711 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2712 val = Qnil;
2713 pset_encode_coding_system (p, val);
2715 setup_process_coding_systems (proc);
2716 pset_decoding_buf (p, empty_unibyte_string);
2717 p->decoding_carryover = 0;
2718 pset_encoding_buf (p, empty_unibyte_string);
2719 p->inherit_coding_system_flag
2720 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2722 Fserial_process_configure (nargs, args);
2724 specpdl_ptr = specpdl + specpdl_count;
2726 UNGCPRO;
2727 return proc;
2730 /* Create a network stream/datagram client/server process. Treated
2731 exactly like a normal process when reading and writing. Primary
2732 differences are in status display and process deletion. A network
2733 connection has no PID; you cannot signal it. All you can do is
2734 stop/continue it and deactivate/close it via delete-process. */
2736 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2737 0, MANY, 0,
2738 doc: /* Create and return a network server or client process.
2740 In Emacs, network connections are represented by process objects, so
2741 input and output work as for subprocesses and `delete-process' closes
2742 a network connection. However, a network process has no process id,
2743 it cannot be signaled, and the status codes are different from normal
2744 processes.
2746 Arguments are specified as keyword/argument pairs. The following
2747 arguments are defined:
2749 :name NAME -- NAME is name for process. It is modified if necessary
2750 to make it unique.
2752 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2753 with the process. Process output goes at end of that buffer, unless
2754 you specify an output stream or filter function to handle the output.
2755 BUFFER may be also nil, meaning that this process is not associated
2756 with any buffer.
2758 :host HOST -- HOST is name of the host to connect to, or its IP
2759 address. The symbol `local' specifies the local host. If specified
2760 for a server process, it must be a valid name or address for the local
2761 host, and only clients connecting to that address will be accepted.
2763 :service SERVICE -- SERVICE is name of the service desired, or an
2764 integer specifying a port number to connect to. If SERVICE is t,
2765 a random port number is selected for the server. (If Emacs was
2766 compiled with getaddrinfo, a port number can also be specified as a
2767 string, e.g. "80", as well as an integer. This is not portable.)
2769 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2770 stream type connection, `datagram' creates a datagram type connection,
2771 `seqpacket' creates a reliable datagram connection.
2773 :family FAMILY -- FAMILY is the address (and protocol) family for the
2774 service specified by HOST and SERVICE. The default (nil) is to use
2775 whatever address family (IPv4 or IPv6) that is defined for the host
2776 and port number specified by HOST and SERVICE. Other address families
2777 supported are:
2778 local -- for a local (i.e. UNIX) address specified by SERVICE.
2779 ipv4 -- use IPv4 address family only.
2780 ipv6 -- use IPv6 address family only.
2782 :local ADDRESS -- ADDRESS is the local address used for the connection.
2783 This parameter is ignored when opening a client process. When specified
2784 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2786 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2787 connection. This parameter is ignored when opening a stream server
2788 process. For a datagram server process, it specifies the initial
2789 setting of the remote datagram address. When specified for a client
2790 process, the FAMILY, HOST, and SERVICE args are ignored.
2792 The format of ADDRESS depends on the address family:
2793 - An IPv4 address is represented as an vector of integers [A B C D P]
2794 corresponding to numeric IP address A.B.C.D and port number P.
2795 - A local address is represented as a string with the address in the
2796 local address space.
2797 - An "unsupported family" address is represented by a cons (F . AV)
2798 where F is the family number and AV is a vector containing the socket
2799 address data with one element per address data byte. Do not rely on
2800 this format in portable code, as it may depend on implementation
2801 defined constants, data sizes, and data structure alignment.
2803 :coding CODING -- If CODING is a symbol, it specifies the coding
2804 system used for both reading and writing for this process. If CODING
2805 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2806 ENCODING is used for writing.
2808 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2809 return without waiting for the connection to complete; instead, the
2810 sentinel function will be called with second arg matching "open" (if
2811 successful) or "failed" when the connect completes. Default is to use
2812 a blocking connect (i.e. wait) for stream type connections.
2814 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2815 running when Emacs is exited.
2817 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2818 In the stopped state, a server process does not accept new
2819 connections, and a client process does not handle incoming traffic.
2820 The stopped state is cleared by `continue-process' and set by
2821 `stop-process'.
2823 :filter FILTER -- Install FILTER as the process filter.
2825 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2826 process filter are multibyte, otherwise they are unibyte.
2827 If this keyword is not specified, the strings are multibyte if
2828 the default value of `enable-multibyte-characters' is non-nil.
2830 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2832 :log LOG -- Install LOG as the server process log function. This
2833 function is called when the server accepts a network connection from a
2834 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2835 is the server process, CLIENT is the new process for the connection,
2836 and MESSAGE is a string.
2838 :plist PLIST -- Install PLIST as the new process's initial plist.
2840 :server QLEN -- if QLEN is non-nil, create a server process for the
2841 specified FAMILY, SERVICE, and connection type (stream or datagram).
2842 If QLEN is an integer, it is used as the max. length of the server's
2843 pending connection queue (also known as the backlog); the default
2844 queue length is 5. Default is to create a client process.
2846 The following network options can be specified for this connection:
2848 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2849 :dontroute BOOL -- Only send to directly connected hosts.
2850 :keepalive BOOL -- Send keep-alive messages on network stream.
2851 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2852 :oobinline BOOL -- Place out-of-band data in receive data stream.
2853 :priority INT -- Set protocol defined priority for sent packets.
2854 :reuseaddr BOOL -- Allow reusing a recently used local address
2855 (this is allowed by default for a server process).
2856 :bindtodevice NAME -- bind to interface NAME. Using this may require
2857 special privileges on some systems.
2859 Consult the relevant system programmer's manual pages for more
2860 information on using these options.
2863 A server process will listen for and accept connections from clients.
2864 When a client connection is accepted, a new network process is created
2865 for the connection with the following parameters:
2867 - The client's process name is constructed by concatenating the server
2868 process's NAME and a client identification string.
2869 - If the FILTER argument is non-nil, the client process will not get a
2870 separate process buffer; otherwise, the client's process buffer is a newly
2871 created buffer named after the server process's BUFFER name or process
2872 NAME concatenated with the client identification string.
2873 - The connection type and the process filter and sentinel parameters are
2874 inherited from the server process's TYPE, FILTER and SENTINEL.
2875 - The client process's contact info is set according to the client's
2876 addressing information (typically an IP address and a port number).
2877 - The client process's plist is initialized from the server's plist.
2879 Notice that the FILTER and SENTINEL args are never used directly by
2880 the server process. Also, the BUFFER argument is not used directly by
2881 the server process, but via the optional :log function, accepted (and
2882 failed) connections may be logged in the server process's buffer.
2884 The original argument list, modified with the actual connection
2885 information, is available via the `process-contact' function.
2887 usage: (make-network-process &rest ARGS) */)
2888 (ptrdiff_t nargs, Lisp_Object *args)
2890 Lisp_Object proc;
2891 Lisp_Object contact;
2892 struct Lisp_Process *p;
2893 #ifdef HAVE_GETADDRINFO
2894 struct addrinfo ai, *res, *lres;
2895 struct addrinfo hints;
2896 const char *portstring;
2897 char portbuf[128];
2898 #else /* HAVE_GETADDRINFO */
2899 struct _emacs_addrinfo
2901 int ai_family;
2902 int ai_socktype;
2903 int ai_protocol;
2904 int ai_addrlen;
2905 struct sockaddr *ai_addr;
2906 struct _emacs_addrinfo *ai_next;
2907 } ai, *res, *lres;
2908 #endif /* HAVE_GETADDRINFO */
2909 struct sockaddr_in address_in;
2910 #ifdef HAVE_LOCAL_SOCKETS
2911 struct sockaddr_un address_un;
2912 #endif
2913 int port;
2914 int ret = 0;
2915 int xerrno = 0;
2916 int s = -1, outch, inch;
2917 struct gcpro gcpro1;
2918 ptrdiff_t count = SPECPDL_INDEX ();
2919 ptrdiff_t count1;
2920 Lisp_Object colon_address; /* Either QClocal or QCremote. */
2921 Lisp_Object tem;
2922 Lisp_Object name, buffer, host, service, address;
2923 Lisp_Object filter, sentinel;
2924 bool is_non_blocking_client = 0;
2925 bool is_server = 0;
2926 int backlog = 5;
2927 int socktype;
2928 int family = -1;
2930 if (nargs == 0)
2931 return Qnil;
2933 /* Save arguments for process-contact and clone-process. */
2934 contact = Flist (nargs, args);
2935 GCPRO1 (contact);
2937 #ifdef WINDOWSNT
2938 /* Ensure socket support is loaded if available. */
2939 init_winsock (TRUE);
2940 #endif
2942 /* :type TYPE (nil: stream, datagram */
2943 tem = Fplist_get (contact, QCtype);
2944 if (NILP (tem))
2945 socktype = SOCK_STREAM;
2946 #ifdef DATAGRAM_SOCKETS
2947 else if (EQ (tem, Qdatagram))
2948 socktype = SOCK_DGRAM;
2949 #endif
2950 #ifdef HAVE_SEQPACKET
2951 else if (EQ (tem, Qseqpacket))
2952 socktype = SOCK_SEQPACKET;
2953 #endif
2954 else
2955 error ("Unsupported connection type");
2957 /* :server BOOL */
2958 tem = Fplist_get (contact, QCserver);
2959 if (!NILP (tem))
2961 /* Don't support network sockets when non-blocking mode is
2962 not available, since a blocked Emacs is not useful. */
2963 is_server = 1;
2964 if (TYPE_RANGED_INTEGERP (int, tem))
2965 backlog = XINT (tem);
2968 /* Make colon_address an alias for :local (server) or :remote (client). */
2969 colon_address = is_server ? QClocal : QCremote;
2971 /* :nowait BOOL */
2972 if (!is_server && socktype != SOCK_DGRAM
2973 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2975 #ifndef NON_BLOCKING_CONNECT
2976 error ("Non-blocking connect not supported");
2977 #else
2978 is_non_blocking_client = 1;
2979 #endif
2982 name = Fplist_get (contact, QCname);
2983 buffer = Fplist_get (contact, QCbuffer);
2984 filter = Fplist_get (contact, QCfilter);
2985 sentinel = Fplist_get (contact, QCsentinel);
2987 CHECK_STRING (name);
2989 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2990 ai.ai_socktype = socktype;
2991 ai.ai_protocol = 0;
2992 ai.ai_next = NULL;
2993 res = &ai;
2995 /* :local ADDRESS or :remote ADDRESS */
2996 address = Fplist_get (contact, colon_address);
2997 if (!NILP (address))
2999 host = service = Qnil;
3001 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3002 error ("Malformed :address");
3003 ai.ai_family = family;
3004 ai.ai_addr = alloca (ai.ai_addrlen);
3005 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3006 goto open_socket;
3009 /* :family FAMILY -- nil (for Inet), local, or integer. */
3010 tem = Fplist_get (contact, QCfamily);
3011 if (NILP (tem))
3013 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3014 family = AF_UNSPEC;
3015 #else
3016 family = AF_INET;
3017 #endif
3019 #ifdef HAVE_LOCAL_SOCKETS
3020 else if (EQ (tem, Qlocal))
3021 family = AF_LOCAL;
3022 #endif
3023 #ifdef AF_INET6
3024 else if (EQ (tem, Qipv6))
3025 family = AF_INET6;
3026 #endif
3027 else if (EQ (tem, Qipv4))
3028 family = AF_INET;
3029 else if (TYPE_RANGED_INTEGERP (int, tem))
3030 family = XINT (tem);
3031 else
3032 error ("Unknown address family");
3034 ai.ai_family = family;
3036 /* :service SERVICE -- string, integer (port number), or t (random port). */
3037 service = Fplist_get (contact, QCservice);
3039 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3040 host = Fplist_get (contact, QChost);
3041 if (!NILP (host))
3043 if (EQ (host, Qlocal))
3044 /* Depending on setup, "localhost" may map to different IPv4 and/or
3045 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3046 host = build_string ("127.0.0.1");
3047 CHECK_STRING (host);
3050 #ifdef HAVE_LOCAL_SOCKETS
3051 if (family == AF_LOCAL)
3053 if (!NILP (host))
3055 message (":family local ignores the :host \"%s\" property",
3056 SDATA (host));
3057 contact = Fplist_put (contact, QChost, Qnil);
3058 host = Qnil;
3060 CHECK_STRING (service);
3061 memset (&address_un, 0, sizeof address_un);
3062 address_un.sun_family = AF_LOCAL;
3063 if (sizeof address_un.sun_path <= SBYTES (service))
3064 error ("Service name too long");
3065 lispstpcpy (address_un.sun_path, service);
3066 ai.ai_addr = (struct sockaddr *) &address_un;
3067 ai.ai_addrlen = sizeof address_un;
3068 goto open_socket;
3070 #endif
3072 /* Slow down polling to every ten seconds.
3073 Some kernels have a bug which causes retrying connect to fail
3074 after a connect. Polling can interfere with gethostbyname too. */
3075 #ifdef POLL_FOR_INPUT
3076 if (socktype != SOCK_DGRAM)
3078 record_unwind_protect_void (run_all_atimers);
3079 bind_polling_period (10);
3081 #endif
3083 #ifdef HAVE_GETADDRINFO
3084 /* If we have a host, use getaddrinfo to resolve both host and service.
3085 Otherwise, use getservbyname to lookup the service. */
3086 if (!NILP (host))
3089 /* SERVICE can either be a string or int.
3090 Convert to a C string for later use by getaddrinfo. */
3091 if (EQ (service, Qt))
3092 portstring = "0";
3093 else if (INTEGERP (service))
3095 sprintf (portbuf, "%"pI"d", XINT (service));
3096 portstring = portbuf;
3098 else
3100 CHECK_STRING (service);
3101 portstring = SSDATA (service);
3104 immediate_quit = 1;
3105 QUIT;
3106 memset (&hints, 0, sizeof (hints));
3107 hints.ai_flags = 0;
3108 hints.ai_family = family;
3109 hints.ai_socktype = socktype;
3110 hints.ai_protocol = 0;
3112 #ifdef HAVE_RES_INIT
3113 res_init ();
3114 #endif
3116 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3117 if (ret)
3118 #ifdef HAVE_GAI_STRERROR
3119 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3120 #else
3121 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3122 #endif
3123 immediate_quit = 0;
3125 goto open_socket;
3127 #endif /* HAVE_GETADDRINFO */
3129 /* We end up here if getaddrinfo is not defined, or in case no hostname
3130 has been specified (e.g. for a local server process). */
3132 if (EQ (service, Qt))
3133 port = 0;
3134 else if (INTEGERP (service))
3135 port = htons ((unsigned short) XINT (service));
3136 else
3138 struct servent *svc_info;
3139 CHECK_STRING (service);
3140 svc_info = getservbyname (SSDATA (service),
3141 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3142 if (svc_info == 0)
3143 error ("Unknown service: %s", SDATA (service));
3144 port = svc_info->s_port;
3147 memset (&address_in, 0, sizeof address_in);
3148 address_in.sin_family = family;
3149 address_in.sin_addr.s_addr = INADDR_ANY;
3150 address_in.sin_port = port;
3152 #ifndef HAVE_GETADDRINFO
3153 if (!NILP (host))
3155 struct hostent *host_info_ptr;
3157 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3158 as it may `hang' Emacs for a very long time. */
3159 immediate_quit = 1;
3160 QUIT;
3162 #ifdef HAVE_RES_INIT
3163 res_init ();
3164 #endif
3166 host_info_ptr = gethostbyname (SDATA (host));
3167 immediate_quit = 0;
3169 if (host_info_ptr)
3171 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3172 host_info_ptr->h_length);
3173 family = host_info_ptr->h_addrtype;
3174 address_in.sin_family = family;
3176 else
3177 /* Attempt to interpret host as numeric inet address. */
3179 unsigned long numeric_addr;
3180 numeric_addr = inet_addr (SSDATA (host));
3181 if (numeric_addr == -1)
3182 error ("Unknown host \"%s\"", SDATA (host));
3184 memcpy (&address_in.sin_addr, &numeric_addr,
3185 sizeof (address_in.sin_addr));
3189 #endif /* not HAVE_GETADDRINFO */
3191 ai.ai_family = family;
3192 ai.ai_addr = (struct sockaddr *) &address_in;
3193 ai.ai_addrlen = sizeof address_in;
3195 open_socket:
3197 /* Do this in case we never enter the for-loop below. */
3198 count1 = SPECPDL_INDEX ();
3199 s = -1;
3201 for (lres = res; lres; lres = lres->ai_next)
3203 ptrdiff_t optn;
3204 int optbits;
3206 #ifdef WINDOWSNT
3207 retry_connect:
3208 #endif
3210 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3211 lres->ai_protocol);
3212 if (s < 0)
3214 xerrno = errno;
3215 continue;
3218 #ifdef DATAGRAM_SOCKETS
3219 if (!is_server && socktype == SOCK_DGRAM)
3220 break;
3221 #endif /* DATAGRAM_SOCKETS */
3223 #ifdef NON_BLOCKING_CONNECT
3224 if (is_non_blocking_client)
3226 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3227 if (ret < 0)
3229 xerrno = errno;
3230 emacs_close (s);
3231 s = -1;
3232 continue;
3235 #endif
3237 /* Make us close S if quit. */
3238 record_unwind_protect_int (close_file_unwind, s);
3240 /* Parse network options in the arg list.
3241 We simply ignore anything which isn't a known option (including other keywords).
3242 An error is signaled if setting a known option fails. */
3243 for (optn = optbits = 0; optn < nargs - 1; optn += 2)
3244 optbits |= set_socket_option (s, args[optn], args[optn + 1]);
3246 if (is_server)
3248 /* Configure as a server socket. */
3250 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3251 explicit :reuseaddr key to override this. */
3252 #ifdef HAVE_LOCAL_SOCKETS
3253 if (family != AF_LOCAL)
3254 #endif
3255 if (!(optbits & (1 << OPIX_REUSEADDR)))
3257 int optval = 1;
3258 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3259 report_file_error ("Cannot set reuse option on server socket", Qnil);
3262 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3263 report_file_error ("Cannot bind server socket", Qnil);
3265 #ifdef HAVE_GETSOCKNAME
3266 if (EQ (service, Qt))
3268 struct sockaddr_in sa1;
3269 socklen_t len1 = sizeof (sa1);
3270 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3272 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3273 service = make_number (ntohs (sa1.sin_port));
3274 contact = Fplist_put (contact, QCservice, service);
3277 #endif
3279 if (socktype != SOCK_DGRAM && listen (s, backlog))
3280 report_file_error ("Cannot listen on server socket", Qnil);
3282 break;
3285 immediate_quit = 1;
3286 QUIT;
3288 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3289 xerrno = errno;
3291 if (ret == 0 || xerrno == EISCONN)
3293 /* The unwind-protect will be discarded afterwards.
3294 Likewise for immediate_quit. */
3295 break;
3298 #ifdef NON_BLOCKING_CONNECT
3299 #ifdef EINPROGRESS
3300 if (is_non_blocking_client && xerrno == EINPROGRESS)
3301 break;
3302 #else
3303 #ifdef EWOULDBLOCK
3304 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3305 break;
3306 #endif
3307 #endif
3308 #endif
3310 #ifndef WINDOWSNT
3311 if (xerrno == EINTR)
3313 /* Unlike most other syscalls connect() cannot be called
3314 again. (That would return EALREADY.) The proper way to
3315 wait for completion is pselect(). */
3316 int sc;
3317 socklen_t len;
3318 fd_set fdset;
3319 retry_select:
3320 FD_ZERO (&fdset);
3321 FD_SET (s, &fdset);
3322 QUIT;
3323 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3324 if (sc == -1)
3326 if (errno == EINTR)
3327 goto retry_select;
3328 else
3329 report_file_error ("Failed select", Qnil);
3331 eassert (sc > 0);
3333 len = sizeof xerrno;
3334 eassert (FD_ISSET (s, &fdset));
3335 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3336 report_file_error ("Failed getsockopt", Qnil);
3337 if (xerrno)
3338 report_file_errno ("Failed connect", Qnil, xerrno);
3339 break;
3341 #endif /* !WINDOWSNT */
3343 immediate_quit = 0;
3345 /* Discard the unwind protect closing S. */
3346 specpdl_ptr = specpdl + count1;
3347 emacs_close (s);
3348 s = -1;
3350 #ifdef WINDOWSNT
3351 if (xerrno == EINTR)
3352 goto retry_connect;
3353 #endif
3356 if (s >= 0)
3358 #ifdef DATAGRAM_SOCKETS
3359 if (socktype == SOCK_DGRAM)
3361 if (datagram_address[s].sa)
3362 emacs_abort ();
3363 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3364 datagram_address[s].len = lres->ai_addrlen;
3365 if (is_server)
3367 Lisp_Object remote;
3368 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3369 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3371 int rfamily, rlen;
3372 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3373 if (rlen != 0 && rfamily == lres->ai_family
3374 && rlen == lres->ai_addrlen)
3375 conv_lisp_to_sockaddr (rfamily, remote,
3376 datagram_address[s].sa, rlen);
3379 else
3380 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3382 #endif
3383 contact = Fplist_put (contact, colon_address,
3384 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3385 #ifdef HAVE_GETSOCKNAME
3386 if (!is_server)
3388 struct sockaddr_in sa1;
3389 socklen_t len1 = sizeof (sa1);
3390 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3391 contact = Fplist_put (contact, QClocal,
3392 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3394 #endif
3397 immediate_quit = 0;
3399 #ifdef HAVE_GETADDRINFO
3400 if (res != &ai)
3402 block_input ();
3403 freeaddrinfo (res);
3404 unblock_input ();
3406 #endif
3408 if (s < 0)
3410 /* If non-blocking got this far - and failed - assume non-blocking is
3411 not supported after all. This is probably a wrong assumption, but
3412 the normal blocking calls to open-network-stream handles this error
3413 better. */
3414 if (is_non_blocking_client)
3415 return Qnil;
3417 report_file_errno ((is_server
3418 ? "make server process failed"
3419 : "make client process failed"),
3420 contact, xerrno);
3423 inch = s;
3424 outch = s;
3426 if (!NILP (buffer))
3427 buffer = Fget_buffer_create (buffer);
3428 proc = make_process (name);
3430 chan_process[inch] = proc;
3432 fcntl (inch, F_SETFL, O_NONBLOCK);
3434 p = XPROCESS (proc);
3436 pset_childp (p, contact);
3437 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3438 pset_type (p, Qnetwork);
3440 pset_buffer (p, buffer);
3441 pset_sentinel (p, sentinel);
3442 pset_filter (p, filter);
3443 pset_log (p, Fplist_get (contact, QClog));
3444 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3445 p->kill_without_query = 1;
3446 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3447 pset_command (p, Qt);
3448 p->pid = 0;
3450 p->open_fd[SUBPROCESS_STDIN] = inch;
3451 p->infd = inch;
3452 p->outfd = outch;
3454 /* Discard the unwind protect for closing S, if any. */
3455 specpdl_ptr = specpdl + count1;
3457 /* Unwind bind_polling_period and request_sigio. */
3458 unbind_to (count, Qnil);
3460 if (is_server && socktype != SOCK_DGRAM)
3461 pset_status (p, Qlisten);
3463 /* Make the process marker point into the process buffer (if any). */
3464 if (BUFFERP (buffer))
3465 set_marker_both (p->mark, buffer,
3466 BUF_ZV (XBUFFER (buffer)),
3467 BUF_ZV_BYTE (XBUFFER (buffer)));
3469 #ifdef NON_BLOCKING_CONNECT
3470 if (is_non_blocking_client)
3472 /* We may get here if connect did succeed immediately. However,
3473 in that case, we still need to signal this like a non-blocking
3474 connection. */
3475 pset_status (p, Qconnect);
3476 if (!FD_ISSET (inch, &connect_wait_mask))
3478 FD_SET (inch, &connect_wait_mask);
3479 FD_SET (inch, &write_mask);
3480 num_pending_connects++;
3483 else
3484 #endif
3485 /* A server may have a client filter setting of Qt, but it must
3486 still listen for incoming connects unless it is stopped. */
3487 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3488 || (EQ (p->status, Qlisten) && NILP (p->command)))
3490 FD_SET (inch, &input_wait_mask);
3491 FD_SET (inch, &non_keyboard_wait_mask);
3494 if (inch > max_process_desc)
3495 max_process_desc = inch;
3497 tem = Fplist_member (contact, QCcoding);
3498 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3499 tem = Qnil; /* No error message (too late!). */
3502 /* Setup coding systems for communicating with the network stream. */
3503 struct gcpro gcpro1;
3504 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3505 Lisp_Object coding_systems = Qt;
3506 Lisp_Object val;
3508 if (!NILP (tem))
3510 val = XCAR (XCDR (tem));
3511 if (CONSP (val))
3512 val = XCAR (val);
3514 else if (!NILP (Vcoding_system_for_read))
3515 val = Vcoding_system_for_read;
3516 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3517 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3518 /* We dare not decode end-of-line format by setting VAL to
3519 Qraw_text, because the existing Emacs Lisp libraries
3520 assume that they receive bare code including a sequence of
3521 CR LF. */
3522 val = Qnil;
3523 else
3525 if (NILP (host) || NILP (service))
3526 coding_systems = Qnil;
3527 else
3529 GCPRO1 (proc);
3530 coding_systems = CALLN (Ffind_operation_coding_system,
3531 Qopen_network_stream, name, buffer,
3532 host, service);
3533 UNGCPRO;
3535 if (CONSP (coding_systems))
3536 val = XCAR (coding_systems);
3537 else if (CONSP (Vdefault_process_coding_system))
3538 val = XCAR (Vdefault_process_coding_system);
3539 else
3540 val = Qnil;
3542 pset_decode_coding_system (p, val);
3544 if (!NILP (tem))
3546 val = XCAR (XCDR (tem));
3547 if (CONSP (val))
3548 val = XCDR (val);
3550 else if (!NILP (Vcoding_system_for_write))
3551 val = Vcoding_system_for_write;
3552 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3553 val = Qnil;
3554 else
3556 if (EQ (coding_systems, Qt))
3558 if (NILP (host) || NILP (service))
3559 coding_systems = Qnil;
3560 else
3562 GCPRO1 (proc);
3563 coding_systems = CALLN (Ffind_operation_coding_system,
3564 Qopen_network_stream, name, buffer,
3565 host, service);
3566 UNGCPRO;
3569 if (CONSP (coding_systems))
3570 val = XCDR (coding_systems);
3571 else if (CONSP (Vdefault_process_coding_system))
3572 val = XCDR (Vdefault_process_coding_system);
3573 else
3574 val = Qnil;
3576 pset_encode_coding_system (p, val);
3578 setup_process_coding_systems (proc);
3580 pset_decoding_buf (p, empty_unibyte_string);
3581 p->decoding_carryover = 0;
3582 pset_encoding_buf (p, empty_unibyte_string);
3584 p->inherit_coding_system_flag
3585 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3587 UNGCPRO;
3588 return proc;
3592 #ifdef HAVE_NET_IF_H
3594 #ifdef SIOCGIFCONF
3595 static Lisp_Object
3596 network_interface_list (void)
3598 struct ifconf ifconf;
3599 struct ifreq *ifreq;
3600 void *buf = NULL;
3601 ptrdiff_t buf_size = 512;
3602 int s;
3603 Lisp_Object res;
3604 ptrdiff_t count;
3606 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3607 if (s < 0)
3608 return Qnil;
3609 count = SPECPDL_INDEX ();
3610 record_unwind_protect_int (close_file_unwind, s);
3614 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3615 ifconf.ifc_buf = buf;
3616 ifconf.ifc_len = buf_size;
3617 if (ioctl (s, SIOCGIFCONF, &ifconf))
3619 emacs_close (s);
3620 xfree (buf);
3621 return Qnil;
3624 while (ifconf.ifc_len == buf_size);
3626 res = unbind_to (count, Qnil);
3627 ifreq = ifconf.ifc_req;
3628 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3630 struct ifreq *ifq = ifreq;
3631 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3632 #define SIZEOF_IFREQ(sif) \
3633 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3634 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3636 int len = SIZEOF_IFREQ (ifq);
3637 #else
3638 int len = sizeof (*ifreq);
3639 #endif
3640 char namebuf[sizeof (ifq->ifr_name) + 1];
3641 ifreq = (struct ifreq *) ((char *) ifreq + len);
3643 if (ifq->ifr_addr.sa_family != AF_INET)
3644 continue;
3646 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3647 namebuf[sizeof (ifq->ifr_name)] = 0;
3648 res = Fcons (Fcons (build_string (namebuf),
3649 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3650 sizeof (struct sockaddr))),
3651 res);
3654 xfree (buf);
3655 return res;
3657 #endif /* SIOCGIFCONF */
3659 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3661 struct ifflag_def {
3662 int flag_bit;
3663 const char *flag_sym;
3666 static const struct ifflag_def ifflag_table[] = {
3667 #ifdef IFF_UP
3668 { IFF_UP, "up" },
3669 #endif
3670 #ifdef IFF_BROADCAST
3671 { IFF_BROADCAST, "broadcast" },
3672 #endif
3673 #ifdef IFF_DEBUG
3674 { IFF_DEBUG, "debug" },
3675 #endif
3676 #ifdef IFF_LOOPBACK
3677 { IFF_LOOPBACK, "loopback" },
3678 #endif
3679 #ifdef IFF_POINTOPOINT
3680 { IFF_POINTOPOINT, "pointopoint" },
3681 #endif
3682 #ifdef IFF_RUNNING
3683 { IFF_RUNNING, "running" },
3684 #endif
3685 #ifdef IFF_NOARP
3686 { IFF_NOARP, "noarp" },
3687 #endif
3688 #ifdef IFF_PROMISC
3689 { IFF_PROMISC, "promisc" },
3690 #endif
3691 #ifdef IFF_NOTRAILERS
3692 #ifdef NS_IMPL_COCOA
3693 /* Really means smart, notrailers is obsolete. */
3694 { IFF_NOTRAILERS, "smart" },
3695 #else
3696 { IFF_NOTRAILERS, "notrailers" },
3697 #endif
3698 #endif
3699 #ifdef IFF_ALLMULTI
3700 { IFF_ALLMULTI, "allmulti" },
3701 #endif
3702 #ifdef IFF_MASTER
3703 { IFF_MASTER, "master" },
3704 #endif
3705 #ifdef IFF_SLAVE
3706 { IFF_SLAVE, "slave" },
3707 #endif
3708 #ifdef IFF_MULTICAST
3709 { IFF_MULTICAST, "multicast" },
3710 #endif
3711 #ifdef IFF_PORTSEL
3712 { IFF_PORTSEL, "portsel" },
3713 #endif
3714 #ifdef IFF_AUTOMEDIA
3715 { IFF_AUTOMEDIA, "automedia" },
3716 #endif
3717 #ifdef IFF_DYNAMIC
3718 { IFF_DYNAMIC, "dynamic" },
3719 #endif
3720 #ifdef IFF_OACTIVE
3721 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
3722 #endif
3723 #ifdef IFF_SIMPLEX
3724 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
3725 #endif
3726 #ifdef IFF_LINK0
3727 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
3728 #endif
3729 #ifdef IFF_LINK1
3730 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
3731 #endif
3732 #ifdef IFF_LINK2
3733 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
3734 #endif
3735 { 0, 0 }
3738 static Lisp_Object
3739 network_interface_info (Lisp_Object ifname)
3741 struct ifreq rq;
3742 Lisp_Object res = Qnil;
3743 Lisp_Object elt;
3744 int s;
3745 bool any = 0;
3746 ptrdiff_t count;
3747 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3748 && defined HAVE_GETIFADDRS && defined LLADDR)
3749 struct ifaddrs *ifap;
3750 #endif
3752 CHECK_STRING (ifname);
3754 if (sizeof rq.ifr_name <= SBYTES (ifname))
3755 error ("interface name too long");
3756 lispstpcpy (rq.ifr_name, ifname);
3758 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3759 if (s < 0)
3760 return Qnil;
3761 count = SPECPDL_INDEX ();
3762 record_unwind_protect_int (close_file_unwind, s);
3764 elt = Qnil;
3765 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3766 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3768 int flags = rq.ifr_flags;
3769 const struct ifflag_def *fp;
3770 int fnum;
3772 /* If flags is smaller than int (i.e. short) it may have the high bit set
3773 due to IFF_MULTICAST. In that case, sign extending it into
3774 an int is wrong. */
3775 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3776 flags = (unsigned short) rq.ifr_flags;
3778 any = 1;
3779 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3781 if (flags & fp->flag_bit)
3783 elt = Fcons (intern (fp->flag_sym), elt);
3784 flags -= fp->flag_bit;
3787 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3789 if (flags & 1)
3791 elt = Fcons (make_number (fnum), elt);
3795 #endif
3796 res = Fcons (elt, res);
3798 elt = Qnil;
3799 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3800 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3802 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3803 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3804 int n;
3806 any = 1;
3807 for (n = 0; n < 6; n++)
3808 p->contents[n] = make_number (((unsigned char *)
3809 &rq.ifr_hwaddr.sa_data[0])
3810 [n]);
3811 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3813 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3814 if (getifaddrs (&ifap) != -1)
3816 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3817 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3818 struct ifaddrs *it;
3820 for (it = ifap; it != NULL; it = it->ifa_next)
3822 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3823 unsigned char linkaddr[6];
3824 int n;
3826 if (it->ifa_addr->sa_family != AF_LINK
3827 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3828 || sdl->sdl_alen != 6)
3829 continue;
3831 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3832 for (n = 0; n < 6; n++)
3833 p->contents[n] = make_number (linkaddr[n]);
3835 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
3836 break;
3839 #ifdef HAVE_FREEIFADDRS
3840 freeifaddrs (ifap);
3841 #endif
3843 #endif /* HAVE_GETIFADDRS && LLADDR */
3845 res = Fcons (elt, res);
3847 elt = Qnil;
3848 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3849 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3851 any = 1;
3852 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3853 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3854 #else
3855 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3856 #endif
3858 #endif
3859 res = Fcons (elt, res);
3861 elt = Qnil;
3862 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3863 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3865 any = 1;
3866 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3868 #endif
3869 res = Fcons (elt, res);
3871 elt = Qnil;
3872 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3873 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3875 any = 1;
3876 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3878 #endif
3879 res = Fcons (elt, res);
3881 return unbind_to (count, any ? res : Qnil);
3883 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
3884 #endif /* defined (HAVE_NET_IF_H) */
3886 DEFUN ("network-interface-list", Fnetwork_interface_list,
3887 Snetwork_interface_list, 0, 0, 0,
3888 doc: /* Return an alist of all network interfaces and their network address.
3889 Each element is a cons, the car of which is a string containing the
3890 interface name, and the cdr is the network address in internal
3891 format; see the description of ADDRESS in `make-network-process'.
3893 If the information is not available, return nil. */)
3894 (void)
3896 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
3897 return network_interface_list ();
3898 #else
3899 return Qnil;
3900 #endif
3903 DEFUN ("network-interface-info", Fnetwork_interface_info,
3904 Snetwork_interface_info, 1, 1, 0,
3905 doc: /* Return information about network interface named IFNAME.
3906 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3907 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3908 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3909 FLAGS is the current flags of the interface.
3911 Data that is unavailable is returned as nil. */)
3912 (Lisp_Object ifname)
3914 #if ((defined HAVE_NET_IF_H \
3915 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
3916 || defined SIOCGIFFLAGS)) \
3917 || defined WINDOWSNT)
3918 return network_interface_info (ifname);
3919 #else
3920 return Qnil;
3921 #endif
3924 /* If program file NAME starts with /: for quoting a magic
3925 name, remove that, preserving the multibyteness of NAME. */
3927 Lisp_Object
3928 remove_slash_colon (Lisp_Object name)
3930 return
3931 ((SBYTES (name) > 2 && SREF (name, 0) == '/' && SREF (name, 1) == ':')
3932 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
3933 SBYTES (name) - 2, STRING_MULTIBYTE (name))
3934 : name);
3937 /* Turn off input and output for process PROC. */
3939 static void
3940 deactivate_process (Lisp_Object proc)
3942 int inchannel;
3943 struct Lisp_Process *p = XPROCESS (proc);
3944 int i;
3946 #ifdef HAVE_GNUTLS
3947 /* Delete GnuTLS structures in PROC, if any. */
3948 emacs_gnutls_deinit (proc);
3949 #endif /* HAVE_GNUTLS */
3951 #ifdef ADAPTIVE_READ_BUFFERING
3952 if (p->read_output_delay > 0)
3954 if (--process_output_delay_count < 0)
3955 process_output_delay_count = 0;
3956 p->read_output_delay = 0;
3957 p->read_output_skip = 0;
3959 #endif
3961 /* Beware SIGCHLD hereabouts. */
3963 for (i = 0; i < PROCESS_OPEN_FDS; i++)
3964 close_process_fd (&p->open_fd[i]);
3966 inchannel = p->infd;
3967 if (inchannel >= 0)
3969 p->infd = -1;
3970 p->outfd = -1;
3971 #ifdef DATAGRAM_SOCKETS
3972 if (DATAGRAM_CHAN_P (inchannel))
3974 xfree (datagram_address[inchannel].sa);
3975 datagram_address[inchannel].sa = 0;
3976 datagram_address[inchannel].len = 0;
3978 #endif
3979 chan_process[inchannel] = Qnil;
3980 FD_CLR (inchannel, &input_wait_mask);
3981 FD_CLR (inchannel, &non_keyboard_wait_mask);
3982 #ifdef NON_BLOCKING_CONNECT
3983 if (FD_ISSET (inchannel, &connect_wait_mask))
3985 FD_CLR (inchannel, &connect_wait_mask);
3986 FD_CLR (inchannel, &write_mask);
3987 if (--num_pending_connects < 0)
3988 emacs_abort ();
3990 #endif
3991 if (inchannel == max_process_desc)
3993 /* We just closed the highest-numbered process input descriptor,
3994 so recompute the highest-numbered one now. */
3995 int i = inchannel;
3997 i--;
3998 while (0 <= i && NILP (chan_process[i]));
4000 max_process_desc = i;
4006 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4007 0, 4, 0,
4008 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4009 It is given to their filter functions.
4010 Optional argument PROCESS means do not return until output has been
4011 received from PROCESS.
4013 Optional second argument SECONDS and third argument MILLISEC
4014 specify a timeout; return after that much time even if there is
4015 no subprocess output. If SECONDS is a floating point number,
4016 it specifies a fractional number of seconds to wait.
4017 The MILLISEC argument is obsolete and should be avoided.
4019 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4020 from PROCESS only, suspending reading output from other processes.
4021 If JUST-THIS-ONE is an integer, don't run any timers either.
4022 Return non-nil if we received any output from PROCESS (or, if PROCESS
4023 is nil, from any process) before the timeout expired. */)
4024 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4026 intmax_t secs;
4027 int nsecs;
4029 if (! NILP (process))
4030 CHECK_PROCESS (process);
4031 else
4032 just_this_one = Qnil;
4034 if (!NILP (millisec))
4035 { /* Obsolete calling convention using integers rather than floats. */
4036 CHECK_NUMBER (millisec);
4037 if (NILP (seconds))
4038 seconds = make_float (XINT (millisec) / 1000.0);
4039 else
4041 CHECK_NUMBER (seconds);
4042 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4046 secs = 0;
4047 nsecs = -1;
4049 if (!NILP (seconds))
4051 if (INTEGERP (seconds))
4053 if (XINT (seconds) > 0)
4055 secs = XINT (seconds);
4056 nsecs = 0;
4059 else if (FLOATP (seconds))
4061 if (XFLOAT_DATA (seconds) > 0)
4063 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4064 secs = min (t.tv_sec, WAIT_READING_MAX);
4065 nsecs = t.tv_nsec;
4068 else
4069 wrong_type_argument (Qnumberp, seconds);
4071 else if (! NILP (process))
4072 nsecs = 0;
4074 return
4075 ((wait_reading_process_output (secs, nsecs, 0, 0,
4076 Qnil,
4077 !NILP (process) ? XPROCESS (process) : NULL,
4078 (NILP (just_this_one) ? 0
4079 : !INTEGERP (just_this_one) ? 1 : -1))
4080 <= 0)
4081 ? Qnil : Qt);
4084 /* Accept a connection for server process SERVER on CHANNEL. */
4086 static EMACS_INT connect_counter = 0;
4088 static void
4089 server_accept_connection (Lisp_Object server, int channel)
4091 Lisp_Object proc, caller, name, buffer;
4092 Lisp_Object contact, host, service;
4093 struct Lisp_Process *ps = XPROCESS (server);
4094 struct Lisp_Process *p;
4095 int s;
4096 union u_sockaddr {
4097 struct sockaddr sa;
4098 struct sockaddr_in in;
4099 #ifdef AF_INET6
4100 struct sockaddr_in6 in6;
4101 #endif
4102 #ifdef HAVE_LOCAL_SOCKETS
4103 struct sockaddr_un un;
4104 #endif
4105 } saddr;
4106 socklen_t len = sizeof saddr;
4107 ptrdiff_t count;
4109 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4111 if (s < 0)
4113 int code = errno;
4115 if (code == EAGAIN)
4116 return;
4117 #ifdef EWOULDBLOCK
4118 if (code == EWOULDBLOCK)
4119 return;
4120 #endif
4122 if (!NILP (ps->log))
4123 call3 (ps->log, server, Qnil,
4124 concat3 (build_string ("accept failed with code"),
4125 Fnumber_to_string (make_number (code)),
4126 build_string ("\n")));
4127 return;
4130 count = SPECPDL_INDEX ();
4131 record_unwind_protect_int (close_file_unwind, s);
4133 connect_counter++;
4135 /* Setup a new process to handle the connection. */
4137 /* Generate a unique identification of the caller, and build contact
4138 information for this process. */
4139 host = Qt;
4140 service = Qnil;
4141 switch (saddr.sa.sa_family)
4143 case AF_INET:
4145 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4147 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4148 host = CALLN (Fformat, ipv4_format,
4149 make_number (ip[0]), make_number (ip[1]),
4150 make_number (ip[2]), make_number (ip[3]));
4151 service = make_number (ntohs (saddr.in.sin_port));
4152 AUTO_STRING (caller_format, " <%s:%d>");
4153 caller = CALLN (Fformat, caller_format, host, service);
4155 break;
4157 #ifdef AF_INET6
4158 case AF_INET6:
4160 Lisp_Object args[9];
4161 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4162 int i;
4164 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4165 args[0] = ipv6_format;
4166 for (i = 0; i < 8; i++)
4167 args[i + 1] = make_number (ntohs (ip6[i]));
4168 host = CALLMANY (Fformat, args);
4169 service = make_number (ntohs (saddr.in.sin_port));
4170 AUTO_STRING (caller_format, " <[%s]:%d>");
4171 caller = CALLN (Fformat, caller_format, host, service);
4173 break;
4174 #endif
4176 #ifdef HAVE_LOCAL_SOCKETS
4177 case AF_LOCAL:
4178 #endif
4179 default:
4180 caller = Fnumber_to_string (make_number (connect_counter));
4181 AUTO_STRING (space_less_than, " <");
4182 AUTO_STRING (greater_than, ">");
4183 caller = concat3 (space_less_than, caller, greater_than);
4184 break;
4187 /* Create a new buffer name for this process if it doesn't have a
4188 filter. The new buffer name is based on the buffer name or
4189 process name of the server process concatenated with the caller
4190 identification. */
4192 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4193 || EQ (ps->filter, Qt)))
4194 buffer = Qnil;
4195 else
4197 buffer = ps->buffer;
4198 if (!NILP (buffer))
4199 buffer = Fbuffer_name (buffer);
4200 else
4201 buffer = ps->name;
4202 if (!NILP (buffer))
4204 buffer = concat2 (buffer, caller);
4205 buffer = Fget_buffer_create (buffer);
4209 /* Generate a unique name for the new server process. Combine the
4210 server process name with the caller identification. */
4212 name = concat2 (ps->name, caller);
4213 proc = make_process (name);
4215 chan_process[s] = proc;
4217 fcntl (s, F_SETFL, O_NONBLOCK);
4219 p = XPROCESS (proc);
4221 /* Build new contact information for this setup. */
4222 contact = Fcopy_sequence (ps->childp);
4223 contact = Fplist_put (contact, QCserver, Qnil);
4224 contact = Fplist_put (contact, QChost, host);
4225 if (!NILP (service))
4226 contact = Fplist_put (contact, QCservice, service);
4227 contact = Fplist_put (contact, QCremote,
4228 conv_sockaddr_to_lisp (&saddr.sa, len));
4229 #ifdef HAVE_GETSOCKNAME
4230 len = sizeof saddr;
4231 if (getsockname (s, &saddr.sa, &len) == 0)
4232 contact = Fplist_put (contact, QClocal,
4233 conv_sockaddr_to_lisp (&saddr.sa, len));
4234 #endif
4236 pset_childp (p, contact);
4237 pset_plist (p, Fcopy_sequence (ps->plist));
4238 pset_type (p, Qnetwork);
4240 pset_buffer (p, buffer);
4241 pset_sentinel (p, ps->sentinel);
4242 pset_filter (p, ps->filter);
4243 pset_command (p, Qnil);
4244 p->pid = 0;
4246 /* Discard the unwind protect for closing S. */
4247 specpdl_ptr = specpdl + count;
4249 p->open_fd[SUBPROCESS_STDIN] = s;
4250 p->infd = s;
4251 p->outfd = s;
4252 pset_status (p, Qrun);
4254 /* Client processes for accepted connections are not stopped initially. */
4255 if (!EQ (p->filter, Qt))
4257 FD_SET (s, &input_wait_mask);
4258 FD_SET (s, &non_keyboard_wait_mask);
4261 if (s > max_process_desc)
4262 max_process_desc = s;
4264 /* Setup coding system for new process based on server process.
4265 This seems to be the proper thing to do, as the coding system
4266 of the new process should reflect the settings at the time the
4267 server socket was opened; not the current settings. */
4269 pset_decode_coding_system (p, ps->decode_coding_system);
4270 pset_encode_coding_system (p, ps->encode_coding_system);
4271 setup_process_coding_systems (proc);
4273 pset_decoding_buf (p, empty_unibyte_string);
4274 p->decoding_carryover = 0;
4275 pset_encoding_buf (p, empty_unibyte_string);
4277 p->inherit_coding_system_flag
4278 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4280 AUTO_STRING (dash, "-");
4281 AUTO_STRING (nl, "\n");
4282 Lisp_Object host_string = STRINGP (host) ? host : dash;
4284 if (!NILP (ps->log))
4286 AUTO_STRING (accept_from, "accept from ");
4287 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4290 AUTO_STRING (open_from, "open from ");
4291 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4294 /* This variable is different from waiting_for_input in keyboard.c.
4295 It is used to communicate to a lisp process-filter/sentinel (via the
4296 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4297 for user-input when that process-filter was called.
4298 waiting_for_input cannot be used as that is by definition 0 when
4299 lisp code is being evalled.
4300 This is also used in record_asynch_buffer_change.
4301 For that purpose, this must be 0
4302 when not inside wait_reading_process_output. */
4303 static int waiting_for_user_input_p;
4305 static void
4306 wait_reading_process_output_unwind (int data)
4308 waiting_for_user_input_p = data;
4311 /* This is here so breakpoints can be put on it. */
4312 static void
4313 wait_reading_process_output_1 (void)
4317 /* Read and dispose of subprocess output while waiting for timeout to
4318 elapse and/or keyboard input to be available.
4320 TIME_LIMIT is:
4321 timeout in seconds
4322 If negative, gobble data immediately available but don't wait for any.
4324 NSECS is:
4325 an additional duration to wait, measured in nanoseconds
4326 If TIME_LIMIT is zero, then:
4327 If NSECS == 0, there is no limit.
4328 If NSECS > 0, the timeout consists of NSECS only.
4329 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4331 READ_KBD is:
4332 0 to ignore keyboard input, or
4333 1 to return when input is available, or
4334 -1 meaning caller will actually read the input, so don't throw to
4335 the quit handler, or
4337 DO_DISPLAY means redisplay should be done to show subprocess
4338 output that arrives.
4340 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4341 (and gobble terminal input into the buffer if any arrives).
4343 If WAIT_PROC is specified, wait until something arrives from that
4344 process.
4346 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4347 (suspending output from other processes). A negative value
4348 means don't run any timers either.
4350 Return positive if we received input from WAIT_PROC (or from any
4351 process if WAIT_PROC is null), zero if we attempted to receive
4352 input but got none, and negative if we didn't even try. */
4355 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4356 bool do_display,
4357 Lisp_Object wait_for_cell,
4358 struct Lisp_Process *wait_proc, int just_wait_proc)
4360 int channel, nfds;
4361 fd_set Available;
4362 fd_set Writeok;
4363 bool check_write;
4364 int check_delay;
4365 bool no_avail;
4366 int xerrno;
4367 Lisp_Object proc;
4368 struct timespec timeout, end_time;
4369 int got_some_input = -1;
4370 ptrdiff_t count = SPECPDL_INDEX ();
4372 FD_ZERO (&Available);
4373 FD_ZERO (&Writeok);
4375 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4376 && !(CONSP (wait_proc->status)
4377 && EQ (XCAR (wait_proc->status), Qexit)))
4378 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4380 record_unwind_protect_int (wait_reading_process_output_unwind,
4381 waiting_for_user_input_p);
4382 waiting_for_user_input_p = read_kbd;
4384 if (time_limit < 0)
4386 time_limit = 0;
4387 nsecs = -1;
4389 else if (TYPE_MAXIMUM (time_t) < time_limit)
4390 time_limit = TYPE_MAXIMUM (time_t);
4392 /* Since we may need to wait several times,
4393 compute the absolute time to return at. */
4394 if (time_limit || nsecs > 0)
4396 timeout = make_timespec (time_limit, nsecs);
4397 end_time = timespec_add (current_timespec (), timeout);
4400 while (1)
4402 bool timeout_reduced_for_timers = false;
4404 /* If calling from keyboard input, do not quit
4405 since we want to return C-g as an input character.
4406 Otherwise, do pending quit if requested. */
4407 if (read_kbd >= 0)
4408 QUIT;
4409 else if (pending_signals)
4410 process_pending_signals ();
4412 /* Exit now if the cell we're waiting for became non-nil. */
4413 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4414 break;
4416 /* After reading input, vacuum up any leftovers without waiting. */
4417 if (0 <= got_some_input)
4418 nsecs = -1;
4420 /* Compute time from now till when time limit is up. */
4421 /* Exit if already run out. */
4422 if (nsecs < 0)
4424 /* A negative timeout means
4425 gobble output available now
4426 but don't wait at all. */
4428 timeout = make_timespec (0, 0);
4430 else if (time_limit || nsecs > 0)
4432 struct timespec now = current_timespec ();
4433 if (timespec_cmp (end_time, now) <= 0)
4434 break;
4435 timeout = timespec_sub (end_time, now);
4437 else
4439 timeout = make_timespec (100000, 0);
4442 /* Normally we run timers here.
4443 But not if wait_for_cell; in those cases,
4444 the wait is supposed to be short,
4445 and those callers cannot handle running arbitrary Lisp code here. */
4446 if (NILP (wait_for_cell)
4447 && just_wait_proc >= 0)
4449 struct timespec timer_delay;
4453 unsigned old_timers_run = timers_run;
4454 struct buffer *old_buffer = current_buffer;
4455 Lisp_Object old_window = selected_window;
4457 timer_delay = timer_check ();
4459 /* If a timer has run, this might have changed buffers
4460 an alike. Make read_key_sequence aware of that. */
4461 if (timers_run != old_timers_run
4462 && (old_buffer != current_buffer
4463 || !EQ (old_window, selected_window))
4464 && waiting_for_user_input_p == -1)
4465 record_asynch_buffer_change ();
4467 if (timers_run != old_timers_run && do_display)
4468 /* We must retry, since a timer may have requeued itself
4469 and that could alter the time_delay. */
4470 redisplay_preserve_echo_area (9);
4471 else
4472 break;
4474 while (!detect_input_pending ());
4476 /* If there is unread keyboard input, also return. */
4477 if (read_kbd != 0
4478 && requeued_events_pending_p ())
4479 break;
4481 /* A negative timeout means do not wait at all. */
4482 if (nsecs >= 0)
4484 if (timespec_valid_p (timer_delay))
4486 if (timespec_cmp (timer_delay, timeout) < 0)
4488 timeout = timer_delay;
4489 timeout_reduced_for_timers = true;
4492 else
4494 /* This is so a breakpoint can be put here. */
4495 wait_reading_process_output_1 ();
4500 /* Cause C-g and alarm signals to take immediate action,
4501 and cause input available signals to zero out timeout.
4503 It is important that we do this before checking for process
4504 activity. If we get a SIGCHLD after the explicit checks for
4505 process activity, timeout is the only way we will know. */
4506 if (read_kbd < 0)
4507 set_waiting_for_input (&timeout);
4509 /* If status of something has changed, and no input is
4510 available, notify the user of the change right away. After
4511 this explicit check, we'll let the SIGCHLD handler zap
4512 timeout to get our attention. */
4513 if (update_tick != process_tick)
4515 fd_set Atemp;
4516 fd_set Ctemp;
4518 if (kbd_on_hold_p ())
4519 FD_ZERO (&Atemp);
4520 else
4521 Atemp = input_wait_mask;
4522 Ctemp = write_mask;
4524 timeout = make_timespec (0, 0);
4525 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4526 &Atemp,
4527 #ifdef NON_BLOCKING_CONNECT
4528 (num_pending_connects > 0 ? &Ctemp : NULL),
4529 #else
4530 NULL,
4531 #endif
4532 NULL, &timeout, NULL)
4533 <= 0))
4535 /* It's okay for us to do this and then continue with
4536 the loop, since timeout has already been zeroed out. */
4537 clear_waiting_for_input ();
4538 got_some_input = status_notify (NULL, wait_proc);
4539 if (do_display) redisplay_preserve_echo_area (13);
4543 /* Don't wait for output from a non-running process. Just
4544 read whatever data has already been received. */
4545 if (wait_proc && wait_proc->raw_status_new)
4546 update_status (wait_proc);
4547 if (wait_proc
4548 && wait_proc->infd >= 0
4549 && ! EQ (wait_proc->status, Qrun)
4550 && ! EQ (wait_proc->status, Qconnect))
4552 bool read_some_bytes = false;
4554 clear_waiting_for_input ();
4555 XSETPROCESS (proc, wait_proc);
4557 /* Read data from the process, until we exhaust it. */
4558 while (true)
4560 int nread = read_process_output (proc, wait_proc->infd);
4561 if (nread < 0)
4563 if (errno == EIO || errno == EAGAIN)
4564 break;
4565 #ifdef EWOULDBLOCK
4566 if (errno == EWOULDBLOCK)
4567 break;
4568 #endif
4570 else
4572 if (got_some_input < nread)
4573 got_some_input = nread;
4574 if (nread == 0)
4575 break;
4576 read_some_bytes = true;
4579 if (read_some_bytes && do_display)
4580 redisplay_preserve_echo_area (10);
4582 break;
4585 /* Wait till there is something to do. */
4587 if (wait_proc && just_wait_proc)
4589 if (wait_proc->infd < 0) /* Terminated. */
4590 break;
4591 FD_SET (wait_proc->infd, &Available);
4592 check_delay = 0;
4593 check_write = 0;
4595 else if (!NILP (wait_for_cell))
4597 Available = non_process_wait_mask;
4598 check_delay = 0;
4599 check_write = 0;
4601 else
4603 if (! read_kbd)
4604 Available = non_keyboard_wait_mask;
4605 else
4606 Available = input_wait_mask;
4607 Writeok = write_mask;
4608 check_delay = wait_proc ? 0 : process_output_delay_count;
4609 check_write = SELECT_CAN_DO_WRITE_MASK;
4612 /* If frame size has changed or the window is newly mapped,
4613 redisplay now, before we start to wait. There is a race
4614 condition here; if a SIGIO arrives between now and the select
4615 and indicates that a frame is trashed, the select may block
4616 displaying a trashed screen. */
4617 if (frame_garbaged && do_display)
4619 clear_waiting_for_input ();
4620 redisplay_preserve_echo_area (11);
4621 if (read_kbd < 0)
4622 set_waiting_for_input (&timeout);
4625 /* Skip the `select' call if input is available and we're
4626 waiting for keyboard input or a cell change (which can be
4627 triggered by processing X events). In the latter case, set
4628 nfds to 1 to avoid breaking the loop. */
4629 no_avail = 0;
4630 if ((read_kbd || !NILP (wait_for_cell))
4631 && detect_input_pending ())
4633 nfds = read_kbd ? 0 : 1;
4634 no_avail = 1;
4635 FD_ZERO (&Available);
4638 if (!no_avail)
4641 #ifdef ADAPTIVE_READ_BUFFERING
4642 /* Set the timeout for adaptive read buffering if any
4643 process has non-zero read_output_skip and non-zero
4644 read_output_delay, and we are not reading output for a
4645 specific process. It is not executed if
4646 Vprocess_adaptive_read_buffering is nil. */
4647 if (process_output_skip && check_delay > 0)
4649 int nsecs = timeout.tv_nsec;
4650 if (timeout.tv_sec > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4651 nsecs = READ_OUTPUT_DELAY_MAX;
4652 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4654 proc = chan_process[channel];
4655 if (NILP (proc))
4656 continue;
4657 /* Find minimum non-zero read_output_delay among the
4658 processes with non-zero read_output_skip. */
4659 if (XPROCESS (proc)->read_output_delay > 0)
4661 check_delay--;
4662 if (!XPROCESS (proc)->read_output_skip)
4663 continue;
4664 FD_CLR (channel, &Available);
4665 XPROCESS (proc)->read_output_skip = 0;
4666 if (XPROCESS (proc)->read_output_delay < nsecs)
4667 nsecs = XPROCESS (proc)->read_output_delay;
4670 timeout = make_timespec (0, nsecs);
4671 process_output_skip = 0;
4673 #endif
4675 #if defined (HAVE_NS)
4676 nfds = ns_select
4677 #elif defined (HAVE_GLIB)
4678 nfds = xg_select
4679 #else
4680 nfds = pselect
4681 #endif
4682 (max (max_process_desc, max_input_desc) + 1,
4683 &Available,
4684 (check_write ? &Writeok : 0),
4685 NULL, &timeout, NULL);
4687 #ifdef HAVE_GNUTLS
4688 /* GnuTLS buffers data internally. In lowat mode it leaves
4689 some data in the TCP buffers so that select works, but
4690 with custom pull/push functions we need to check if some
4691 data is available in the buffers manually. */
4692 if (nfds == 0)
4694 if (! wait_proc)
4696 /* We're not waiting on a specific process, so loop
4697 through all the channels and check for data.
4698 This is a workaround needed for some versions of
4699 the gnutls library -- 2.12.14 has been confirmed
4700 to need it. See
4701 http://comments.gmane.org/gmane.emacs.devel/145074 */
4702 for (channel = 0; channel < FD_SETSIZE; ++channel)
4703 if (! NILP (chan_process[channel]))
4705 struct Lisp_Process *p =
4706 XPROCESS (chan_process[channel]);
4707 if (p && p->gnutls_p && p->gnutls_state
4708 && ((emacs_gnutls_record_check_pending
4709 (p->gnutls_state))
4710 > 0))
4712 nfds++;
4713 eassert (p->infd == channel);
4714 FD_SET (p->infd, &Available);
4718 else
4720 /* Check this specific channel. */
4721 if (wait_proc->gnutls_p /* Check for valid process. */
4722 && wait_proc->gnutls_state
4723 /* Do we have pending data? */
4724 && ((emacs_gnutls_record_check_pending
4725 (wait_proc->gnutls_state))
4726 > 0))
4728 nfds = 1;
4729 eassert (0 <= wait_proc->infd);
4730 /* Set to Available. */
4731 FD_SET (wait_proc->infd, &Available);
4735 #endif
4738 xerrno = errno;
4740 /* Make C-g and alarm signals set flags again. */
4741 clear_waiting_for_input ();
4743 /* If we woke up due to SIGWINCH, actually change size now. */
4744 do_pending_window_change (0);
4746 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4747 /* We waited the full specified time, so return now. */
4748 break;
4749 if (nfds < 0)
4751 if (xerrno == EINTR)
4752 no_avail = 1;
4753 else if (xerrno == EBADF)
4754 emacs_abort ();
4755 else
4756 report_file_errno ("Failed select", Qnil, xerrno);
4759 /* Check for keyboard input. */
4760 /* If there is any, return immediately
4761 to give it higher priority than subprocesses. */
4763 if (read_kbd != 0)
4765 unsigned old_timers_run = timers_run;
4766 struct buffer *old_buffer = current_buffer;
4767 Lisp_Object old_window = selected_window;
4768 bool leave = false;
4770 if (detect_input_pending_run_timers (do_display))
4772 swallow_events (do_display);
4773 if (detect_input_pending_run_timers (do_display))
4774 leave = true;
4777 /* If a timer has run, this might have changed buffers
4778 an alike. Make read_key_sequence aware of that. */
4779 if (timers_run != old_timers_run
4780 && waiting_for_user_input_p == -1
4781 && (old_buffer != current_buffer
4782 || !EQ (old_window, selected_window)))
4783 record_asynch_buffer_change ();
4785 if (leave)
4786 break;
4789 /* If there is unread keyboard input, also return. */
4790 if (read_kbd != 0
4791 && requeued_events_pending_p ())
4792 break;
4794 /* If we are not checking for keyboard input now,
4795 do process events (but don't run any timers).
4796 This is so that X events will be processed.
4797 Otherwise they may have to wait until polling takes place.
4798 That would causes delays in pasting selections, for example.
4800 (We used to do this only if wait_for_cell.) */
4801 if (read_kbd == 0 && detect_input_pending ())
4803 swallow_events (do_display);
4804 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4805 if (detect_input_pending ())
4806 break;
4807 #endif
4810 /* Exit now if the cell we're waiting for became non-nil. */
4811 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4812 break;
4814 #ifdef USABLE_SIGIO
4815 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4816 go read it. This can happen with X on BSD after logging out.
4817 In that case, there really is no input and no SIGIO,
4818 but select says there is input. */
4820 if (read_kbd && interrupt_input
4821 && keyboard_bit_set (&Available) && ! noninteractive)
4822 handle_input_available_signal (SIGIO);
4823 #endif
4825 /* If checking input just got us a size-change event from X,
4826 obey it now if we should. */
4827 if (read_kbd || ! NILP (wait_for_cell))
4828 do_pending_window_change (0);
4830 /* Check for data from a process. */
4831 if (no_avail || nfds == 0)
4832 continue;
4834 for (channel = 0; channel <= max_input_desc; ++channel)
4836 struct fd_callback_data *d = &fd_callback_info[channel];
4837 if (d->func
4838 && ((d->condition & FOR_READ
4839 && FD_ISSET (channel, &Available))
4840 || (d->condition & FOR_WRITE
4841 && FD_ISSET (channel, &write_mask))))
4842 d->func (channel, d->data);
4845 for (channel = 0; channel <= max_process_desc; channel++)
4847 if (FD_ISSET (channel, &Available)
4848 && FD_ISSET (channel, &non_keyboard_wait_mask)
4849 && !FD_ISSET (channel, &non_process_wait_mask))
4851 int nread;
4853 /* If waiting for this channel, arrange to return as
4854 soon as no more input to be processed. No more
4855 waiting. */
4856 proc = chan_process[channel];
4857 if (NILP (proc))
4858 continue;
4860 /* If this is a server stream socket, accept connection. */
4861 if (EQ (XPROCESS (proc)->status, Qlisten))
4863 server_accept_connection (proc, channel);
4864 continue;
4867 /* Read data from the process, starting with our
4868 buffered-ahead character if we have one. */
4870 nread = read_process_output (proc, channel);
4871 if ((!wait_proc || wait_proc == XPROCESS (proc)) && got_some_input < nread)
4872 got_some_input = nread;
4873 if (nread > 0)
4875 /* Since read_process_output can run a filter,
4876 which can call accept-process-output,
4877 don't try to read from any other processes
4878 before doing the select again. */
4879 FD_ZERO (&Available);
4881 if (do_display)
4882 redisplay_preserve_echo_area (12);
4884 #ifdef EWOULDBLOCK
4885 else if (nread == -1 && errno == EWOULDBLOCK)
4887 #endif
4888 else if (nread == -1 && errno == EAGAIN)
4890 #ifdef WINDOWSNT
4891 /* FIXME: Is this special case still needed? */
4892 /* Note that we cannot distinguish between no input
4893 available now and a closed pipe.
4894 With luck, a closed pipe will be accompanied by
4895 subprocess termination and SIGCHLD. */
4896 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4898 #endif
4899 #ifdef HAVE_PTYS
4900 /* On some OSs with ptys, when the process on one end of
4901 a pty exits, the other end gets an error reading with
4902 errno = EIO instead of getting an EOF (0 bytes read).
4903 Therefore, if we get an error reading and errno =
4904 EIO, just continue, because the child process has
4905 exited and should clean itself up soon (e.g. when we
4906 get a SIGCHLD). */
4907 else if (nread == -1 && errno == EIO)
4909 struct Lisp_Process *p = XPROCESS (proc);
4911 /* Clear the descriptor now, so we only raise the
4912 signal once. */
4913 FD_CLR (channel, &input_wait_mask);
4914 FD_CLR (channel, &non_keyboard_wait_mask);
4916 if (p->pid == -2)
4918 /* If the EIO occurs on a pty, the SIGCHLD handler's
4919 waitpid call will not find the process object to
4920 delete. Do it here. */
4921 p->tick = ++process_tick;
4922 pset_status (p, Qfailed);
4925 #endif /* HAVE_PTYS */
4926 /* If we can detect process termination, don't consider the
4927 process gone just because its pipe is closed. */
4928 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4930 else
4932 /* Preserve status of processes already terminated. */
4933 XPROCESS (proc)->tick = ++process_tick;
4934 deactivate_process (proc);
4935 if (XPROCESS (proc)->raw_status_new)
4936 update_status (XPROCESS (proc));
4937 if (EQ (XPROCESS (proc)->status, Qrun))
4938 pset_status (XPROCESS (proc),
4939 list2 (Qexit, make_number (256)));
4942 #ifdef NON_BLOCKING_CONNECT
4943 if (FD_ISSET (channel, &Writeok)
4944 && FD_ISSET (channel, &connect_wait_mask))
4946 struct Lisp_Process *p;
4948 FD_CLR (channel, &connect_wait_mask);
4949 FD_CLR (channel, &write_mask);
4950 if (--num_pending_connects < 0)
4951 emacs_abort ();
4953 proc = chan_process[channel];
4954 if (NILP (proc))
4955 continue;
4957 p = XPROCESS (proc);
4959 #ifdef GNU_LINUX
4960 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4961 So only use it on systems where it is known to work. */
4963 socklen_t xlen = sizeof (xerrno);
4964 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4965 xerrno = errno;
4967 #else
4969 struct sockaddr pname;
4970 socklen_t pnamelen = sizeof (pname);
4972 /* If connection failed, getpeername will fail. */
4973 xerrno = 0;
4974 if (getpeername (channel, &pname, &pnamelen) < 0)
4976 /* Obtain connect failure code through error slippage. */
4977 char dummy;
4978 xerrno = errno;
4979 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
4980 xerrno = errno;
4983 #endif
4984 if (xerrno)
4986 p->tick = ++process_tick;
4987 pset_status (p, list2 (Qfailed, make_number (xerrno)));
4988 deactivate_process (proc);
4990 else
4992 pset_status (p, Qrun);
4993 /* Execute the sentinel here. If we had relied on
4994 status_notify to do it later, it will read input
4995 from the process before calling the sentinel. */
4996 exec_sentinel (proc, build_string ("open\n"));
4997 if (0 <= p->infd && !EQ (p->filter, Qt)
4998 && !EQ (p->command, Qt))
5000 FD_SET (p->infd, &input_wait_mask);
5001 FD_SET (p->infd, &non_keyboard_wait_mask);
5005 #endif /* NON_BLOCKING_CONNECT */
5006 } /* End for each file descriptor. */
5007 } /* End while exit conditions not met. */
5009 unbind_to (count, Qnil);
5011 /* If calling from keyboard input, do not quit
5012 since we want to return C-g as an input character.
5013 Otherwise, do pending quit if requested. */
5014 if (read_kbd >= 0)
5016 /* Prevent input_pending from remaining set if we quit. */
5017 clear_input_pending ();
5018 QUIT;
5021 return got_some_input;
5024 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5026 static Lisp_Object
5027 read_process_output_call (Lisp_Object fun_and_args)
5029 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5032 static Lisp_Object
5033 read_process_output_error_handler (Lisp_Object error_val)
5035 cmd_error_internal (error_val, "error in process filter: ");
5036 Vinhibit_quit = Qt;
5037 update_echo_area ();
5038 Fsleep_for (make_number (2), Qnil);
5039 return Qt;
5042 static void
5043 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5044 ssize_t nbytes,
5045 struct coding_system *coding);
5047 /* Read pending output from the process channel,
5048 starting with our buffered-ahead character if we have one.
5049 Yield number of decoded characters read.
5051 This function reads at most 4096 characters.
5052 If you want to read all available subprocess output,
5053 you must call it repeatedly until it returns zero.
5055 The characters read are decoded according to PROC's coding-system
5056 for decoding. */
5058 static int
5059 read_process_output (Lisp_Object proc, int channel)
5061 ssize_t nbytes;
5062 struct Lisp_Process *p = XPROCESS (proc);
5063 struct coding_system *coding = proc_decode_coding_system[channel];
5064 int carryover = p->decoding_carryover;
5065 enum { readmax = 4096 };
5066 ptrdiff_t count = SPECPDL_INDEX ();
5067 Lisp_Object odeactivate;
5068 char chars[sizeof coding->carryover + readmax];
5070 if (carryover)
5071 /* See the comment above. */
5072 memcpy (chars, SDATA (p->decoding_buf), carryover);
5074 #ifdef DATAGRAM_SOCKETS
5075 /* We have a working select, so proc_buffered_char is always -1. */
5076 if (DATAGRAM_CHAN_P (channel))
5078 socklen_t len = datagram_address[channel].len;
5079 nbytes = recvfrom (channel, chars + carryover, readmax,
5080 0, datagram_address[channel].sa, &len);
5082 else
5083 #endif
5085 bool buffered = proc_buffered_char[channel] >= 0;
5086 if (buffered)
5088 chars[carryover] = proc_buffered_char[channel];
5089 proc_buffered_char[channel] = -1;
5091 #ifdef HAVE_GNUTLS
5092 if (p->gnutls_p && p->gnutls_state)
5093 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5094 readmax - buffered);
5095 else
5096 #endif
5097 nbytes = emacs_read (channel, chars + carryover + buffered,
5098 readmax - buffered);
5099 #ifdef ADAPTIVE_READ_BUFFERING
5100 if (nbytes > 0 && p->adaptive_read_buffering)
5102 int delay = p->read_output_delay;
5103 if (nbytes < 256)
5105 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5107 if (delay == 0)
5108 process_output_delay_count++;
5109 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5112 else if (delay > 0 && nbytes == readmax - buffered)
5114 delay -= READ_OUTPUT_DELAY_INCREMENT;
5115 if (delay == 0)
5116 process_output_delay_count--;
5118 p->read_output_delay = delay;
5119 if (delay)
5121 p->read_output_skip = 1;
5122 process_output_skip = 1;
5125 #endif
5126 nbytes += buffered;
5127 nbytes += buffered && nbytes <= 0;
5130 p->decoding_carryover = 0;
5132 /* At this point, NBYTES holds number of bytes just received
5133 (including the one in proc_buffered_char[channel]). */
5134 if (nbytes <= 0)
5136 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5137 return nbytes;
5138 coding->mode |= CODING_MODE_LAST_BLOCK;
5141 /* Now set NBYTES how many bytes we must decode. */
5142 nbytes += carryover;
5144 odeactivate = Vdeactivate_mark;
5145 /* There's no good reason to let process filters change the current
5146 buffer, and many callers of accept-process-output, sit-for, and
5147 friends don't expect current-buffer to be changed from under them. */
5148 record_unwind_current_buffer ();
5150 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5152 /* Handling the process output should not deactivate the mark. */
5153 Vdeactivate_mark = odeactivate;
5155 unbind_to (count, Qnil);
5156 return nbytes;
5159 static void
5160 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5161 ssize_t nbytes,
5162 struct coding_system *coding)
5164 Lisp_Object outstream = p->filter;
5165 Lisp_Object text;
5166 bool outer_running_asynch_code = running_asynch_code;
5167 int waiting = waiting_for_user_input_p;
5169 /* No need to gcpro these, because all we do with them later
5170 is test them for EQness, and none of them should be a string. */
5171 #if 0
5172 Lisp_Object obuffer, okeymap;
5173 XSETBUFFER (obuffer, current_buffer);
5174 okeymap = BVAR (current_buffer, keymap);
5175 #endif
5177 /* We inhibit quit here instead of just catching it so that
5178 hitting ^G when a filter happens to be running won't screw
5179 it up. */
5180 specbind (Qinhibit_quit, Qt);
5181 specbind (Qlast_nonmenu_event, Qt);
5183 /* In case we get recursively called,
5184 and we already saved the match data nonrecursively,
5185 save the same match data in safely recursive fashion. */
5186 if (outer_running_asynch_code)
5188 Lisp_Object tem;
5189 /* Don't clobber the CURRENT match data, either! */
5190 tem = Fmatch_data (Qnil, Qnil, Qnil);
5191 restore_search_regs ();
5192 record_unwind_save_match_data ();
5193 Fset_match_data (tem, Qt);
5196 /* For speed, if a search happens within this code,
5197 save the match data in a special nonrecursive fashion. */
5198 running_asynch_code = 1;
5200 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5201 text = coding->dst_object;
5202 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5203 /* A new coding system might be found. */
5204 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5206 pset_decode_coding_system (p, Vlast_coding_system_used);
5208 /* Don't call setup_coding_system for
5209 proc_decode_coding_system[channel] here. It is done in
5210 detect_coding called via decode_coding above. */
5212 /* If a coding system for encoding is not yet decided, we set
5213 it as the same as coding-system for decoding.
5215 But, before doing that we must check if
5216 proc_encode_coding_system[p->outfd] surely points to a
5217 valid memory because p->outfd will be changed once EOF is
5218 sent to the process. */
5219 if (NILP (p->encode_coding_system) && p->outfd >= 0
5220 && proc_encode_coding_system[p->outfd])
5222 pset_encode_coding_system
5223 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5224 setup_coding_system (p->encode_coding_system,
5225 proc_encode_coding_system[p->outfd]);
5229 if (coding->carryover_bytes > 0)
5231 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5232 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5233 memcpy (SDATA (p->decoding_buf), coding->carryover,
5234 coding->carryover_bytes);
5235 p->decoding_carryover = coding->carryover_bytes;
5237 if (SBYTES (text) > 0)
5238 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5239 sometimes it's simply wrong to wrap (e.g. when called from
5240 accept-process-output). */
5241 internal_condition_case_1 (read_process_output_call,
5242 list3 (outstream, make_lisp_proc (p), text),
5243 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5244 read_process_output_error_handler);
5246 /* If we saved the match data nonrecursively, restore it now. */
5247 restore_search_regs ();
5248 running_asynch_code = outer_running_asynch_code;
5250 /* Restore waiting_for_user_input_p as it was
5251 when we were called, in case the filter clobbered it. */
5252 waiting_for_user_input_p = waiting;
5254 #if 0 /* Call record_asynch_buffer_change unconditionally,
5255 because we might have changed minor modes or other things
5256 that affect key bindings. */
5257 if (! EQ (Fcurrent_buffer (), obuffer)
5258 || ! EQ (current_buffer->keymap, okeymap))
5259 #endif
5260 /* But do it only if the caller is actually going to read events.
5261 Otherwise there's no need to make him wake up, and it could
5262 cause trouble (for example it would make sit_for return). */
5263 if (waiting_for_user_input_p == -1)
5264 record_asynch_buffer_change ();
5267 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5268 Sinternal_default_process_filter, 2, 2, 0,
5269 doc: /* Function used as default process filter.
5270 This inserts the process's output into its buffer, if there is one.
5271 Otherwise it discards the output. */)
5272 (Lisp_Object proc, Lisp_Object text)
5274 struct Lisp_Process *p;
5275 ptrdiff_t opoint;
5277 CHECK_PROCESS (proc);
5278 p = XPROCESS (proc);
5279 CHECK_STRING (text);
5281 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5283 Lisp_Object old_read_only;
5284 ptrdiff_t old_begv, old_zv;
5285 ptrdiff_t old_begv_byte, old_zv_byte;
5286 ptrdiff_t before, before_byte;
5287 ptrdiff_t opoint_byte;
5288 struct buffer *b;
5290 Fset_buffer (p->buffer);
5291 opoint = PT;
5292 opoint_byte = PT_BYTE;
5293 old_read_only = BVAR (current_buffer, read_only);
5294 old_begv = BEGV;
5295 old_zv = ZV;
5296 old_begv_byte = BEGV_BYTE;
5297 old_zv_byte = ZV_BYTE;
5299 bset_read_only (current_buffer, Qnil);
5301 /* Insert new output into buffer at the current end-of-output
5302 marker, thus preserving logical ordering of input and output. */
5303 if (XMARKER (p->mark)->buffer)
5304 set_point_from_marker (p->mark);
5305 else
5306 SET_PT_BOTH (ZV, ZV_BYTE);
5307 before = PT;
5308 before_byte = PT_BYTE;
5310 /* If the output marker is outside of the visible region, save
5311 the restriction and widen. */
5312 if (! (BEGV <= PT && PT <= ZV))
5313 Fwiden ();
5315 /* Adjust the multibyteness of TEXT to that of the buffer. */
5316 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5317 != ! STRING_MULTIBYTE (text))
5318 text = (STRING_MULTIBYTE (text)
5319 ? Fstring_as_unibyte (text)
5320 : Fstring_to_multibyte (text));
5321 /* Insert before markers in case we are inserting where
5322 the buffer's mark is, and the user's next command is Meta-y. */
5323 insert_from_string_before_markers (text, 0, 0,
5324 SCHARS (text), SBYTES (text), 0);
5326 /* Make sure the process marker's position is valid when the
5327 process buffer is changed in the signal_after_change above.
5328 W3 is known to do that. */
5329 if (BUFFERP (p->buffer)
5330 && (b = XBUFFER (p->buffer), b != current_buffer))
5331 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5332 else
5333 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5335 update_mode_lines = 23;
5337 /* Make sure opoint and the old restrictions
5338 float ahead of any new text just as point would. */
5339 if (opoint >= before)
5341 opoint += PT - before;
5342 opoint_byte += PT_BYTE - before_byte;
5344 if (old_begv > before)
5346 old_begv += PT - before;
5347 old_begv_byte += PT_BYTE - before_byte;
5349 if (old_zv >= before)
5351 old_zv += PT - before;
5352 old_zv_byte += PT_BYTE - before_byte;
5355 /* If the restriction isn't what it should be, set it. */
5356 if (old_begv != BEGV || old_zv != ZV)
5357 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5359 bset_read_only (current_buffer, old_read_only);
5360 SET_PT_BOTH (opoint, opoint_byte);
5362 return Qnil;
5365 /* Sending data to subprocess. */
5367 /* In send_process, when a write fails temporarily,
5368 wait_reading_process_output is called. It may execute user code,
5369 e.g. timers, that attempts to write new data to the same process.
5370 We must ensure that data is sent in the right order, and not
5371 interspersed half-completed with other writes (Bug#10815). This is
5372 handled by the write_queue element of struct process. It is a list
5373 with each entry having the form
5375 (string . (offset . length))
5377 where STRING is a lisp string, OFFSET is the offset into the
5378 string's byte sequence from which we should begin to send, and
5379 LENGTH is the number of bytes left to send. */
5381 /* Create a new entry in write_queue.
5382 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5383 BUF is a pointer to the string sequence of the input_obj or a C
5384 string in case of Qt or Qnil. */
5386 static void
5387 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5388 const char *buf, ptrdiff_t len, bool front)
5390 ptrdiff_t offset;
5391 Lisp_Object entry, obj;
5393 if (STRINGP (input_obj))
5395 offset = buf - SSDATA (input_obj);
5396 obj = input_obj;
5398 else
5400 offset = 0;
5401 obj = make_unibyte_string (buf, len);
5404 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5406 if (front)
5407 pset_write_queue (p, Fcons (entry, p->write_queue));
5408 else
5409 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5412 /* Remove the first element in the write_queue of process P, put its
5413 contents in OBJ, BUF and LEN, and return true. If the
5414 write_queue is empty, return false. */
5416 static bool
5417 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5418 const char **buf, ptrdiff_t *len)
5420 Lisp_Object entry, offset_length;
5421 ptrdiff_t offset;
5423 if (NILP (p->write_queue))
5424 return 0;
5426 entry = XCAR (p->write_queue);
5427 pset_write_queue (p, XCDR (p->write_queue));
5429 *obj = XCAR (entry);
5430 offset_length = XCDR (entry);
5432 *len = XINT (XCDR (offset_length));
5433 offset = XINT (XCAR (offset_length));
5434 *buf = SSDATA (*obj) + offset;
5436 return 1;
5439 /* Send some data to process PROC.
5440 BUF is the beginning of the data; LEN is the number of characters.
5441 OBJECT is the Lisp object that the data comes from. If OBJECT is
5442 nil or t, it means that the data comes from C string.
5444 If OBJECT is not nil, the data is encoded by PROC's coding-system
5445 for encoding before it is sent.
5447 This function can evaluate Lisp code and can garbage collect. */
5449 static void
5450 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5451 Lisp_Object object)
5453 struct Lisp_Process *p = XPROCESS (proc);
5454 ssize_t rv;
5455 struct coding_system *coding;
5457 if (p->raw_status_new)
5458 update_status (p);
5459 if (! EQ (p->status, Qrun))
5460 error ("Process %s not running", SDATA (p->name));
5461 if (p->outfd < 0)
5462 error ("Output file descriptor of %s is closed", SDATA (p->name));
5464 coding = proc_encode_coding_system[p->outfd];
5465 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5467 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5468 || (BUFFERP (object)
5469 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5470 || EQ (object, Qt))
5472 pset_encode_coding_system
5473 (p, complement_process_encoding_system (p->encode_coding_system));
5474 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5476 /* The coding system for encoding was changed to raw-text
5477 because we sent a unibyte text previously. Now we are
5478 sending a multibyte text, thus we must encode it by the
5479 original coding system specified for the current process.
5481 Another reason we come here is that the coding system
5482 was just complemented and a new one was returned by
5483 complement_process_encoding_system. */
5484 setup_coding_system (p->encode_coding_system, coding);
5485 Vlast_coding_system_used = p->encode_coding_system;
5487 coding->src_multibyte = 1;
5489 else
5491 coding->src_multibyte = 0;
5492 /* For sending a unibyte text, character code conversion should
5493 not take place but EOL conversion should. So, setup raw-text
5494 or one of the subsidiary if we have not yet done it. */
5495 if (CODING_REQUIRE_ENCODING (coding))
5497 if (CODING_REQUIRE_FLUSHING (coding))
5499 /* But, before changing the coding, we must flush out data. */
5500 coding->mode |= CODING_MODE_LAST_BLOCK;
5501 send_process (proc, "", 0, Qt);
5502 coding->mode &= CODING_MODE_LAST_BLOCK;
5504 setup_coding_system (raw_text_coding_system
5505 (Vlast_coding_system_used),
5506 coding);
5507 coding->src_multibyte = 0;
5510 coding->dst_multibyte = 0;
5512 if (CODING_REQUIRE_ENCODING (coding))
5514 coding->dst_object = Qt;
5515 if (BUFFERP (object))
5517 ptrdiff_t from_byte, from, to;
5518 ptrdiff_t save_pt, save_pt_byte;
5519 struct buffer *cur = current_buffer;
5521 set_buffer_internal (XBUFFER (object));
5522 save_pt = PT, save_pt_byte = PT_BYTE;
5524 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5525 from = BYTE_TO_CHAR (from_byte);
5526 to = BYTE_TO_CHAR (from_byte + len);
5527 TEMP_SET_PT_BOTH (from, from_byte);
5528 encode_coding_object (coding, object, from, from_byte,
5529 to, from_byte + len, Qt);
5530 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5531 set_buffer_internal (cur);
5533 else if (STRINGP (object))
5535 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5536 SBYTES (object), Qt);
5538 else
5540 coding->dst_object = make_unibyte_string (buf, len);
5541 coding->produced = len;
5544 len = coding->produced;
5545 object = coding->dst_object;
5546 buf = SSDATA (object);
5549 /* If there is already data in the write_queue, put the new data
5550 in the back of queue. Otherwise, ignore it. */
5551 if (!NILP (p->write_queue))
5552 write_queue_push (p, object, buf, len, 0);
5554 do /* while !NILP (p->write_queue) */
5556 ptrdiff_t cur_len = -1;
5557 const char *cur_buf;
5558 Lisp_Object cur_object;
5560 /* If write_queue is empty, ignore it. */
5561 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5563 cur_len = len;
5564 cur_buf = buf;
5565 cur_object = object;
5568 while (cur_len > 0)
5570 /* Send this batch, using one or more write calls. */
5571 ptrdiff_t written = 0;
5572 int outfd = p->outfd;
5573 #ifdef DATAGRAM_SOCKETS
5574 if (DATAGRAM_CHAN_P (outfd))
5576 rv = sendto (outfd, cur_buf, cur_len,
5577 0, datagram_address[outfd].sa,
5578 datagram_address[outfd].len);
5579 if (rv >= 0)
5580 written = rv;
5581 else if (errno == EMSGSIZE)
5582 report_file_error ("Sending datagram", proc);
5584 else
5585 #endif
5587 #ifdef HAVE_GNUTLS
5588 if (p->gnutls_p && p->gnutls_state)
5589 written = emacs_gnutls_write (p, cur_buf, cur_len);
5590 else
5591 #endif
5592 written = emacs_write_sig (outfd, cur_buf, cur_len);
5593 rv = (written ? 0 : -1);
5594 #ifdef ADAPTIVE_READ_BUFFERING
5595 if (p->read_output_delay > 0
5596 && p->adaptive_read_buffering == 1)
5598 p->read_output_delay = 0;
5599 process_output_delay_count--;
5600 p->read_output_skip = 0;
5602 #endif
5605 if (rv < 0)
5607 if (errno == EAGAIN
5608 #ifdef EWOULDBLOCK
5609 || errno == EWOULDBLOCK
5610 #endif
5612 /* Buffer is full. Wait, accepting input;
5613 that may allow the program
5614 to finish doing output and read more. */
5616 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5617 /* A gross hack to work around a bug in FreeBSD.
5618 In the following sequence, read(2) returns
5619 bogus data:
5621 write(2) 1022 bytes
5622 write(2) 954 bytes, get EAGAIN
5623 read(2) 1024 bytes in process_read_output
5624 read(2) 11 bytes in process_read_output
5626 That is, read(2) returns more bytes than have
5627 ever been written successfully. The 1033 bytes
5628 read are the 1022 bytes written successfully
5629 after processing (for example with CRs added if
5630 the terminal is set up that way which it is
5631 here). The same bytes will be seen again in a
5632 later read(2), without the CRs. */
5634 if (errno == EAGAIN)
5636 int flags = FWRITE;
5637 ioctl (p->outfd, TIOCFLUSH, &flags);
5639 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5641 /* Put what we should have written in wait_queue. */
5642 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5643 wait_reading_process_output (0, 20 * 1000 * 1000,
5644 0, 0, Qnil, NULL, 0);
5645 /* Reread queue, to see what is left. */
5646 break;
5648 else if (errno == EPIPE)
5650 p->raw_status_new = 0;
5651 pset_status (p, list2 (Qexit, make_number (256)));
5652 p->tick = ++process_tick;
5653 deactivate_process (proc);
5654 error ("process %s no longer connected to pipe; closed it",
5655 SDATA (p->name));
5657 else
5658 /* This is a real error. */
5659 report_file_error ("Writing to process", proc);
5661 cur_buf += written;
5662 cur_len -= written;
5665 while (!NILP (p->write_queue));
5668 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5669 3, 3, 0,
5670 doc: /* Send current contents of region as input to PROCESS.
5671 PROCESS may be a process, a buffer, the name of a process or buffer, or
5672 nil, indicating the current buffer's process.
5673 Called from program, takes three arguments, PROCESS, START and END.
5674 If the region is more than 500 characters long,
5675 it is sent in several bunches. This may happen even for shorter regions.
5676 Output from processes can arrive in between bunches. */)
5677 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5679 Lisp_Object proc = get_process (process);
5680 ptrdiff_t start_byte, end_byte;
5682 validate_region (&start, &end);
5684 start_byte = CHAR_TO_BYTE (XINT (start));
5685 end_byte = CHAR_TO_BYTE (XINT (end));
5687 if (XINT (start) < GPT && XINT (end) > GPT)
5688 move_gap_both (XINT (start), start_byte);
5690 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5691 end_byte - start_byte, Fcurrent_buffer ());
5693 return Qnil;
5696 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5697 2, 2, 0,
5698 doc: /* Send PROCESS the contents of STRING as input.
5699 PROCESS may be a process, a buffer, the name of a process or buffer, or
5700 nil, indicating the current buffer's process.
5701 If STRING is more than 500 characters long,
5702 it is sent in several bunches. This may happen even for shorter strings.
5703 Output from processes can arrive in between bunches. */)
5704 (Lisp_Object process, Lisp_Object string)
5706 Lisp_Object proc;
5707 CHECK_STRING (string);
5708 proc = get_process (process);
5709 send_process (proc, SSDATA (string),
5710 SBYTES (string), string);
5711 return Qnil;
5714 /* Return the foreground process group for the tty/pty that
5715 the process P uses. */
5716 static pid_t
5717 emacs_get_tty_pgrp (struct Lisp_Process *p)
5719 pid_t gid = -1;
5721 #ifdef TIOCGPGRP
5722 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5724 int fd;
5725 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5726 master side. Try the slave side. */
5727 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5729 if (fd != -1)
5731 ioctl (fd, TIOCGPGRP, &gid);
5732 emacs_close (fd);
5735 #endif /* defined (TIOCGPGRP ) */
5737 return gid;
5740 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5741 Sprocess_running_child_p, 0, 1, 0,
5742 doc: /* Return non-nil if PROCESS has given the terminal to a
5743 child. If the operating system does not make it possible to find out,
5744 return t. If we can find out, return the numeric ID of the foreground
5745 process group. */)
5746 (Lisp_Object process)
5748 /* Initialize in case ioctl doesn't exist or gives an error,
5749 in a way that will cause returning t. */
5750 pid_t gid;
5751 Lisp_Object proc;
5752 struct Lisp_Process *p;
5754 proc = get_process (process);
5755 p = XPROCESS (proc);
5757 if (!EQ (p->type, Qreal))
5758 error ("Process %s is not a subprocess",
5759 SDATA (p->name));
5760 if (p->infd < 0)
5761 error ("Process %s is not active",
5762 SDATA (p->name));
5764 gid = emacs_get_tty_pgrp (p);
5766 if (gid == p->pid)
5767 return Qnil;
5768 if (gid != -1)
5769 return make_number (gid);
5770 return Qt;
5773 /* Send a signal number SIGNO to PROCESS.
5774 If CURRENT_GROUP is t, that means send to the process group
5775 that currently owns the terminal being used to communicate with PROCESS.
5776 This is used for various commands in shell mode.
5777 If CURRENT_GROUP is lambda, that means send to the process group
5778 that currently owns the terminal, but only if it is NOT the shell itself.
5780 If NOMSG is false, insert signal-announcements into process's buffers
5781 right away.
5783 If we can, we try to signal PROCESS by sending control characters
5784 down the pty. This allows us to signal inferiors who have changed
5785 their uid, for which kill would return an EPERM error. */
5787 static void
5788 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5789 bool nomsg)
5791 Lisp_Object proc;
5792 struct Lisp_Process *p;
5793 pid_t gid;
5794 bool no_pgrp = 0;
5796 proc = get_process (process);
5797 p = XPROCESS (proc);
5799 if (!EQ (p->type, Qreal))
5800 error ("Process %s is not a subprocess",
5801 SDATA (p->name));
5802 if (p->infd < 0)
5803 error ("Process %s is not active",
5804 SDATA (p->name));
5806 if (!p->pty_flag)
5807 current_group = Qnil;
5809 /* If we are using pgrps, get a pgrp number and make it negative. */
5810 if (NILP (current_group))
5811 /* Send the signal to the shell's process group. */
5812 gid = p->pid;
5813 else
5815 #ifdef SIGNALS_VIA_CHARACTERS
5816 /* If possible, send signals to the entire pgrp
5817 by sending an input character to it. */
5819 struct termios t;
5820 cc_t *sig_char = NULL;
5822 tcgetattr (p->infd, &t);
5824 switch (signo)
5826 case SIGINT:
5827 sig_char = &t.c_cc[VINTR];
5828 break;
5830 case SIGQUIT:
5831 sig_char = &t.c_cc[VQUIT];
5832 break;
5834 case SIGTSTP:
5835 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5836 sig_char = &t.c_cc[VSWTCH];
5837 #else
5838 sig_char = &t.c_cc[VSUSP];
5839 #endif
5840 break;
5843 if (sig_char && *sig_char != CDISABLE)
5845 send_process (proc, (char *) sig_char, 1, Qnil);
5846 return;
5848 /* If we can't send the signal with a character,
5849 fall through and send it another way. */
5851 /* The code above may fall through if it can't
5852 handle the signal. */
5853 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5855 #ifdef TIOCGPGRP
5856 /* Get the current pgrp using the tty itself, if we have that.
5857 Otherwise, use the pty to get the pgrp.
5858 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5859 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5860 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5861 His patch indicates that if TIOCGPGRP returns an error, then
5862 we should just assume that p->pid is also the process group id. */
5864 gid = emacs_get_tty_pgrp (p);
5866 if (gid == -1)
5867 /* If we can't get the information, assume
5868 the shell owns the tty. */
5869 gid = p->pid;
5871 /* It is not clear whether anything really can set GID to -1.
5872 Perhaps on some system one of those ioctls can or could do so.
5873 Or perhaps this is vestigial. */
5874 if (gid == -1)
5875 no_pgrp = 1;
5876 #else /* ! defined (TIOCGPGRP) */
5877 /* Can't select pgrps on this system, so we know that
5878 the child itself heads the pgrp. */
5879 gid = p->pid;
5880 #endif /* ! defined (TIOCGPGRP) */
5882 /* If current_group is lambda, and the shell owns the terminal,
5883 don't send any signal. */
5884 if (EQ (current_group, Qlambda) && gid == p->pid)
5885 return;
5888 #ifdef SIGCONT
5889 if (signo == SIGCONT)
5891 p->raw_status_new = 0;
5892 pset_status (p, Qrun);
5893 p->tick = ++process_tick;
5894 if (!nomsg)
5896 status_notify (NULL, NULL);
5897 redisplay_preserve_echo_area (13);
5900 #endif
5902 #ifdef TIOCSIGSEND
5903 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
5904 We don't know whether the bug is fixed in later HP-UX versions. */
5905 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
5906 return;
5907 #endif
5909 /* If we don't have process groups, send the signal to the immediate
5910 subprocess. That isn't really right, but it's better than any
5911 obvious alternative. */
5912 pid_t pid = no_pgrp ? gid : - gid;
5914 /* Do not kill an already-reaped process, as that could kill an
5915 innocent bystander that happens to have the same process ID. */
5916 sigset_t oldset;
5917 block_child_signal (&oldset);
5918 if (p->alive)
5919 kill (pid, signo);
5920 unblock_child_signal (&oldset);
5923 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5924 doc: /* Interrupt process PROCESS.
5925 PROCESS may be a process, a buffer, or the name of a process or buffer.
5926 No arg or nil means current buffer's process.
5927 Second arg CURRENT-GROUP non-nil means send signal to
5928 the current process-group of the process's controlling terminal
5929 rather than to the process's own process group.
5930 If the process is a shell, this means interrupt current subjob
5931 rather than the shell.
5933 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5934 don't send the signal. */)
5935 (Lisp_Object process, Lisp_Object current_group)
5937 process_send_signal (process, SIGINT, current_group, 0);
5938 return process;
5941 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5942 doc: /* Kill process PROCESS. May be process or name of one.
5943 See function `interrupt-process' for more details on usage. */)
5944 (Lisp_Object process, Lisp_Object current_group)
5946 process_send_signal (process, SIGKILL, current_group, 0);
5947 return process;
5950 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5951 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5952 See function `interrupt-process' for more details on usage. */)
5953 (Lisp_Object process, Lisp_Object current_group)
5955 process_send_signal (process, SIGQUIT, current_group, 0);
5956 return process;
5959 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
5960 doc: /* Stop process PROCESS. May be process or name of one.
5961 See function `interrupt-process' for more details on usage.
5962 If PROCESS is a network or serial process, inhibit handling of incoming
5963 traffic. */)
5964 (Lisp_Object process, Lisp_Object current_group)
5966 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5968 struct Lisp_Process *p;
5970 p = XPROCESS (process);
5971 if (NILP (p->command)
5972 && p->infd >= 0)
5974 FD_CLR (p->infd, &input_wait_mask);
5975 FD_CLR (p->infd, &non_keyboard_wait_mask);
5977 pset_command (p, Qt);
5978 return process;
5980 #ifndef SIGTSTP
5981 error ("No SIGTSTP support");
5982 #else
5983 process_send_signal (process, SIGTSTP, current_group, 0);
5984 #endif
5985 return process;
5988 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
5989 doc: /* Continue process PROCESS. May be process or name of one.
5990 See function `interrupt-process' for more details on usage.
5991 If PROCESS is a network or serial process, resume handling of incoming
5992 traffic. */)
5993 (Lisp_Object process, Lisp_Object current_group)
5995 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5997 struct Lisp_Process *p;
5999 p = XPROCESS (process);
6000 if (EQ (p->command, Qt)
6001 && p->infd >= 0
6002 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6004 FD_SET (p->infd, &input_wait_mask);
6005 FD_SET (p->infd, &non_keyboard_wait_mask);
6006 #ifdef WINDOWSNT
6007 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6008 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6009 #else /* not WINDOWSNT */
6010 tcflush (p->infd, TCIFLUSH);
6011 #endif /* not WINDOWSNT */
6013 pset_command (p, Qnil);
6014 return process;
6016 #ifdef SIGCONT
6017 process_send_signal (process, SIGCONT, current_group, 0);
6018 #else
6019 error ("No SIGCONT support");
6020 #endif
6021 return process;
6024 /* Return the integer value of the signal whose abbreviation is ABBR,
6025 or a negative number if there is no such signal. */
6026 static int
6027 abbr_to_signal (char const *name)
6029 int i, signo;
6030 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6032 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6033 name += 3;
6035 for (i = 0; i < sizeof sigbuf; i++)
6037 sigbuf[i] = c_toupper (name[i]);
6038 if (! sigbuf[i])
6039 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6042 return -1;
6045 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6046 2, 2, "sProcess (name or number): \nnSignal code: ",
6047 doc: /* Send PROCESS the signal with code SIGCODE.
6048 PROCESS may also be a number specifying the process id of the
6049 process to signal; in this case, the process need not be a child of
6050 this Emacs.
6051 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6052 (Lisp_Object process, Lisp_Object sigcode)
6054 pid_t pid;
6055 int signo;
6057 if (STRINGP (process))
6059 Lisp_Object tem = Fget_process (process);
6060 if (NILP (tem))
6062 Lisp_Object process_number
6063 = string_to_number (SSDATA (process), 10, 1);
6064 if (INTEGERP (process_number) || FLOATP (process_number))
6065 tem = process_number;
6067 process = tem;
6069 else if (!NUMBERP (process))
6070 process = get_process (process);
6072 if (NILP (process))
6073 return process;
6075 if (NUMBERP (process))
6076 CONS_TO_INTEGER (process, pid_t, pid);
6077 else
6079 CHECK_PROCESS (process);
6080 pid = XPROCESS (process)->pid;
6081 if (pid <= 0)
6082 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6085 if (INTEGERP (sigcode))
6087 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6088 signo = XINT (sigcode);
6090 else
6092 char *name;
6094 CHECK_SYMBOL (sigcode);
6095 name = SSDATA (SYMBOL_NAME (sigcode));
6097 signo = abbr_to_signal (name);
6098 if (signo < 0)
6099 error ("Undefined signal name %s", name);
6102 return make_number (kill (pid, signo));
6105 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6106 doc: /* Make PROCESS see end-of-file in its input.
6107 EOF comes after any text already sent to it.
6108 PROCESS may be a process, a buffer, the name of a process or buffer, or
6109 nil, indicating the current buffer's process.
6110 If PROCESS is a network connection, or is a process communicating
6111 through a pipe (as opposed to a pty), then you cannot send any more
6112 text to PROCESS after you call this function.
6113 If PROCESS is a serial process, wait until all output written to the
6114 process has been transmitted to the serial port. */)
6115 (Lisp_Object process)
6117 Lisp_Object proc;
6118 struct coding_system *coding = NULL;
6119 int outfd;
6121 if (DATAGRAM_CONN_P (process))
6122 return process;
6124 proc = get_process (process);
6125 outfd = XPROCESS (proc)->outfd;
6126 if (outfd >= 0)
6127 coding = proc_encode_coding_system[outfd];
6129 /* Make sure the process is really alive. */
6130 if (XPROCESS (proc)->raw_status_new)
6131 update_status (XPROCESS (proc));
6132 if (! EQ (XPROCESS (proc)->status, Qrun))
6133 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6135 if (coding && CODING_REQUIRE_FLUSHING (coding))
6137 coding->mode |= CODING_MODE_LAST_BLOCK;
6138 send_process (proc, "", 0, Qnil);
6141 if (XPROCESS (proc)->pty_flag)
6142 send_process (proc, "\004", 1, Qnil);
6143 else if (EQ (XPROCESS (proc)->type, Qserial))
6145 #ifndef WINDOWSNT
6146 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6147 report_file_error ("Failed tcdrain", Qnil);
6148 #endif /* not WINDOWSNT */
6149 /* Do nothing on Windows because writes are blocking. */
6151 else
6153 struct Lisp_Process *p = XPROCESS (proc);
6154 int old_outfd = p->outfd;
6155 int new_outfd;
6157 #ifdef HAVE_SHUTDOWN
6158 /* If this is a network connection, or socketpair is used
6159 for communication with the subprocess, call shutdown to cause EOF.
6160 (In some old system, shutdown to socketpair doesn't work.
6161 Then we just can't win.) */
6162 if (0 <= old_outfd
6163 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6164 shutdown (old_outfd, 1);
6165 #endif
6166 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6167 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6168 if (new_outfd < 0)
6169 report_file_error ("Opening null device", Qnil);
6170 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6171 p->outfd = new_outfd;
6173 if (!proc_encode_coding_system[new_outfd])
6174 proc_encode_coding_system[new_outfd]
6175 = xmalloc (sizeof (struct coding_system));
6176 if (old_outfd >= 0)
6178 *proc_encode_coding_system[new_outfd]
6179 = *proc_encode_coding_system[old_outfd];
6180 memset (proc_encode_coding_system[old_outfd], 0,
6181 sizeof (struct coding_system));
6183 else
6184 setup_coding_system (p->encode_coding_system,
6185 proc_encode_coding_system[new_outfd]);
6187 return process;
6190 /* The main Emacs thread records child processes in three places:
6192 - Vprocess_alist, for asynchronous subprocesses, which are child
6193 processes visible to Lisp.
6195 - deleted_pid_list, for child processes invisible to Lisp,
6196 typically because of delete-process. These are recorded so that
6197 the processes can be reaped when they exit, so that the operating
6198 system's process table is not cluttered by zombies.
6200 - the local variable PID in Fcall_process, call_process_cleanup and
6201 call_process_kill, for synchronous subprocesses.
6202 record_unwind_protect is used to make sure this process is not
6203 forgotten: if the user interrupts call-process and the child
6204 process refuses to exit immediately even with two C-g's,
6205 call_process_kill adds PID's contents to deleted_pid_list before
6206 returning.
6208 The main Emacs thread invokes waitpid only on child processes that
6209 it creates and that have not been reaped. This avoid races on
6210 platforms such as GTK, where other threads create their own
6211 subprocesses which the main thread should not reap. For example,
6212 if the main thread attempted to reap an already-reaped child, it
6213 might inadvertently reap a GTK-created process that happened to
6214 have the same process ID. */
6216 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6217 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6218 keep track of its own children. GNUstep is similar. */
6220 static void dummy_handler (int sig) {}
6221 static signal_handler_t volatile lib_child_handler;
6223 /* Handle a SIGCHLD signal by looking for known child processes of
6224 Emacs whose status have changed. For each one found, record its
6225 new status.
6227 All we do is change the status; we do not run sentinels or print
6228 notifications. That is saved for the next time keyboard input is
6229 done, in order to avoid timing errors.
6231 ** WARNING: this can be called during garbage collection.
6232 Therefore, it must not be fooled by the presence of mark bits in
6233 Lisp objects.
6235 ** USG WARNING: Although it is not obvious from the documentation
6236 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6237 signal() before executing at least one wait(), otherwise the
6238 handler will be called again, resulting in an infinite loop. The
6239 relevant portion of the documentation reads "SIGCLD signals will be
6240 queued and the signal-catching function will be continually
6241 reentered until the queue is empty". Invoking signal() causes the
6242 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6243 Inc.
6245 ** Malloc WARNING: This should never call malloc either directly or
6246 indirectly; if it does, that is a bug. */
6248 static void
6249 handle_child_signal (int sig)
6251 Lisp_Object tail, proc;
6253 /* Find the process that signaled us, and record its status. */
6255 /* The process can have been deleted by Fdelete_process, or have
6256 been started asynchronously by Fcall_process. */
6257 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6259 bool all_pids_are_fixnums
6260 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6261 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6262 Lisp_Object head = XCAR (tail);
6263 Lisp_Object xpid;
6264 if (! CONSP (head))
6265 continue;
6266 xpid = XCAR (head);
6267 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6269 pid_t deleted_pid;
6270 if (INTEGERP (xpid))
6271 deleted_pid = XINT (xpid);
6272 else
6273 deleted_pid = XFLOAT_DATA (xpid);
6274 if (child_status_changed (deleted_pid, 0, 0))
6276 if (STRINGP (XCDR (head)))
6277 unlink (SSDATA (XCDR (head)));
6278 XSETCAR (tail, Qnil);
6283 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6284 FOR_EACH_PROCESS (tail, proc)
6286 struct Lisp_Process *p = XPROCESS (proc);
6287 int status;
6289 if (p->alive
6290 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6292 /* Change the status of the process that was found. */
6293 p->tick = ++process_tick;
6294 p->raw_status = status;
6295 p->raw_status_new = 1;
6297 /* If process has terminated, stop waiting for its output. */
6298 if (WIFSIGNALED (status) || WIFEXITED (status))
6300 bool clear_desc_flag = 0;
6301 p->alive = 0;
6302 if (p->infd >= 0)
6303 clear_desc_flag = 1;
6305 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6306 if (clear_desc_flag)
6308 FD_CLR (p->infd, &input_wait_mask);
6309 FD_CLR (p->infd, &non_keyboard_wait_mask);
6315 lib_child_handler (sig);
6316 #ifdef NS_IMPL_GNUSTEP
6317 /* NSTask in GNUstep sets its child handler each time it is called.
6318 So we must re-set ours. */
6319 catch_child_signal ();
6320 #endif
6323 static void
6324 deliver_child_signal (int sig)
6326 deliver_process_signal (sig, handle_child_signal);
6330 static Lisp_Object
6331 exec_sentinel_error_handler (Lisp_Object error_val)
6333 cmd_error_internal (error_val, "error in process sentinel: ");
6334 Vinhibit_quit = Qt;
6335 update_echo_area ();
6336 Fsleep_for (make_number (2), Qnil);
6337 return Qt;
6340 static void
6341 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6343 Lisp_Object sentinel, odeactivate;
6344 struct Lisp_Process *p = XPROCESS (proc);
6345 ptrdiff_t count = SPECPDL_INDEX ();
6346 bool outer_running_asynch_code = running_asynch_code;
6347 int waiting = waiting_for_user_input_p;
6349 if (inhibit_sentinels)
6350 return;
6352 /* No need to gcpro these, because all we do with them later
6353 is test them for EQness, and none of them should be a string. */
6354 odeactivate = Vdeactivate_mark;
6355 #if 0
6356 Lisp_Object obuffer, okeymap;
6357 XSETBUFFER (obuffer, current_buffer);
6358 okeymap = BVAR (current_buffer, keymap);
6359 #endif
6361 /* There's no good reason to let sentinels change the current
6362 buffer, and many callers of accept-process-output, sit-for, and
6363 friends don't expect current-buffer to be changed from under them. */
6364 record_unwind_current_buffer ();
6366 sentinel = p->sentinel;
6368 /* Inhibit quit so that random quits don't screw up a running filter. */
6369 specbind (Qinhibit_quit, Qt);
6370 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6372 /* In case we get recursively called,
6373 and we already saved the match data nonrecursively,
6374 save the same match data in safely recursive fashion. */
6375 if (outer_running_asynch_code)
6377 Lisp_Object tem;
6378 tem = Fmatch_data (Qnil, Qnil, Qnil);
6379 restore_search_regs ();
6380 record_unwind_save_match_data ();
6381 Fset_match_data (tem, Qt);
6384 /* For speed, if a search happens within this code,
6385 save the match data in a special nonrecursive fashion. */
6386 running_asynch_code = 1;
6388 internal_condition_case_1 (read_process_output_call,
6389 list3 (sentinel, proc, reason),
6390 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6391 exec_sentinel_error_handler);
6393 /* If we saved the match data nonrecursively, restore it now. */
6394 restore_search_regs ();
6395 running_asynch_code = outer_running_asynch_code;
6397 Vdeactivate_mark = odeactivate;
6399 /* Restore waiting_for_user_input_p as it was
6400 when we were called, in case the filter clobbered it. */
6401 waiting_for_user_input_p = waiting;
6403 #if 0
6404 if (! EQ (Fcurrent_buffer (), obuffer)
6405 || ! EQ (current_buffer->keymap, okeymap))
6406 #endif
6407 /* But do it only if the caller is actually going to read events.
6408 Otherwise there's no need to make him wake up, and it could
6409 cause trouble (for example it would make sit_for return). */
6410 if (waiting_for_user_input_p == -1)
6411 record_asynch_buffer_change ();
6413 unbind_to (count, Qnil);
6416 /* Report all recent events of a change in process status
6417 (either run the sentinel or output a message).
6418 This is usually done while Emacs is waiting for keyboard input
6419 but can be done at other times.
6421 Return positive if any input was received from WAIT_PROC (or from
6422 any process if WAIT_PROC is null), zero if input was attempted but
6423 none received, and negative if we didn't even try. */
6425 static int
6426 status_notify (struct Lisp_Process *deleting_process,
6427 struct Lisp_Process *wait_proc)
6429 Lisp_Object proc;
6430 Lisp_Object tail, msg;
6431 struct gcpro gcpro1, gcpro2;
6432 int got_some_input = -1;
6434 tail = Qnil;
6435 msg = Qnil;
6436 /* We need to gcpro tail; if read_process_output calls a filter
6437 which deletes a process and removes the cons to which tail points
6438 from Vprocess_alist, and then causes a GC, tail is an unprotected
6439 reference. */
6440 GCPRO2 (tail, msg);
6442 /* Set this now, so that if new processes are created by sentinels
6443 that we run, we get called again to handle their status changes. */
6444 update_tick = process_tick;
6446 FOR_EACH_PROCESS (tail, proc)
6448 Lisp_Object symbol;
6449 register struct Lisp_Process *p = XPROCESS (proc);
6451 if (p->tick != p->update_tick)
6453 p->update_tick = p->tick;
6455 /* If process is still active, read any output that remains. */
6456 while (! EQ (p->filter, Qt)
6457 && ! EQ (p->status, Qconnect)
6458 && ! EQ (p->status, Qlisten)
6459 /* Network or serial process not stopped: */
6460 && ! EQ (p->command, Qt)
6461 && p->infd >= 0
6462 && p != deleting_process)
6464 int nread = read_process_output (proc, p->infd);
6465 if (got_some_input < nread)
6466 got_some_input = nread;
6467 if (nread <= 0)
6468 break;
6471 /* Get the text to use for the message. */
6472 if (p->raw_status_new)
6473 update_status (p);
6474 msg = status_message (p);
6476 /* If process is terminated, deactivate it or delete it. */
6477 symbol = p->status;
6478 if (CONSP (p->status))
6479 symbol = XCAR (p->status);
6481 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6482 || EQ (symbol, Qclosed))
6484 if (delete_exited_processes)
6485 remove_process (proc);
6486 else
6487 deactivate_process (proc);
6490 /* The actions above may have further incremented p->tick.
6491 So set p->update_tick again so that an error in the sentinel will
6492 not cause this code to be run again. */
6493 p->update_tick = p->tick;
6494 /* Now output the message suitably. */
6495 exec_sentinel (proc, msg);
6497 } /* end for */
6499 update_mode_lines = 24; /* In case buffers use %s in mode-line-format. */
6500 UNGCPRO;
6501 return got_some_input;
6504 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6505 Sinternal_default_process_sentinel, 2, 2, 0,
6506 doc: /* Function used as default sentinel for processes.
6507 This inserts a status message into the process's buffer, if there is one. */)
6508 (Lisp_Object proc, Lisp_Object msg)
6510 Lisp_Object buffer, symbol;
6511 struct Lisp_Process *p;
6512 CHECK_PROCESS (proc);
6513 p = XPROCESS (proc);
6514 buffer = p->buffer;
6515 symbol = p->status;
6516 if (CONSP (symbol))
6517 symbol = XCAR (symbol);
6519 if (!EQ (symbol, Qrun) && !NILP (buffer))
6521 Lisp_Object tem;
6522 struct buffer *old = current_buffer;
6523 ptrdiff_t opoint, opoint_byte;
6524 ptrdiff_t before, before_byte;
6526 /* Avoid error if buffer is deleted
6527 (probably that's why the process is dead, too). */
6528 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6529 return Qnil;
6530 Fset_buffer (buffer);
6532 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6533 msg = (code_convert_string_norecord
6534 (msg, Vlocale_coding_system, 1));
6536 opoint = PT;
6537 opoint_byte = PT_BYTE;
6538 /* Insert new output into buffer
6539 at the current end-of-output marker,
6540 thus preserving logical ordering of input and output. */
6541 if (XMARKER (p->mark)->buffer)
6542 Fgoto_char (p->mark);
6543 else
6544 SET_PT_BOTH (ZV, ZV_BYTE);
6546 before = PT;
6547 before_byte = PT_BYTE;
6549 tem = BVAR (current_buffer, read_only);
6550 bset_read_only (current_buffer, Qnil);
6551 insert_string ("\nProcess ");
6552 { /* FIXME: temporary kludge. */
6553 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6554 insert_string (" ");
6555 Finsert (1, &msg);
6556 bset_read_only (current_buffer, tem);
6557 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6559 if (opoint >= before)
6560 SET_PT_BOTH (opoint + (PT - before),
6561 opoint_byte + (PT_BYTE - before_byte));
6562 else
6563 SET_PT_BOTH (opoint, opoint_byte);
6565 set_buffer_internal (old);
6567 return Qnil;
6571 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6572 Sset_process_coding_system, 1, 3, 0,
6573 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6574 DECODING will be used to decode subprocess output and ENCODING to
6575 encode subprocess input. */)
6576 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6578 register struct Lisp_Process *p;
6580 CHECK_PROCESS (process);
6581 p = XPROCESS (process);
6582 if (p->infd < 0)
6583 error ("Input file descriptor of %s closed", SDATA (p->name));
6584 if (p->outfd < 0)
6585 error ("Output file descriptor of %s closed", SDATA (p->name));
6586 Fcheck_coding_system (decoding);
6587 Fcheck_coding_system (encoding);
6588 encoding = coding_inherit_eol_type (encoding, Qnil);
6589 pset_decode_coding_system (p, decoding);
6590 pset_encode_coding_system (p, encoding);
6591 setup_process_coding_systems (process);
6593 return Qnil;
6596 DEFUN ("process-coding-system",
6597 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6598 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6599 (register Lisp_Object process)
6601 CHECK_PROCESS (process);
6602 return Fcons (XPROCESS (process)->decode_coding_system,
6603 XPROCESS (process)->encode_coding_system);
6606 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6607 Sset_process_filter_multibyte, 2, 2, 0,
6608 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6609 If FLAG is non-nil, the filter is given multibyte strings.
6610 If FLAG is nil, the filter is given unibyte strings. In this case,
6611 all character code conversion except for end-of-line conversion is
6612 suppressed. */)
6613 (Lisp_Object process, Lisp_Object flag)
6615 register struct Lisp_Process *p;
6617 CHECK_PROCESS (process);
6618 p = XPROCESS (process);
6619 if (NILP (flag))
6620 pset_decode_coding_system
6621 (p, raw_text_coding_system (p->decode_coding_system));
6622 setup_process_coding_systems (process);
6624 return Qnil;
6627 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6628 Sprocess_filter_multibyte_p, 1, 1, 0,
6629 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6630 (Lisp_Object process)
6632 register struct Lisp_Process *p;
6633 struct coding_system *coding;
6635 CHECK_PROCESS (process);
6636 p = XPROCESS (process);
6637 if (p->infd < 0)
6638 return Qnil;
6639 coding = proc_decode_coding_system[p->infd];
6640 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6646 # ifdef HAVE_GPM
6648 void
6649 add_gpm_wait_descriptor (int desc)
6651 add_keyboard_wait_descriptor (desc);
6654 void
6655 delete_gpm_wait_descriptor (int desc)
6657 delete_keyboard_wait_descriptor (desc);
6660 # endif
6662 # ifdef USABLE_SIGIO
6664 /* Return true if *MASK has a bit set
6665 that corresponds to one of the keyboard input descriptors. */
6667 static bool
6668 keyboard_bit_set (fd_set *mask)
6670 int fd;
6672 for (fd = 0; fd <= max_input_desc; fd++)
6673 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6674 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6675 return 1;
6677 return 0;
6679 # endif
6681 #else /* not subprocesses */
6683 /* Defined in msdos.c. */
6684 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6685 struct timespec *, void *);
6687 /* Implementation of wait_reading_process_output, assuming that there
6688 are no subprocesses. Used only by the MS-DOS build.
6690 Wait for timeout to elapse and/or keyboard input to be available.
6692 TIME_LIMIT is:
6693 timeout in seconds
6694 If negative, gobble data immediately available but don't wait for any.
6696 NSECS is:
6697 an additional duration to wait, measured in nanoseconds
6698 If TIME_LIMIT is zero, then:
6699 If NSECS == 0, there is no limit.
6700 If NSECS > 0, the timeout consists of NSECS only.
6701 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6703 READ_KBD is:
6704 0 to ignore keyboard input, or
6705 1 to return when input is available, or
6706 -1 means caller will actually read the input, so don't throw to
6707 the quit handler.
6709 see full version for other parameters. We know that wait_proc will
6710 always be NULL, since `subprocesses' isn't defined.
6712 DO_DISPLAY means redisplay should be done to show subprocess
6713 output that arrives.
6715 Return positive if we received input from WAIT_PROC (or from any
6716 process if WAIT_PROC is null), zero if we attempted to receive
6717 input but got none, and negative if we didn't even try. */
6720 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6721 bool do_display,
6722 Lisp_Object wait_for_cell,
6723 struct Lisp_Process *wait_proc, int just_wait_proc)
6725 register int nfds;
6726 struct timespec end_time, timeout;
6728 if (time_limit < 0)
6730 time_limit = 0;
6731 nsecs = -1;
6733 else if (TYPE_MAXIMUM (time_t) < time_limit)
6734 time_limit = TYPE_MAXIMUM (time_t);
6736 /* What does time_limit really mean? */
6737 if (time_limit || nsecs > 0)
6739 timeout = make_timespec (time_limit, nsecs);
6740 end_time = timespec_add (current_timespec (), timeout);
6743 /* Turn off periodic alarms (in case they are in use)
6744 and then turn off any other atimers,
6745 because the select emulator uses alarms. */
6746 stop_polling ();
6747 turn_on_atimers (0);
6749 while (1)
6751 bool timeout_reduced_for_timers = false;
6752 fd_set waitchannels;
6753 int xerrno;
6755 /* If calling from keyboard input, do not quit
6756 since we want to return C-g as an input character.
6757 Otherwise, do pending quit if requested. */
6758 if (read_kbd >= 0)
6759 QUIT;
6761 /* Exit now if the cell we're waiting for became non-nil. */
6762 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6763 break;
6765 /* Compute time from now till when time limit is up. */
6766 /* Exit if already run out. */
6767 if (nsecs < 0)
6769 /* A negative timeout means
6770 gobble output available now
6771 but don't wait at all. */
6773 timeout = make_timespec (0, 0);
6775 else if (time_limit || nsecs > 0)
6777 struct timespec now = current_timespec ();
6778 if (timespec_cmp (end_time, now) <= 0)
6779 break;
6780 timeout = timespec_sub (end_time, now);
6782 else
6784 timeout = make_timespec (100000, 0);
6787 /* If our caller will not immediately handle keyboard events,
6788 run timer events directly.
6789 (Callers that will immediately read keyboard events
6790 call timer_delay on their own.) */
6791 if (NILP (wait_for_cell))
6793 struct timespec timer_delay;
6797 unsigned old_timers_run = timers_run;
6798 timer_delay = timer_check ();
6799 if (timers_run != old_timers_run && do_display)
6800 /* We must retry, since a timer may have requeued itself
6801 and that could alter the time delay. */
6802 redisplay_preserve_echo_area (14);
6803 else
6804 break;
6806 while (!detect_input_pending ());
6808 /* If there is unread keyboard input, also return. */
6809 if (read_kbd != 0
6810 && requeued_events_pending_p ())
6811 break;
6813 if (timespec_valid_p (timer_delay) && nsecs >= 0)
6815 if (timespec_cmp (timer_delay, timeout) < 0)
6817 timeout = timer_delay;
6818 timeout_reduced_for_timers = true;
6823 /* Cause C-g and alarm signals to take immediate action,
6824 and cause input available signals to zero out timeout. */
6825 if (read_kbd < 0)
6826 set_waiting_for_input (&timeout);
6828 /* If a frame has been newly mapped and needs updating,
6829 reprocess its display stuff. */
6830 if (frame_garbaged && do_display)
6832 clear_waiting_for_input ();
6833 redisplay_preserve_echo_area (15);
6834 if (read_kbd < 0)
6835 set_waiting_for_input (&timeout);
6838 /* Wait till there is something to do. */
6839 FD_ZERO (&waitchannels);
6840 if (read_kbd && detect_input_pending ())
6841 nfds = 0;
6842 else
6844 if (read_kbd || !NILP (wait_for_cell))
6845 FD_SET (0, &waitchannels);
6846 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
6849 xerrno = errno;
6851 /* Make C-g and alarm signals set flags again. */
6852 clear_waiting_for_input ();
6854 /* If we woke up due to SIGWINCH, actually change size now. */
6855 do_pending_window_change (0);
6857 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
6858 /* We waited the full specified time, so return now. */
6859 break;
6861 if (nfds == -1)
6863 /* If the system call was interrupted, then go around the
6864 loop again. */
6865 if (xerrno == EINTR)
6866 FD_ZERO (&waitchannels);
6867 else
6868 report_file_errno ("Failed select", Qnil, xerrno);
6871 /* Check for keyboard input. */
6873 if (read_kbd
6874 && detect_input_pending_run_timers (do_display))
6876 swallow_events (do_display);
6877 if (detect_input_pending_run_timers (do_display))
6878 break;
6881 /* If there is unread keyboard input, also return. */
6882 if (read_kbd
6883 && requeued_events_pending_p ())
6884 break;
6886 /* If wait_for_cell. check for keyboard input
6887 but don't run any timers.
6888 ??? (It seems wrong to me to check for keyboard
6889 input at all when wait_for_cell, but the code
6890 has been this way since July 1994.
6891 Try changing this after version 19.31.) */
6892 if (! NILP (wait_for_cell)
6893 && detect_input_pending ())
6895 swallow_events (do_display);
6896 if (detect_input_pending ())
6897 break;
6900 /* Exit now if the cell we're waiting for became non-nil. */
6901 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6902 break;
6905 start_polling ();
6907 return -1;
6910 #endif /* not subprocesses */
6912 /* The following functions are needed even if async subprocesses are
6913 not supported. Some of them are no-op stubs in that case. */
6915 #ifdef HAVE_TIMERFD
6917 /* Add FD, which is a descriptor returned by timerfd_create,
6918 to the set of non-keyboard input descriptors. */
6920 void
6921 add_timer_wait_descriptor (int fd)
6923 FD_SET (fd, &input_wait_mask);
6924 FD_SET (fd, &non_keyboard_wait_mask);
6925 FD_SET (fd, &non_process_wait_mask);
6926 fd_callback_info[fd].func = timerfd_callback;
6927 fd_callback_info[fd].data = NULL;
6928 fd_callback_info[fd].condition |= FOR_READ;
6929 if (fd > max_input_desc)
6930 max_input_desc = fd;
6933 #endif /* HAVE_TIMERFD */
6935 /* Add DESC to the set of keyboard input descriptors. */
6937 void
6938 add_keyboard_wait_descriptor (int desc)
6940 #ifdef subprocesses /* Actually means "not MSDOS". */
6941 FD_SET (desc, &input_wait_mask);
6942 FD_SET (desc, &non_process_wait_mask);
6943 if (desc > max_input_desc)
6944 max_input_desc = desc;
6945 #endif
6948 /* From now on, do not expect DESC to give keyboard input. */
6950 void
6951 delete_keyboard_wait_descriptor (int desc)
6953 #ifdef subprocesses
6954 FD_CLR (desc, &input_wait_mask);
6955 FD_CLR (desc, &non_process_wait_mask);
6956 delete_input_desc (desc);
6957 #endif
6960 /* Setup coding systems of PROCESS. */
6962 void
6963 setup_process_coding_systems (Lisp_Object process)
6965 #ifdef subprocesses
6966 struct Lisp_Process *p = XPROCESS (process);
6967 int inch = p->infd;
6968 int outch = p->outfd;
6969 Lisp_Object coding_system;
6971 if (inch < 0 || outch < 0)
6972 return;
6974 if (!proc_decode_coding_system[inch])
6975 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
6976 coding_system = p->decode_coding_system;
6977 if (EQ (p->filter, Qinternal_default_process_filter)
6978 && BUFFERP (p->buffer))
6980 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
6981 coding_system = raw_text_coding_system (coding_system);
6983 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
6985 if (!proc_encode_coding_system[outch])
6986 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
6987 setup_coding_system (p->encode_coding_system,
6988 proc_encode_coding_system[outch]);
6989 #endif
6992 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
6993 doc: /* Return the (or a) process associated with BUFFER.
6994 BUFFER may be a buffer or the name of one. */)
6995 (register Lisp_Object buffer)
6997 #ifdef subprocesses
6998 register Lisp_Object buf, tail, proc;
7000 if (NILP (buffer)) return Qnil;
7001 buf = Fget_buffer (buffer);
7002 if (NILP (buf)) return Qnil;
7004 FOR_EACH_PROCESS (tail, proc)
7005 if (EQ (XPROCESS (proc)->buffer, buf))
7006 return proc;
7007 #endif /* subprocesses */
7008 return Qnil;
7011 DEFUN ("process-inherit-coding-system-flag",
7012 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7013 1, 1, 0,
7014 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7015 If this flag is t, `buffer-file-coding-system' of the buffer
7016 associated with PROCESS will inherit the coding system used to decode
7017 the process output. */)
7018 (register Lisp_Object process)
7020 #ifdef subprocesses
7021 CHECK_PROCESS (process);
7022 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7023 #else
7024 /* Ignore the argument and return the value of
7025 inherit-process-coding-system. */
7026 return inherit_process_coding_system ? Qt : Qnil;
7027 #endif
7030 /* Kill all processes associated with `buffer'.
7031 If `buffer' is nil, kill all processes. */
7033 void
7034 kill_buffer_processes (Lisp_Object buffer)
7036 #ifdef subprocesses
7037 Lisp_Object tail, proc;
7039 FOR_EACH_PROCESS (tail, proc)
7040 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7042 if (NETCONN_P (proc) || SERIALCONN_P (proc))
7043 Fdelete_process (proc);
7044 else if (XPROCESS (proc)->infd >= 0)
7045 process_send_signal (proc, SIGHUP, Qnil, 1);
7047 #else /* subprocesses */
7048 /* Since we have no subprocesses, this does nothing. */
7049 #endif /* subprocesses */
7052 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7053 Swaiting_for_user_input_p, 0, 0, 0,
7054 doc: /* Return non-nil if Emacs is waiting for input from the user.
7055 This is intended for use by asynchronous process output filters and sentinels. */)
7056 (void)
7058 #ifdef subprocesses
7059 return (waiting_for_user_input_p ? Qt : Qnil);
7060 #else
7061 return Qnil;
7062 #endif
7065 /* Stop reading input from keyboard sources. */
7067 void
7068 hold_keyboard_input (void)
7070 kbd_is_on_hold = 1;
7073 /* Resume reading input from keyboard sources. */
7075 void
7076 unhold_keyboard_input (void)
7078 kbd_is_on_hold = 0;
7081 /* Return true if keyboard input is on hold, zero otherwise. */
7083 bool
7084 kbd_on_hold_p (void)
7086 return kbd_is_on_hold;
7090 /* Enumeration of and access to system processes a-la ps(1). */
7092 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7093 0, 0, 0,
7094 doc: /* Return a list of numerical process IDs of all running processes.
7095 If this functionality is unsupported, return nil.
7097 See `process-attributes' for getting attributes of a process given its ID. */)
7098 (void)
7100 return list_system_processes ();
7103 DEFUN ("process-attributes", Fprocess_attributes,
7104 Sprocess_attributes, 1, 1, 0,
7105 doc: /* Return attributes of the process given by its PID, a number.
7107 Value is an alist where each element is a cons cell of the form
7109 \(KEY . VALUE)
7111 If this functionality is unsupported, the value is nil.
7113 See `list-system-processes' for getting a list of all process IDs.
7115 The KEYs of the attributes that this function may return are listed
7116 below, together with the type of the associated VALUE (in parentheses).
7117 Not all platforms support all of these attributes; unsupported
7118 attributes will not appear in the returned alist.
7119 Unless explicitly indicated otherwise, numbers can have either
7120 integer or floating point values.
7122 euid -- Effective user User ID of the process (number)
7123 user -- User name corresponding to euid (string)
7124 egid -- Effective user Group ID of the process (number)
7125 group -- Group name corresponding to egid (string)
7126 comm -- Command name (executable name only) (string)
7127 state -- Process state code, such as "S", "R", or "T" (string)
7128 ppid -- Parent process ID (number)
7129 pgrp -- Process group ID (number)
7130 sess -- Session ID, i.e. process ID of session leader (number)
7131 ttname -- Controlling tty name (string)
7132 tpgid -- ID of foreground process group on the process's tty (number)
7133 minflt -- number of minor page faults (number)
7134 majflt -- number of major page faults (number)
7135 cminflt -- cumulative number of minor page faults (number)
7136 cmajflt -- cumulative number of major page faults (number)
7137 utime -- user time used by the process, in (current-time) format,
7138 which is a list of integers (HIGH LOW USEC PSEC)
7139 stime -- system time used by the process (current-time)
7140 time -- sum of utime and stime (current-time)
7141 cutime -- user time used by the process and its children (current-time)
7142 cstime -- system time used by the process and its children (current-time)
7143 ctime -- sum of cutime and cstime (current-time)
7144 pri -- priority of the process (number)
7145 nice -- nice value of the process (number)
7146 thcount -- process thread count (number)
7147 start -- time the process started (current-time)
7148 vsize -- virtual memory size of the process in KB's (number)
7149 rss -- resident set size of the process in KB's (number)
7150 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7151 pcpu -- percents of CPU time used by the process (floating-point number)
7152 pmem -- percents of total physical memory used by process's resident set
7153 (floating-point number)
7154 args -- command line which invoked the process (string). */)
7155 ( Lisp_Object pid)
7157 return system_process_attributes (pid);
7160 #ifdef subprocesses
7161 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7162 Invoke this after init_process_emacs, and after glib and/or GNUstep
7163 futz with the SIGCHLD handler, but before Emacs forks any children.
7164 This function's caller should block SIGCHLD. */
7166 void
7167 catch_child_signal (void)
7169 struct sigaction action, old_action;
7170 sigset_t oldset;
7171 emacs_sigaction_init (&action, deliver_child_signal);
7172 block_child_signal (&oldset);
7173 sigaction (SIGCHLD, &action, &old_action);
7174 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7175 || ! (old_action.sa_flags & SA_SIGINFO));
7177 if (old_action.sa_handler != deliver_child_signal)
7178 lib_child_handler
7179 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7180 ? dummy_handler
7181 : old_action.sa_handler);
7182 unblock_child_signal (&oldset);
7184 #endif /* subprocesses */
7187 /* This is not called "init_process" because that is the name of a
7188 Mach system call, so it would cause problems on Darwin systems. */
7189 void
7190 init_process_emacs (void)
7192 #ifdef subprocesses
7193 register int i;
7195 inhibit_sentinels = 0;
7197 #ifndef CANNOT_DUMP
7198 if (! noninteractive || initialized)
7199 #endif
7201 #if defined HAVE_GLIB && !defined WINDOWSNT
7202 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7203 this should always fail, but is enough to initialize glib's
7204 private SIGCHLD handler, allowing catch_child_signal to copy
7205 it into lib_child_handler. */
7206 g_source_unref (g_child_watch_source_new (getpid ()));
7207 #endif
7208 catch_child_signal ();
7211 FD_ZERO (&input_wait_mask);
7212 FD_ZERO (&non_keyboard_wait_mask);
7213 FD_ZERO (&non_process_wait_mask);
7214 FD_ZERO (&write_mask);
7215 max_process_desc = max_input_desc = -1;
7216 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7218 #ifdef NON_BLOCKING_CONNECT
7219 FD_ZERO (&connect_wait_mask);
7220 num_pending_connects = 0;
7221 #endif
7223 #ifdef ADAPTIVE_READ_BUFFERING
7224 process_output_delay_count = 0;
7225 process_output_skip = 0;
7226 #endif
7228 /* Don't do this, it caused infinite select loops. The display
7229 method should call add_keyboard_wait_descriptor on stdin if it
7230 needs that. */
7231 #if 0
7232 FD_SET (0, &input_wait_mask);
7233 #endif
7235 Vprocess_alist = Qnil;
7236 deleted_pid_list = Qnil;
7237 for (i = 0; i < FD_SETSIZE; i++)
7239 chan_process[i] = Qnil;
7240 proc_buffered_char[i] = -1;
7242 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7243 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7244 #ifdef DATAGRAM_SOCKETS
7245 memset (datagram_address, 0, sizeof datagram_address);
7246 #endif
7249 Lisp_Object subfeatures = Qnil;
7250 const struct socket_options *sopt;
7252 #define ADD_SUBFEATURE(key, val) \
7253 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7255 #ifdef NON_BLOCKING_CONNECT
7256 ADD_SUBFEATURE (QCnowait, Qt);
7257 #endif
7258 #ifdef DATAGRAM_SOCKETS
7259 ADD_SUBFEATURE (QCtype, Qdatagram);
7260 #endif
7261 #ifdef HAVE_SEQPACKET
7262 ADD_SUBFEATURE (QCtype, Qseqpacket);
7263 #endif
7264 #ifdef HAVE_LOCAL_SOCKETS
7265 ADD_SUBFEATURE (QCfamily, Qlocal);
7266 #endif
7267 ADD_SUBFEATURE (QCfamily, Qipv4);
7268 #ifdef AF_INET6
7269 ADD_SUBFEATURE (QCfamily, Qipv6);
7270 #endif
7271 #ifdef HAVE_GETSOCKNAME
7272 ADD_SUBFEATURE (QCservice, Qt);
7273 #endif
7274 ADD_SUBFEATURE (QCserver, Qt);
7276 for (sopt = socket_options; sopt->name; sopt++)
7277 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7279 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7282 #if defined (DARWIN_OS)
7283 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7284 processes. As such, we only change the default value. */
7285 if (initialized)
7287 char const *release = (STRINGP (Voperating_system_release)
7288 ? SSDATA (Voperating_system_release)
7289 : 0);
7290 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7291 Vprocess_connection_type = Qnil;
7294 #endif
7295 #endif /* subprocesses */
7296 kbd_is_on_hold = 0;
7299 void
7300 syms_of_process (void)
7302 #ifdef subprocesses
7304 DEFSYM (Qprocessp, "processp");
7305 DEFSYM (Qrun, "run");
7306 DEFSYM (Qstop, "stop");
7307 DEFSYM (Qsignal, "signal");
7309 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7310 here again. */
7312 DEFSYM (Qopen, "open");
7313 DEFSYM (Qclosed, "closed");
7314 DEFSYM (Qconnect, "connect");
7315 DEFSYM (Qfailed, "failed");
7316 DEFSYM (Qlisten, "listen");
7317 DEFSYM (Qlocal, "local");
7318 DEFSYM (Qipv4, "ipv4");
7319 #ifdef AF_INET6
7320 DEFSYM (Qipv6, "ipv6");
7321 #endif
7322 DEFSYM (Qdatagram, "datagram");
7323 DEFSYM (Qseqpacket, "seqpacket");
7325 DEFSYM (QCport, ":port");
7326 DEFSYM (QCspeed, ":speed");
7327 DEFSYM (QCprocess, ":process");
7329 DEFSYM (QCbytesize, ":bytesize");
7330 DEFSYM (QCstopbits, ":stopbits");
7331 DEFSYM (QCparity, ":parity");
7332 DEFSYM (Qodd, "odd");
7333 DEFSYM (Qeven, "even");
7334 DEFSYM (QCflowcontrol, ":flowcontrol");
7335 DEFSYM (Qhw, "hw");
7336 DEFSYM (Qsw, "sw");
7337 DEFSYM (QCsummary, ":summary");
7339 DEFSYM (Qreal, "real");
7340 DEFSYM (Qnetwork, "network");
7341 DEFSYM (Qserial, "serial");
7342 DEFSYM (QCbuffer, ":buffer");
7343 DEFSYM (QChost, ":host");
7344 DEFSYM (QCservice, ":service");
7345 DEFSYM (QClocal, ":local");
7346 DEFSYM (QCremote, ":remote");
7347 DEFSYM (QCcoding, ":coding");
7348 DEFSYM (QCserver, ":server");
7349 DEFSYM (QCnowait, ":nowait");
7350 DEFSYM (QCsentinel, ":sentinel");
7351 DEFSYM (QClog, ":log");
7352 DEFSYM (QCnoquery, ":noquery");
7353 DEFSYM (QCstop, ":stop");
7354 DEFSYM (QCoptions, ":options");
7355 DEFSYM (QCplist, ":plist");
7356 DEFSYM (QCcommand, ":command");
7357 DEFSYM (QCconnection_type, ":connection-type");
7358 DEFSYM (Qpty, "pty");
7359 DEFSYM (Qpipe, "pipe");
7361 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7363 staticpro (&Vprocess_alist);
7364 staticpro (&deleted_pid_list);
7366 #endif /* subprocesses */
7368 DEFSYM (QCname, ":name");
7369 DEFSYM (QCtype, ":type");
7371 DEFSYM (Qeuid, "euid");
7372 DEFSYM (Qegid, "egid");
7373 DEFSYM (Quser, "user");
7374 DEFSYM (Qgroup, "group");
7375 DEFSYM (Qcomm, "comm");
7376 DEFSYM (Qstate, "state");
7377 DEFSYM (Qppid, "ppid");
7378 DEFSYM (Qpgrp, "pgrp");
7379 DEFSYM (Qsess, "sess");
7380 DEFSYM (Qttname, "ttname");
7381 DEFSYM (Qtpgid, "tpgid");
7382 DEFSYM (Qminflt, "minflt");
7383 DEFSYM (Qmajflt, "majflt");
7384 DEFSYM (Qcminflt, "cminflt");
7385 DEFSYM (Qcmajflt, "cmajflt");
7386 DEFSYM (Qutime, "utime");
7387 DEFSYM (Qstime, "stime");
7388 DEFSYM (Qtime, "time");
7389 DEFSYM (Qcutime, "cutime");
7390 DEFSYM (Qcstime, "cstime");
7391 DEFSYM (Qctime, "ctime");
7392 #ifdef subprocesses
7393 DEFSYM (Qinternal_default_process_sentinel,
7394 "internal-default-process-sentinel");
7395 DEFSYM (Qinternal_default_process_filter,
7396 "internal-default-process-filter");
7397 #endif
7398 DEFSYM (Qpri, "pri");
7399 DEFSYM (Qnice, "nice");
7400 DEFSYM (Qthcount, "thcount");
7401 DEFSYM (Qstart, "start");
7402 DEFSYM (Qvsize, "vsize");
7403 DEFSYM (Qrss, "rss");
7404 DEFSYM (Qetime, "etime");
7405 DEFSYM (Qpcpu, "pcpu");
7406 DEFSYM (Qpmem, "pmem");
7407 DEFSYM (Qargs, "args");
7409 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7410 doc: /* Non-nil means delete processes immediately when they exit.
7411 A value of nil means don't delete them until `list-processes' is run. */);
7413 delete_exited_processes = 1;
7415 #ifdef subprocesses
7416 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7417 doc: /* Control type of device used to communicate with subprocesses.
7418 Values are nil to use a pipe, or t or `pty' to use a pty.
7419 The value has no effect if the system has no ptys or if all ptys are busy:
7420 then a pipe is used in any case.
7421 The value takes effect when `start-process' is called. */);
7422 Vprocess_connection_type = Qt;
7424 #ifdef ADAPTIVE_READ_BUFFERING
7425 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7426 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7427 On some systems, when Emacs reads the output from a subprocess, the output data
7428 is read in very small blocks, potentially resulting in very poor performance.
7429 This behavior can be remedied to some extent by setting this variable to a
7430 non-nil value, as it will automatically delay reading from such processes, to
7431 allow them to produce more output before Emacs tries to read it.
7432 If the value is t, the delay is reset after each write to the process; any other
7433 non-nil value means that the delay is not reset on write.
7434 The variable takes effect when `start-process' is called. */);
7435 Vprocess_adaptive_read_buffering = Qt;
7436 #endif
7438 defsubr (&Sprocessp);
7439 defsubr (&Sget_process);
7440 defsubr (&Sdelete_process);
7441 defsubr (&Sprocess_status);
7442 defsubr (&Sprocess_exit_status);
7443 defsubr (&Sprocess_id);
7444 defsubr (&Sprocess_name);
7445 defsubr (&Sprocess_tty_name);
7446 defsubr (&Sprocess_command);
7447 defsubr (&Sset_process_buffer);
7448 defsubr (&Sprocess_buffer);
7449 defsubr (&Sprocess_mark);
7450 defsubr (&Sset_process_filter);
7451 defsubr (&Sprocess_filter);
7452 defsubr (&Sset_process_sentinel);
7453 defsubr (&Sprocess_sentinel);
7454 defsubr (&Sset_process_window_size);
7455 defsubr (&Sset_process_inherit_coding_system_flag);
7456 defsubr (&Sset_process_query_on_exit_flag);
7457 defsubr (&Sprocess_query_on_exit_flag);
7458 defsubr (&Sprocess_contact);
7459 defsubr (&Sprocess_plist);
7460 defsubr (&Sset_process_plist);
7461 defsubr (&Sprocess_list);
7462 defsubr (&Smake_process);
7463 defsubr (&Sserial_process_configure);
7464 defsubr (&Smake_serial_process);
7465 defsubr (&Sset_network_process_option);
7466 defsubr (&Smake_network_process);
7467 defsubr (&Sformat_network_address);
7468 defsubr (&Snetwork_interface_list);
7469 defsubr (&Snetwork_interface_info);
7470 #ifdef DATAGRAM_SOCKETS
7471 defsubr (&Sprocess_datagram_address);
7472 defsubr (&Sset_process_datagram_address);
7473 #endif
7474 defsubr (&Saccept_process_output);
7475 defsubr (&Sprocess_send_region);
7476 defsubr (&Sprocess_send_string);
7477 defsubr (&Sinterrupt_process);
7478 defsubr (&Skill_process);
7479 defsubr (&Squit_process);
7480 defsubr (&Sstop_process);
7481 defsubr (&Scontinue_process);
7482 defsubr (&Sprocess_running_child_p);
7483 defsubr (&Sprocess_send_eof);
7484 defsubr (&Ssignal_process);
7485 defsubr (&Swaiting_for_user_input_p);
7486 defsubr (&Sprocess_type);
7487 defsubr (&Sinternal_default_process_sentinel);
7488 defsubr (&Sinternal_default_process_filter);
7489 defsubr (&Sset_process_coding_system);
7490 defsubr (&Sprocess_coding_system);
7491 defsubr (&Sset_process_filter_multibyte);
7492 defsubr (&Sprocess_filter_multibyte_p);
7494 #endif /* subprocesses */
7496 defsubr (&Sget_buffer_process);
7497 defsubr (&Sprocess_inherit_coding_system_flag);
7498 defsubr (&Slist_system_processes);
7499 defsubr (&Sprocess_attributes);