Stick with debbugs-supported tags in triage
[emacs.git] / src / process.c
blob9a0ab00c505c93f1368a2df6bc81fe5e75cba9f2
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2016 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 (at
11 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 #ifdef HAVE_SETRLIMIT
43 # include <sys/resource.h>
44 #endif
46 /* Are local (unix) sockets supported? */
47 #if defined (HAVE_SYS_UN_H)
48 #if !defined (AF_LOCAL) && defined (AF_UNIX)
49 #define AF_LOCAL AF_UNIX
50 #endif
51 #ifdef AF_LOCAL
52 #define HAVE_LOCAL_SOCKETS
53 #include <sys/un.h>
54 #endif
55 #endif
57 #include <sys/ioctl.h>
58 #if defined (HAVE_NET_IF_H)
59 #include <net/if.h>
60 #endif /* HAVE_NET_IF_H */
62 #if defined (HAVE_IFADDRS_H)
63 /* Must be after net/if.h */
64 #include <ifaddrs.h>
66 /* We only use structs from this header when we use getifaddrs. */
67 #if defined (HAVE_NET_IF_DL_H)
68 #include <net/if_dl.h>
69 #endif
71 #endif
73 #ifdef NEED_BSDTTY
74 #include <bsdtty.h>
75 #endif
77 #ifdef USG5_4
78 # include <sys/stream.h>
79 # include <sys/stropts.h>
80 #endif
82 #ifdef HAVE_UTIL_H
83 #include <util.h>
84 #endif
86 #ifdef HAVE_PTY_H
87 #include <pty.h>
88 #endif
90 #include <c-ctype.h>
91 #include <flexmember.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 "termopts.h"
107 #include "keyboard.h"
108 #include "blockinput.h"
109 #include "atimer.h"
110 #include "sysselect.h"
111 #include "syssignal.h"
112 #include "syswait.h"
113 #ifdef HAVE_GNUTLS
114 #include "gnutls.h"
115 #endif
117 #ifdef HAVE_WINDOW_SYSTEM
118 #include TERM_HEADER
119 #endif /* HAVE_WINDOW_SYSTEM */
121 #ifdef HAVE_GLIB
122 #include "xgselect.h"
123 #ifndef WINDOWSNT
124 #include <glib.h>
125 #endif
126 #endif
128 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
129 /* This is 0.1s in nanoseconds. */
130 #define ASYNC_RETRY_NSEC 100000000
131 #endif
133 #ifdef WINDOWSNT
134 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
135 struct timespec *, void *);
136 #endif
138 /* Work around GCC 4.3.0 bug with strict overflow checking; see
139 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
140 This bug appears to be fixed in GCC 5.1, so don't work around it there. */
141 #if GNUC_PREREQ (4, 3, 0) && ! GNUC_PREREQ (5, 1, 0)
142 # pragma GCC diagnostic ignored "-Wstrict-overflow"
143 #endif
145 /* True if keyboard input is on hold, zero otherwise. */
147 static bool kbd_is_on_hold;
149 /* Nonzero means don't run process sentinels. This is used
150 when exiting. */
151 bool inhibit_sentinels;
153 #ifdef subprocesses
155 #ifndef SOCK_CLOEXEC
156 # define SOCK_CLOEXEC 0
157 #endif
158 #ifndef SOCK_NONBLOCK
159 # define SOCK_NONBLOCK 0
160 #endif
162 /* True if ERRNUM represents an error where the system call would
163 block if a blocking variant were used. */
164 static bool
165 would_block (int errnum)
167 #ifdef EWOULDBLOCK
168 if (EWOULDBLOCK != EAGAIN && errnum == EWOULDBLOCK)
169 return true;
170 #endif
171 return errnum == EAGAIN;
174 #ifndef HAVE_ACCEPT4
176 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
178 static int
179 close_on_exec (int fd)
181 if (0 <= fd)
182 fcntl (fd, F_SETFD, FD_CLOEXEC);
183 return fd;
186 # undef accept4
187 # define accept4(sockfd, addr, addrlen, flags) \
188 process_accept4 (sockfd, addr, addrlen, flags)
189 static int
190 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
192 return close_on_exec (accept (sockfd, addr, addrlen));
195 static int
196 process_socket (int domain, int type, int protocol)
198 return close_on_exec (socket (domain, type, protocol));
200 # undef socket
201 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
202 #endif
204 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
205 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
206 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
207 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
208 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
209 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
211 /* Number of events of change of status of a process. */
212 static EMACS_INT process_tick;
213 /* Number of events for which the user or sentinel has been notified. */
214 static EMACS_INT update_tick;
216 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
217 this system. We need to read full packets, so we need a
218 "non-destructive" select. So we require either native select,
219 or emulation of select using FIONREAD. */
221 #ifndef BROKEN_DATAGRAM_SOCKETS
222 # if defined HAVE_SELECT || defined USABLE_FIONREAD
223 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
224 # define DATAGRAM_SOCKETS
225 # endif
226 # endif
227 #endif
229 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
230 # define HAVE_SEQPACKET
231 #endif
233 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
234 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
235 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
237 /* Number of processes which have a non-zero read_output_delay,
238 and therefore might be delayed for adaptive read buffering. */
240 static int process_output_delay_count;
242 /* True if any process has non-nil read_output_skip. */
244 static bool process_output_skip;
246 static void start_process_unwind (Lisp_Object);
247 static void create_process (Lisp_Object, char **, Lisp_Object);
248 #ifdef USABLE_SIGIO
249 static bool keyboard_bit_set (fd_set *);
250 #endif
251 static void deactivate_process (Lisp_Object);
252 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
253 static int read_process_output (Lisp_Object, int);
254 static void create_pty (Lisp_Object);
255 static void exec_sentinel (Lisp_Object, Lisp_Object);
257 /* Mask of bits indicating the descriptors that we wait for input on. */
259 static fd_set input_wait_mask;
261 /* Mask that excludes keyboard input descriptor(s). */
263 static fd_set non_keyboard_wait_mask;
265 /* Mask that excludes process input descriptor(s). */
267 static fd_set non_process_wait_mask;
269 /* Mask for selecting for write. */
271 static fd_set write_mask;
273 /* Mask of bits indicating the descriptors that we wait for connect to
274 complete on. Once they complete, they are removed from this mask
275 and added to the input_wait_mask and non_keyboard_wait_mask. */
277 static fd_set connect_wait_mask;
279 /* Number of bits set in connect_wait_mask. */
280 static int num_pending_connects;
282 /* The largest descriptor currently in use for a process object; -1 if none. */
283 static int max_process_desc;
285 /* The largest descriptor currently in use for input; -1 if none. */
286 static int max_input_desc;
288 /* Set the external socket descriptor for Emacs to use when
289 `make-network-process' is called with a non-nil
290 `:use-external-socket' option. The value should be either -1, or
291 the file descriptor of a socket that is already bound. */
292 static int external_sock_fd;
294 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
295 static Lisp_Object chan_process[FD_SETSIZE];
296 static void wait_for_socket_fds (Lisp_Object, char const *);
298 /* Alist of elements (NAME . PROCESS). */
299 static Lisp_Object Vprocess_alist;
301 /* Buffered-ahead input char from process, indexed by channel.
302 -1 means empty (no char is buffered).
303 Used on sys V where the only way to tell if there is any
304 output from the process is to read at least one char.
305 Always -1 on systems that support FIONREAD. */
307 static int proc_buffered_char[FD_SETSIZE];
309 /* Table of `struct coding-system' for each process. */
310 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
311 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
313 #ifdef DATAGRAM_SOCKETS
314 /* Table of `partner address' for datagram sockets. */
315 static struct sockaddr_and_len {
316 struct sockaddr *sa;
317 ptrdiff_t len;
318 } datagram_address[FD_SETSIZE];
319 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
320 #define DATAGRAM_CONN_P(proc) \
321 (PROCESSP (proc) && \
322 XPROCESS (proc)->infd >= 0 && \
323 datagram_address[XPROCESS (proc)->infd].sa != 0)
324 #else
325 #define DATAGRAM_CONN_P(proc) (0)
326 #endif
328 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
329 a `for' loop which iterates over processes from Vprocess_alist. */
331 #define FOR_EACH_PROCESS(list_var, proc_var) \
332 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
334 /* These setters are used only in this file, so they can be private. */
335 static void
336 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
338 p->buffer = val;
340 static void
341 pset_command (struct Lisp_Process *p, Lisp_Object val)
343 p->command = val;
345 static void
346 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
348 p->decode_coding_system = val;
350 static void
351 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
353 p->decoding_buf = val;
355 static void
356 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
358 p->encode_coding_system = val;
360 static void
361 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
363 p->encoding_buf = val;
365 static void
366 pset_filter (struct Lisp_Process *p, Lisp_Object val)
368 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
370 static void
371 pset_log (struct Lisp_Process *p, Lisp_Object val)
373 p->log = val;
375 static void
376 pset_mark (struct Lisp_Process *p, Lisp_Object val)
378 p->mark = val;
380 static void
381 pset_name (struct Lisp_Process *p, Lisp_Object val)
383 p->name = val;
385 static void
386 pset_plist (struct Lisp_Process *p, Lisp_Object val)
388 p->plist = val;
390 static void
391 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
393 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
395 static void
396 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
398 p->tty_name = val;
400 static void
401 pset_type (struct Lisp_Process *p, Lisp_Object val)
403 p->type = val;
405 static void
406 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
408 p->write_queue = val;
410 static void
411 pset_stderrproc (struct Lisp_Process *p, Lisp_Object val)
413 p->stderrproc = val;
417 static Lisp_Object
418 make_lisp_proc (struct Lisp_Process *p)
420 return make_lisp_ptr (p, Lisp_Vectorlike);
423 static struct fd_callback_data
425 fd_callback func;
426 void *data;
427 #define FOR_READ 1
428 #define FOR_WRITE 2
429 int condition; /* Mask of the defines above. */
430 } fd_callback_info[FD_SETSIZE];
433 /* Add a file descriptor FD to be monitored for when read is possible.
434 When read is possible, call FUNC with argument DATA. */
436 void
437 add_read_fd (int fd, fd_callback func, void *data)
439 add_keyboard_wait_descriptor (fd);
441 fd_callback_info[fd].func = func;
442 fd_callback_info[fd].data = data;
443 fd_callback_info[fd].condition |= FOR_READ;
446 /* Stop monitoring file descriptor FD for when read is possible. */
448 void
449 delete_read_fd (int fd)
451 delete_keyboard_wait_descriptor (fd);
453 fd_callback_info[fd].condition &= ~FOR_READ;
454 if (fd_callback_info[fd].condition == 0)
456 fd_callback_info[fd].func = 0;
457 fd_callback_info[fd].data = 0;
461 /* Add a file descriptor FD to be monitored for when write is possible.
462 When write is possible, call FUNC with argument DATA. */
464 void
465 add_write_fd (int fd, fd_callback func, void *data)
467 FD_SET (fd, &write_mask);
468 if (fd > max_input_desc)
469 max_input_desc = fd;
471 fd_callback_info[fd].func = func;
472 fd_callback_info[fd].data = data;
473 fd_callback_info[fd].condition |= FOR_WRITE;
476 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
478 static void
479 delete_input_desc (int fd)
481 if (fd == max_input_desc)
484 fd--;
485 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
486 || FD_ISSET (fd, &write_mask)));
488 max_input_desc = fd;
492 /* Stop monitoring file descriptor FD for when write is possible. */
494 void
495 delete_write_fd (int fd)
497 FD_CLR (fd, &write_mask);
498 fd_callback_info[fd].condition &= ~FOR_WRITE;
499 if (fd_callback_info[fd].condition == 0)
501 fd_callback_info[fd].func = 0;
502 fd_callback_info[fd].data = 0;
503 delete_input_desc (fd);
508 /* Compute the Lisp form of the process status, p->status, from
509 the numeric status that was returned by `wait'. */
511 static Lisp_Object status_convert (int);
513 static void
514 update_status (struct Lisp_Process *p)
516 eassert (p->raw_status_new);
517 pset_status (p, status_convert (p->raw_status));
518 p->raw_status_new = 0;
521 /* Convert a process status word in Unix format to
522 the list that we use internally. */
524 static Lisp_Object
525 status_convert (int w)
527 if (WIFSTOPPED (w))
528 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
529 else if (WIFEXITED (w))
530 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
531 WCOREDUMP (w) ? Qt : Qnil));
532 else if (WIFSIGNALED (w))
533 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
534 WCOREDUMP (w) ? Qt : Qnil));
535 else
536 return Qrun;
539 /* True if STATUS is that of a process attempting connection. */
541 static bool
542 connecting_status (Lisp_Object status)
544 return CONSP (status) && EQ (XCAR (status), Qconnect);
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, Lisp_Object *code,
552 bool *coredump)
554 Lisp_Object tem;
556 if (connecting_status (l))
557 l = XCAR (l);
559 if (SYMBOLP (l))
561 *symbol = l;
562 *code = make_number (0);
563 *coredump = 0;
565 else
567 *symbol = XCAR (l);
568 tem = XCDR (l);
569 *code = XCAR (tem);
570 tem = XCDR (tem);
571 *coredump = !NILP (tem);
575 /* Return a string describing a process status list. */
577 static Lisp_Object
578 status_message (struct Lisp_Process *p)
580 Lisp_Object status = p->status;
581 Lisp_Object symbol, code;
582 bool coredump;
583 Lisp_Object string;
585 decode_status (status, &symbol, &code, &coredump);
587 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
589 char const *signame;
590 synchronize_system_messages_locale ();
591 signame = strsignal (XFASTINT (code));
592 if (signame == 0)
593 string = build_string ("unknown");
594 else
596 int c1, c2;
598 string = build_unibyte_string (signame);
599 if (! NILP (Vlocale_coding_system))
600 string = (code_convert_string_norecord
601 (string, Vlocale_coding_system, 0));
602 c1 = STRING_CHAR (SDATA (string));
603 c2 = downcase (c1);
604 if (c1 != c2)
605 Faset (string, make_number (0), make_number (c2));
607 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
608 return concat2 (string, suffix);
610 else if (EQ (symbol, Qexit))
612 if (NETCONN1_P (p))
613 return build_string (XFASTINT (code) == 0
614 ? "deleted\n"
615 : "connection broken by remote peer\n");
616 if (XFASTINT (code) == 0)
617 return build_string ("finished\n");
618 AUTO_STRING (prefix, "exited abnormally with code ");
619 string = Fnumber_to_string (code);
620 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
621 return concat3 (prefix, string, suffix);
623 else if (EQ (symbol, Qfailed))
625 AUTO_STRING (format, "failed with code %s\n");
626 return CALLN (Fformat, format, code);
628 else
629 return Fcopy_sequence (Fsymbol_name (symbol));
632 enum { PTY_NAME_SIZE = 24 };
634 /* Open an available pty, returning a file descriptor.
635 Store into PTY_NAME the file name of the terminal corresponding to the pty.
636 Return -1 on failure. */
638 static int
639 allocate_pty (char pty_name[PTY_NAME_SIZE])
641 #ifdef HAVE_PTYS
642 int fd;
644 #ifdef PTY_ITERATION
645 PTY_ITERATION
646 #else
647 register int c, i;
648 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
649 for (i = 0; i < 16; i++)
650 #endif
652 #ifdef PTY_NAME_SPRINTF
653 PTY_NAME_SPRINTF
654 #else
655 sprintf (pty_name, "/dev/pty%c%x", c, i);
656 #endif /* no PTY_NAME_SPRINTF */
658 #ifdef PTY_OPEN
659 PTY_OPEN;
660 #else /* no PTY_OPEN */
661 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
662 #endif /* no PTY_OPEN */
664 if (fd >= 0)
666 #ifdef PTY_TTY_NAME_SPRINTF
667 PTY_TTY_NAME_SPRINTF
668 #else
669 sprintf (pty_name, "/dev/tty%c%x", c, i);
670 #endif /* no PTY_TTY_NAME_SPRINTF */
672 /* Set FD's close-on-exec flag. This is needed even if
673 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
674 doesn't require support for that combination.
675 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
676 doesn't work if the close-on-exec flag is set (Bug#20555).
677 Multithreaded platforms where posix_openpt ignores
678 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
679 have a race condition between the PTY_OPEN and here. */
680 fcntl (fd, F_SETFD, FD_CLOEXEC);
682 /* Check to make certain that both sides are available.
683 This avoids a nasty yet stupid bug in rlogins. */
684 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
686 emacs_close (fd);
687 # ifndef __sgi
688 continue;
689 # else
690 return -1;
691 # endif /* __sgi */
693 setup_pty (fd);
694 return fd;
697 #endif /* HAVE_PTYS */
698 return -1;
701 /* Allocate basically initialized process. */
703 static struct Lisp_Process *
704 allocate_process (void)
706 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
709 static Lisp_Object
710 make_process (Lisp_Object name)
712 struct Lisp_Process *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 (int i = 0; i < PROCESS_OPEN_FDS; i++)
723 p->open_fd[i] = -1;
725 #ifdef HAVE_GNUTLS
726 verify (GNUTLS_STAGE_EMPTY == 0);
727 eassert (p->gnutls_initstage == GNUTLS_STAGE_EMPTY);
728 eassert (NILP (p->gnutls_boot_parameters));
729 #endif
731 /* If name is already in use, modify it until it is unused. */
733 Lisp_Object name1 = name;
734 for (printmax_t i = 1; ; i++)
736 Lisp_Object tem = Fget_process (name1);
737 if (NILP (tem))
738 break;
739 char const suffix_fmt[] = "<%"pMd">";
740 char suffix[sizeof suffix_fmt + INT_STRLEN_BOUND (printmax_t)];
741 AUTO_STRING_WITH_LEN (lsuffix, suffix, sprintf (suffix, suffix_fmt, i));
742 name1 = concat2 (name, lsuffix);
744 name = name1;
745 pset_name (p, name);
746 pset_sentinel (p, Qinternal_default_process_sentinel);
747 pset_filter (p, Qinternal_default_process_filter);
748 Lisp_Object val;
749 XSETPROCESS (val, p);
750 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
751 return val;
754 static void
755 remove_process (register Lisp_Object proc)
757 register Lisp_Object pair;
759 pair = Frassq (proc, Vprocess_alist);
760 Vprocess_alist = Fdelq (pair, Vprocess_alist);
762 deactivate_process (proc);
765 #ifdef HAVE_GETADDRINFO_A
766 static void
767 free_dns_request (Lisp_Object proc)
769 struct Lisp_Process *p = XPROCESS (proc);
771 if (p->dns_request->ar_result)
772 freeaddrinfo (p->dns_request->ar_result);
773 xfree (p->dns_request);
774 p->dns_request = NULL;
776 #endif
779 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
780 doc: /* Return t if OBJECT is a process. */)
781 (Lisp_Object object)
783 return PROCESSP (object) ? Qt : Qnil;
786 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
787 doc: /* Return the process named NAME, or nil if there is none. */)
788 (register Lisp_Object name)
790 if (PROCESSP (name))
791 return name;
792 CHECK_STRING (name);
793 return Fcdr (Fassoc (name, Vprocess_alist));
796 /* This is how commands for the user decode process arguments. It
797 accepts a process, a process name, a buffer, a buffer name, or nil.
798 Buffers denote the first process in the buffer, and nil denotes the
799 current buffer. */
801 static Lisp_Object
802 get_process (register Lisp_Object name)
804 register Lisp_Object proc, obj;
805 if (STRINGP (name))
807 obj = Fget_process (name);
808 if (NILP (obj))
809 obj = Fget_buffer (name);
810 if (NILP (obj))
811 error ("Process %s does not exist", SDATA (name));
813 else if (NILP (name))
814 obj = Fcurrent_buffer ();
815 else
816 obj = name;
818 /* Now obj should be either a buffer object or a process object. */
819 if (BUFFERP (obj))
821 if (NILP (BVAR (XBUFFER (obj), name)))
822 error ("Attempt to get process for a dead buffer");
823 proc = Fget_buffer_process (obj);
824 if (NILP (proc))
825 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
827 else
829 CHECK_PROCESS (obj);
830 proc = obj;
832 return proc;
836 /* Fdelete_process promises to immediately forget about the process, but in
837 reality, Emacs needs to remember those processes until they have been
838 treated by the SIGCHLD handler and waitpid has been invoked on them;
839 otherwise they might fill up the kernel's process table.
841 Some processes created by call-process are also put onto this list.
843 Members of this list are (process-ID . filename) pairs. The
844 process-ID is a number; the filename, if a string, is a file that
845 needs to be removed after the process exits. */
846 static Lisp_Object deleted_pid_list;
848 void
849 record_deleted_pid (pid_t pid, Lisp_Object filename)
851 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
852 /* GC treated elements set to nil. */
853 Fdelq (Qnil, deleted_pid_list));
857 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
858 doc: /* Delete PROCESS: kill it and forget about it immediately.
859 PROCESS may be a process, a buffer, the name of a process or buffer, or
860 nil, indicating the current buffer's process. */)
861 (register Lisp_Object process)
863 register struct Lisp_Process *p;
865 process = get_process (process);
866 p = XPROCESS (process);
868 #ifdef HAVE_GETADDRINFO_A
869 if (p->dns_request)
871 /* Cancel the request. Unless shutting down, wait until
872 completion. Free the request if completely canceled. */
874 bool canceled = gai_cancel (p->dns_request) != EAI_NOTCANCELED;
875 if (!canceled && !inhibit_sentinels)
877 struct gaicb const *req = p->dns_request;
878 while (gai_suspend (&req, 1, NULL) != 0)
879 continue;
880 canceled = true;
882 if (canceled)
883 free_dns_request (process);
885 #endif
887 p->raw_status_new = 0;
888 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
890 pset_status (p, list2 (Qexit, make_number (0)));
891 p->tick = ++process_tick;
892 status_notify (p, NULL);
893 redisplay_preserve_echo_area (13);
895 else
897 if (p->alive)
898 record_kill_process (p, Qnil);
900 if (p->infd >= 0)
902 /* Update P's status, since record_kill_process will make the
903 SIGCHLD handler update deleted_pid_list, not *P. */
904 Lisp_Object symbol;
905 if (p->raw_status_new)
906 update_status (p);
907 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
908 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
909 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
911 p->tick = ++process_tick;
912 status_notify (p, NULL);
913 redisplay_preserve_echo_area (13);
916 remove_process (process);
917 return Qnil;
920 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
921 doc: /* Return the status of PROCESS.
922 The returned value is one of the following symbols:
923 run -- for a process that is running.
924 stop -- for a process stopped but continuable.
925 exit -- for a process that has exited.
926 signal -- for a process that has got a fatal signal.
927 open -- for a network stream connection that is open.
928 listen -- for a network stream server that is listening.
929 closed -- for a network stream connection that is closed.
930 connect -- when waiting for a non-blocking connection to complete.
931 failed -- when a non-blocking connection has failed.
932 nil -- if arg is a process name and no such process exists.
933 PROCESS may be a process, a buffer, the name of a process, or
934 nil, indicating the current buffer's process. */)
935 (register Lisp_Object process)
937 register struct Lisp_Process *p;
938 register Lisp_Object status;
940 if (STRINGP (process))
941 process = Fget_process (process);
942 else
943 process = get_process (process);
945 if (NILP (process))
946 return process;
948 p = XPROCESS (process);
949 if (p->raw_status_new)
950 update_status (p);
951 status = p->status;
952 if (CONSP (status))
953 status = XCAR (status);
954 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
956 if (EQ (status, Qexit))
957 status = Qclosed;
958 else if (EQ (p->command, Qt))
959 status = Qstop;
960 else if (EQ (status, Qrun))
961 status = Qopen;
963 return status;
966 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
967 1, 1, 0,
968 doc: /* Return the exit status of PROCESS or the signal number that killed it.
969 If PROCESS has not yet exited or died, return 0. */)
970 (register Lisp_Object process)
972 CHECK_PROCESS (process);
973 if (XPROCESS (process)->raw_status_new)
974 update_status (XPROCESS (process));
975 if (CONSP (XPROCESS (process)->status))
976 return XCAR (XCDR (XPROCESS (process)->status));
977 return make_number (0);
980 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
981 doc: /* Return the process id of PROCESS.
982 This is the pid of the external process which PROCESS uses or talks to.
983 For a network, serial, and pipe connections, this value is nil. */)
984 (register Lisp_Object process)
986 pid_t pid;
988 CHECK_PROCESS (process);
989 pid = XPROCESS (process)->pid;
990 return (pid ? make_fixnum_or_float (pid) : Qnil);
993 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
994 doc: /* Return the name of PROCESS, as a string.
995 This is the name of the program invoked in PROCESS,
996 possibly modified to make it unique among process names. */)
997 (register Lisp_Object process)
999 CHECK_PROCESS (process);
1000 return XPROCESS (process)->name;
1003 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
1004 doc: /* Return the command that was executed to start PROCESS.
1005 This is a list of strings, the first string being the program executed
1006 and the rest of the strings being the arguments given to it.
1007 For a network or serial or pipe connection, this is nil (process is running)
1008 or t (process is stopped). */)
1009 (register Lisp_Object process)
1011 CHECK_PROCESS (process);
1012 return XPROCESS (process)->command;
1015 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
1016 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
1017 This is the terminal that the process itself reads and writes on,
1018 not the name of the pty that Emacs uses to talk with that terminal. */)
1019 (register Lisp_Object process)
1021 CHECK_PROCESS (process);
1022 return XPROCESS (process)->tty_name;
1025 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1026 2, 2, 0,
1027 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1028 Return BUFFER. */)
1029 (register Lisp_Object process, Lisp_Object buffer)
1031 struct Lisp_Process *p;
1033 CHECK_PROCESS (process);
1034 if (!NILP (buffer))
1035 CHECK_BUFFER (buffer);
1036 p = XPROCESS (process);
1037 pset_buffer (p, buffer);
1038 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1039 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1040 setup_process_coding_systems (process);
1041 return buffer;
1044 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1045 1, 1, 0,
1046 doc: /* Return the buffer PROCESS is associated with.
1047 The default process filter inserts output from PROCESS into this buffer. */)
1048 (register Lisp_Object process)
1050 CHECK_PROCESS (process);
1051 return XPROCESS (process)->buffer;
1054 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1055 1, 1, 0,
1056 doc: /* Return the marker for the end of the last output from PROCESS. */)
1057 (register Lisp_Object process)
1059 CHECK_PROCESS (process);
1060 return XPROCESS (process)->mark;
1063 static void
1064 set_process_filter_masks (struct Lisp_Process *p)
1066 if (EQ (p->filter, Qt) && !EQ (p->status, Qlisten))
1068 FD_CLR (p->infd, &input_wait_mask);
1069 FD_CLR (p->infd, &non_keyboard_wait_mask);
1071 else if (EQ (p->filter, Qt)
1072 /* Network or serial process not stopped: */
1073 && !EQ (p->command, Qt))
1075 FD_SET (p->infd, &input_wait_mask);
1076 FD_SET (p->infd, &non_keyboard_wait_mask);
1080 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1081 2, 2, 0,
1082 doc: /* Give PROCESS the filter function FILTER; nil means default.
1083 A value of t means stop accepting output from the process.
1085 When a process has a non-default filter, its buffer is not used for output.
1086 Instead, each time it does output, the entire string of output is
1087 passed to the filter.
1089 The filter gets two arguments: the process and the string of output.
1090 The string argument is normally a multibyte string, except:
1091 - if the process's input coding system is no-conversion or raw-text,
1092 it is a unibyte string (the non-converted input), or else
1093 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1094 string (the result of converting the decoded input multibyte
1095 string to unibyte with `string-make-unibyte'). */)
1096 (Lisp_Object process, Lisp_Object filter)
1098 CHECK_PROCESS (process);
1099 struct Lisp_Process *p = XPROCESS (process);
1101 /* Don't signal an error if the process's input file descriptor
1102 is closed. This could make debugging Lisp more difficult,
1103 for example when doing something like
1105 (setq process (start-process ...))
1106 (debug)
1107 (set-process-filter process ...) */
1109 if (NILP (filter))
1110 filter = Qinternal_default_process_filter;
1112 pset_filter (p, filter);
1114 if (p->infd >= 0)
1115 set_process_filter_masks (p);
1117 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1118 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1119 setup_process_coding_systems (process);
1120 return filter;
1123 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1124 1, 1, 0,
1125 doc: /* Return the filter function of PROCESS.
1126 See `set-process-filter' for more info on filter functions. */)
1127 (register Lisp_Object process)
1129 CHECK_PROCESS (process);
1130 return XPROCESS (process)->filter;
1133 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1134 2, 2, 0,
1135 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1136 The sentinel is called as a function when the process changes state.
1137 It gets two arguments: the process, and a string describing the change. */)
1138 (register Lisp_Object process, Lisp_Object sentinel)
1140 struct Lisp_Process *p;
1142 CHECK_PROCESS (process);
1143 p = XPROCESS (process);
1145 if (NILP (sentinel))
1146 sentinel = Qinternal_default_process_sentinel;
1148 pset_sentinel (p, sentinel);
1149 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1150 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1151 return sentinel;
1154 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1155 1, 1, 0,
1156 doc: /* Return the sentinel of PROCESS.
1157 See `set-process-sentinel' for more info on sentinels. */)
1158 (register Lisp_Object process)
1160 CHECK_PROCESS (process);
1161 return XPROCESS (process)->sentinel;
1164 DEFUN ("set-process-window-size", Fset_process_window_size,
1165 Sset_process_window_size, 3, 3, 0,
1166 doc: /* Tell PROCESS that it has logical window size WIDTH by HEIGHT.
1167 Value is t if PROCESS was successfully told about the window size,
1168 nil otherwise. */)
1169 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1171 CHECK_PROCESS (process);
1173 /* All known platforms store window sizes as 'unsigned short'. */
1174 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1175 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1177 if (NETCONN_P (process)
1178 || XPROCESS (process)->infd < 0
1179 || (set_window_size (XPROCESS (process)->infd,
1180 XINT (height), XINT (width))
1181 < 0))
1182 return Qnil;
1183 else
1184 return Qt;
1187 DEFUN ("set-process-inherit-coding-system-flag",
1188 Fset_process_inherit_coding_system_flag,
1189 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1190 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1191 If the second argument FLAG is non-nil, then the variable
1192 `buffer-file-coding-system' of the buffer associated with PROCESS
1193 will be bound to the value of the coding system used to decode
1194 the process output.
1196 This is useful when the coding system specified for the process buffer
1197 leaves either the character code conversion or the end-of-line conversion
1198 unspecified, or if the coding system used to decode the process output
1199 is more appropriate for saving the process buffer.
1201 Binding the variable `inherit-process-coding-system' to non-nil before
1202 starting the process is an alternative way of setting the inherit flag
1203 for the process which will run.
1205 This function returns FLAG. */)
1206 (register Lisp_Object process, Lisp_Object flag)
1208 CHECK_PROCESS (process);
1209 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1210 return flag;
1213 DEFUN ("set-process-query-on-exit-flag",
1214 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1215 2, 2, 0,
1216 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1217 If the second argument FLAG is non-nil, Emacs will query the user before
1218 exiting or killing a buffer if PROCESS is running. This function
1219 returns FLAG. */)
1220 (register Lisp_Object process, Lisp_Object flag)
1222 CHECK_PROCESS (process);
1223 XPROCESS (process)->kill_without_query = NILP (flag);
1224 return flag;
1227 DEFUN ("process-query-on-exit-flag",
1228 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1229 1, 1, 0,
1230 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1231 (register Lisp_Object process)
1233 CHECK_PROCESS (process);
1234 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1237 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1238 1, 2, 0,
1239 doc: /* Return the contact info of PROCESS; t for a real child.
1240 For a network or serial or pipe connection, the value depends on the
1241 optional KEY arg. If KEY is nil, value is a cons cell of the form
1242 \(HOST SERVICE) for a network connection or (PORT SPEED) for a serial
1243 connection; it is t for a pipe connection. If KEY is t, the complete
1244 contact information for the connection is returned, else the specific
1245 value for the keyword KEY is returned. See `make-network-process',
1246 `make-serial-process', or `make pipe-process' for the list of keywords.
1247 If PROCESS is a non-blocking network process that hasn't been fully
1248 set up yet, this function will block until socket setup has completed. */)
1249 (Lisp_Object process, Lisp_Object key)
1251 Lisp_Object contact;
1253 CHECK_PROCESS (process);
1254 contact = XPROCESS (process)->childp;
1256 #ifdef DATAGRAM_SOCKETS
1258 if (NETCONN_P (process))
1259 wait_for_socket_fds (process, "process-contact");
1261 if (DATAGRAM_CONN_P (process)
1262 && (EQ (key, Qt) || EQ (key, QCremote)))
1263 contact = Fplist_put (contact, QCremote,
1264 Fprocess_datagram_address (process));
1265 #endif
1267 if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1268 || EQ (key, Qt))
1269 return contact;
1270 if (NILP (key) && NETCONN_P (process))
1271 return list2 (Fplist_get (contact, QChost),
1272 Fplist_get (contact, QCservice));
1273 if (NILP (key) && SERIALCONN_P (process))
1274 return list2 (Fplist_get (contact, QCport),
1275 Fplist_get (contact, QCspeed));
1276 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1277 if the pipe process is useful for purposes other than receiving
1278 stderr. */
1279 if (NILP (key) && PIPECONN_P (process))
1280 return Qt;
1281 return Fplist_get (contact, key);
1284 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1285 1, 1, 0,
1286 doc: /* Return the plist of PROCESS. */)
1287 (register Lisp_Object process)
1289 CHECK_PROCESS (process);
1290 return XPROCESS (process)->plist;
1293 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1294 2, 2, 0,
1295 doc: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1296 (Lisp_Object process, Lisp_Object plist)
1298 CHECK_PROCESS (process);
1299 CHECK_LIST (plist);
1301 pset_plist (XPROCESS (process), plist);
1302 return plist;
1305 #if 0 /* Turned off because we don't currently record this info
1306 in the process. Perhaps add it. */
1307 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1308 doc: /* Return the connection type of PROCESS.
1309 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1310 a socket connection. */)
1311 (Lisp_Object process)
1313 return XPROCESS (process)->type;
1315 #endif
1317 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1318 doc: /* Return the connection type of PROCESS.
1319 The value is either the symbol `real', `network', `serial', or `pipe'.
1320 PROCESS may be a process, a buffer, the name of a process or buffer, or
1321 nil, indicating the current buffer's process. */)
1322 (Lisp_Object process)
1324 Lisp_Object proc;
1325 proc = get_process (process);
1326 return XPROCESS (proc)->type;
1329 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1330 1, 2, 0,
1331 doc: /* Convert network ADDRESS from internal format to a string.
1332 A 4 or 5 element vector represents an IPv4 address (with port number).
1333 An 8 or 9 element vector represents an IPv6 address (with port number).
1334 If optional second argument OMIT-PORT is non-nil, don't include a port
1335 number in the string, even when present in ADDRESS.
1336 Return nil if format of ADDRESS is invalid. */)
1337 (Lisp_Object address, Lisp_Object omit_port)
1339 if (NILP (address))
1340 return Qnil;
1342 if (STRINGP (address)) /* AF_LOCAL */
1343 return address;
1345 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1347 register struct Lisp_Vector *p = XVECTOR (address);
1348 ptrdiff_t size = p->header.size;
1349 Lisp_Object args[10];
1350 int nargs, i;
1351 char const *format;
1353 if (size == 4 || (size == 5 && !NILP (omit_port)))
1355 format = "%d.%d.%d.%d";
1356 nargs = 4;
1358 else if (size == 5)
1360 format = "%d.%d.%d.%d:%d";
1361 nargs = 5;
1363 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1365 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1366 nargs = 8;
1368 else if (size == 9)
1370 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1371 nargs = 9;
1373 else
1374 return Qnil;
1376 AUTO_STRING (format_obj, format);
1377 args[0] = format_obj;
1379 for (i = 0; i < nargs; i++)
1381 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1382 return Qnil;
1384 if (nargs <= 5 /* IPv4 */
1385 && i < 4 /* host, not port */
1386 && XINT (p->contents[i]) > 255)
1387 return Qnil;
1389 args[i + 1] = p->contents[i];
1392 return Fformat (nargs + 1, args);
1395 if (CONSP (address))
1397 AUTO_STRING (format, "<Family %d>");
1398 return CALLN (Fformat, format, Fcar (address));
1401 return Qnil;
1404 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1405 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1406 (void)
1408 return Fmapcar (Qcdr, Vprocess_alist);
1411 /* Starting asynchronous inferior processes. */
1413 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1414 doc: /* Start a program in a subprocess. Return the process object for it.
1416 This is similar to `start-process', but arguments are specified as
1417 keyword/argument pairs. The following arguments are defined:
1419 :name NAME -- NAME is name for process. It is modified if necessary
1420 to make it unique.
1422 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1423 with the process. Process output goes at end of that buffer, unless
1424 you specify an output stream or filter function to handle the output.
1425 BUFFER may be also nil, meaning that this process is not associated
1426 with any buffer.
1428 :command COMMAND -- COMMAND is a list starting with the program file
1429 name, followed by strings to give to the program as arguments.
1431 :coding CODING -- If CODING is a symbol, it specifies the coding
1432 system used for both reading and writing for this process. If CODING
1433 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1434 ENCODING is used for writing.
1436 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1437 the process is running. If BOOL is not given, query before exiting.
1439 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1440 In the stopped state, a process does not accept incoming data, but you
1441 can send outgoing data. The stopped state is cleared by
1442 `continue-process' and set by `stop-process'.
1444 :connection-type TYPE -- TYPE is control type of device used to
1445 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1446 to use a pty, or nil to use the default specified through
1447 `process-connection-type'.
1449 :filter FILTER -- Install FILTER as the process filter.
1451 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1453 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1454 to the standard error of subprocess. Specifying this implies
1455 `:connection-type' is set to `pipe'.
1457 usage: (make-process &rest ARGS) */)
1458 (ptrdiff_t nargs, Lisp_Object *args)
1460 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1461 Lisp_Object xstderr, stderrproc;
1462 ptrdiff_t count = SPECPDL_INDEX ();
1464 if (nargs == 0)
1465 return Qnil;
1467 /* Save arguments for process-contact and clone-process. */
1468 contact = Flist (nargs, args);
1470 buffer = Fplist_get (contact, QCbuffer);
1471 if (!NILP (buffer))
1472 buffer = Fget_buffer_create (buffer);
1474 /* Make sure that the child will be able to chdir to the current
1475 buffer's current directory, or its unhandled equivalent. We
1476 can't just have the child check for an error when it does the
1477 chdir, since it's in a vfork. */
1478 current_dir = encode_current_directory ();
1480 name = Fplist_get (contact, QCname);
1481 CHECK_STRING (name);
1483 command = Fplist_get (contact, QCcommand);
1484 if (CONSP (command))
1485 program = XCAR (command);
1486 else
1487 program = Qnil;
1489 if (!NILP (program))
1490 CHECK_STRING (program);
1492 stderrproc = Qnil;
1493 xstderr = Fplist_get (contact, QCstderr);
1494 if (PROCESSP (xstderr))
1496 if (!PIPECONN_P (xstderr))
1497 error ("Process is not a pipe process");
1498 stderrproc = xstderr;
1500 else if (!NILP (xstderr))
1502 CHECK_STRING (program);
1503 stderrproc = CALLN (Fmake_pipe_process,
1504 QCname,
1505 concat2 (name, build_string (" stderr")),
1506 QCbuffer,
1507 Fget_buffer_create (xstderr));
1510 proc = make_process (name);
1511 record_unwind_protect (start_process_unwind, proc);
1513 pset_childp (XPROCESS (proc), Qt);
1514 eassert (NILP (XPROCESS (proc)->plist));
1515 pset_type (XPROCESS (proc), Qreal);
1516 pset_buffer (XPROCESS (proc), buffer);
1517 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1518 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1519 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1521 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
1522 XPROCESS (proc)->kill_without_query = 1;
1523 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1524 pset_command (XPROCESS (proc), Qt);
1526 tem = Fplist_get (contact, QCconnection_type);
1527 if (EQ (tem, Qpty))
1528 XPROCESS (proc)->pty_flag = true;
1529 else if (EQ (tem, Qpipe))
1530 XPROCESS (proc)->pty_flag = false;
1531 else if (NILP (tem))
1532 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1533 else
1534 report_file_error ("Unknown connection type", tem);
1536 if (!NILP (stderrproc))
1538 pset_stderrproc (XPROCESS (proc), stderrproc);
1540 XPROCESS (proc)->pty_flag = false;
1543 #ifdef HAVE_GNUTLS
1544 /* AKA GNUTLS_INITSTAGE(proc). */
1545 verify (GNUTLS_STAGE_EMPTY == 0);
1546 eassert (XPROCESS (proc)->gnutls_initstage == GNUTLS_STAGE_EMPTY);
1547 eassert (NILP (XPROCESS (proc)->gnutls_cred_type));
1548 #endif
1550 XPROCESS (proc)->adaptive_read_buffering
1551 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1552 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1554 /* Make the process marker point into the process buffer (if any). */
1555 if (BUFFERP (buffer))
1556 set_marker_both (XPROCESS (proc)->mark, buffer,
1557 BUF_ZV (XBUFFER (buffer)),
1558 BUF_ZV_BYTE (XBUFFER (buffer)));
1560 USE_SAFE_ALLOCA;
1563 /* Decide coding systems for communicating with the process. Here
1564 we don't setup the structure coding_system nor pay attention to
1565 unibyte mode. They are done in create_process. */
1567 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1568 Lisp_Object coding_systems = Qt;
1569 Lisp_Object val, *args2;
1571 tem = Fplist_get (contact, QCcoding);
1572 if (!NILP (tem))
1574 val = tem;
1575 if (CONSP (val))
1576 val = XCAR (val);
1578 else
1579 val = Vcoding_system_for_read;
1580 if (NILP (val))
1582 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1583 Lisp_Object tem2;
1584 SAFE_ALLOCA_LISP (args2, nargs2);
1585 ptrdiff_t i = 0;
1586 args2[i++] = Qstart_process;
1587 args2[i++] = name;
1588 args2[i++] = buffer;
1589 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1590 args2[i++] = XCAR (tem2);
1591 if (!NILP (program))
1592 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1593 if (CONSP (coding_systems))
1594 val = XCAR (coding_systems);
1595 else if (CONSP (Vdefault_process_coding_system))
1596 val = XCAR (Vdefault_process_coding_system);
1598 pset_decode_coding_system (XPROCESS (proc), val);
1600 if (!NILP (tem))
1602 val = tem;
1603 if (CONSP (val))
1604 val = XCDR (val);
1606 else
1607 val = Vcoding_system_for_write;
1608 if (NILP (val))
1610 if (EQ (coding_systems, Qt))
1612 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1613 Lisp_Object tem2;
1614 SAFE_ALLOCA_LISP (args2, nargs2);
1615 ptrdiff_t i = 0;
1616 args2[i++] = Qstart_process;
1617 args2[i++] = name;
1618 args2[i++] = buffer;
1619 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1620 args2[i++] = XCAR (tem2);
1621 if (!NILP (program))
1622 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1624 if (CONSP (coding_systems))
1625 val = XCDR (coding_systems);
1626 else if (CONSP (Vdefault_process_coding_system))
1627 val = XCDR (Vdefault_process_coding_system);
1629 pset_encode_coding_system (XPROCESS (proc), val);
1630 /* Note: At this moment, the above coding system may leave
1631 text-conversion or eol-conversion unspecified. They will be
1632 decided after we read output from the process and decode it by
1633 some coding system, or just before we actually send a text to
1634 the process. */
1638 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1639 eassert (XPROCESS (proc)->decoding_carryover == 0);
1640 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1642 XPROCESS (proc)->inherit_coding_system_flag
1643 = !(NILP (buffer) || !inherit_process_coding_system);
1645 if (!NILP (program))
1647 Lisp_Object program_args = XCDR (command);
1649 /* If program file name is not absolute, search our path for it.
1650 Put the name we will really use in TEM. */
1651 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1652 && !(SCHARS (program) > 1
1653 && IS_DEVICE_SEP (SREF (program, 1))))
1655 tem = Qnil;
1656 openp (Vexec_path, program, Vexec_suffixes, &tem,
1657 make_number (X_OK), false);
1658 if (NILP (tem))
1659 report_file_error ("Searching for program", program);
1660 tem = Fexpand_file_name (tem, Qnil);
1662 else
1664 if (!NILP (Ffile_directory_p (program)))
1665 error ("Specified program for new process is a directory");
1666 tem = program;
1669 /* Remove "/:" from TEM. */
1670 tem = remove_slash_colon (tem);
1672 Lisp_Object arg_encoding = Qnil;
1674 /* Encode the file name and put it in NEW_ARGV.
1675 That's where the child will use it to execute the program. */
1676 tem = list1 (ENCODE_FILE (tem));
1677 ptrdiff_t new_argc = 1;
1679 /* Here we encode arguments by the coding system used for sending
1680 data to the process. We don't support using different coding
1681 systems for encoding arguments and for encoding data sent to the
1682 process. */
1684 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1686 Lisp_Object arg = XCAR (tem2);
1687 CHECK_STRING (arg);
1688 if (STRING_MULTIBYTE (arg))
1690 if (NILP (arg_encoding))
1691 arg_encoding = (complement_process_encoding_system
1692 (XPROCESS (proc)->encode_coding_system));
1693 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1695 tem = Fcons (arg, tem);
1696 new_argc++;
1699 /* Now that everything is encoded we can collect the strings into
1700 NEW_ARGV. */
1701 char **new_argv;
1702 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1703 new_argv[new_argc] = 0;
1705 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1707 new_argv[i] = SSDATA (XCAR (tem));
1708 tem = XCDR (tem);
1711 create_process (proc, new_argv, current_dir);
1713 else
1714 create_pty (proc);
1716 SAFE_FREE ();
1717 return unbind_to (count, proc);
1720 /* If PROC doesn't have its pid set, then an error was signaled and
1721 the process wasn't started successfully, so remove it. */
1722 static void
1723 start_process_unwind (Lisp_Object proc)
1725 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1726 remove_process (proc);
1729 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1731 static void
1732 close_process_fd (int *fd_addr)
1734 int fd = *fd_addr;
1735 if (0 <= fd)
1737 *fd_addr = -1;
1738 emacs_close (fd);
1742 /* Indexes of file descriptors in open_fds. */
1743 enum
1745 /* The pipe from Emacs to its subprocess. */
1746 SUBPROCESS_STDIN,
1747 WRITE_TO_SUBPROCESS,
1749 /* The main pipe from the subprocess to Emacs. */
1750 READ_FROM_SUBPROCESS,
1751 SUBPROCESS_STDOUT,
1753 /* The pipe from the subprocess to Emacs that is closed when the
1754 subprocess execs. */
1755 READ_FROM_EXEC_MONITOR,
1756 EXEC_MONITOR_OUTPUT
1759 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1761 static void
1762 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1764 struct Lisp_Process *p = XPROCESS (process);
1765 int inchannel, outchannel;
1766 pid_t pid;
1767 int vfork_errno;
1768 int forkin, forkout, forkerr = -1;
1769 bool pty_flag = 0;
1770 char pty_name[PTY_NAME_SIZE];
1771 Lisp_Object lisp_pty_name = Qnil;
1772 sigset_t oldset;
1774 inchannel = outchannel = -1;
1776 if (p->pty_flag)
1777 outchannel = inchannel = allocate_pty (pty_name);
1779 if (inchannel >= 0)
1781 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1782 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1783 /* On most USG systems it does not work to open the pty's tty here,
1784 then close it and reopen it in the child. */
1785 /* Don't let this terminal become our controlling terminal
1786 (in case we don't have one). */
1787 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1788 if (forkin < 0)
1789 report_file_error ("Opening pty", Qnil);
1790 p->open_fd[SUBPROCESS_STDIN] = forkin;
1791 #else
1792 forkin = forkout = -1;
1793 #endif /* not USG, or USG_SUBTTY_WORKS */
1794 pty_flag = 1;
1795 lisp_pty_name = build_string (pty_name);
1797 else
1799 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1800 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1801 report_file_error ("Creating pipe", Qnil);
1802 forkin = p->open_fd[SUBPROCESS_STDIN];
1803 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1804 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1805 forkout = p->open_fd[SUBPROCESS_STDOUT];
1807 if (!NILP (p->stderrproc))
1809 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
1811 forkerr = pp->open_fd[SUBPROCESS_STDOUT];
1813 /* Close unnecessary file descriptors. */
1814 close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
1815 close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
1819 #ifndef WINDOWSNT
1820 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1821 report_file_error ("Creating pipe", Qnil);
1822 #endif
1824 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1825 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1827 /* Record this as an active process, with its channels. */
1828 chan_process[inchannel] = process;
1829 p->infd = inchannel;
1830 p->outfd = outchannel;
1832 /* Previously we recorded the tty descriptor used in the subprocess.
1833 It was only used for getting the foreground tty process, so now
1834 we just reopen the device (see emacs_get_tty_pgrp) as this is
1835 more portable (see USG_SUBTTY_WORKS above). */
1837 p->pty_flag = pty_flag;
1838 pset_status (p, Qrun);
1840 if (!EQ (p->command, Qt))
1842 FD_SET (inchannel, &input_wait_mask);
1843 FD_SET (inchannel, &non_keyboard_wait_mask);
1846 if (inchannel > max_process_desc)
1847 max_process_desc = inchannel;
1849 /* This may signal an error. */
1850 setup_process_coding_systems (process);
1852 block_input ();
1853 block_child_signal (&oldset);
1855 #ifndef WINDOWSNT
1856 /* vfork, and prevent local vars from being clobbered by the vfork. */
1857 Lisp_Object volatile current_dir_volatile = current_dir;
1858 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1859 char **volatile new_argv_volatile = new_argv;
1860 int volatile forkin_volatile = forkin;
1861 int volatile forkout_volatile = forkout;
1862 int volatile forkerr_volatile = forkerr;
1863 struct Lisp_Process *p_volatile = p;
1865 pid = vfork ();
1867 current_dir = current_dir_volatile;
1868 lisp_pty_name = lisp_pty_name_volatile;
1869 new_argv = new_argv_volatile;
1870 forkin = forkin_volatile;
1871 forkout = forkout_volatile;
1872 forkerr = forkerr_volatile;
1873 p = p_volatile;
1875 pty_flag = p->pty_flag;
1877 if (pid == 0)
1878 #endif /* not WINDOWSNT */
1880 /* Make the pty be the controlling terminal of the process. */
1881 #ifdef HAVE_PTYS
1882 /* First, disconnect its current controlling terminal. */
1883 /* We tried doing setsid only if pty_flag, but it caused
1884 process_set_signal to fail on SGI when using a pipe. */
1885 setsid ();
1886 /* Make the pty's terminal the controlling terminal. */
1887 if (pty_flag && forkin >= 0)
1889 #ifdef TIOCSCTTY
1890 /* We ignore the return value
1891 because faith@cs.unc.edu says that is necessary on Linux. */
1892 ioctl (forkin, TIOCSCTTY, 0);
1893 #endif
1895 #if defined (LDISC1)
1896 if (pty_flag && forkin >= 0)
1898 struct termios t;
1899 tcgetattr (forkin, &t);
1900 t.c_lflag = LDISC1;
1901 if (tcsetattr (forkin, TCSANOW, &t) < 0)
1902 emacs_perror ("create_process/tcsetattr LDISC1");
1904 #else
1905 #if defined (NTTYDISC) && defined (TIOCSETD)
1906 if (pty_flag && forkin >= 0)
1908 /* Use new line discipline. */
1909 int ldisc = NTTYDISC;
1910 ioctl (forkin, TIOCSETD, &ldisc);
1912 #endif
1913 #endif
1914 #ifdef TIOCNOTTY
1915 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1916 can do TIOCSPGRP only to the process's controlling tty. */
1917 if (pty_flag)
1919 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1920 I can't test it since I don't have 4.3. */
1921 int j = emacs_open (DEV_TTY, O_RDWR, 0);
1922 if (j >= 0)
1924 ioctl (j, TIOCNOTTY, 0);
1925 emacs_close (j);
1928 #endif /* TIOCNOTTY */
1930 #if !defined (DONT_REOPEN_PTY)
1931 /*** There is a suggestion that this ought to be a
1932 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1933 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1934 that system does seem to need this code, even though
1935 both TIOCSCTTY is defined. */
1936 /* Now close the pty (if we had it open) and reopen it.
1937 This makes the pty the controlling terminal of the subprocess. */
1938 if (pty_flag)
1941 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1942 would work? */
1943 if (forkin >= 0)
1944 emacs_close (forkin);
1945 forkout = forkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1947 if (forkin < 0)
1949 emacs_perror (SSDATA (lisp_pty_name));
1950 _exit (EXIT_CANCELED);
1954 #endif /* not DONT_REOPEN_PTY */
1956 #ifdef SETUP_SLAVE_PTY
1957 if (pty_flag)
1959 SETUP_SLAVE_PTY;
1961 #endif /* SETUP_SLAVE_PTY */
1962 #endif /* HAVE_PTYS */
1964 signal (SIGINT, SIG_DFL);
1965 signal (SIGQUIT, SIG_DFL);
1966 #ifdef SIGPROF
1967 signal (SIGPROF, SIG_DFL);
1968 #endif
1970 /* Emacs ignores SIGPIPE, but the child should not. */
1971 signal (SIGPIPE, SIG_DFL);
1973 /* Stop blocking SIGCHLD in the child. */
1974 unblock_child_signal (&oldset);
1976 if (pty_flag)
1977 child_setup_tty (forkout);
1979 if (forkerr < 0)
1980 forkerr = forkout;
1981 #ifdef WINDOWSNT
1982 pid = child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1983 #else /* not WINDOWSNT */
1984 child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1985 #endif /* not WINDOWSNT */
1988 /* Back in the parent process. */
1990 vfork_errno = errno;
1991 p->pid = pid;
1992 if (pid >= 0)
1993 p->alive = 1;
1995 /* Stop blocking in the parent. */
1996 unblock_child_signal (&oldset);
1997 unblock_input ();
1999 if (pid < 0)
2000 report_file_errno ("Doing vfork", Qnil, vfork_errno);
2001 else
2003 /* vfork succeeded. */
2005 /* Close the pipe ends that the child uses, or the child's pty. */
2006 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
2007 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
2009 #ifdef WINDOWSNT
2010 register_child (pid, inchannel);
2011 #endif /* WINDOWSNT */
2013 pset_tty_name (p, lisp_pty_name);
2015 #ifndef WINDOWSNT
2016 /* Wait for child_setup to complete in case that vfork is
2017 actually defined as fork. The descriptor
2018 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2019 of a pipe is closed at the child side either by close-on-exec
2020 on successful execve or the _exit call in child_setup. */
2022 char dummy;
2024 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
2025 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
2026 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
2028 #endif
2029 if (!NILP (p->stderrproc))
2031 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2032 close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
2037 static void
2038 create_pty (Lisp_Object process)
2040 struct Lisp_Process *p = XPROCESS (process);
2041 char pty_name[PTY_NAME_SIZE];
2042 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
2044 if (pty_fd >= 0)
2046 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
2047 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2048 /* On most USG systems it does not work to open the pty's tty here,
2049 then close it and reopen it in the child. */
2050 /* Don't let this terminal become our controlling terminal
2051 (in case we don't have one). */
2052 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2053 if (forkout < 0)
2054 report_file_error ("Opening pty", Qnil);
2055 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2056 #if defined (DONT_REOPEN_PTY)
2057 /* In the case that vfork is defined as fork, the parent process
2058 (Emacs) may send some data before the child process completes
2059 tty options setup. So we setup tty before forking. */
2060 child_setup_tty (forkout);
2061 #endif /* DONT_REOPEN_PTY */
2062 #endif /* not USG, or USG_SUBTTY_WORKS */
2064 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2066 /* Record this as an active process, with its channels.
2067 As a result, child_setup will close Emacs's side of the pipes. */
2068 chan_process[pty_fd] = process;
2069 p->infd = pty_fd;
2070 p->outfd = pty_fd;
2072 /* Previously we recorded the tty descriptor used in the subprocess.
2073 It was only used for getting the foreground tty process, so now
2074 we just reopen the device (see emacs_get_tty_pgrp) as this is
2075 more portable (see USG_SUBTTY_WORKS above). */
2077 p->pty_flag = 1;
2078 pset_status (p, Qrun);
2079 setup_process_coding_systems (process);
2081 FD_SET (pty_fd, &input_wait_mask);
2082 FD_SET (pty_fd, &non_keyboard_wait_mask);
2083 if (pty_fd > max_process_desc)
2084 max_process_desc = pty_fd;
2086 pset_tty_name (p, build_string (pty_name));
2089 p->pid = -2;
2092 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2093 0, MANY, 0,
2094 doc: /* Create and return a bidirectional pipe process.
2096 In Emacs, pipes are represented by process objects, so input and
2097 output work as for subprocesses, and `delete-process' closes a pipe.
2098 However, a pipe process has no process id, it cannot be signaled,
2099 and the status codes are different from normal processes.
2101 Arguments are specified as keyword/argument pairs. The following
2102 arguments are defined:
2104 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2106 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2107 with the process. Process output goes at the end of that buffer,
2108 unless you specify an output stream or filter function to handle the
2109 output. If BUFFER is not given, the value of NAME is used.
2111 :coding CODING -- If CODING is a symbol, it specifies the coding
2112 system used for both reading and writing for this process. If CODING
2113 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2114 ENCODING is used for writing.
2116 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2117 the process is running. If BOOL is not given, query before exiting.
2119 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2120 In the stopped state, a pipe process does not accept incoming data,
2121 but you can send outgoing data. The stopped state is cleared by
2122 `continue-process' and set by `stop-process'.
2124 :filter FILTER -- Install FILTER as the process filter.
2126 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2128 usage: (make-pipe-process &rest ARGS) */)
2129 (ptrdiff_t nargs, Lisp_Object *args)
2131 Lisp_Object proc, contact;
2132 struct Lisp_Process *p;
2133 Lisp_Object name, buffer;
2134 Lisp_Object tem;
2135 ptrdiff_t specpdl_count;
2136 int inchannel, outchannel;
2138 if (nargs == 0)
2139 return Qnil;
2141 contact = Flist (nargs, args);
2143 name = Fplist_get (contact, QCname);
2144 CHECK_STRING (name);
2145 proc = make_process (name);
2146 specpdl_count = SPECPDL_INDEX ();
2147 record_unwind_protect (remove_process, proc);
2148 p = XPROCESS (proc);
2150 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2151 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2152 report_file_error ("Creating pipe", Qnil);
2153 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2154 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2156 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2157 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2159 #ifdef WINDOWSNT
2160 register_aux_fd (inchannel);
2161 #endif
2163 /* Record this as an active process, with its channels. */
2164 chan_process[inchannel] = proc;
2165 p->infd = inchannel;
2166 p->outfd = outchannel;
2168 if (inchannel > max_process_desc)
2169 max_process_desc = inchannel;
2171 buffer = Fplist_get (contact, QCbuffer);
2172 if (NILP (buffer))
2173 buffer = name;
2174 buffer = Fget_buffer_create (buffer);
2175 pset_buffer (p, buffer);
2177 pset_childp (p, contact);
2178 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2179 pset_type (p, Qpipe);
2180 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2181 pset_filter (p, Fplist_get (contact, QCfilter));
2182 eassert (NILP (p->log));
2183 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2184 p->kill_without_query = 1;
2185 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2186 pset_command (p, Qt);
2187 eassert (! p->pty_flag);
2189 if (!EQ (p->command, Qt))
2191 FD_SET (inchannel, &input_wait_mask);
2192 FD_SET (inchannel, &non_keyboard_wait_mask);
2194 p->adaptive_read_buffering
2195 = (NILP (Vprocess_adaptive_read_buffering) ? 0
2196 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2198 /* Make the process marker point into the process buffer (if any). */
2199 if (BUFFERP (buffer))
2200 set_marker_both (p->mark, buffer,
2201 BUF_ZV (XBUFFER (buffer)),
2202 BUF_ZV_BYTE (XBUFFER (buffer)));
2205 /* Setup coding systems for communicating with the network stream. */
2207 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2208 Lisp_Object coding_systems = Qt;
2209 Lisp_Object val;
2211 tem = Fplist_get (contact, QCcoding);
2212 val = Qnil;
2213 if (!NILP (tem))
2215 val = tem;
2216 if (CONSP (val))
2217 val = XCAR (val);
2219 else if (!NILP (Vcoding_system_for_read))
2220 val = Vcoding_system_for_read;
2221 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2222 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2223 /* We dare not decode end-of-line format by setting VAL to
2224 Qraw_text, because the existing Emacs Lisp libraries
2225 assume that they receive bare code including a sequence of
2226 CR LF. */
2227 val = Qnil;
2228 else
2230 if (CONSP (coding_systems))
2231 val = XCAR (coding_systems);
2232 else if (CONSP (Vdefault_process_coding_system))
2233 val = XCAR (Vdefault_process_coding_system);
2234 else
2235 val = Qnil;
2237 pset_decode_coding_system (p, val);
2239 if (!NILP (tem))
2241 val = tem;
2242 if (CONSP (val))
2243 val = XCDR (val);
2245 else if (!NILP (Vcoding_system_for_write))
2246 val = Vcoding_system_for_write;
2247 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2248 val = Qnil;
2249 else
2251 if (CONSP (coding_systems))
2252 val = XCDR (coding_systems);
2253 else if (CONSP (Vdefault_process_coding_system))
2254 val = XCDR (Vdefault_process_coding_system);
2255 else
2256 val = Qnil;
2258 pset_encode_coding_system (p, val);
2260 /* This may signal an error. */
2261 setup_process_coding_systems (proc);
2263 specpdl_ptr = specpdl + specpdl_count;
2265 return proc;
2269 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2270 The address family of sa is not included in the result. */
2272 Lisp_Object
2273 conv_sockaddr_to_lisp (struct sockaddr *sa, ptrdiff_t len)
2275 Lisp_Object address;
2276 ptrdiff_t i;
2277 unsigned char *cp;
2278 struct Lisp_Vector *p;
2280 /* Workaround for a bug in getsockname on BSD: Names bound to
2281 sockets in the UNIX domain are inaccessible; getsockname returns
2282 a zero length name. */
2283 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2284 return empty_unibyte_string;
2286 switch (sa->sa_family)
2288 case AF_INET:
2290 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2291 len = sizeof (sin->sin_addr) + 1;
2292 address = Fmake_vector (make_number (len), Qnil);
2293 p = XVECTOR (address);
2294 p->contents[--len] = make_number (ntohs (sin->sin_port));
2295 cp = (unsigned char *) &sin->sin_addr;
2296 break;
2298 #ifdef AF_INET6
2299 case AF_INET6:
2301 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2302 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2303 len = sizeof (sin6->sin6_addr) / 2 + 1;
2304 address = Fmake_vector (make_number (len), Qnil);
2305 p = XVECTOR (address);
2306 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2307 for (i = 0; i < len; i++)
2308 p->contents[i] = make_number (ntohs (ip6[i]));
2309 return address;
2311 #endif
2312 #ifdef HAVE_LOCAL_SOCKETS
2313 case AF_LOCAL:
2315 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2316 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2317 /* If the first byte is NUL, the name is a Linux abstract
2318 socket name, and the name can contain embedded NULs. If
2319 it's not, we have a NUL-terminated string. Be careful not
2320 to walk past the end of the object looking for the name
2321 terminator, however. */
2322 if (name_length > 0 && sockun->sun_path[0] != '\0')
2324 const char *terminator
2325 = memchr (sockun->sun_path, '\0', name_length);
2327 if (terminator)
2328 name_length = terminator - (const char *) sockun->sun_path;
2331 return make_unibyte_string (sockun->sun_path, name_length);
2333 #endif
2334 default:
2335 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2336 address = Fcons (make_number (sa->sa_family),
2337 Fmake_vector (make_number (len), Qnil));
2338 p = XVECTOR (XCDR (address));
2339 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2340 break;
2343 i = 0;
2344 while (i < len)
2345 p->contents[i++] = make_number (*cp++);
2347 return address;
2350 /* Convert an internal struct addrinfo to a Lisp object. */
2352 static Lisp_Object
2353 conv_addrinfo_to_lisp (struct addrinfo *res)
2355 Lisp_Object protocol = make_number (res->ai_protocol);
2356 eassert (XINT (protocol) == res->ai_protocol);
2357 return Fcons (protocol, conv_sockaddr_to_lisp (res->ai_addr, res->ai_addrlen));
2361 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2363 static ptrdiff_t
2364 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2366 struct Lisp_Vector *p;
2368 if (VECTORP (address))
2370 p = XVECTOR (address);
2371 if (p->header.size == 5)
2373 *familyp = AF_INET;
2374 return sizeof (struct sockaddr_in);
2376 #ifdef AF_INET6
2377 else if (p->header.size == 9)
2379 *familyp = AF_INET6;
2380 return sizeof (struct sockaddr_in6);
2382 #endif
2384 #ifdef HAVE_LOCAL_SOCKETS
2385 else if (STRINGP (address))
2387 *familyp = AF_LOCAL;
2388 return sizeof (struct sockaddr_un);
2390 #endif
2391 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2392 && VECTORP (XCDR (address)))
2394 struct sockaddr *sa;
2395 p = XVECTOR (XCDR (address));
2396 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2397 return 0;
2398 *familyp = XINT (XCAR (address));
2399 return p->header.size + sizeof (sa->sa_family);
2401 return 0;
2404 /* Convert an address object (vector or string) to an internal sockaddr.
2406 The address format has been basically validated by
2407 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2408 it could have come from user data. So if FAMILY is not valid,
2409 we return after zeroing *SA. */
2411 static void
2412 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2414 register struct Lisp_Vector *p;
2415 register unsigned char *cp = NULL;
2416 register int i;
2417 EMACS_INT hostport;
2419 memset (sa, 0, len);
2421 if (VECTORP (address))
2423 p = XVECTOR (address);
2424 if (family == AF_INET)
2426 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2427 len = sizeof (sin->sin_addr) + 1;
2428 hostport = XINT (p->contents[--len]);
2429 sin->sin_port = htons (hostport);
2430 cp = (unsigned char *)&sin->sin_addr;
2431 sa->sa_family = family;
2433 #ifdef AF_INET6
2434 else if (family == AF_INET6)
2436 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2437 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2438 len = sizeof (sin6->sin6_addr) / 2 + 1;
2439 hostport = XINT (p->contents[--len]);
2440 sin6->sin6_port = htons (hostport);
2441 for (i = 0; i < len; i++)
2442 if (INTEGERP (p->contents[i]))
2444 int j = XFASTINT (p->contents[i]) & 0xffff;
2445 ip6[i] = ntohs (j);
2447 sa->sa_family = family;
2448 return;
2450 #endif
2451 else
2452 return;
2454 else if (STRINGP (address))
2456 #ifdef HAVE_LOCAL_SOCKETS
2457 if (family == AF_LOCAL)
2459 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2460 cp = SDATA (address);
2461 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2462 sockun->sun_path[i] = *cp++;
2463 sa->sa_family = family;
2465 #endif
2466 return;
2468 else
2470 p = XVECTOR (XCDR (address));
2471 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2474 for (i = 0; i < len; i++)
2475 if (INTEGERP (p->contents[i]))
2476 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2479 #ifdef DATAGRAM_SOCKETS
2480 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2481 1, 1, 0,
2482 doc: /* Get the current datagram address associated with PROCESS.
2483 If PROCESS is a non-blocking network process that hasn't been fully
2484 set up yet, this function will block until socket setup has completed. */)
2485 (Lisp_Object process)
2487 int channel;
2489 CHECK_PROCESS (process);
2491 if (NETCONN_P (process))
2492 wait_for_socket_fds (process, "process-datagram-address");
2494 if (!DATAGRAM_CONN_P (process))
2495 return Qnil;
2497 channel = XPROCESS (process)->infd;
2498 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2499 datagram_address[channel].len);
2502 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2503 2, 2, 0,
2504 doc: /* Set the datagram address for PROCESS to ADDRESS.
2505 Return nil upon error setting address, ADDRESS otherwise.
2507 If PROCESS is a non-blocking network process that hasn't been fully
2508 set up yet, this function will block until socket setup has completed. */)
2509 (Lisp_Object process, Lisp_Object address)
2511 int channel;
2512 int family;
2513 ptrdiff_t len;
2515 CHECK_PROCESS (process);
2517 if (NETCONN_P (process))
2518 wait_for_socket_fds (process, "set-process-datagram-address");
2520 if (!DATAGRAM_CONN_P (process))
2521 return Qnil;
2523 channel = XPROCESS (process)->infd;
2525 len = get_lisp_to_sockaddr_size (address, &family);
2526 if (len == 0 || datagram_address[channel].len != len)
2527 return Qnil;
2528 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2529 return address;
2531 #endif
2534 static const struct socket_options {
2535 /* The name of this option. Should be lowercase version of option
2536 name without SO_ prefix. */
2537 const char *name;
2538 /* Option level SOL_... */
2539 int optlevel;
2540 /* Option number SO_... */
2541 int optnum;
2542 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2543 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2544 } socket_options[] =
2546 #ifdef SO_BINDTODEVICE
2547 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2548 #endif
2549 #ifdef SO_BROADCAST
2550 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2551 #endif
2552 #ifdef SO_DONTROUTE
2553 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2554 #endif
2555 #ifdef SO_KEEPALIVE
2556 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2557 #endif
2558 #ifdef SO_LINGER
2559 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2560 #endif
2561 #ifdef SO_OOBINLINE
2562 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2563 #endif
2564 #ifdef SO_PRIORITY
2565 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2566 #endif
2567 #ifdef SO_REUSEADDR
2568 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2569 #endif
2570 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2573 /* Set option OPT to value VAL on socket S.
2575 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2576 Signals an error if setting a known option fails.
2579 static int
2580 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2582 char *name;
2583 const struct socket_options *sopt;
2584 int ret = 0;
2586 CHECK_SYMBOL (opt);
2588 name = SSDATA (SYMBOL_NAME (opt));
2589 for (sopt = socket_options; sopt->name; sopt++)
2590 if (strcmp (name, sopt->name) == 0)
2591 break;
2593 switch (sopt->opttype)
2595 case SOPT_BOOL:
2597 int optval;
2598 optval = NILP (val) ? 0 : 1;
2599 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2600 &optval, sizeof (optval));
2601 break;
2604 case SOPT_INT:
2606 int optval;
2607 if (TYPE_RANGED_INTEGERP (int, val))
2608 optval = XINT (val);
2609 else
2610 error ("Bad option value for %s", name);
2611 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2612 &optval, sizeof (optval));
2613 break;
2616 #ifdef SO_BINDTODEVICE
2617 case SOPT_IFNAME:
2619 char devname[IFNAMSIZ + 1];
2621 /* This is broken, at least in the Linux 2.4 kernel.
2622 To unbind, the arg must be a zero integer, not the empty string.
2623 This should work on all systems. KFS. 2003-09-23. */
2624 memset (devname, 0, sizeof devname);
2625 if (STRINGP (val))
2627 char *arg = SSDATA (val);
2628 int len = min (strlen (arg), IFNAMSIZ);
2629 memcpy (devname, arg, len);
2631 else if (!NILP (val))
2632 error ("Bad option value for %s", name);
2633 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2634 devname, IFNAMSIZ);
2635 break;
2637 #endif
2639 #ifdef SO_LINGER
2640 case SOPT_LINGER:
2642 struct linger linger;
2644 linger.l_onoff = 1;
2645 linger.l_linger = 0;
2646 if (TYPE_RANGED_INTEGERP (int, val))
2647 linger.l_linger = XINT (val);
2648 else
2649 linger.l_onoff = NILP (val) ? 0 : 1;
2650 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2651 &linger, sizeof (linger));
2652 break;
2654 #endif
2656 default:
2657 return 0;
2660 if (ret < 0)
2662 int setsockopt_errno = errno;
2663 report_file_errno ("Cannot set network option", list2 (opt, val),
2664 setsockopt_errno);
2667 return (1 << sopt->optbit);
2671 DEFUN ("set-network-process-option",
2672 Fset_network_process_option, Sset_network_process_option,
2673 3, 4, 0,
2674 doc: /* For network process PROCESS set option OPTION to value VALUE.
2675 See `make-network-process' for a list of options and values.
2676 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2677 OPTION is not a supported option, return nil instead; otherwise return t.
2679 If PROCESS is a non-blocking network process that hasn't been fully
2680 set up yet, this function will block until socket setup has completed. */)
2681 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2683 int s;
2684 struct Lisp_Process *p;
2686 CHECK_PROCESS (process);
2687 p = XPROCESS (process);
2688 if (!NETCONN1_P (p))
2689 error ("Process is not a network process");
2691 wait_for_socket_fds (process, "set-network-process-option");
2693 s = p->infd;
2694 if (s < 0)
2695 error ("Process is not running");
2697 if (set_socket_option (s, option, value))
2699 pset_childp (p, Fplist_put (p->childp, option, value));
2700 return Qt;
2703 if (NILP (no_error))
2704 error ("Unknown or unsupported option");
2706 return Qnil;
2710 DEFUN ("serial-process-configure",
2711 Fserial_process_configure,
2712 Sserial_process_configure,
2713 0, MANY, 0,
2714 doc: /* Configure speed, bytesize, etc. of a serial process.
2716 Arguments are specified as keyword/argument pairs. Attributes that
2717 are not given are re-initialized from the process's current
2718 configuration (available via the function `process-contact') or set to
2719 reasonable default values. The following arguments are defined:
2721 :process PROCESS
2722 :name NAME
2723 :buffer BUFFER
2724 :port PORT
2725 -- Any of these arguments can be given to identify the process that is
2726 to be configured. If none of these arguments is given, the current
2727 buffer's process is used.
2729 :speed SPEED -- SPEED is the speed of the serial port in bits per
2730 second, also called baud rate. Any value can be given for SPEED, but
2731 most serial ports work only at a few defined values between 1200 and
2732 115200, with 9600 being the most common value. If SPEED is nil, the
2733 serial port is not configured any further, i.e., all other arguments
2734 are ignored. This may be useful for special serial ports such as
2735 Bluetooth-to-serial converters which can only be configured through AT
2736 commands. A value of nil for SPEED can be used only when passed
2737 through `make-serial-process' or `serial-term'.
2739 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2740 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2742 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2743 `odd' (use odd parity), or the symbol `even' (use even parity). If
2744 PARITY is not given, no parity is used.
2746 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2747 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2748 is not given or nil, 1 stopbit is used.
2750 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2751 flowcontrol to be used, which is either nil (don't use flowcontrol),
2752 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2753 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2754 flowcontrol is used.
2756 `serial-process-configure' is called by `make-serial-process' for the
2757 initial configuration of the serial port.
2759 Examples:
2761 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2763 \(serial-process-configure
2764 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2766 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2768 usage: (serial-process-configure &rest ARGS) */)
2769 (ptrdiff_t nargs, Lisp_Object *args)
2771 struct Lisp_Process *p;
2772 Lisp_Object contact = Qnil;
2773 Lisp_Object proc = Qnil;
2775 contact = Flist (nargs, args);
2777 proc = Fplist_get (contact, QCprocess);
2778 if (NILP (proc))
2779 proc = Fplist_get (contact, QCname);
2780 if (NILP (proc))
2781 proc = Fplist_get (contact, QCbuffer);
2782 if (NILP (proc))
2783 proc = Fplist_get (contact, QCport);
2784 proc = get_process (proc);
2785 p = XPROCESS (proc);
2786 if (!EQ (p->type, Qserial))
2787 error ("Not a serial process");
2789 if (NILP (Fplist_get (p->childp, QCspeed)))
2790 return Qnil;
2792 serial_configure (p, contact);
2793 return Qnil;
2796 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2797 0, MANY, 0,
2798 doc: /* Create and return a serial port process.
2800 In Emacs, serial port connections are represented by process objects,
2801 so input and output work as for subprocesses, and `delete-process'
2802 closes a serial port connection. However, a serial process has no
2803 process id, it cannot be signaled, and the status codes are different
2804 from normal processes.
2806 `make-serial-process' creates a process and a buffer, on which you
2807 probably want to use `process-send-string'. Try \\[serial-term] for
2808 an interactive terminal. See below for examples.
2810 Arguments are specified as keyword/argument pairs. The following
2811 arguments are defined:
2813 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2814 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2815 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2816 the backslashes in strings).
2818 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2819 which this function calls.
2821 :name NAME -- NAME is the name of the process. If NAME is not given,
2822 the value of PORT is used.
2824 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2825 with the process. Process output goes at the end of that buffer,
2826 unless you specify an output stream or filter function to handle the
2827 output. If BUFFER is not given, the value of NAME is used.
2829 :coding CODING -- If CODING is a symbol, it specifies the coding
2830 system used for both reading and writing for this process. If CODING
2831 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2832 ENCODING is used for writing.
2834 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2835 the process is running. If BOOL is not given, query before exiting.
2837 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2838 In the stopped state, a serial process does not accept incoming data,
2839 but you can send outgoing data. The stopped state is cleared by
2840 `continue-process' and set by `stop-process'.
2842 :filter FILTER -- Install FILTER as the process filter.
2844 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2846 :plist PLIST -- Install PLIST as the initial plist of the process.
2848 :bytesize
2849 :parity
2850 :stopbits
2851 :flowcontrol
2852 -- This function calls `serial-process-configure' to handle these
2853 arguments.
2855 The original argument list, possibly modified by later configuration,
2856 is available via the function `process-contact'.
2858 Examples:
2860 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2862 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2864 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2866 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2868 usage: (make-serial-process &rest ARGS) */)
2869 (ptrdiff_t nargs, Lisp_Object *args)
2871 int fd = -1;
2872 Lisp_Object proc, contact, port;
2873 struct Lisp_Process *p;
2874 Lisp_Object name, buffer;
2875 Lisp_Object tem, val;
2876 ptrdiff_t specpdl_count;
2878 if (nargs == 0)
2879 return Qnil;
2881 contact = Flist (nargs, args);
2883 port = Fplist_get (contact, QCport);
2884 if (NILP (port))
2885 error ("No port specified");
2886 CHECK_STRING (port);
2888 if (NILP (Fplist_member (contact, QCspeed)))
2889 error (":speed not specified");
2890 if (!NILP (Fplist_get (contact, QCspeed)))
2891 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2893 name = Fplist_get (contact, QCname);
2894 if (NILP (name))
2895 name = port;
2896 CHECK_STRING (name);
2897 proc = make_process (name);
2898 specpdl_count = SPECPDL_INDEX ();
2899 record_unwind_protect (remove_process, proc);
2900 p = XPROCESS (proc);
2902 fd = serial_open (port);
2903 p->open_fd[SUBPROCESS_STDIN] = fd;
2904 p->infd = fd;
2905 p->outfd = fd;
2906 if (fd > max_process_desc)
2907 max_process_desc = fd;
2908 chan_process[fd] = proc;
2910 buffer = Fplist_get (contact, QCbuffer);
2911 if (NILP (buffer))
2912 buffer = name;
2913 buffer = Fget_buffer_create (buffer);
2914 pset_buffer (p, buffer);
2916 pset_childp (p, contact);
2917 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2918 pset_type (p, Qserial);
2919 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2920 pset_filter (p, Fplist_get (contact, QCfilter));
2921 eassert (NILP (p->log));
2922 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2923 p->kill_without_query = 1;
2924 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2925 pset_command (p, Qt);
2926 eassert (! p->pty_flag);
2928 if (!EQ (p->command, Qt))
2930 FD_SET (fd, &input_wait_mask);
2931 FD_SET (fd, &non_keyboard_wait_mask);
2934 if (BUFFERP (buffer))
2936 set_marker_both (p->mark, buffer,
2937 BUF_ZV (XBUFFER (buffer)),
2938 BUF_ZV_BYTE (XBUFFER (buffer)));
2941 tem = Fplist_member (contact, QCcoding);
2942 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2943 tem = Qnil;
2945 val = Qnil;
2946 if (!NILP (tem))
2948 val = XCAR (XCDR (tem));
2949 if (CONSP (val))
2950 val = XCAR (val);
2952 else if (!NILP (Vcoding_system_for_read))
2953 val = Vcoding_system_for_read;
2954 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2955 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2956 val = Qnil;
2957 pset_decode_coding_system (p, val);
2959 val = Qnil;
2960 if (!NILP (tem))
2962 val = XCAR (XCDR (tem));
2963 if (CONSP (val))
2964 val = XCDR (val);
2966 else if (!NILP (Vcoding_system_for_write))
2967 val = Vcoding_system_for_write;
2968 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2969 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2970 val = Qnil;
2971 pset_encode_coding_system (p, val);
2973 setup_process_coding_systems (proc);
2974 pset_decoding_buf (p, empty_unibyte_string);
2975 eassert (p->decoding_carryover == 0);
2976 pset_encoding_buf (p, empty_unibyte_string);
2977 p->inherit_coding_system_flag
2978 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2980 Fserial_process_configure (nargs, args);
2982 specpdl_ptr = specpdl + specpdl_count;
2984 return proc;
2987 static void
2988 set_network_socket_coding_system (Lisp_Object proc, Lisp_Object host,
2989 Lisp_Object service, Lisp_Object name)
2991 Lisp_Object tem;
2992 struct Lisp_Process *p = XPROCESS (proc);
2993 Lisp_Object contact = p->childp;
2994 Lisp_Object coding_systems = Qt;
2995 Lisp_Object val;
2997 tem = Fplist_member (contact, QCcoding);
2998 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2999 tem = Qnil; /* No error message (too late!). */
3001 /* Setup coding systems for communicating with the network stream. */
3002 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3004 if (!NILP (tem))
3006 val = XCAR (XCDR (tem));
3007 if (CONSP (val))
3008 val = XCAR (val);
3010 else if (!NILP (Vcoding_system_for_read))
3011 val = Vcoding_system_for_read;
3012 else if ((!NILP (p->buffer)
3013 && NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
3014 || (NILP (p->buffer)
3015 && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3016 /* We dare not decode end-of-line format by setting VAL to
3017 Qraw_text, because the existing Emacs Lisp libraries
3018 assume that they receive bare code including a sequence of
3019 CR LF. */
3020 val = Qnil;
3021 else
3023 if (NILP (host) || NILP (service))
3024 coding_systems = Qnil;
3025 else
3026 coding_systems = CALLN (Ffind_operation_coding_system,
3027 Qopen_network_stream, name, p->buffer,
3028 host, service);
3029 if (CONSP (coding_systems))
3030 val = XCAR (coding_systems);
3031 else if (CONSP (Vdefault_process_coding_system))
3032 val = XCAR (Vdefault_process_coding_system);
3033 else
3034 val = Qnil;
3036 pset_decode_coding_system (p, val);
3038 if (!NILP (tem))
3040 val = XCAR (XCDR (tem));
3041 if (CONSP (val))
3042 val = XCDR (val);
3044 else if (!NILP (Vcoding_system_for_write))
3045 val = Vcoding_system_for_write;
3046 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3047 val = Qnil;
3048 else
3050 if (EQ (coding_systems, Qt))
3052 if (NILP (host) || NILP (service))
3053 coding_systems = Qnil;
3054 else
3055 coding_systems = CALLN (Ffind_operation_coding_system,
3056 Qopen_network_stream, name, p->buffer,
3057 host, service);
3059 if (CONSP (coding_systems))
3060 val = XCDR (coding_systems);
3061 else if (CONSP (Vdefault_process_coding_system))
3062 val = XCDR (Vdefault_process_coding_system);
3063 else
3064 val = Qnil;
3066 pset_encode_coding_system (p, val);
3068 pset_decoding_buf (p, empty_unibyte_string);
3069 p->decoding_carryover = 0;
3070 pset_encoding_buf (p, empty_unibyte_string);
3072 p->inherit_coding_system_flag
3073 = !(!NILP (tem) || NILP (p->buffer) || !inherit_process_coding_system);
3076 #ifdef HAVE_GNUTLS
3077 static void
3078 finish_after_tls_connection (Lisp_Object proc)
3080 struct Lisp_Process *p = XPROCESS (proc);
3081 Lisp_Object contact = p->childp;
3082 Lisp_Object result = Qt;
3084 if (!NILP (Ffboundp (Qnsm_verify_connection)))
3085 result = call3 (Qnsm_verify_connection,
3086 proc,
3087 Fplist_get (contact, QChost),
3088 Fplist_get (contact, QCservice));
3090 if (NILP (result))
3092 pset_status (p, list2 (Qfailed,
3093 build_string ("The Network Security Manager stopped the connections")));
3094 deactivate_process (proc);
3096 else
3098 /* If we cleared the connection wait mask before we did
3099 the TLS setup, then we have to say that the process
3100 is finally "open" here. */
3101 if (! FD_ISSET (p->outfd, &connect_wait_mask))
3103 pset_status (p, Qrun);
3104 /* Execute the sentinel here. If we had relied on
3105 status_notify to do it later, it will read input
3106 from the process before calling the sentinel. */
3107 exec_sentinel (proc, build_string ("open\n"));
3111 #endif
3113 static void
3114 connect_network_socket (Lisp_Object proc, Lisp_Object addrinfos,
3115 Lisp_Object use_external_socket_p)
3117 ptrdiff_t count = SPECPDL_INDEX ();
3118 int s = -1, outch, inch;
3119 int xerrno = 0;
3120 int family;
3121 struct sockaddr *sa = NULL;
3122 int ret;
3123 ptrdiff_t addrlen;
3124 struct Lisp_Process *p = XPROCESS (proc);
3125 Lisp_Object contact = p->childp;
3126 int optbits = 0;
3127 int socket_to_use = -1;
3129 if (!NILP (use_external_socket_p))
3131 socket_to_use = external_sock_fd;
3133 /* Ensure we don't consume the external socket twice. */
3134 external_sock_fd = -1;
3137 /* Do this in case we never enter the while-loop below. */
3138 s = -1;
3140 while (!NILP (addrinfos))
3142 Lisp_Object addrinfo = XCAR (addrinfos);
3143 addrinfos = XCDR (addrinfos);
3144 int protocol = XINT (XCAR (addrinfo));
3145 Lisp_Object ip_address = XCDR (addrinfo);
3147 #ifdef WINDOWSNT
3148 retry_connect:
3149 #endif
3151 addrlen = get_lisp_to_sockaddr_size (ip_address, &family);
3152 if (sa)
3153 free (sa);
3154 sa = xmalloc (addrlen);
3155 conv_lisp_to_sockaddr (family, ip_address, sa, addrlen);
3157 s = socket_to_use;
3158 if (s < 0)
3160 int socktype = p->socktype | SOCK_CLOEXEC;
3161 if (p->is_non_blocking_client)
3162 socktype |= SOCK_NONBLOCK;
3163 s = socket (family, socktype, protocol);
3164 if (s < 0)
3166 xerrno = errno;
3167 continue;
3171 if (p->is_non_blocking_client && ! (SOCK_NONBLOCK && socket_to_use < 0))
3173 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3174 if (ret < 0)
3176 xerrno = errno;
3177 emacs_close (s);
3178 s = -1;
3179 if (0 <= socket_to_use)
3180 break;
3181 continue;
3185 #ifdef DATAGRAM_SOCKETS
3186 if (!p->is_server && p->socktype == SOCK_DGRAM)
3187 break;
3188 #endif /* DATAGRAM_SOCKETS */
3190 /* Make us close S if quit. */
3191 record_unwind_protect_int (close_file_unwind, s);
3193 /* Parse network options in the arg list. We simply ignore anything
3194 which isn't a known option (including other keywords). An error
3195 is signaled if setting a known option fails. */
3197 Lisp_Object params = contact, key, val;
3199 while (!NILP (params))
3201 key = XCAR (params);
3202 params = XCDR (params);
3203 val = XCAR (params);
3204 params = XCDR (params);
3205 optbits |= set_socket_option (s, key, val);
3209 if (p->is_server)
3211 /* Configure as a server socket. */
3213 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3214 explicit :reuseaddr key to override this. */
3215 #ifdef HAVE_LOCAL_SOCKETS
3216 if (family != AF_LOCAL)
3217 #endif
3218 if (!(optbits & (1 << OPIX_REUSEADDR)))
3220 int optval = 1;
3221 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3222 report_file_error ("Cannot set reuse option on server socket", Qnil);
3225 /* If passed a socket descriptor, it should be already bound. */
3226 if (socket_to_use < 0 && bind (s, sa, addrlen) != 0)
3227 report_file_error ("Cannot bind server socket", Qnil);
3229 #ifdef HAVE_GETSOCKNAME
3230 if (p->port == 0)
3232 struct sockaddr_in sa1;
3233 socklen_t len1 = sizeof (sa1);
3234 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3236 Lisp_Object service;
3237 service = make_number (ntohs (sa1.sin_port));
3238 contact = Fplist_put (contact, QCservice, service);
3239 /* Save the port number so that we can stash it in
3240 the process object later. */
3241 ((struct sockaddr_in *)sa)->sin_port = sa1.sin_port;
3244 #endif
3246 if (p->socktype != SOCK_DGRAM && listen (s, p->backlog))
3247 report_file_error ("Cannot listen on server socket", Qnil);
3249 break;
3252 immediate_quit = 1;
3253 QUIT;
3255 ret = connect (s, sa, addrlen);
3256 xerrno = errno;
3258 if (ret == 0 || xerrno == EISCONN)
3260 /* The unwind-protect will be discarded afterwards.
3261 Likewise for immediate_quit. */
3262 break;
3265 if (p->is_non_blocking_client && xerrno == EINPROGRESS)
3266 break;
3268 #ifndef WINDOWSNT
3269 if (xerrno == EINTR)
3271 /* Unlike most other syscalls connect() cannot be called
3272 again. (That would return EALREADY.) The proper way to
3273 wait for completion is pselect(). */
3274 int sc;
3275 socklen_t len;
3276 fd_set fdset;
3277 retry_select:
3278 FD_ZERO (&fdset);
3279 FD_SET (s, &fdset);
3280 QUIT;
3281 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3282 if (sc == -1)
3284 if (errno == EINTR)
3285 goto retry_select;
3286 else
3287 report_file_error ("Failed select", Qnil);
3289 eassert (sc > 0);
3291 len = sizeof xerrno;
3292 eassert (FD_ISSET (s, &fdset));
3293 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3294 report_file_error ("Failed getsockopt", Qnil);
3295 if (xerrno == 0)
3296 break;
3297 if (NILP (addrinfos))
3298 report_file_errno ("Failed connect", Qnil, xerrno);
3300 #endif /* !WINDOWSNT */
3302 immediate_quit = 0;
3304 /* Discard the unwind protect closing S. */
3305 specpdl_ptr = specpdl + count;
3306 emacs_close (s);
3307 s = -1;
3308 if (0 <= socket_to_use)
3309 break;
3311 #ifdef WINDOWSNT
3312 if (xerrno == EINTR)
3313 goto retry_connect;
3314 #endif
3317 if (s >= 0)
3319 #ifdef DATAGRAM_SOCKETS
3320 if (p->socktype == SOCK_DGRAM)
3322 if (datagram_address[s].sa)
3323 emacs_abort ();
3325 datagram_address[s].sa = xmalloc (addrlen);
3326 datagram_address[s].len = addrlen;
3327 if (p->is_server)
3329 Lisp_Object remote;
3330 memset (datagram_address[s].sa, 0, addrlen);
3331 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3333 int rfamily;
3334 ptrdiff_t rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3335 if (rlen != 0 && rfamily == family
3336 && rlen == addrlen)
3337 conv_lisp_to_sockaddr (rfamily, remote,
3338 datagram_address[s].sa, rlen);
3341 else
3342 memcpy (datagram_address[s].sa, sa, addrlen);
3344 #endif
3346 contact = Fplist_put (contact, p->is_server? QClocal: QCremote,
3347 conv_sockaddr_to_lisp (sa, addrlen));
3348 #ifdef HAVE_GETSOCKNAME
3349 if (!p->is_server)
3351 struct sockaddr_in sa1;
3352 socklen_t len1 = sizeof (sa1);
3353 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3354 contact = Fplist_put (contact, QClocal,
3355 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3357 #endif
3360 immediate_quit = 0;
3362 if (s < 0)
3364 /* If non-blocking got this far - and failed - assume non-blocking is
3365 not supported after all. This is probably a wrong assumption, but
3366 the normal blocking calls to open-network-stream handles this error
3367 better. */
3368 if (p->is_non_blocking_client)
3369 return;
3371 report_file_errno ((p->is_server
3372 ? "make server process failed"
3373 : "make client process failed"),
3374 contact, xerrno);
3377 inch = s;
3378 outch = s;
3380 chan_process[inch] = proc;
3382 fcntl (inch, F_SETFL, O_NONBLOCK);
3384 p = XPROCESS (proc);
3385 p->open_fd[SUBPROCESS_STDIN] = inch;
3386 p->infd = inch;
3387 p->outfd = outch;
3389 /* Discard the unwind protect for closing S, if any. */
3390 specpdl_ptr = specpdl + count;
3392 if (p->is_server && p->socktype != SOCK_DGRAM)
3393 pset_status (p, Qlisten);
3395 /* Make the process marker point into the process buffer (if any). */
3396 if (BUFFERP (p->buffer))
3397 set_marker_both (p->mark, p->buffer,
3398 BUF_ZV (XBUFFER (p->buffer)),
3399 BUF_ZV_BYTE (XBUFFER (p->buffer)));
3401 if (p->is_non_blocking_client)
3403 /* We may get here if connect did succeed immediately. However,
3404 in that case, we still need to signal this like a non-blocking
3405 connection. */
3406 if (! (connecting_status (p->status)
3407 && EQ (XCDR (p->status), addrinfos)))
3408 pset_status (p, Fcons (Qconnect, addrinfos));
3409 if (!FD_ISSET (inch, &connect_wait_mask))
3411 FD_SET (inch, &connect_wait_mask);
3412 FD_SET (inch, &write_mask);
3413 num_pending_connects++;
3416 else
3417 /* A server may have a client filter setting of Qt, but it must
3418 still listen for incoming connects unless it is stopped. */
3419 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3420 || (EQ (p->status, Qlisten) && NILP (p->command)))
3422 FD_SET (inch, &input_wait_mask);
3423 FD_SET (inch, &non_keyboard_wait_mask);
3426 if (inch > max_process_desc)
3427 max_process_desc = inch;
3429 /* Set up the masks based on the process filter. */
3430 set_process_filter_masks (p);
3432 setup_process_coding_systems (proc);
3434 #ifdef HAVE_GNUTLS
3435 /* Continue the asynchronous connection. */
3436 if (!NILP (p->gnutls_boot_parameters))
3438 Lisp_Object boot, params = p->gnutls_boot_parameters;
3440 boot = Fgnutls_boot (proc, XCAR (params), XCDR (params));
3441 p->gnutls_boot_parameters = Qnil;
3443 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
3444 /* Run sentinels, etc. */
3445 finish_after_tls_connection (proc);
3446 else if (p->gnutls_initstage != GNUTLS_STAGE_HANDSHAKE_TRIED)
3448 deactivate_process (proc);
3449 if (NILP (boot))
3450 pset_status (p, list2 (Qfailed,
3451 build_string ("TLS negotiation failed")));
3452 else
3453 pset_status (p, list2 (Qfailed, boot));
3456 #endif
3460 /* Create a network stream/datagram client/server process. Treated
3461 exactly like a normal process when reading and writing. Primary
3462 differences are in status display and process deletion. A network
3463 connection has no PID; you cannot signal it. All you can do is
3464 stop/continue it and deactivate/close it via delete-process. */
3466 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
3467 0, MANY, 0,
3468 doc: /* Create and return a network server or client process.
3470 In Emacs, network connections are represented by process objects, so
3471 input and output work as for subprocesses and `delete-process' closes
3472 a network connection. However, a network process has no process id,
3473 it cannot be signaled, and the status codes are different from normal
3474 processes.
3476 Arguments are specified as keyword/argument pairs. The following
3477 arguments are defined:
3479 :name NAME -- NAME is name for process. It is modified if necessary
3480 to make it unique.
3482 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3483 with the process. Process output goes at end of that buffer, unless
3484 you specify an output stream or filter function to handle the output.
3485 BUFFER may be also nil, meaning that this process is not associated
3486 with any buffer.
3488 :host HOST -- HOST is name of the host to connect to, or its IP
3489 address. The symbol `local' specifies the local host. If specified
3490 for a server process, it must be a valid name or address for the local
3491 host, and only clients connecting to that address will be accepted.
3493 :service SERVICE -- SERVICE is name of the service desired, or an
3494 integer specifying a port number to connect to. If SERVICE is t,
3495 a random port number is selected for the server. A port number can
3496 be specified as an integer string, e.g., "80", as well as an integer.
3498 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3499 stream type connection, `datagram' creates a datagram type connection,
3500 `seqpacket' creates a reliable datagram connection.
3502 :family FAMILY -- FAMILY is the address (and protocol) family for the
3503 service specified by HOST and SERVICE. The default (nil) is to use
3504 whatever address family (IPv4 or IPv6) that is defined for the host
3505 and port number specified by HOST and SERVICE. Other address families
3506 supported are:
3507 local -- for a local (i.e. UNIX) address specified by SERVICE.
3508 ipv4 -- use IPv4 address family only.
3509 ipv6 -- use IPv6 address family only.
3511 :local ADDRESS -- ADDRESS is the local address used for the connection.
3512 This parameter is ignored when opening a client process. When specified
3513 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3515 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3516 connection. This parameter is ignored when opening a stream server
3517 process. For a datagram server process, it specifies the initial
3518 setting of the remote datagram address. When specified for a client
3519 process, the FAMILY, HOST, and SERVICE args are ignored.
3521 The format of ADDRESS depends on the address family:
3522 - An IPv4 address is represented as an vector of integers [A B C D P]
3523 corresponding to numeric IP address A.B.C.D and port number P.
3524 - A local address is represented as a string with the address in the
3525 local address space.
3526 - An "unsupported family" address is represented by a cons (F . AV)
3527 where F is the family number and AV is a vector containing the socket
3528 address data with one element per address data byte. Do not rely on
3529 this format in portable code, as it may depend on implementation
3530 defined constants, data sizes, and data structure alignment.
3532 :coding CODING -- If CODING is a symbol, it specifies the coding
3533 system used for both reading and writing for this process. If CODING
3534 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3535 ENCODING is used for writing.
3537 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3538 process, return without waiting for the connection to complete;
3539 instead, the sentinel function will be called with second arg matching
3540 "open" (if successful) or "failed" when the connect completes.
3541 Default is to use a blocking connect (i.e. wait) for stream type
3542 connections.
3544 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3545 running when Emacs is exited.
3547 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3548 In the stopped state, a server process does not accept new
3549 connections, and a client process does not handle incoming traffic.
3550 The stopped state is cleared by `continue-process' and set by
3551 `stop-process'.
3553 :filter FILTER -- Install FILTER as the process filter.
3555 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3556 process filter are multibyte, otherwise they are unibyte.
3557 If this keyword is not specified, the strings are multibyte if
3558 the default value of `enable-multibyte-characters' is non-nil.
3560 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3562 :log LOG -- Install LOG as the server process log function. This
3563 function is called when the server accepts a network connection from a
3564 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3565 is the server process, CLIENT is the new process for the connection,
3566 and MESSAGE is a string.
3568 :plist PLIST -- Install PLIST as the new process's initial plist.
3570 :tls-parameters LIST -- is a list that should be supplied if you're
3571 opening a TLS connection. The first element is the TLS type (either
3572 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3573 be a keyword list accepted by gnutls-boot (as returned by
3574 `gnutls-boot-parameters').
3576 :server QLEN -- if QLEN is non-nil, create a server process for the
3577 specified FAMILY, SERVICE, and connection type (stream or datagram).
3578 If QLEN is an integer, it is used as the max. length of the server's
3579 pending connection queue (also known as the backlog); the default
3580 queue length is 5. Default is to create a client process.
3582 The following network options can be specified for this connection:
3584 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3585 :dontroute BOOL -- Only send to directly connected hosts.
3586 :keepalive BOOL -- Send keep-alive messages on network stream.
3587 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3588 :oobinline BOOL -- Place out-of-band data in receive data stream.
3589 :priority INT -- Set protocol defined priority for sent packets.
3590 :reuseaddr BOOL -- Allow reusing a recently used local address
3591 (this is allowed by default for a server process).
3592 :bindtodevice NAME -- bind to interface NAME. Using this may require
3593 special privileges on some systems.
3594 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3595 been passed to Emacs. If Emacs wasn't
3596 passed a socket, this option is silently
3597 ignored.
3600 Consult the relevant system programmer's manual pages for more
3601 information on using these options.
3604 A server process will listen for and accept connections from clients.
3605 When a client connection is accepted, a new network process is created
3606 for the connection with the following parameters:
3608 - The client's process name is constructed by concatenating the server
3609 process's NAME and a client identification string.
3610 - If the FILTER argument is non-nil, the client process will not get a
3611 separate process buffer; otherwise, the client's process buffer is a newly
3612 created buffer named after the server process's BUFFER name or process
3613 NAME concatenated with the client identification string.
3614 - The connection type and the process filter and sentinel parameters are
3615 inherited from the server process's TYPE, FILTER and SENTINEL.
3616 - The client process's contact info is set according to the client's
3617 addressing information (typically an IP address and a port number).
3618 - The client process's plist is initialized from the server's plist.
3620 Notice that the FILTER and SENTINEL args are never used directly by
3621 the server process. Also, the BUFFER argument is not used directly by
3622 the server process, but via the optional :log function, accepted (and
3623 failed) connections may be logged in the server process's buffer.
3625 The original argument list, modified with the actual connection
3626 information, is available via the `process-contact' function.
3628 usage: (make-network-process &rest ARGS) */)
3629 (ptrdiff_t nargs, Lisp_Object *args)
3631 Lisp_Object proc;
3632 Lisp_Object contact;
3633 struct Lisp_Process *p;
3634 const char *portstring;
3635 ptrdiff_t portstringlen ATTRIBUTE_UNUSED;
3636 char portbuf[INT_BUFSIZE_BOUND (EMACS_INT)];
3637 #ifdef HAVE_LOCAL_SOCKETS
3638 struct sockaddr_un address_un;
3639 #endif
3640 EMACS_INT port = 0;
3641 Lisp_Object tem;
3642 Lisp_Object name, buffer, host, service, address;
3643 Lisp_Object filter, sentinel, use_external_socket_p;
3644 Lisp_Object addrinfos = Qnil;
3645 int socktype;
3646 int family = -1;
3647 enum { any_protocol = 0 };
3648 #ifdef HAVE_GETADDRINFO_A
3649 struct gaicb *dns_request = NULL;
3650 #endif
3651 ptrdiff_t count = SPECPDL_INDEX ();
3653 if (nargs == 0)
3654 return Qnil;
3656 /* Save arguments for process-contact and clone-process. */
3657 contact = Flist (nargs, args);
3659 #ifdef WINDOWSNT
3660 /* Ensure socket support is loaded if available. */
3661 init_winsock (TRUE);
3662 #endif
3664 /* :type TYPE (nil: stream, datagram */
3665 tem = Fplist_get (contact, QCtype);
3666 if (NILP (tem))
3667 socktype = SOCK_STREAM;
3668 #ifdef DATAGRAM_SOCKETS
3669 else if (EQ (tem, Qdatagram))
3670 socktype = SOCK_DGRAM;
3671 #endif
3672 #ifdef HAVE_SEQPACKET
3673 else if (EQ (tem, Qseqpacket))
3674 socktype = SOCK_SEQPACKET;
3675 #endif
3676 else
3677 error ("Unsupported connection type");
3679 name = Fplist_get (contact, QCname);
3680 buffer = Fplist_get (contact, QCbuffer);
3681 filter = Fplist_get (contact, QCfilter);
3682 sentinel = Fplist_get (contact, QCsentinel);
3683 use_external_socket_p = Fplist_get (contact, QCuse_external_socket);
3685 CHECK_STRING (name);
3687 /* :local ADDRESS or :remote ADDRESS */
3688 tem = Fplist_get (contact, QCserver);
3689 if (NILP (tem))
3690 address = Fplist_get (contact, QCremote);
3691 else
3692 address = Fplist_get (contact, QClocal);
3693 if (!NILP (address))
3695 host = service = Qnil;
3697 if (!get_lisp_to_sockaddr_size (address, &family))
3698 error ("Malformed :address");
3700 addrinfos = list1 (Fcons (make_number (any_protocol), address));
3701 goto open_socket;
3704 /* :family FAMILY -- nil (for Inet), local, or integer. */
3705 tem = Fplist_get (contact, QCfamily);
3706 if (NILP (tem))
3708 #ifdef AF_INET6
3709 family = AF_UNSPEC;
3710 #else
3711 family = AF_INET;
3712 #endif
3714 #ifdef HAVE_LOCAL_SOCKETS
3715 else if (EQ (tem, Qlocal))
3716 family = AF_LOCAL;
3717 #endif
3718 #ifdef AF_INET6
3719 else if (EQ (tem, Qipv6))
3720 family = AF_INET6;
3721 #endif
3722 else if (EQ (tem, Qipv4))
3723 family = AF_INET;
3724 else if (TYPE_RANGED_INTEGERP (int, tem))
3725 family = XINT (tem);
3726 else
3727 error ("Unknown address family");
3729 /* :service SERVICE -- string, integer (port number), or t (random port). */
3730 service = Fplist_get (contact, QCservice);
3732 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3733 host = Fplist_get (contact, QChost);
3734 if (NILP (host))
3736 /* The "connection" function gets it bind info from the address we're
3737 given, so use this dummy address if nothing is specified. */
3738 #ifdef HAVE_LOCAL_SOCKETS
3739 if (family != AF_LOCAL)
3740 #endif
3741 host = build_string ("127.0.0.1");
3743 else
3745 if (EQ (host, Qlocal))
3746 /* Depending on setup, "localhost" may map to different IPv4 and/or
3747 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3748 host = build_string ("127.0.0.1");
3749 CHECK_STRING (host);
3752 #ifdef HAVE_LOCAL_SOCKETS
3753 if (family == AF_LOCAL)
3755 if (!NILP (host))
3757 message (":family local ignores the :host property");
3758 contact = Fplist_put (contact, QChost, Qnil);
3759 host = Qnil;
3761 CHECK_STRING (service);
3762 if (sizeof address_un.sun_path <= SBYTES (service))
3763 error ("Service name too long");
3764 addrinfos = list1 (Fcons (make_number (any_protocol), service));
3765 goto open_socket;
3767 #endif
3769 /* Slow down polling to every ten seconds.
3770 Some kernels have a bug which causes retrying connect to fail
3771 after a connect. Polling can interfere with gethostbyname too. */
3772 #ifdef POLL_FOR_INPUT
3773 if (socktype != SOCK_DGRAM)
3775 record_unwind_protect_void (run_all_atimers);
3776 bind_polling_period (10);
3778 #endif
3780 if (!NILP (host))
3782 /* SERVICE can either be a string or int.
3783 Convert to a C string for later use by getaddrinfo. */
3784 if (EQ (service, Qt))
3786 portstring = "0";
3787 portstringlen = 1;
3789 else if (INTEGERP (service))
3791 portstring = portbuf;
3792 portstringlen = sprintf (portbuf, "%"pI"d", XINT (service));
3794 else
3796 CHECK_STRING (service);
3797 portstring = SSDATA (service);
3798 portstringlen = SBYTES (service);
3802 #ifdef HAVE_GETADDRINFO_A
3803 if (!NILP (host) && !NILP (Fplist_get (contact, QCnowait)))
3805 ptrdiff_t hostlen = SBYTES (host);
3806 struct req
3808 struct gaicb gaicb;
3809 struct addrinfo hints;
3810 char str[FLEXIBLE_ARRAY_MEMBER];
3811 } *req = xmalloc (FLEXSIZEOF (struct req, str,
3812 hostlen + 1 + portstringlen + 1));
3813 dns_request = &req->gaicb;
3814 dns_request->ar_name = req->str;
3815 dns_request->ar_service = req->str + hostlen + 1;
3816 dns_request->ar_request = &req->hints;
3817 dns_request->ar_result = NULL;
3818 memset (&req->hints, 0, sizeof req->hints);
3819 req->hints.ai_family = family;
3820 req->hints.ai_socktype = socktype;
3821 strcpy (req->str, SSDATA (host));
3822 strcpy (req->str + hostlen + 1, portstring);
3824 int ret = getaddrinfo_a (GAI_NOWAIT, &dns_request, 1, NULL);
3825 if (ret)
3826 error ("%s/%s getaddrinfo_a error %d", SSDATA (host), portstring, ret);
3828 goto open_socket;
3830 #endif /* HAVE_GETADDRINFO_A */
3832 /* If we have a host, use getaddrinfo to resolve both host and service.
3833 Otherwise, use getservbyname to lookup the service. */
3835 if (!NILP (host))
3837 struct addrinfo *res, *lres;
3838 int ret;
3840 immediate_quit = 1;
3841 QUIT;
3843 struct addrinfo hints;
3844 memset (&hints, 0, sizeof hints);
3845 hints.ai_family = family;
3846 hints.ai_socktype = socktype;
3848 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3849 if (ret)
3850 #ifdef HAVE_GAI_STRERROR
3852 synchronize_system_messages_locale ();
3853 char const *str = gai_strerror (ret);
3854 if (! NILP (Vlocale_coding_system))
3855 str = SSDATA (code_convert_string_norecord
3856 (build_string (str), Vlocale_coding_system, 0));
3857 error ("%s/%s %s", SSDATA (host), portstring, str);
3859 #else
3860 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3861 #endif
3862 immediate_quit = 0;
3864 for (lres = res; lres; lres = lres->ai_next)
3865 addrinfos = Fcons (conv_addrinfo_to_lisp (lres), addrinfos);
3867 addrinfos = Fnreverse (addrinfos);
3869 freeaddrinfo (res);
3871 goto open_socket;
3874 /* No hostname has been specified (e.g., a local server process). */
3876 if (EQ (service, Qt))
3877 port = 0;
3878 else if (INTEGERP (service))
3879 port = XINT (service);
3880 else
3882 CHECK_STRING (service);
3884 port = -1;
3885 if (SBYTES (service) != 0)
3887 /* Allow the service to be a string containing the port number,
3888 because that's allowed if you have getaddrbyname. */
3889 char *service_end;
3890 long int lport = strtol (SSDATA (service), &service_end, 10);
3891 if (service_end == SSDATA (service) + SBYTES (service))
3892 port = lport;
3893 else
3895 struct servent *svc_info
3896 = getservbyname (SSDATA (service),
3897 socktype == SOCK_DGRAM ? "udp" : "tcp");
3898 if (svc_info)
3899 port = ntohs (svc_info->s_port);
3904 if (! (0 <= port && port < 1 << 16))
3906 AUTO_STRING (unknown_service, "Unknown service: %s");
3907 xsignal1 (Qerror, CALLN (Fformat, unknown_service, service));
3910 open_socket:
3912 if (!NILP (buffer))
3913 buffer = Fget_buffer_create (buffer);
3915 /* Unwind bind_polling_period. */
3916 unbind_to (count, Qnil);
3918 proc = make_process (name);
3919 record_unwind_protect (remove_process, proc);
3920 p = XPROCESS (proc);
3921 pset_childp (p, contact);
3922 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3923 pset_type (p, Qnetwork);
3925 pset_buffer (p, buffer);
3926 pset_sentinel (p, sentinel);
3927 pset_filter (p, filter);
3928 pset_log (p, Fplist_get (contact, QClog));
3929 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3930 p->kill_without_query = 1;
3931 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3932 pset_command (p, Qt);
3933 eassert (p->pid == 0);
3934 p->backlog = 5;
3935 eassert (! p->is_non_blocking_client);
3936 eassert (! p->is_server);
3937 p->port = port;
3938 p->socktype = socktype;
3939 #ifdef HAVE_GETADDRINFO_A
3940 eassert (! p->dns_request);
3941 #endif
3942 #ifdef HAVE_GNUTLS
3943 tem = Fplist_get (contact, QCtls_parameters);
3944 CHECK_LIST (tem);
3945 p->gnutls_boot_parameters = tem;
3946 #endif
3948 set_network_socket_coding_system (proc, host, service, name);
3950 /* :server BOOL */
3951 tem = Fplist_get (contact, QCserver);
3952 if (!NILP (tem))
3954 /* Don't support network sockets when non-blocking mode is
3955 not available, since a blocked Emacs is not useful. */
3956 p->is_server = true;
3957 if (TYPE_RANGED_INTEGERP (int, tem))
3958 p->backlog = XINT (tem);
3961 /* :nowait BOOL */
3962 if (!p->is_server && socktype != SOCK_DGRAM
3963 && !NILP (Fplist_get (contact, QCnowait)))
3964 p->is_non_blocking_client = true;
3966 bool postpone_connection = false;
3967 #ifdef HAVE_GETADDRINFO_A
3968 /* With async address resolution, the list of addresses is empty, so
3969 postpone connecting to the server. */
3970 if (!p->is_server && NILP (addrinfos))
3972 p->dns_request = dns_request;
3973 p->status = list1 (Qconnect);
3974 postpone_connection = true;
3976 #endif
3977 if (! postpone_connection)
3978 connect_network_socket (proc, addrinfos, use_external_socket_p);
3980 specpdl_ptr = specpdl + count;
3981 return proc;
3985 #ifdef HAVE_NET_IF_H
3987 #ifdef SIOCGIFCONF
3988 static Lisp_Object
3989 network_interface_list (void)
3991 struct ifconf ifconf;
3992 struct ifreq *ifreq;
3993 void *buf = NULL;
3994 ptrdiff_t buf_size = 512;
3995 int s;
3996 Lisp_Object res;
3997 ptrdiff_t count;
3999 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4000 if (s < 0)
4001 return Qnil;
4002 count = SPECPDL_INDEX ();
4003 record_unwind_protect_int (close_file_unwind, s);
4007 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
4008 ifconf.ifc_buf = buf;
4009 ifconf.ifc_len = buf_size;
4010 if (ioctl (s, SIOCGIFCONF, &ifconf))
4012 emacs_close (s);
4013 xfree (buf);
4014 return Qnil;
4017 while (ifconf.ifc_len == buf_size);
4019 res = unbind_to (count, Qnil);
4020 ifreq = ifconf.ifc_req;
4021 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
4023 struct ifreq *ifq = ifreq;
4024 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4025 #define SIZEOF_IFREQ(sif) \
4026 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4027 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4029 int len = SIZEOF_IFREQ (ifq);
4030 #else
4031 int len = sizeof (*ifreq);
4032 #endif
4033 char namebuf[sizeof (ifq->ifr_name) + 1];
4034 ifreq = (struct ifreq *) ((char *) ifreq + len);
4036 if (ifq->ifr_addr.sa_family != AF_INET)
4037 continue;
4039 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
4040 namebuf[sizeof (ifq->ifr_name)] = 0;
4041 res = Fcons (Fcons (build_string (namebuf),
4042 conv_sockaddr_to_lisp (&ifq->ifr_addr,
4043 sizeof (struct sockaddr))),
4044 res);
4047 xfree (buf);
4048 return res;
4050 #endif /* SIOCGIFCONF */
4052 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4054 struct ifflag_def {
4055 int flag_bit;
4056 const char *flag_sym;
4059 static const struct ifflag_def ifflag_table[] = {
4060 #ifdef IFF_UP
4061 { IFF_UP, "up" },
4062 #endif
4063 #ifdef IFF_BROADCAST
4064 { IFF_BROADCAST, "broadcast" },
4065 #endif
4066 #ifdef IFF_DEBUG
4067 { IFF_DEBUG, "debug" },
4068 #endif
4069 #ifdef IFF_LOOPBACK
4070 { IFF_LOOPBACK, "loopback" },
4071 #endif
4072 #ifdef IFF_POINTOPOINT
4073 { IFF_POINTOPOINT, "pointopoint" },
4074 #endif
4075 #ifdef IFF_RUNNING
4076 { IFF_RUNNING, "running" },
4077 #endif
4078 #ifdef IFF_NOARP
4079 { IFF_NOARP, "noarp" },
4080 #endif
4081 #ifdef IFF_PROMISC
4082 { IFF_PROMISC, "promisc" },
4083 #endif
4084 #ifdef IFF_NOTRAILERS
4085 #ifdef NS_IMPL_COCOA
4086 /* Really means smart, notrailers is obsolete. */
4087 { IFF_NOTRAILERS, "smart" },
4088 #else
4089 { IFF_NOTRAILERS, "notrailers" },
4090 #endif
4091 #endif
4092 #ifdef IFF_ALLMULTI
4093 { IFF_ALLMULTI, "allmulti" },
4094 #endif
4095 #ifdef IFF_MASTER
4096 { IFF_MASTER, "master" },
4097 #endif
4098 #ifdef IFF_SLAVE
4099 { IFF_SLAVE, "slave" },
4100 #endif
4101 #ifdef IFF_MULTICAST
4102 { IFF_MULTICAST, "multicast" },
4103 #endif
4104 #ifdef IFF_PORTSEL
4105 { IFF_PORTSEL, "portsel" },
4106 #endif
4107 #ifdef IFF_AUTOMEDIA
4108 { IFF_AUTOMEDIA, "automedia" },
4109 #endif
4110 #ifdef IFF_DYNAMIC
4111 { IFF_DYNAMIC, "dynamic" },
4112 #endif
4113 #ifdef IFF_OACTIVE
4114 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
4115 #endif
4116 #ifdef IFF_SIMPLEX
4117 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4118 #endif
4119 #ifdef IFF_LINK0
4120 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
4121 #endif
4122 #ifdef IFF_LINK1
4123 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
4124 #endif
4125 #ifdef IFF_LINK2
4126 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
4127 #endif
4128 { 0, 0 }
4131 static Lisp_Object
4132 network_interface_info (Lisp_Object ifname)
4134 struct ifreq rq;
4135 Lisp_Object res = Qnil;
4136 Lisp_Object elt;
4137 int s;
4138 bool any = 0;
4139 ptrdiff_t count;
4140 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4141 && defined HAVE_GETIFADDRS && defined LLADDR)
4142 struct ifaddrs *ifap;
4143 #endif
4145 CHECK_STRING (ifname);
4147 if (sizeof rq.ifr_name <= SBYTES (ifname))
4148 error ("interface name too long");
4149 lispstpcpy (rq.ifr_name, ifname);
4151 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4152 if (s < 0)
4153 return Qnil;
4154 count = SPECPDL_INDEX ();
4155 record_unwind_protect_int (close_file_unwind, s);
4157 elt = Qnil;
4158 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4159 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4161 int flags = rq.ifr_flags;
4162 const struct ifflag_def *fp;
4163 int fnum;
4165 /* If flags is smaller than int (i.e. short) it may have the high bit set
4166 due to IFF_MULTICAST. In that case, sign extending it into
4167 an int is wrong. */
4168 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
4169 flags = (unsigned short) rq.ifr_flags;
4171 any = 1;
4172 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4174 if (flags & fp->flag_bit)
4176 elt = Fcons (intern (fp->flag_sym), elt);
4177 flags -= fp->flag_bit;
4180 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
4182 if (flags & 1)
4184 elt = Fcons (make_number (fnum), elt);
4188 #endif
4189 res = Fcons (elt, res);
4191 elt = Qnil;
4192 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4193 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4195 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4196 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4197 int n;
4199 any = 1;
4200 for (n = 0; n < 6; n++)
4201 p->contents[n] = make_number (((unsigned char *)
4202 &rq.ifr_hwaddr.sa_data[0])
4203 [n]);
4204 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4206 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4207 if (getifaddrs (&ifap) != -1)
4209 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4210 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4211 struct ifaddrs *it;
4213 for (it = ifap; it != NULL; it = it->ifa_next)
4215 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
4216 unsigned char linkaddr[6];
4217 int n;
4219 if (it->ifa_addr->sa_family != AF_LINK
4220 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4221 || sdl->sdl_alen != 6)
4222 continue;
4224 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4225 for (n = 0; n < 6; n++)
4226 p->contents[n] = make_number (linkaddr[n]);
4228 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4229 break;
4232 #ifdef HAVE_FREEIFADDRS
4233 freeifaddrs (ifap);
4234 #endif
4236 #endif /* HAVE_GETIFADDRS && LLADDR */
4238 res = Fcons (elt, res);
4240 elt = Qnil;
4241 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4242 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4244 any = 1;
4245 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4246 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4247 #else
4248 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4249 #endif
4251 #endif
4252 res = Fcons (elt, res);
4254 elt = Qnil;
4255 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4256 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4258 any = 1;
4259 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4261 #endif
4262 res = Fcons (elt, res);
4264 elt = Qnil;
4265 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4266 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4268 any = 1;
4269 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4271 #endif
4272 res = Fcons (elt, res);
4274 return unbind_to (count, any ? res : Qnil);
4276 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4277 #endif /* defined (HAVE_NET_IF_H) */
4279 DEFUN ("network-interface-list", Fnetwork_interface_list,
4280 Snetwork_interface_list, 0, 0, 0,
4281 doc: /* Return an alist of all network interfaces and their network address.
4282 Each element is a cons, the car of which is a string containing the
4283 interface name, and the cdr is the network address in internal
4284 format; see the description of ADDRESS in `make-network-process'.
4286 If the information is not available, return nil. */)
4287 (void)
4289 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4290 return network_interface_list ();
4291 #else
4292 return Qnil;
4293 #endif
4296 DEFUN ("network-interface-info", Fnetwork_interface_info,
4297 Snetwork_interface_info, 1, 1, 0,
4298 doc: /* Return information about network interface named IFNAME.
4299 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4300 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4301 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4302 FLAGS is the current flags of the interface.
4304 Data that is unavailable is returned as nil. */)
4305 (Lisp_Object ifname)
4307 #if ((defined HAVE_NET_IF_H \
4308 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4309 || defined SIOCGIFFLAGS)) \
4310 || defined WINDOWSNT)
4311 return network_interface_info (ifname);
4312 #else
4313 return Qnil;
4314 #endif
4317 /* Turn off input and output for process PROC. */
4319 static void
4320 deactivate_process (Lisp_Object proc)
4322 int inchannel;
4323 struct Lisp_Process *p = XPROCESS (proc);
4324 int i;
4326 #ifdef HAVE_GNUTLS
4327 /* Delete GnuTLS structures in PROC, if any. */
4328 emacs_gnutls_deinit (proc);
4329 #endif /* HAVE_GNUTLS */
4331 if (p->read_output_delay > 0)
4333 if (--process_output_delay_count < 0)
4334 process_output_delay_count = 0;
4335 p->read_output_delay = 0;
4336 p->read_output_skip = 0;
4339 /* Beware SIGCHLD hereabouts. */
4341 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4342 close_process_fd (&p->open_fd[i]);
4344 inchannel = p->infd;
4345 if (inchannel >= 0)
4347 p->infd = -1;
4348 p->outfd = -1;
4349 #ifdef DATAGRAM_SOCKETS
4350 if (DATAGRAM_CHAN_P (inchannel))
4352 xfree (datagram_address[inchannel].sa);
4353 datagram_address[inchannel].sa = 0;
4354 datagram_address[inchannel].len = 0;
4356 #endif
4357 chan_process[inchannel] = Qnil;
4358 FD_CLR (inchannel, &input_wait_mask);
4359 FD_CLR (inchannel, &non_keyboard_wait_mask);
4360 if (FD_ISSET (inchannel, &connect_wait_mask))
4362 FD_CLR (inchannel, &connect_wait_mask);
4363 FD_CLR (inchannel, &write_mask);
4364 if (--num_pending_connects < 0)
4365 emacs_abort ();
4367 if (inchannel == max_process_desc)
4369 /* We just closed the highest-numbered process input descriptor,
4370 so recompute the highest-numbered one now. */
4371 int i = inchannel;
4373 i--;
4374 while (0 <= i && NILP (chan_process[i]));
4376 max_process_desc = i;
4382 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4383 0, 4, 0,
4384 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4385 It is given to their filter functions.
4386 Optional argument PROCESS means do not return until output has been
4387 received from PROCESS.
4389 Optional second argument SECONDS and third argument MILLISEC
4390 specify a timeout; return after that much time even if there is
4391 no subprocess output. If SECONDS is a floating point number,
4392 it specifies a fractional number of seconds to wait.
4393 The MILLISEC argument is obsolete and should be avoided.
4395 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4396 from PROCESS only, suspending reading output from other processes.
4397 If JUST-THIS-ONE is an integer, don't run any timers either.
4398 Return non-nil if we received any output from PROCESS (or, if PROCESS
4399 is nil, from any process) before the timeout expired. */)
4400 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4402 intmax_t secs;
4403 int nsecs;
4405 if (! NILP (process))
4406 CHECK_PROCESS (process);
4407 else
4408 just_this_one = Qnil;
4410 if (!NILP (millisec))
4411 { /* Obsolete calling convention using integers rather than floats. */
4412 CHECK_NUMBER (millisec);
4413 if (NILP (seconds))
4414 seconds = make_float (XINT (millisec) / 1000.0);
4415 else
4417 CHECK_NUMBER (seconds);
4418 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4422 secs = 0;
4423 nsecs = -1;
4425 if (!NILP (seconds))
4427 if (INTEGERP (seconds))
4429 if (XINT (seconds) > 0)
4431 secs = XINT (seconds);
4432 nsecs = 0;
4435 else if (FLOATP (seconds))
4437 if (XFLOAT_DATA (seconds) > 0)
4439 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4440 secs = min (t.tv_sec, WAIT_READING_MAX);
4441 nsecs = t.tv_nsec;
4444 else
4445 wrong_type_argument (Qnumberp, seconds);
4447 else if (! NILP (process))
4448 nsecs = 0;
4450 return
4451 ((wait_reading_process_output (secs, nsecs, 0, 0,
4452 Qnil,
4453 !NILP (process) ? XPROCESS (process) : NULL,
4454 (NILP (just_this_one) ? 0
4455 : !INTEGERP (just_this_one) ? 1 : -1))
4456 <= 0)
4457 ? Qnil : Qt);
4460 /* Accept a connection for server process SERVER on CHANNEL. */
4462 static EMACS_INT connect_counter = 0;
4464 static void
4465 server_accept_connection (Lisp_Object server, int channel)
4467 Lisp_Object proc, caller, name, buffer;
4468 Lisp_Object contact, host, service;
4469 struct Lisp_Process *ps = XPROCESS (server);
4470 struct Lisp_Process *p;
4471 int s;
4472 union u_sockaddr {
4473 struct sockaddr sa;
4474 struct sockaddr_in in;
4475 #ifdef AF_INET6
4476 struct sockaddr_in6 in6;
4477 #endif
4478 #ifdef HAVE_LOCAL_SOCKETS
4479 struct sockaddr_un un;
4480 #endif
4481 } saddr;
4482 socklen_t len = sizeof saddr;
4483 ptrdiff_t count;
4485 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4487 if (s < 0)
4489 int code = errno;
4490 if (!would_block (code) && !NILP (ps->log))
4491 call3 (ps->log, server, Qnil,
4492 concat3 (build_string ("accept failed with code"),
4493 Fnumber_to_string (make_number (code)),
4494 build_string ("\n")));
4495 return;
4498 count = SPECPDL_INDEX ();
4499 record_unwind_protect_int (close_file_unwind, s);
4501 connect_counter++;
4503 /* Setup a new process to handle the connection. */
4505 /* Generate a unique identification of the caller, and build contact
4506 information for this process. */
4507 host = Qt;
4508 service = Qnil;
4509 switch (saddr.sa.sa_family)
4511 case AF_INET:
4513 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4515 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4516 host = CALLN (Fformat, ipv4_format,
4517 make_number (ip[0]), make_number (ip[1]),
4518 make_number (ip[2]), make_number (ip[3]));
4519 service = make_number (ntohs (saddr.in.sin_port));
4520 AUTO_STRING (caller_format, " <%s:%d>");
4521 caller = CALLN (Fformat, caller_format, host, service);
4523 break;
4525 #ifdef AF_INET6
4526 case AF_INET6:
4528 Lisp_Object args[9];
4529 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4530 int i;
4532 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4533 args[0] = ipv6_format;
4534 for (i = 0; i < 8; i++)
4535 args[i + 1] = make_number (ntohs (ip6[i]));
4536 host = CALLMANY (Fformat, args);
4537 service = make_number (ntohs (saddr.in.sin_port));
4538 AUTO_STRING (caller_format, " <[%s]:%d>");
4539 caller = CALLN (Fformat, caller_format, host, service);
4541 break;
4542 #endif
4544 #ifdef HAVE_LOCAL_SOCKETS
4545 case AF_LOCAL:
4546 #endif
4547 default:
4548 caller = Fnumber_to_string (make_number (connect_counter));
4549 AUTO_STRING (space_less_than, " <");
4550 AUTO_STRING (greater_than, ">");
4551 caller = concat3 (space_less_than, caller, greater_than);
4552 break;
4555 /* Create a new buffer name for this process if it doesn't have a
4556 filter. The new buffer name is based on the buffer name or
4557 process name of the server process concatenated with the caller
4558 identification. */
4560 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4561 || EQ (ps->filter, Qt)))
4562 buffer = Qnil;
4563 else
4565 buffer = ps->buffer;
4566 if (!NILP (buffer))
4567 buffer = Fbuffer_name (buffer);
4568 else
4569 buffer = ps->name;
4570 if (!NILP (buffer))
4572 buffer = concat2 (buffer, caller);
4573 buffer = Fget_buffer_create (buffer);
4577 /* Generate a unique name for the new server process. Combine the
4578 server process name with the caller identification. */
4580 name = concat2 (ps->name, caller);
4581 proc = make_process (name);
4583 chan_process[s] = proc;
4585 fcntl (s, F_SETFL, O_NONBLOCK);
4587 p = XPROCESS (proc);
4589 /* Build new contact information for this setup. */
4590 contact = Fcopy_sequence (ps->childp);
4591 contact = Fplist_put (contact, QCserver, Qnil);
4592 contact = Fplist_put (contact, QChost, host);
4593 if (!NILP (service))
4594 contact = Fplist_put (contact, QCservice, service);
4595 contact = Fplist_put (contact, QCremote,
4596 conv_sockaddr_to_lisp (&saddr.sa, len));
4597 #ifdef HAVE_GETSOCKNAME
4598 len = sizeof saddr;
4599 if (getsockname (s, &saddr.sa, &len) == 0)
4600 contact = Fplist_put (contact, QClocal,
4601 conv_sockaddr_to_lisp (&saddr.sa, len));
4602 #endif
4604 pset_childp (p, contact);
4605 pset_plist (p, Fcopy_sequence (ps->plist));
4606 pset_type (p, Qnetwork);
4608 pset_buffer (p, buffer);
4609 pset_sentinel (p, ps->sentinel);
4610 pset_filter (p, ps->filter);
4611 eassert (NILP (p->command));
4612 eassert (p->pid == 0);
4614 /* Discard the unwind protect for closing S. */
4615 specpdl_ptr = specpdl + count;
4617 p->open_fd[SUBPROCESS_STDIN] = s;
4618 p->infd = s;
4619 p->outfd = s;
4620 pset_status (p, Qrun);
4622 /* Client processes for accepted connections are not stopped initially. */
4623 if (!EQ (p->filter, Qt))
4625 FD_SET (s, &input_wait_mask);
4626 FD_SET (s, &non_keyboard_wait_mask);
4629 if (s > max_process_desc)
4630 max_process_desc = s;
4632 /* Setup coding system for new process based on server process.
4633 This seems to be the proper thing to do, as the coding system
4634 of the new process should reflect the settings at the time the
4635 server socket was opened; not the current settings. */
4637 pset_decode_coding_system (p, ps->decode_coding_system);
4638 pset_encode_coding_system (p, ps->encode_coding_system);
4639 setup_process_coding_systems (proc);
4641 pset_decoding_buf (p, empty_unibyte_string);
4642 eassert (p->decoding_carryover == 0);
4643 pset_encoding_buf (p, empty_unibyte_string);
4645 p->inherit_coding_system_flag
4646 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4648 AUTO_STRING (dash, "-");
4649 AUTO_STRING (nl, "\n");
4650 Lisp_Object host_string = STRINGP (host) ? host : dash;
4652 if (!NILP (ps->log))
4654 AUTO_STRING (accept_from, "accept from ");
4655 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4658 AUTO_STRING (open_from, "open from ");
4659 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4662 #ifdef HAVE_GETADDRINFO_A
4663 static Lisp_Object
4664 check_for_dns (Lisp_Object proc)
4666 struct Lisp_Process *p = XPROCESS (proc);
4667 Lisp_Object addrinfos = Qnil;
4669 /* Sanity check. */
4670 if (! p->dns_request)
4671 return Qnil;
4673 int ret = gai_error (p->dns_request);
4674 if (ret == EAI_INPROGRESS)
4675 return Qt;
4677 /* We got a response. */
4678 if (ret == 0)
4680 struct addrinfo *res;
4682 for (res = p->dns_request->ar_result; res; res = res->ai_next)
4683 addrinfos = Fcons (conv_addrinfo_to_lisp (res), addrinfos);
4685 addrinfos = Fnreverse (addrinfos);
4687 /* The DNS lookup failed. */
4688 else if (connecting_status (p->status))
4690 deactivate_process (proc);
4691 pset_status (p, (list2
4692 (Qfailed,
4693 concat3 (build_string ("Name lookup of "),
4694 build_string (p->dns_request->ar_name),
4695 build_string (" failed")))));
4698 free_dns_request (proc);
4700 /* This process should not already be connected (or killed). */
4701 if (! connecting_status (p->status))
4702 return Qnil;
4704 return addrinfos;
4707 #endif /* HAVE_GETADDRINFO_A */
4709 static void
4710 wait_for_socket_fds (Lisp_Object process, char const *name)
4712 while (XPROCESS (process)->infd < 0
4713 && connecting_status (XPROCESS (process)->status))
4715 add_to_log ("Waiting for socket from %s...", build_string (name));
4716 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4720 static void
4721 wait_while_connecting (Lisp_Object process)
4723 while (connecting_status (XPROCESS (process)->status))
4725 add_to_log ("Waiting for connection...");
4726 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4730 static void
4731 wait_for_tls_negotiation (Lisp_Object process)
4733 #ifdef HAVE_GNUTLS
4734 while (XPROCESS (process)->gnutls_p
4735 && XPROCESS (process)->gnutls_initstage != GNUTLS_STAGE_READY)
4737 add_to_log ("Waiting for TLS...");
4738 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4740 #endif
4743 /* This variable is different from waiting_for_input in keyboard.c.
4744 It is used to communicate to a lisp process-filter/sentinel (via the
4745 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4746 for user-input when that process-filter was called.
4747 waiting_for_input cannot be used as that is by definition 0 when
4748 lisp code is being evalled.
4749 This is also used in record_asynch_buffer_change.
4750 For that purpose, this must be 0
4751 when not inside wait_reading_process_output. */
4752 static int waiting_for_user_input_p;
4754 static void
4755 wait_reading_process_output_unwind (int data)
4757 waiting_for_user_input_p = data;
4760 /* This is here so breakpoints can be put on it. */
4761 static void
4762 wait_reading_process_output_1 (void)
4766 /* Read and dispose of subprocess output while waiting for timeout to
4767 elapse and/or keyboard input to be available.
4769 TIME_LIMIT is:
4770 timeout in seconds
4771 If negative, gobble data immediately available but don't wait for any.
4773 NSECS is:
4774 an additional duration to wait, measured in nanoseconds
4775 If TIME_LIMIT is zero, then:
4776 If NSECS == 0, there is no limit.
4777 If NSECS > 0, the timeout consists of NSECS only.
4778 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4780 READ_KBD is:
4781 0 to ignore keyboard input, or
4782 1 to return when input is available, or
4783 -1 meaning caller will actually read the input, so don't throw to
4784 the quit handler, or
4786 DO_DISPLAY means redisplay should be done to show subprocess
4787 output that arrives.
4789 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4790 (and gobble terminal input into the buffer if any arrives).
4792 If WAIT_PROC is specified, wait until something arrives from that
4793 process.
4795 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4796 (suspending output from other processes). A negative value
4797 means don't run any timers either.
4799 Return positive if we received input from WAIT_PROC (or from any
4800 process if WAIT_PROC is null), zero if we attempted to receive
4801 input but got none, and negative if we didn't even try. */
4804 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4805 bool do_display,
4806 Lisp_Object wait_for_cell,
4807 struct Lisp_Process *wait_proc, int just_wait_proc)
4809 int channel, nfds;
4810 fd_set Available;
4811 fd_set Writeok;
4812 bool check_write;
4813 int check_delay;
4814 bool no_avail;
4815 int xerrno;
4816 Lisp_Object proc;
4817 struct timespec timeout, end_time, timer_delay;
4818 struct timespec got_output_end_time = invalid_timespec ();
4819 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
4820 int got_some_output = -1;
4821 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4822 bool retry_for_async;
4823 #endif
4824 ptrdiff_t count = SPECPDL_INDEX ();
4826 /* Close to the current time if known, an invalid timespec otherwise. */
4827 struct timespec now = invalid_timespec ();
4829 FD_ZERO (&Available);
4830 FD_ZERO (&Writeok);
4832 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4833 && !(CONSP (wait_proc->status)
4834 && EQ (XCAR (wait_proc->status), Qexit)))
4835 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4837 record_unwind_protect_int (wait_reading_process_output_unwind,
4838 waiting_for_user_input_p);
4839 waiting_for_user_input_p = read_kbd;
4841 if (TYPE_MAXIMUM (time_t) < time_limit)
4842 time_limit = TYPE_MAXIMUM (time_t);
4844 if (time_limit < 0 || nsecs < 0)
4845 wait = MINIMUM;
4846 else if (time_limit > 0 || nsecs > 0)
4848 wait = TIMEOUT;
4849 now = current_timespec ();
4850 end_time = timespec_add (now, make_timespec (time_limit, nsecs));
4852 else
4853 wait = INFINITY;
4855 while (1)
4857 bool process_skipped = false;
4859 /* If calling from keyboard input, do not quit
4860 since we want to return C-g as an input character.
4861 Otherwise, do pending quit if requested. */
4862 if (read_kbd >= 0)
4863 QUIT;
4864 else if (pending_signals)
4865 process_pending_signals ();
4867 /* Exit now if the cell we're waiting for became non-nil. */
4868 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4869 break;
4871 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4873 Lisp_Object process_list_head, aproc;
4874 struct Lisp_Process *p;
4876 retry_for_async = false;
4877 FOR_EACH_PROCESS(process_list_head, aproc)
4879 p = XPROCESS (aproc);
4881 if (! wait_proc || p == wait_proc)
4883 #ifdef HAVE_GETADDRINFO_A
4884 /* Check for pending DNS requests. */
4885 if (p->dns_request)
4887 Lisp_Object addrinfos = check_for_dns (aproc);
4888 if (!NILP (addrinfos) && !EQ (addrinfos, Qt))
4889 connect_network_socket (aproc, addrinfos, Qnil);
4890 else
4891 retry_for_async = true;
4893 #endif
4894 #ifdef HAVE_GNUTLS
4895 /* Continue TLS negotiation. */
4896 if (p->gnutls_initstage == GNUTLS_STAGE_HANDSHAKE_TRIED
4897 && p->is_non_blocking_client)
4899 gnutls_try_handshake (p);
4900 p->gnutls_handshakes_tried++;
4902 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
4904 gnutls_verify_boot (aproc, Qnil);
4905 finish_after_tls_connection (aproc);
4907 else
4909 retry_for_async = true;
4910 if (p->gnutls_handshakes_tried
4911 > GNUTLS_EMACS_HANDSHAKES_LIMIT)
4913 deactivate_process (aproc);
4914 pset_status (p, list2 (Qfailed,
4915 build_string ("TLS negotiation failed")));
4919 #endif
4923 #endif /* GETADDRINFO_A or GNUTLS */
4925 /* Compute time from now till when time limit is up. */
4926 /* Exit if already run out. */
4927 if (wait == TIMEOUT)
4929 if (!timespec_valid_p (now))
4930 now = current_timespec ();
4931 if (timespec_cmp (end_time, now) <= 0)
4932 break;
4933 timeout = timespec_sub (end_time, now);
4935 else
4936 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
4938 /* Normally we run timers here.
4939 But not if wait_for_cell; in those cases,
4940 the wait is supposed to be short,
4941 and those callers cannot handle running arbitrary Lisp code here. */
4942 if (NILP (wait_for_cell)
4943 && just_wait_proc >= 0)
4947 unsigned old_timers_run = timers_run;
4948 struct buffer *old_buffer = current_buffer;
4949 Lisp_Object old_window = selected_window;
4951 timer_delay = timer_check ();
4953 /* If a timer has run, this might have changed buffers
4954 an alike. Make read_key_sequence aware of that. */
4955 if (timers_run != old_timers_run
4956 && (old_buffer != current_buffer
4957 || !EQ (old_window, selected_window))
4958 && waiting_for_user_input_p == -1)
4959 record_asynch_buffer_change ();
4961 if (timers_run != old_timers_run && do_display)
4962 /* We must retry, since a timer may have requeued itself
4963 and that could alter the time_delay. */
4964 redisplay_preserve_echo_area (9);
4965 else
4966 break;
4968 while (!detect_input_pending ());
4970 /* If there is unread keyboard input, also return. */
4971 if (read_kbd != 0
4972 && requeued_events_pending_p ())
4973 break;
4975 /* This is so a breakpoint can be put here. */
4976 if (!timespec_valid_p (timer_delay))
4977 wait_reading_process_output_1 ();
4980 /* Cause C-g and alarm signals to take immediate action,
4981 and cause input available signals to zero out timeout.
4983 It is important that we do this before checking for process
4984 activity. If we get a SIGCHLD after the explicit checks for
4985 process activity, timeout is the only way we will know. */
4986 if (read_kbd < 0)
4987 set_waiting_for_input (&timeout);
4989 /* If status of something has changed, and no input is
4990 available, notify the user of the change right away. After
4991 this explicit check, we'll let the SIGCHLD handler zap
4992 timeout to get our attention. */
4993 if (update_tick != process_tick)
4995 fd_set Atemp;
4996 fd_set Ctemp;
4998 if (kbd_on_hold_p ())
4999 FD_ZERO (&Atemp);
5000 else
5001 Atemp = input_wait_mask;
5002 Ctemp = write_mask;
5004 timeout = make_timespec (0, 0);
5005 if ((pselect (max (max_process_desc, max_input_desc) + 1,
5006 &Atemp,
5007 (num_pending_connects > 0 ? &Ctemp : NULL),
5008 NULL, &timeout, NULL)
5009 <= 0))
5011 /* It's okay for us to do this and then continue with
5012 the loop, since timeout has already been zeroed out. */
5013 clear_waiting_for_input ();
5014 got_some_output = status_notify (NULL, wait_proc);
5015 if (do_display) redisplay_preserve_echo_area (13);
5019 /* Don't wait for output from a non-running process. Just
5020 read whatever data has already been received. */
5021 if (wait_proc && wait_proc->raw_status_new)
5022 update_status (wait_proc);
5023 if (wait_proc
5024 && ! EQ (wait_proc->status, Qrun)
5025 && ! connecting_status (wait_proc->status))
5027 bool read_some_bytes = false;
5029 clear_waiting_for_input ();
5031 /* If data can be read from the process, do so until exhausted. */
5032 if (wait_proc->infd >= 0)
5034 XSETPROCESS (proc, wait_proc);
5036 while (true)
5038 int nread = read_process_output (proc, wait_proc->infd);
5039 if (nread < 0)
5041 if (errno == EIO || would_block (errno))
5042 break;
5044 else
5046 if (got_some_output < nread)
5047 got_some_output = nread;
5048 if (nread == 0)
5049 break;
5050 read_some_bytes = true;
5055 if (read_some_bytes && do_display)
5056 redisplay_preserve_echo_area (10);
5058 break;
5061 /* Wait till there is something to do. */
5063 if (wait_proc && just_wait_proc)
5065 if (wait_proc->infd < 0) /* Terminated. */
5066 break;
5067 FD_SET (wait_proc->infd, &Available);
5068 check_delay = 0;
5069 check_write = 0;
5071 else if (!NILP (wait_for_cell))
5073 Available = non_process_wait_mask;
5074 check_delay = 0;
5075 check_write = 0;
5077 else
5079 if (! read_kbd)
5080 Available = non_keyboard_wait_mask;
5081 else
5082 Available = input_wait_mask;
5083 Writeok = write_mask;
5084 check_delay = wait_proc ? 0 : process_output_delay_count;
5085 check_write = true;
5088 /* If frame size has changed or the window is newly mapped,
5089 redisplay now, before we start to wait. There is a race
5090 condition here; if a SIGIO arrives between now and the select
5091 and indicates that a frame is trashed, the select may block
5092 displaying a trashed screen. */
5093 if (frame_garbaged && do_display)
5095 clear_waiting_for_input ();
5096 redisplay_preserve_echo_area (11);
5097 if (read_kbd < 0)
5098 set_waiting_for_input (&timeout);
5101 /* Skip the `select' call if input is available and we're
5102 waiting for keyboard input or a cell change (which can be
5103 triggered by processing X events). In the latter case, set
5104 nfds to 1 to avoid breaking the loop. */
5105 no_avail = 0;
5106 if ((read_kbd || !NILP (wait_for_cell))
5107 && detect_input_pending ())
5109 nfds = read_kbd ? 0 : 1;
5110 no_avail = 1;
5111 FD_ZERO (&Available);
5113 else
5115 /* Set the timeout for adaptive read buffering if any
5116 process has non-zero read_output_skip and non-zero
5117 read_output_delay, and we are not reading output for a
5118 specific process. It is not executed if
5119 Vprocess_adaptive_read_buffering is nil. */
5120 if (process_output_skip && check_delay > 0)
5122 int adaptive_nsecs = timeout.tv_nsec;
5123 if (timeout.tv_sec > 0 || adaptive_nsecs > READ_OUTPUT_DELAY_MAX)
5124 adaptive_nsecs = READ_OUTPUT_DELAY_MAX;
5125 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
5127 proc = chan_process[channel];
5128 if (NILP (proc))
5129 continue;
5130 /* Find minimum non-zero read_output_delay among the
5131 processes with non-zero read_output_skip. */
5132 if (XPROCESS (proc)->read_output_delay > 0)
5134 check_delay--;
5135 if (!XPROCESS (proc)->read_output_skip)
5136 continue;
5137 FD_CLR (channel, &Available);
5138 process_skipped = true;
5139 XPROCESS (proc)->read_output_skip = 0;
5140 if (XPROCESS (proc)->read_output_delay < adaptive_nsecs)
5141 adaptive_nsecs = XPROCESS (proc)->read_output_delay;
5144 timeout = make_timespec (0, adaptive_nsecs);
5145 process_output_skip = 0;
5148 /* If we've got some output and haven't limited our timeout
5149 with adaptive read buffering, limit it. */
5150 if (got_some_output > 0 && !process_skipped
5151 && (timeout.tv_sec
5152 || timeout.tv_nsec > READ_OUTPUT_DELAY_INCREMENT))
5153 timeout = make_timespec (0, READ_OUTPUT_DELAY_INCREMENT);
5156 if (NILP (wait_for_cell) && just_wait_proc >= 0
5157 && timespec_valid_p (timer_delay)
5158 && timespec_cmp (timer_delay, timeout) < 0)
5160 if (!timespec_valid_p (now))
5161 now = current_timespec ();
5162 struct timespec timeout_abs = timespec_add (now, timeout);
5163 if (!timespec_valid_p (got_output_end_time)
5164 || timespec_cmp (timeout_abs, got_output_end_time) < 0)
5165 got_output_end_time = timeout_abs;
5166 timeout = timer_delay;
5168 else
5169 got_output_end_time = invalid_timespec ();
5171 /* NOW can become inaccurate if time can pass during pselect. */
5172 if (timeout.tv_sec > 0 || timeout.tv_nsec > 0)
5173 now = invalid_timespec ();
5175 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5176 if (retry_for_async
5177 && (timeout.tv_sec > 0 || timeout.tv_nsec > ASYNC_RETRY_NSEC))
5179 timeout.tv_sec = 0;
5180 timeout.tv_nsec = ASYNC_RETRY_NSEC;
5182 #endif
5184 #if defined (HAVE_NS)
5185 nfds = ns_select
5186 #elif defined (HAVE_GLIB)
5187 nfds = xg_select
5188 #else
5189 nfds = pselect
5190 #endif
5191 (max (max_process_desc, max_input_desc) + 1,
5192 &Available,
5193 (check_write ? &Writeok : 0),
5194 NULL, &timeout, NULL);
5196 #ifdef HAVE_GNUTLS
5197 /* GnuTLS buffers data internally. In lowat mode it leaves
5198 some data in the TCP buffers so that select works, but
5199 with custom pull/push functions we need to check if some
5200 data is available in the buffers manually. */
5201 if (nfds == 0)
5203 fd_set tls_available;
5204 int set = 0;
5206 FD_ZERO (&tls_available);
5207 if (! wait_proc)
5209 /* We're not waiting on a specific process, so loop
5210 through all the channels and check for data.
5211 This is a workaround needed for some versions of
5212 the gnutls library -- 2.12.14 has been confirmed
5213 to need it. See
5214 http://comments.gmane.org/gmane.emacs.devel/145074 */
5215 for (channel = 0; channel < FD_SETSIZE; ++channel)
5216 if (! NILP (chan_process[channel]))
5218 struct Lisp_Process *p =
5219 XPROCESS (chan_process[channel]);
5220 if (p && p->gnutls_p && p->gnutls_state
5221 && ((emacs_gnutls_record_check_pending
5222 (p->gnutls_state))
5223 > 0))
5225 nfds++;
5226 eassert (p->infd == channel);
5227 FD_SET (p->infd, &tls_available);
5228 set++;
5232 else
5234 /* Check this specific channel. */
5235 if (wait_proc->gnutls_p /* Check for valid process. */
5236 && wait_proc->gnutls_state
5237 /* Do we have pending data? */
5238 && ((emacs_gnutls_record_check_pending
5239 (wait_proc->gnutls_state))
5240 > 0))
5242 nfds = 1;
5243 eassert (0 <= wait_proc->infd);
5244 /* Set to Available. */
5245 FD_SET (wait_proc->infd, &tls_available);
5246 set++;
5249 if (set)
5250 Available = tls_available;
5252 #endif
5255 xerrno = errno;
5257 /* Make C-g and alarm signals set flags again. */
5258 clear_waiting_for_input ();
5260 /* If we woke up due to SIGWINCH, actually change size now. */
5261 do_pending_window_change (0);
5263 if (nfds == 0)
5265 /* Exit the main loop if we've passed the requested timeout,
5266 or aren't skipping processes and got some output and
5267 haven't lowered our timeout due to timers or SIGIO and
5268 have waited a long amount of time due to repeated
5269 timers. */
5270 struct timespec huge_timespec
5271 = make_timespec (TYPE_MAXIMUM (time_t), 2 * TIMESPEC_RESOLUTION);
5272 struct timespec cmp_time = huge_timespec;
5273 if (wait < TIMEOUT)
5274 break;
5275 if (wait == TIMEOUT)
5276 cmp_time = end_time;
5277 if (!process_skipped && got_some_output > 0
5278 && (timeout.tv_sec > 0 || timeout.tv_nsec > 0))
5280 if (!timespec_valid_p (got_output_end_time))
5281 break;
5282 if (timespec_cmp (got_output_end_time, cmp_time) < 0)
5283 cmp_time = got_output_end_time;
5285 if (timespec_cmp (cmp_time, huge_timespec) < 0)
5287 now = current_timespec ();
5288 if (timespec_cmp (cmp_time, now) <= 0)
5289 break;
5293 if (nfds < 0)
5295 if (xerrno == EINTR)
5296 no_avail = 1;
5297 else if (xerrno == EBADF)
5298 emacs_abort ();
5299 else
5300 report_file_errno ("Failed select", Qnil, xerrno);
5303 /* Check for keyboard input. */
5304 /* If there is any, return immediately
5305 to give it higher priority than subprocesses. */
5307 if (read_kbd != 0)
5309 unsigned old_timers_run = timers_run;
5310 struct buffer *old_buffer = current_buffer;
5311 Lisp_Object old_window = selected_window;
5312 bool leave = false;
5314 if (detect_input_pending_run_timers (do_display))
5316 swallow_events (do_display);
5317 if (detect_input_pending_run_timers (do_display))
5318 leave = true;
5321 /* If a timer has run, this might have changed buffers
5322 an alike. Make read_key_sequence aware of that. */
5323 if (timers_run != old_timers_run
5324 && waiting_for_user_input_p == -1
5325 && (old_buffer != current_buffer
5326 || !EQ (old_window, selected_window)))
5327 record_asynch_buffer_change ();
5329 if (leave)
5330 break;
5333 /* If there is unread keyboard input, also return. */
5334 if (read_kbd != 0
5335 && requeued_events_pending_p ())
5336 break;
5338 /* If we are not checking for keyboard input now,
5339 do process events (but don't run any timers).
5340 This is so that X events will be processed.
5341 Otherwise they may have to wait until polling takes place.
5342 That would causes delays in pasting selections, for example.
5344 (We used to do this only if wait_for_cell.) */
5345 if (read_kbd == 0 && detect_input_pending ())
5347 swallow_events (do_display);
5348 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5349 if (detect_input_pending ())
5350 break;
5351 #endif
5354 /* Exit now if the cell we're waiting for became non-nil. */
5355 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5356 break;
5358 #ifdef USABLE_SIGIO
5359 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5360 go read it. This can happen with X on BSD after logging out.
5361 In that case, there really is no input and no SIGIO,
5362 but select says there is input. */
5364 if (read_kbd && interrupt_input
5365 && keyboard_bit_set (&Available) && ! noninteractive)
5366 handle_input_available_signal (SIGIO);
5367 #endif
5369 /* If checking input just got us a size-change event from X,
5370 obey it now if we should. */
5371 if (read_kbd || ! NILP (wait_for_cell))
5372 do_pending_window_change (0);
5374 /* Check for data from a process. */
5375 if (no_avail || nfds == 0)
5376 continue;
5378 for (channel = 0; channel <= max_input_desc; ++channel)
5380 struct fd_callback_data *d = &fd_callback_info[channel];
5381 if (d->func
5382 && ((d->condition & FOR_READ
5383 && FD_ISSET (channel, &Available))
5384 || (d->condition & FOR_WRITE
5385 && FD_ISSET (channel, &write_mask))))
5386 d->func (channel, d->data);
5389 for (channel = 0; channel <= max_process_desc; channel++)
5391 if (FD_ISSET (channel, &Available)
5392 && FD_ISSET (channel, &non_keyboard_wait_mask)
5393 && !FD_ISSET (channel, &non_process_wait_mask))
5395 int nread;
5397 /* If waiting for this channel, arrange to return as
5398 soon as no more input to be processed. No more
5399 waiting. */
5400 proc = chan_process[channel];
5401 if (NILP (proc))
5402 continue;
5404 /* If this is a server stream socket, accept connection. */
5405 if (EQ (XPROCESS (proc)->status, Qlisten))
5407 server_accept_connection (proc, channel);
5408 continue;
5411 /* Read data from the process, starting with our
5412 buffered-ahead character if we have one. */
5414 nread = read_process_output (proc, channel);
5415 if ((!wait_proc || wait_proc == XPROCESS (proc))
5416 && got_some_output < nread)
5417 got_some_output = nread;
5418 if (nread > 0)
5420 /* Vacuum up any leftovers without waiting. */
5421 if (wait_proc == XPROCESS (proc))
5422 wait = MINIMUM;
5423 /* Since read_process_output can run a filter,
5424 which can call accept-process-output,
5425 don't try to read from any other processes
5426 before doing the select again. */
5427 FD_ZERO (&Available);
5429 if (do_display)
5430 redisplay_preserve_echo_area (12);
5432 else if (nread == -1 && would_block (errno))
5434 #ifdef WINDOWSNT
5435 /* FIXME: Is this special case still needed? */
5436 /* Note that we cannot distinguish between no input
5437 available now and a closed pipe.
5438 With luck, a closed pipe will be accompanied by
5439 subprocess termination and SIGCHLD. */
5440 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5441 && !PIPECONN_P (proc))
5443 #endif
5444 #ifdef HAVE_PTYS
5445 /* On some OSs with ptys, when the process on one end of
5446 a pty exits, the other end gets an error reading with
5447 errno = EIO instead of getting an EOF (0 bytes read).
5448 Therefore, if we get an error reading and errno =
5449 EIO, just continue, because the child process has
5450 exited and should clean itself up soon (e.g. when we
5451 get a SIGCHLD). */
5452 else if (nread == -1 && errno == EIO)
5454 struct Lisp_Process *p = XPROCESS (proc);
5456 /* Clear the descriptor now, so we only raise the
5457 signal once. */
5458 FD_CLR (channel, &input_wait_mask);
5459 FD_CLR (channel, &non_keyboard_wait_mask);
5461 if (p->pid == -2)
5463 /* If the EIO occurs on a pty, the SIGCHLD handler's
5464 waitpid call will not find the process object to
5465 delete. Do it here. */
5466 p->tick = ++process_tick;
5467 pset_status (p, Qfailed);
5470 #endif /* HAVE_PTYS */
5471 /* If we can detect process termination, don't consider the
5472 process gone just because its pipe is closed. */
5473 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5474 && !PIPECONN_P (proc))
5476 else if (nread == 0 && PIPECONN_P (proc))
5478 /* Preserve status of processes already terminated. */
5479 XPROCESS (proc)->tick = ++process_tick;
5480 deactivate_process (proc);
5481 if (EQ (XPROCESS (proc)->status, Qrun))
5482 pset_status (XPROCESS (proc),
5483 list2 (Qexit, make_number (0)));
5485 else
5487 /* Preserve status of processes already terminated. */
5488 XPROCESS (proc)->tick = ++process_tick;
5489 deactivate_process (proc);
5490 if (XPROCESS (proc)->raw_status_new)
5491 update_status (XPROCESS (proc));
5492 if (EQ (XPROCESS (proc)->status, Qrun))
5493 pset_status (XPROCESS (proc),
5494 list2 (Qexit, make_number (256)));
5497 if (FD_ISSET (channel, &Writeok)
5498 && FD_ISSET (channel, &connect_wait_mask))
5500 struct Lisp_Process *p;
5502 FD_CLR (channel, &connect_wait_mask);
5503 FD_CLR (channel, &write_mask);
5504 if (--num_pending_connects < 0)
5505 emacs_abort ();
5507 proc = chan_process[channel];
5508 if (NILP (proc))
5509 continue;
5511 p = XPROCESS (proc);
5513 #ifndef WINDOWSNT
5515 socklen_t xlen = sizeof (xerrno);
5516 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5517 xerrno = errno;
5519 #else
5520 /* On MS-Windows, getsockopt clears the error for the
5521 entire process, which may not be the right thing; see
5522 w32.c. Use getpeername instead. */
5524 struct sockaddr pname;
5525 socklen_t pnamelen = sizeof (pname);
5527 /* If connection failed, getpeername will fail. */
5528 xerrno = 0;
5529 if (getpeername (channel, &pname, &pnamelen) < 0)
5531 /* Obtain connect failure code through error slippage. */
5532 char dummy;
5533 xerrno = errno;
5534 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5535 xerrno = errno;
5538 #endif
5539 if (xerrno)
5541 Lisp_Object addrinfos
5542 = connecting_status (p->status) ? XCDR (p->status) : Qnil;
5543 if (!NILP (addrinfos))
5544 XSETCDR (p->status, XCDR (addrinfos));
5545 else
5547 p->tick = ++process_tick;
5548 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5550 deactivate_process (proc);
5551 if (!NILP (addrinfos))
5552 connect_network_socket (proc, addrinfos, Qnil);
5554 else
5556 #ifdef HAVE_GNUTLS
5557 /* If we have an incompletely set up TLS connection,
5558 then defer the sentinel signaling until
5559 later. */
5560 if (NILP (p->gnutls_boot_parameters)
5561 && !p->gnutls_p)
5562 #endif
5564 pset_status (p, Qrun);
5565 /* Execute the sentinel here. If we had relied on
5566 status_notify to do it later, it will read input
5567 from the process before calling the sentinel. */
5568 exec_sentinel (proc, build_string ("open\n"));
5571 if (0 <= p->infd && !EQ (p->filter, Qt)
5572 && !EQ (p->command, Qt))
5574 FD_SET (p->infd, &input_wait_mask);
5575 FD_SET (p->infd, &non_keyboard_wait_mask);
5579 } /* End for each file descriptor. */
5580 } /* End while exit conditions not met. */
5582 unbind_to (count, Qnil);
5584 /* If calling from keyboard input, do not quit
5585 since we want to return C-g as an input character.
5586 Otherwise, do pending quit if requested. */
5587 if (read_kbd >= 0)
5589 /* Prevent input_pending from remaining set if we quit. */
5590 clear_input_pending ();
5591 QUIT;
5594 return got_some_output;
5597 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5599 static Lisp_Object
5600 read_process_output_call (Lisp_Object fun_and_args)
5602 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5605 static Lisp_Object
5606 read_process_output_error_handler (Lisp_Object error_val)
5608 cmd_error_internal (error_val, "error in process filter: ");
5609 Vinhibit_quit = Qt;
5610 update_echo_area ();
5611 Fsleep_for (make_number (2), Qnil);
5612 return Qt;
5615 static void
5616 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5617 ssize_t nbytes,
5618 struct coding_system *coding);
5620 /* Read pending output from the process channel,
5621 starting with our buffered-ahead character if we have one.
5622 Yield number of decoded characters read.
5624 This function reads at most 4096 characters.
5625 If you want to read all available subprocess output,
5626 you must call it repeatedly until it returns zero.
5628 The characters read are decoded according to PROC's coding-system
5629 for decoding. */
5631 static int
5632 read_process_output (Lisp_Object proc, int channel)
5634 ssize_t nbytes;
5635 struct Lisp_Process *p = XPROCESS (proc);
5636 struct coding_system *coding = proc_decode_coding_system[channel];
5637 int carryover = p->decoding_carryover;
5638 enum { readmax = 4096 };
5639 ptrdiff_t count = SPECPDL_INDEX ();
5640 Lisp_Object odeactivate;
5641 char chars[sizeof coding->carryover + readmax];
5643 if (carryover)
5644 /* See the comment above. */
5645 memcpy (chars, SDATA (p->decoding_buf), carryover);
5647 #ifdef DATAGRAM_SOCKETS
5648 /* We have a working select, so proc_buffered_char is always -1. */
5649 if (DATAGRAM_CHAN_P (channel))
5651 socklen_t len = datagram_address[channel].len;
5652 nbytes = recvfrom (channel, chars + carryover, readmax,
5653 0, datagram_address[channel].sa, &len);
5655 else
5656 #endif
5658 bool buffered = proc_buffered_char[channel] >= 0;
5659 if (buffered)
5661 chars[carryover] = proc_buffered_char[channel];
5662 proc_buffered_char[channel] = -1;
5664 #ifdef HAVE_GNUTLS
5665 if (p->gnutls_p && p->gnutls_state)
5666 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5667 readmax - buffered);
5668 else
5669 #endif
5670 nbytes = emacs_read (channel, chars + carryover + buffered,
5671 readmax - buffered);
5672 if (nbytes > 0 && p->adaptive_read_buffering)
5674 int delay = p->read_output_delay;
5675 if (nbytes < 256)
5677 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5679 if (delay == 0)
5680 process_output_delay_count++;
5681 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5684 else if (delay > 0 && nbytes == readmax - buffered)
5686 delay -= READ_OUTPUT_DELAY_INCREMENT;
5687 if (delay == 0)
5688 process_output_delay_count--;
5690 p->read_output_delay = delay;
5691 if (delay)
5693 p->read_output_skip = 1;
5694 process_output_skip = 1;
5697 nbytes += buffered;
5698 nbytes += buffered && nbytes <= 0;
5701 p->decoding_carryover = 0;
5703 /* At this point, NBYTES holds number of bytes just received
5704 (including the one in proc_buffered_char[channel]). */
5705 if (nbytes <= 0)
5707 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5708 return nbytes;
5709 coding->mode |= CODING_MODE_LAST_BLOCK;
5712 /* Now set NBYTES how many bytes we must decode. */
5713 nbytes += carryover;
5715 odeactivate = Vdeactivate_mark;
5716 /* There's no good reason to let process filters change the current
5717 buffer, and many callers of accept-process-output, sit-for, and
5718 friends don't expect current-buffer to be changed from under them. */
5719 record_unwind_current_buffer ();
5721 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5723 /* Handling the process output should not deactivate the mark. */
5724 Vdeactivate_mark = odeactivate;
5726 unbind_to (count, Qnil);
5727 return nbytes;
5730 static void
5731 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5732 ssize_t nbytes,
5733 struct coding_system *coding)
5735 Lisp_Object outstream = p->filter;
5736 Lisp_Object text;
5737 bool outer_running_asynch_code = running_asynch_code;
5738 int waiting = waiting_for_user_input_p;
5740 #if 0
5741 Lisp_Object obuffer, okeymap;
5742 XSETBUFFER (obuffer, current_buffer);
5743 okeymap = BVAR (current_buffer, keymap);
5744 #endif
5746 /* We inhibit quit here instead of just catching it so that
5747 hitting ^G when a filter happens to be running won't screw
5748 it up. */
5749 specbind (Qinhibit_quit, Qt);
5750 specbind (Qlast_nonmenu_event, Qt);
5752 /* In case we get recursively called,
5753 and we already saved the match data nonrecursively,
5754 save the same match data in safely recursive fashion. */
5755 if (outer_running_asynch_code)
5757 Lisp_Object tem;
5758 /* Don't clobber the CURRENT match data, either! */
5759 tem = Fmatch_data (Qnil, Qnil, Qnil);
5760 restore_search_regs ();
5761 record_unwind_save_match_data ();
5762 Fset_match_data (tem, Qt);
5765 /* For speed, if a search happens within this code,
5766 save the match data in a special nonrecursive fashion. */
5767 running_asynch_code = 1;
5769 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5770 text = coding->dst_object;
5771 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5772 /* A new coding system might be found. */
5773 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5775 pset_decode_coding_system (p, Vlast_coding_system_used);
5777 /* Don't call setup_coding_system for
5778 proc_decode_coding_system[channel] here. It is done in
5779 detect_coding called via decode_coding above. */
5781 /* If a coding system for encoding is not yet decided, we set
5782 it as the same as coding-system for decoding.
5784 But, before doing that we must check if
5785 proc_encode_coding_system[p->outfd] surely points to a
5786 valid memory because p->outfd will be changed once EOF is
5787 sent to the process. */
5788 if (NILP (p->encode_coding_system) && p->outfd >= 0
5789 && proc_encode_coding_system[p->outfd])
5791 pset_encode_coding_system
5792 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5793 setup_coding_system (p->encode_coding_system,
5794 proc_encode_coding_system[p->outfd]);
5798 if (coding->carryover_bytes > 0)
5800 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5801 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5802 memcpy (SDATA (p->decoding_buf), coding->carryover,
5803 coding->carryover_bytes);
5804 p->decoding_carryover = coding->carryover_bytes;
5806 if (SBYTES (text) > 0)
5807 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5808 sometimes it's simply wrong to wrap (e.g. when called from
5809 accept-process-output). */
5810 internal_condition_case_1 (read_process_output_call,
5811 list3 (outstream, make_lisp_proc (p), text),
5812 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5813 read_process_output_error_handler);
5815 /* If we saved the match data nonrecursively, restore it now. */
5816 restore_search_regs ();
5817 running_asynch_code = outer_running_asynch_code;
5819 /* Restore waiting_for_user_input_p as it was
5820 when we were called, in case the filter clobbered it. */
5821 waiting_for_user_input_p = waiting;
5823 #if 0 /* Call record_asynch_buffer_change unconditionally,
5824 because we might have changed minor modes or other things
5825 that affect key bindings. */
5826 if (! EQ (Fcurrent_buffer (), obuffer)
5827 || ! EQ (current_buffer->keymap, okeymap))
5828 #endif
5829 /* But do it only if the caller is actually going to read events.
5830 Otherwise there's no need to make him wake up, and it could
5831 cause trouble (for example it would make sit_for return). */
5832 if (waiting_for_user_input_p == -1)
5833 record_asynch_buffer_change ();
5836 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5837 Sinternal_default_process_filter, 2, 2, 0,
5838 doc: /* Function used as default process filter.
5839 This inserts the process's output into its buffer, if there is one.
5840 Otherwise it discards the output. */)
5841 (Lisp_Object proc, Lisp_Object text)
5843 struct Lisp_Process *p;
5844 ptrdiff_t opoint;
5846 CHECK_PROCESS (proc);
5847 p = XPROCESS (proc);
5848 CHECK_STRING (text);
5850 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5852 Lisp_Object old_read_only;
5853 ptrdiff_t old_begv, old_zv;
5854 ptrdiff_t old_begv_byte, old_zv_byte;
5855 ptrdiff_t before, before_byte;
5856 ptrdiff_t opoint_byte;
5857 struct buffer *b;
5859 Fset_buffer (p->buffer);
5860 opoint = PT;
5861 opoint_byte = PT_BYTE;
5862 old_read_only = BVAR (current_buffer, read_only);
5863 old_begv = BEGV;
5864 old_zv = ZV;
5865 old_begv_byte = BEGV_BYTE;
5866 old_zv_byte = ZV_BYTE;
5868 bset_read_only (current_buffer, Qnil);
5870 /* Insert new output into buffer at the current end-of-output
5871 marker, thus preserving logical ordering of input and output. */
5872 if (XMARKER (p->mark)->buffer)
5873 set_point_from_marker (p->mark);
5874 else
5875 SET_PT_BOTH (ZV, ZV_BYTE);
5876 before = PT;
5877 before_byte = PT_BYTE;
5879 /* If the output marker is outside of the visible region, save
5880 the restriction and widen. */
5881 if (! (BEGV <= PT && PT <= ZV))
5882 Fwiden ();
5884 /* Adjust the multibyteness of TEXT to that of the buffer. */
5885 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5886 != ! STRING_MULTIBYTE (text))
5887 text = (STRING_MULTIBYTE (text)
5888 ? Fstring_as_unibyte (text)
5889 : Fstring_to_multibyte (text));
5890 /* Insert before markers in case we are inserting where
5891 the buffer's mark is, and the user's next command is Meta-y. */
5892 insert_from_string_before_markers (text, 0, 0,
5893 SCHARS (text), SBYTES (text), 0);
5895 /* Make sure the process marker's position is valid when the
5896 process buffer is changed in the signal_after_change above.
5897 W3 is known to do that. */
5898 if (BUFFERP (p->buffer)
5899 && (b = XBUFFER (p->buffer), b != current_buffer))
5900 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5901 else
5902 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5904 update_mode_lines = 23;
5906 /* Make sure opoint and the old restrictions
5907 float ahead of any new text just as point would. */
5908 if (opoint >= before)
5910 opoint += PT - before;
5911 opoint_byte += PT_BYTE - before_byte;
5913 if (old_begv > before)
5915 old_begv += PT - before;
5916 old_begv_byte += PT_BYTE - before_byte;
5918 if (old_zv >= before)
5920 old_zv += PT - before;
5921 old_zv_byte += PT_BYTE - before_byte;
5924 /* If the restriction isn't what it should be, set it. */
5925 if (old_begv != BEGV || old_zv != ZV)
5926 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5928 bset_read_only (current_buffer, old_read_only);
5929 SET_PT_BOTH (opoint, opoint_byte);
5931 return Qnil;
5934 /* Sending data to subprocess. */
5936 /* In send_process, when a write fails temporarily,
5937 wait_reading_process_output is called. It may execute user code,
5938 e.g. timers, that attempts to write new data to the same process.
5939 We must ensure that data is sent in the right order, and not
5940 interspersed half-completed with other writes (Bug#10815). This is
5941 handled by the write_queue element of struct process. It is a list
5942 with each entry having the form
5944 (string . (offset . length))
5946 where STRING is a lisp string, OFFSET is the offset into the
5947 string's byte sequence from which we should begin to send, and
5948 LENGTH is the number of bytes left to send. */
5950 /* Create a new entry in write_queue.
5951 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5952 BUF is a pointer to the string sequence of the input_obj or a C
5953 string in case of Qt or Qnil. */
5955 static void
5956 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5957 const char *buf, ptrdiff_t len, bool front)
5959 ptrdiff_t offset;
5960 Lisp_Object entry, obj;
5962 if (STRINGP (input_obj))
5964 offset = buf - SSDATA (input_obj);
5965 obj = input_obj;
5967 else
5969 offset = 0;
5970 obj = make_unibyte_string (buf, len);
5973 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5975 if (front)
5976 pset_write_queue (p, Fcons (entry, p->write_queue));
5977 else
5978 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5981 /* Remove the first element in the write_queue of process P, put its
5982 contents in OBJ, BUF and LEN, and return true. If the
5983 write_queue is empty, return false. */
5985 static bool
5986 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5987 const char **buf, ptrdiff_t *len)
5989 Lisp_Object entry, offset_length;
5990 ptrdiff_t offset;
5992 if (NILP (p->write_queue))
5993 return 0;
5995 entry = XCAR (p->write_queue);
5996 pset_write_queue (p, XCDR (p->write_queue));
5998 *obj = XCAR (entry);
5999 offset_length = XCDR (entry);
6001 *len = XINT (XCDR (offset_length));
6002 offset = XINT (XCAR (offset_length));
6003 *buf = SSDATA (*obj) + offset;
6005 return 1;
6008 /* Send some data to process PROC.
6009 BUF is the beginning of the data; LEN is the number of characters.
6010 OBJECT is the Lisp object that the data comes from. If OBJECT is
6011 nil or t, it means that the data comes from C string.
6013 If OBJECT is not nil, the data is encoded by PROC's coding-system
6014 for encoding before it is sent.
6016 This function can evaluate Lisp code and can garbage collect. */
6018 static void
6019 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
6020 Lisp_Object object)
6022 struct Lisp_Process *p = XPROCESS (proc);
6023 ssize_t rv;
6024 struct coding_system *coding;
6026 if (NETCONN_P (proc))
6028 wait_while_connecting (proc);
6029 wait_for_tls_negotiation (proc);
6032 if (p->raw_status_new)
6033 update_status (p);
6034 if (! EQ (p->status, Qrun))
6035 error ("Process %s not running", SDATA (p->name));
6036 if (p->outfd < 0)
6037 error ("Output file descriptor of %s is closed", SDATA (p->name));
6039 coding = proc_encode_coding_system[p->outfd];
6040 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
6042 if ((STRINGP (object) && STRING_MULTIBYTE (object))
6043 || (BUFFERP (object)
6044 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
6045 || EQ (object, Qt))
6047 pset_encode_coding_system
6048 (p, complement_process_encoding_system (p->encode_coding_system));
6049 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
6051 /* The coding system for encoding was changed to raw-text
6052 because we sent a unibyte text previously. Now we are
6053 sending a multibyte text, thus we must encode it by the
6054 original coding system specified for the current process.
6056 Another reason we come here is that the coding system
6057 was just complemented and a new one was returned by
6058 complement_process_encoding_system. */
6059 setup_coding_system (p->encode_coding_system, coding);
6060 Vlast_coding_system_used = p->encode_coding_system;
6062 coding->src_multibyte = 1;
6064 else
6066 coding->src_multibyte = 0;
6067 /* For sending a unibyte text, character code conversion should
6068 not take place but EOL conversion should. So, setup raw-text
6069 or one of the subsidiary if we have not yet done it. */
6070 if (CODING_REQUIRE_ENCODING (coding))
6072 if (CODING_REQUIRE_FLUSHING (coding))
6074 /* But, before changing the coding, we must flush out data. */
6075 coding->mode |= CODING_MODE_LAST_BLOCK;
6076 send_process (proc, "", 0, Qt);
6077 coding->mode &= CODING_MODE_LAST_BLOCK;
6079 setup_coding_system (raw_text_coding_system
6080 (Vlast_coding_system_used),
6081 coding);
6082 coding->src_multibyte = 0;
6085 coding->dst_multibyte = 0;
6087 if (CODING_REQUIRE_ENCODING (coding))
6089 coding->dst_object = Qt;
6090 if (BUFFERP (object))
6092 ptrdiff_t from_byte, from, to;
6093 ptrdiff_t save_pt, save_pt_byte;
6094 struct buffer *cur = current_buffer;
6096 set_buffer_internal (XBUFFER (object));
6097 save_pt = PT, save_pt_byte = PT_BYTE;
6099 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
6100 from = BYTE_TO_CHAR (from_byte);
6101 to = BYTE_TO_CHAR (from_byte + len);
6102 TEMP_SET_PT_BOTH (from, from_byte);
6103 encode_coding_object (coding, object, from, from_byte,
6104 to, from_byte + len, Qt);
6105 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
6106 set_buffer_internal (cur);
6108 else if (STRINGP (object))
6110 encode_coding_object (coding, object, 0, 0, SCHARS (object),
6111 SBYTES (object), Qt);
6113 else
6115 coding->dst_object = make_unibyte_string (buf, len);
6116 coding->produced = len;
6119 len = coding->produced;
6120 object = coding->dst_object;
6121 buf = SSDATA (object);
6124 /* If there is already data in the write_queue, put the new data
6125 in the back of queue. Otherwise, ignore it. */
6126 if (!NILP (p->write_queue))
6127 write_queue_push (p, object, buf, len, 0);
6129 do /* while !NILP (p->write_queue) */
6131 ptrdiff_t cur_len = -1;
6132 const char *cur_buf;
6133 Lisp_Object cur_object;
6135 /* If write_queue is empty, ignore it. */
6136 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
6138 cur_len = len;
6139 cur_buf = buf;
6140 cur_object = object;
6143 while (cur_len > 0)
6145 /* Send this batch, using one or more write calls. */
6146 ptrdiff_t written = 0;
6147 int outfd = p->outfd;
6148 #ifdef DATAGRAM_SOCKETS
6149 if (DATAGRAM_CHAN_P (outfd))
6151 rv = sendto (outfd, cur_buf, cur_len,
6152 0, datagram_address[outfd].sa,
6153 datagram_address[outfd].len);
6154 if (rv >= 0)
6155 written = rv;
6156 else if (errno == EMSGSIZE)
6157 report_file_error ("Sending datagram", proc);
6159 else
6160 #endif
6162 #ifdef HAVE_GNUTLS
6163 if (p->gnutls_p && p->gnutls_state)
6164 written = emacs_gnutls_write (p, cur_buf, cur_len);
6165 else
6166 #endif
6167 written = emacs_write_sig (outfd, cur_buf, cur_len);
6168 rv = (written ? 0 : -1);
6169 if (p->read_output_delay > 0
6170 && p->adaptive_read_buffering == 1)
6172 p->read_output_delay = 0;
6173 process_output_delay_count--;
6174 p->read_output_skip = 0;
6178 if (rv < 0)
6180 if (would_block (errno))
6181 /* Buffer is full. Wait, accepting input;
6182 that may allow the program
6183 to finish doing output and read more. */
6185 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6186 /* A gross hack to work around a bug in FreeBSD.
6187 In the following sequence, read(2) returns
6188 bogus data:
6190 write(2) 1022 bytes
6191 write(2) 954 bytes, get EAGAIN
6192 read(2) 1024 bytes in process_read_output
6193 read(2) 11 bytes in process_read_output
6195 That is, read(2) returns more bytes than have
6196 ever been written successfully. The 1033 bytes
6197 read are the 1022 bytes written successfully
6198 after processing (for example with CRs added if
6199 the terminal is set up that way which it is
6200 here). The same bytes will be seen again in a
6201 later read(2), without the CRs. */
6203 if (errno == EAGAIN)
6205 int flags = FWRITE;
6206 ioctl (p->outfd, TIOCFLUSH, &flags);
6208 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6210 /* Put what we should have written in wait_queue. */
6211 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
6212 wait_reading_process_output (0, 20 * 1000 * 1000,
6213 0, 0, Qnil, NULL, 0);
6214 /* Reread queue, to see what is left. */
6215 break;
6217 else if (errno == EPIPE)
6219 p->raw_status_new = 0;
6220 pset_status (p, list2 (Qexit, make_number (256)));
6221 p->tick = ++process_tick;
6222 deactivate_process (proc);
6223 error ("process %s no longer connected to pipe; closed it",
6224 SDATA (p->name));
6226 else
6227 /* This is a real error. */
6228 report_file_error ("Writing to process", proc);
6230 cur_buf += written;
6231 cur_len -= written;
6234 while (!NILP (p->write_queue));
6237 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
6238 3, 3, 0,
6239 doc: /* Send current contents of region as input to PROCESS.
6240 PROCESS may be a process, a buffer, the name of a process or buffer, or
6241 nil, indicating the current buffer's process.
6242 Called from program, takes three arguments, PROCESS, START and END.
6243 If the region is more than 500 characters long,
6244 it is sent in several bunches. This may happen even for shorter regions.
6245 Output from processes can arrive in between bunches.
6247 If PROCESS is a non-blocking network process that hasn't been fully
6248 set up yet, this function will block until socket setup has completed. */)
6249 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
6251 Lisp_Object proc = get_process (process);
6252 ptrdiff_t start_byte, end_byte;
6254 validate_region (&start, &end);
6256 start_byte = CHAR_TO_BYTE (XINT (start));
6257 end_byte = CHAR_TO_BYTE (XINT (end));
6259 if (XINT (start) < GPT && XINT (end) > GPT)
6260 move_gap_both (XINT (start), start_byte);
6262 if (NETCONN_P (proc))
6263 wait_while_connecting (proc);
6265 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
6266 end_byte - start_byte, Fcurrent_buffer ());
6268 return Qnil;
6271 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
6272 2, 2, 0,
6273 doc: /* Send PROCESS the contents of STRING as input.
6274 PROCESS may be a process, a buffer, the name of a process or buffer, or
6275 nil, indicating the current buffer's process.
6276 If STRING is more than 500 characters long,
6277 it is sent in several bunches. This may happen even for shorter strings.
6278 Output from processes can arrive in between bunches.
6280 If PROCESS is a non-blocking network process that hasn't been fully
6281 set up yet, this function will block until socket setup has completed. */)
6282 (Lisp_Object process, Lisp_Object string)
6284 CHECK_STRING (string);
6285 Lisp_Object proc = get_process (process);
6286 send_process (proc, SSDATA (string),
6287 SBYTES (string), string);
6288 return Qnil;
6291 /* Return the foreground process group for the tty/pty that
6292 the process P uses. */
6293 static pid_t
6294 emacs_get_tty_pgrp (struct Lisp_Process *p)
6296 pid_t gid = -1;
6298 #ifdef TIOCGPGRP
6299 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
6301 int fd;
6302 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6303 master side. Try the slave side. */
6304 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
6306 if (fd != -1)
6308 ioctl (fd, TIOCGPGRP, &gid);
6309 emacs_close (fd);
6312 #endif /* defined (TIOCGPGRP ) */
6314 return gid;
6317 DEFUN ("process-running-child-p", Fprocess_running_child_p,
6318 Sprocess_running_child_p, 0, 1, 0,
6319 doc: /* Return non-nil if PROCESS has given the terminal to a
6320 child. If the operating system does not make it possible to find out,
6321 return t. If we can find out, return the numeric ID of the foreground
6322 process group. */)
6323 (Lisp_Object process)
6325 /* Initialize in case ioctl doesn't exist or gives an error,
6326 in a way that will cause returning t. */
6327 Lisp_Object proc = get_process (process);
6328 struct Lisp_Process *p = XPROCESS (proc);
6330 if (!EQ (p->type, Qreal))
6331 error ("Process %s is not a subprocess",
6332 SDATA (p->name));
6333 if (p->infd < 0)
6334 error ("Process %s is not active",
6335 SDATA (p->name));
6337 pid_t gid = emacs_get_tty_pgrp (p);
6339 if (gid == p->pid)
6340 return Qnil;
6341 if (gid != -1)
6342 return make_number (gid);
6343 return Qt;
6346 /* Send a signal number SIGNO to PROCESS.
6347 If CURRENT_GROUP is t, that means send to the process group
6348 that currently owns the terminal being used to communicate with PROCESS.
6349 This is used for various commands in shell mode.
6350 If CURRENT_GROUP is lambda, that means send to the process group
6351 that currently owns the terminal, but only if it is NOT the shell itself.
6353 If NOMSG is false, insert signal-announcements into process's buffers
6354 right away.
6356 If we can, we try to signal PROCESS by sending control characters
6357 down the pty. This allows us to signal inferiors who have changed
6358 their uid, for which kill would return an EPERM error. */
6360 static void
6361 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
6362 bool nomsg)
6364 Lisp_Object proc;
6365 struct Lisp_Process *p;
6366 pid_t gid;
6367 bool no_pgrp = 0;
6369 proc = get_process (process);
6370 p = XPROCESS (proc);
6372 if (!EQ (p->type, Qreal))
6373 error ("Process %s is not a subprocess",
6374 SDATA (p->name));
6375 if (p->infd < 0)
6376 error ("Process %s is not active",
6377 SDATA (p->name));
6379 if (!p->pty_flag)
6380 current_group = Qnil;
6382 /* If we are using pgrps, get a pgrp number and make it negative. */
6383 if (NILP (current_group))
6384 /* Send the signal to the shell's process group. */
6385 gid = p->pid;
6386 else
6388 #ifdef SIGNALS_VIA_CHARACTERS
6389 /* If possible, send signals to the entire pgrp
6390 by sending an input character to it. */
6392 struct termios t;
6393 cc_t *sig_char = NULL;
6395 tcgetattr (p->infd, &t);
6397 switch (signo)
6399 case SIGINT:
6400 sig_char = &t.c_cc[VINTR];
6401 break;
6403 case SIGQUIT:
6404 sig_char = &t.c_cc[VQUIT];
6405 break;
6407 case SIGTSTP:
6408 #ifdef VSWTCH
6409 sig_char = &t.c_cc[VSWTCH];
6410 #else
6411 sig_char = &t.c_cc[VSUSP];
6412 #endif
6413 break;
6416 if (sig_char && *sig_char != CDISABLE)
6418 send_process (proc, (char *) sig_char, 1, Qnil);
6419 return;
6421 /* If we can't send the signal with a character,
6422 fall through and send it another way. */
6424 /* The code above may fall through if it can't
6425 handle the signal. */
6426 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6428 #ifdef TIOCGPGRP
6429 /* Get the current pgrp using the tty itself, if we have that.
6430 Otherwise, use the pty to get the pgrp.
6431 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6432 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6433 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6434 His patch indicates that if TIOCGPGRP returns an error, then
6435 we should just assume that p->pid is also the process group id. */
6437 gid = emacs_get_tty_pgrp (p);
6439 if (gid == -1)
6440 /* If we can't get the information, assume
6441 the shell owns the tty. */
6442 gid = p->pid;
6444 /* It is not clear whether anything really can set GID to -1.
6445 Perhaps on some system one of those ioctls can or could do so.
6446 Or perhaps this is vestigial. */
6447 if (gid == -1)
6448 no_pgrp = 1;
6449 #else /* ! defined (TIOCGPGRP) */
6450 /* Can't select pgrps on this system, so we know that
6451 the child itself heads the pgrp. */
6452 gid = p->pid;
6453 #endif /* ! defined (TIOCGPGRP) */
6455 /* If current_group is lambda, and the shell owns the terminal,
6456 don't send any signal. */
6457 if (EQ (current_group, Qlambda) && gid == p->pid)
6458 return;
6461 #ifdef SIGCONT
6462 if (signo == SIGCONT)
6464 p->raw_status_new = 0;
6465 pset_status (p, Qrun);
6466 p->tick = ++process_tick;
6467 if (!nomsg)
6469 status_notify (NULL, NULL);
6470 redisplay_preserve_echo_area (13);
6473 #endif
6475 #ifdef TIOCSIGSEND
6476 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6477 We don't know whether the bug is fixed in later HP-UX versions. */
6478 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6479 return;
6480 #endif
6482 /* If we don't have process groups, send the signal to the immediate
6483 subprocess. That isn't really right, but it's better than any
6484 obvious alternative. */
6485 pid_t pid = no_pgrp ? gid : - gid;
6487 /* Do not kill an already-reaped process, as that could kill an
6488 innocent bystander that happens to have the same process ID. */
6489 sigset_t oldset;
6490 block_child_signal (&oldset);
6491 if (p->alive)
6492 kill (pid, signo);
6493 unblock_child_signal (&oldset);
6496 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6497 doc: /* Interrupt process PROCESS.
6498 PROCESS may be a process, a buffer, or the name of a process or buffer.
6499 No arg or nil means current buffer's process.
6500 Second arg CURRENT-GROUP non-nil means send signal to
6501 the current process-group of the process's controlling terminal
6502 rather than to the process's own process group.
6503 If the process is a shell, this means interrupt current subjob
6504 rather than the shell.
6506 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6507 don't send the signal. */)
6508 (Lisp_Object process, Lisp_Object current_group)
6510 process_send_signal (process, SIGINT, current_group, 0);
6511 return process;
6514 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6515 doc: /* Kill process PROCESS. May be process or name of one.
6516 See function `interrupt-process' for more details on usage. */)
6517 (Lisp_Object process, Lisp_Object current_group)
6519 process_send_signal (process, SIGKILL, current_group, 0);
6520 return process;
6523 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6524 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6525 See function `interrupt-process' for more details on usage. */)
6526 (Lisp_Object process, Lisp_Object current_group)
6528 process_send_signal (process, SIGQUIT, current_group, 0);
6529 return process;
6532 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6533 doc: /* Stop process PROCESS. May be process or name of one.
6534 See function `interrupt-process' for more details on usage.
6535 If PROCESS is a network or serial or pipe connection, inhibit handling
6536 of incoming traffic. */)
6537 (Lisp_Object process, Lisp_Object current_group)
6539 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6540 || PIPECONN_P (process)))
6542 struct Lisp_Process *p;
6544 p = XPROCESS (process);
6545 if (NILP (p->command)
6546 && p->infd >= 0)
6548 FD_CLR (p->infd, &input_wait_mask);
6549 FD_CLR (p->infd, &non_keyboard_wait_mask);
6551 pset_command (p, Qt);
6552 return process;
6554 #ifndef SIGTSTP
6555 error ("No SIGTSTP support");
6556 #else
6557 process_send_signal (process, SIGTSTP, current_group, 0);
6558 #endif
6559 return process;
6562 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6563 doc: /* Continue process PROCESS. May be process or name of one.
6564 See function `interrupt-process' for more details on usage.
6565 If PROCESS is a network or serial process, resume handling of incoming
6566 traffic. */)
6567 (Lisp_Object process, Lisp_Object current_group)
6569 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6570 || PIPECONN_P (process)))
6572 struct Lisp_Process *p;
6574 p = XPROCESS (process);
6575 if (EQ (p->command, Qt)
6576 && p->infd >= 0
6577 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6579 FD_SET (p->infd, &input_wait_mask);
6580 FD_SET (p->infd, &non_keyboard_wait_mask);
6581 #ifdef WINDOWSNT
6582 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6583 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6584 #else /* not WINDOWSNT */
6585 tcflush (p->infd, TCIFLUSH);
6586 #endif /* not WINDOWSNT */
6588 pset_command (p, Qnil);
6589 return process;
6591 #ifdef SIGCONT
6592 process_send_signal (process, SIGCONT, current_group, 0);
6593 #else
6594 error ("No SIGCONT support");
6595 #endif
6596 return process;
6599 /* Return the integer value of the signal whose abbreviation is ABBR,
6600 or a negative number if there is no such signal. */
6601 static int
6602 abbr_to_signal (char const *name)
6604 int i, signo;
6605 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6607 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6608 name += 3;
6610 for (i = 0; i < sizeof sigbuf; i++)
6612 sigbuf[i] = c_toupper (name[i]);
6613 if (! sigbuf[i])
6614 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6617 return -1;
6620 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6621 2, 2, "sProcess (name or number): \nnSignal code: ",
6622 doc: /* Send PROCESS the signal with code SIGCODE.
6623 PROCESS may also be a number specifying the process id of the
6624 process to signal; in this case, the process need not be a child of
6625 this Emacs.
6626 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6627 (Lisp_Object process, Lisp_Object sigcode)
6629 pid_t pid;
6630 int signo;
6632 if (STRINGP (process))
6634 Lisp_Object tem = Fget_process (process);
6635 if (NILP (tem))
6637 Lisp_Object process_number
6638 = string_to_number (SSDATA (process), 10, 1);
6639 if (NUMBERP (process_number))
6640 tem = process_number;
6642 process = tem;
6644 else if (!NUMBERP (process))
6645 process = get_process (process);
6647 if (NILP (process))
6648 return process;
6650 if (NUMBERP (process))
6651 CONS_TO_INTEGER (process, pid_t, pid);
6652 else
6654 CHECK_PROCESS (process);
6655 pid = XPROCESS (process)->pid;
6656 if (pid <= 0)
6657 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6660 if (INTEGERP (sigcode))
6662 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6663 signo = XINT (sigcode);
6665 else
6667 char *name;
6669 CHECK_SYMBOL (sigcode);
6670 name = SSDATA (SYMBOL_NAME (sigcode));
6672 signo = abbr_to_signal (name);
6673 if (signo < 0)
6674 error ("Undefined signal name %s", name);
6677 return make_number (kill (pid, signo));
6680 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6681 doc: /* Make PROCESS see end-of-file in its input.
6682 EOF comes after any text already sent to it.
6683 PROCESS may be a process, a buffer, the name of a process or buffer, or
6684 nil, indicating the current buffer's process.
6685 If PROCESS is a network connection, or is a process communicating
6686 through a pipe (as opposed to a pty), then you cannot send any more
6687 text to PROCESS after you call this function.
6688 If PROCESS is a serial process, wait until all output written to the
6689 process has been transmitted to the serial port. */)
6690 (Lisp_Object process)
6692 Lisp_Object proc;
6693 struct coding_system *coding = NULL;
6694 int outfd;
6696 proc = get_process (process);
6698 if (NETCONN_P (proc))
6699 wait_while_connecting (proc);
6701 if (DATAGRAM_CONN_P (proc))
6702 return process;
6705 outfd = XPROCESS (proc)->outfd;
6706 if (outfd >= 0)
6707 coding = proc_encode_coding_system[outfd];
6709 /* Make sure the process is really alive. */
6710 if (XPROCESS (proc)->raw_status_new)
6711 update_status (XPROCESS (proc));
6712 if (! EQ (XPROCESS (proc)->status, Qrun))
6713 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6715 if (coding && CODING_REQUIRE_FLUSHING (coding))
6717 coding->mode |= CODING_MODE_LAST_BLOCK;
6718 send_process (proc, "", 0, Qnil);
6721 if (XPROCESS (proc)->pty_flag)
6722 send_process (proc, "\004", 1, Qnil);
6723 else if (EQ (XPROCESS (proc)->type, Qserial))
6725 #ifndef WINDOWSNT
6726 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6727 report_file_error ("Failed tcdrain", Qnil);
6728 #endif /* not WINDOWSNT */
6729 /* Do nothing on Windows because writes are blocking. */
6731 else
6733 struct Lisp_Process *p = XPROCESS (proc);
6734 int old_outfd = p->outfd;
6735 int new_outfd;
6737 #ifdef HAVE_SHUTDOWN
6738 /* If this is a network connection, or socketpair is used
6739 for communication with the subprocess, call shutdown to cause EOF.
6740 (In some old system, shutdown to socketpair doesn't work.
6741 Then we just can't win.) */
6742 if (0 <= old_outfd
6743 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6744 shutdown (old_outfd, 1);
6745 #endif
6746 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6747 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6748 if (new_outfd < 0)
6749 report_file_error ("Opening null device", Qnil);
6750 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6751 p->outfd = new_outfd;
6753 if (!proc_encode_coding_system[new_outfd])
6754 proc_encode_coding_system[new_outfd]
6755 = xmalloc (sizeof (struct coding_system));
6756 if (old_outfd >= 0)
6758 *proc_encode_coding_system[new_outfd]
6759 = *proc_encode_coding_system[old_outfd];
6760 memset (proc_encode_coding_system[old_outfd], 0,
6761 sizeof (struct coding_system));
6763 else
6764 setup_coding_system (p->encode_coding_system,
6765 proc_encode_coding_system[new_outfd]);
6767 return process;
6770 /* The main Emacs thread records child processes in three places:
6772 - Vprocess_alist, for asynchronous subprocesses, which are child
6773 processes visible to Lisp.
6775 - deleted_pid_list, for child processes invisible to Lisp,
6776 typically because of delete-process. These are recorded so that
6777 the processes can be reaped when they exit, so that the operating
6778 system's process table is not cluttered by zombies.
6780 - the local variable PID in Fcall_process, call_process_cleanup and
6781 call_process_kill, for synchronous subprocesses.
6782 record_unwind_protect is used to make sure this process is not
6783 forgotten: if the user interrupts call-process and the child
6784 process refuses to exit immediately even with two C-g's,
6785 call_process_kill adds PID's contents to deleted_pid_list before
6786 returning.
6788 The main Emacs thread invokes waitpid only on child processes that
6789 it creates and that have not been reaped. This avoid races on
6790 platforms such as GTK, where other threads create their own
6791 subprocesses which the main thread should not reap. For example,
6792 if the main thread attempted to reap an already-reaped child, it
6793 might inadvertently reap a GTK-created process that happened to
6794 have the same process ID. */
6796 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6797 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6798 keep track of its own children. GNUstep is similar. */
6800 static void dummy_handler (int sig) {}
6801 static signal_handler_t volatile lib_child_handler;
6803 /* Handle a SIGCHLD signal by looking for known child processes of
6804 Emacs whose status have changed. For each one found, record its
6805 new status.
6807 All we do is change the status; we do not run sentinels or print
6808 notifications. That is saved for the next time keyboard input is
6809 done, in order to avoid timing errors.
6811 ** WARNING: this can be called during garbage collection.
6812 Therefore, it must not be fooled by the presence of mark bits in
6813 Lisp objects.
6815 ** USG WARNING: Although it is not obvious from the documentation
6816 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6817 signal() before executing at least one wait(), otherwise the
6818 handler will be called again, resulting in an infinite loop. The
6819 relevant portion of the documentation reads "SIGCLD signals will be
6820 queued and the signal-catching function will be continually
6821 reentered until the queue is empty". Invoking signal() causes the
6822 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6823 Inc.
6825 ** Malloc WARNING: This should never call malloc either directly or
6826 indirectly; if it does, that is a bug. */
6828 static void
6829 handle_child_signal (int sig)
6831 Lisp_Object tail, proc;
6833 /* Find the process that signaled us, and record its status. */
6835 /* The process can have been deleted by Fdelete_process, or have
6836 been started asynchronously by Fcall_process. */
6837 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6839 bool all_pids_are_fixnums
6840 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6841 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6842 Lisp_Object head = XCAR (tail);
6843 Lisp_Object xpid;
6844 if (! CONSP (head))
6845 continue;
6846 xpid = XCAR (head);
6847 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6849 pid_t deleted_pid;
6850 if (INTEGERP (xpid))
6851 deleted_pid = XINT (xpid);
6852 else
6853 deleted_pid = XFLOAT_DATA (xpid);
6854 if (child_status_changed (deleted_pid, 0, 0))
6856 if (STRINGP (XCDR (head)))
6857 unlink (SSDATA (XCDR (head)));
6858 XSETCAR (tail, Qnil);
6863 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6864 FOR_EACH_PROCESS (tail, proc)
6866 struct Lisp_Process *p = XPROCESS (proc);
6867 int status;
6869 if (p->alive
6870 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6872 /* Change the status of the process that was found. */
6873 p->tick = ++process_tick;
6874 p->raw_status = status;
6875 p->raw_status_new = 1;
6877 /* If process has terminated, stop waiting for its output. */
6878 if (WIFSIGNALED (status) || WIFEXITED (status))
6880 bool clear_desc_flag = 0;
6881 p->alive = 0;
6882 if (p->infd >= 0)
6883 clear_desc_flag = 1;
6885 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6886 if (clear_desc_flag)
6888 FD_CLR (p->infd, &input_wait_mask);
6889 FD_CLR (p->infd, &non_keyboard_wait_mask);
6895 lib_child_handler (sig);
6896 #ifdef NS_IMPL_GNUSTEP
6897 /* NSTask in GNUstep sets its child handler each time it is called.
6898 So we must re-set ours. */
6899 catch_child_signal ();
6900 #endif
6903 static void
6904 deliver_child_signal (int sig)
6906 deliver_process_signal (sig, handle_child_signal);
6910 static Lisp_Object
6911 exec_sentinel_error_handler (Lisp_Object error_val)
6913 cmd_error_internal (error_val, "error in process sentinel: ");
6914 Vinhibit_quit = Qt;
6915 update_echo_area ();
6916 Fsleep_for (make_number (2), Qnil);
6917 return Qt;
6920 static void
6921 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6923 Lisp_Object sentinel, odeactivate;
6924 struct Lisp_Process *p = XPROCESS (proc);
6925 ptrdiff_t count = SPECPDL_INDEX ();
6926 bool outer_running_asynch_code = running_asynch_code;
6927 int waiting = waiting_for_user_input_p;
6929 if (inhibit_sentinels)
6930 return;
6932 odeactivate = Vdeactivate_mark;
6933 #if 0
6934 Lisp_Object obuffer, okeymap;
6935 XSETBUFFER (obuffer, current_buffer);
6936 okeymap = BVAR (current_buffer, keymap);
6937 #endif
6939 /* There's no good reason to let sentinels change the current
6940 buffer, and many callers of accept-process-output, sit-for, and
6941 friends don't expect current-buffer to be changed from under them. */
6942 record_unwind_current_buffer ();
6944 sentinel = p->sentinel;
6946 /* Inhibit quit so that random quits don't screw up a running filter. */
6947 specbind (Qinhibit_quit, Qt);
6948 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6950 /* In case we get recursively called,
6951 and we already saved the match data nonrecursively,
6952 save the same match data in safely recursive fashion. */
6953 if (outer_running_asynch_code)
6955 Lisp_Object tem;
6956 tem = Fmatch_data (Qnil, Qnil, Qnil);
6957 restore_search_regs ();
6958 record_unwind_save_match_data ();
6959 Fset_match_data (tem, Qt);
6962 /* For speed, if a search happens within this code,
6963 save the match data in a special nonrecursive fashion. */
6964 running_asynch_code = 1;
6966 internal_condition_case_1 (read_process_output_call,
6967 list3 (sentinel, proc, reason),
6968 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6969 exec_sentinel_error_handler);
6971 /* If we saved the match data nonrecursively, restore it now. */
6972 restore_search_regs ();
6973 running_asynch_code = outer_running_asynch_code;
6975 Vdeactivate_mark = odeactivate;
6977 /* Restore waiting_for_user_input_p as it was
6978 when we were called, in case the filter clobbered it. */
6979 waiting_for_user_input_p = waiting;
6981 #if 0
6982 if (! EQ (Fcurrent_buffer (), obuffer)
6983 || ! EQ (current_buffer->keymap, okeymap))
6984 #endif
6985 /* But do it only if the caller is actually going to read events.
6986 Otherwise there's no need to make him wake up, and it could
6987 cause trouble (for example it would make sit_for return). */
6988 if (waiting_for_user_input_p == -1)
6989 record_asynch_buffer_change ();
6991 unbind_to (count, Qnil);
6994 /* Report all recent events of a change in process status
6995 (either run the sentinel or output a message).
6996 This is usually done while Emacs is waiting for keyboard input
6997 but can be done at other times.
6999 Return positive if any input was received from WAIT_PROC (or from
7000 any process if WAIT_PROC is null), zero if input was attempted but
7001 none received, and negative if we didn't even try. */
7003 static int
7004 status_notify (struct Lisp_Process *deleting_process,
7005 struct Lisp_Process *wait_proc)
7007 Lisp_Object proc;
7008 Lisp_Object tail, msg;
7009 int got_some_output = -1;
7011 tail = Qnil;
7012 msg = Qnil;
7014 /* Set this now, so that if new processes are created by sentinels
7015 that we run, we get called again to handle their status changes. */
7016 update_tick = process_tick;
7018 FOR_EACH_PROCESS (tail, proc)
7020 Lisp_Object symbol;
7021 register struct Lisp_Process *p = XPROCESS (proc);
7023 if (p->tick != p->update_tick)
7025 p->update_tick = p->tick;
7027 /* If process is still active, read any output that remains. */
7028 while (! EQ (p->filter, Qt)
7029 && ! connecting_status (p->status)
7030 && ! EQ (p->status, Qlisten)
7031 /* Network or serial process not stopped: */
7032 && ! EQ (p->command, Qt)
7033 && p->infd >= 0
7034 && p != deleting_process)
7036 int nread = read_process_output (proc, p->infd);
7037 if ((!wait_proc || wait_proc == XPROCESS (proc))
7038 && got_some_output < nread)
7039 got_some_output = nread;
7040 if (nread <= 0)
7041 break;
7044 /* Get the text to use for the message. */
7045 if (p->raw_status_new)
7046 update_status (p);
7047 msg = status_message (p);
7049 /* If process is terminated, deactivate it or delete it. */
7050 symbol = p->status;
7051 if (CONSP (p->status))
7052 symbol = XCAR (p->status);
7054 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
7055 || EQ (symbol, Qclosed))
7057 if (delete_exited_processes)
7058 remove_process (proc);
7059 else
7060 deactivate_process (proc);
7063 /* The actions above may have further incremented p->tick.
7064 So set p->update_tick again so that an error in the sentinel will
7065 not cause this code to be run again. */
7066 p->update_tick = p->tick;
7067 /* Now output the message suitably. */
7068 exec_sentinel (proc, msg);
7069 if (BUFFERP (p->buffer))
7070 /* In case it uses %s in mode-line-format. */
7071 bset_update_mode_line (XBUFFER (p->buffer));
7073 } /* end for */
7075 return got_some_output;
7078 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
7079 Sinternal_default_process_sentinel, 2, 2, 0,
7080 doc: /* Function used as default sentinel for processes.
7081 This inserts a status message into the process's buffer, if there is one. */)
7082 (Lisp_Object proc, Lisp_Object msg)
7084 Lisp_Object buffer, symbol;
7085 struct Lisp_Process *p;
7086 CHECK_PROCESS (proc);
7087 p = XPROCESS (proc);
7088 buffer = p->buffer;
7089 symbol = p->status;
7090 if (CONSP (symbol))
7091 symbol = XCAR (symbol);
7093 if (!EQ (symbol, Qrun) && !NILP (buffer))
7095 Lisp_Object tem;
7096 struct buffer *old = current_buffer;
7097 ptrdiff_t opoint, opoint_byte;
7098 ptrdiff_t before, before_byte;
7100 /* Avoid error if buffer is deleted
7101 (probably that's why the process is dead, too). */
7102 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
7103 return Qnil;
7104 Fset_buffer (buffer);
7106 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
7107 msg = (code_convert_string_norecord
7108 (msg, Vlocale_coding_system, 1));
7110 opoint = PT;
7111 opoint_byte = PT_BYTE;
7112 /* Insert new output into buffer
7113 at the current end-of-output marker,
7114 thus preserving logical ordering of input and output. */
7115 if (XMARKER (p->mark)->buffer)
7116 Fgoto_char (p->mark);
7117 else
7118 SET_PT_BOTH (ZV, ZV_BYTE);
7120 before = PT;
7121 before_byte = PT_BYTE;
7123 tem = BVAR (current_buffer, read_only);
7124 bset_read_only (current_buffer, Qnil);
7125 insert_string ("\nProcess ");
7126 { /* FIXME: temporary kludge. */
7127 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
7128 insert_string (" ");
7129 Finsert (1, &msg);
7130 bset_read_only (current_buffer, tem);
7131 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
7133 if (opoint >= before)
7134 SET_PT_BOTH (opoint + (PT - before),
7135 opoint_byte + (PT_BYTE - before_byte));
7136 else
7137 SET_PT_BOTH (opoint, opoint_byte);
7139 set_buffer_internal (old);
7141 return Qnil;
7145 DEFUN ("set-process-coding-system", Fset_process_coding_system,
7146 Sset_process_coding_system, 1, 3, 0,
7147 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
7148 DECODING will be used to decode subprocess output and ENCODING to
7149 encode subprocess input. */)
7150 (Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
7152 CHECK_PROCESS (process);
7154 struct Lisp_Process *p = XPROCESS (process);
7156 Fcheck_coding_system (decoding);
7157 Fcheck_coding_system (encoding);
7158 encoding = coding_inherit_eol_type (encoding, Qnil);
7159 pset_decode_coding_system (p, decoding);
7160 pset_encode_coding_system (p, encoding);
7162 /* If the sockets haven't been set up yet, the final setup part of
7163 this will be called asynchronously. */
7164 if (p->infd < 0 || p->outfd < 0)
7165 return Qnil;
7167 setup_process_coding_systems (process);
7169 return Qnil;
7172 DEFUN ("process-coding-system",
7173 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
7174 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7175 (register Lisp_Object process)
7177 CHECK_PROCESS (process);
7178 return Fcons (XPROCESS (process)->decode_coding_system,
7179 XPROCESS (process)->encode_coding_system);
7182 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
7183 Sset_process_filter_multibyte, 2, 2, 0,
7184 doc: /* Set multibyteness of the strings given to PROCESS's filter.
7185 If FLAG is non-nil, the filter is given multibyte strings.
7186 If FLAG is nil, the filter is given unibyte strings. In this case,
7187 all character code conversion except for end-of-line conversion is
7188 suppressed. */)
7189 (Lisp_Object process, Lisp_Object flag)
7191 CHECK_PROCESS (process);
7193 struct Lisp_Process *p = XPROCESS (process);
7194 if (NILP (flag))
7195 pset_decode_coding_system
7196 (p, raw_text_coding_system (p->decode_coding_system));
7198 /* If the sockets haven't been set up yet, the final setup part of
7199 this will be called asynchronously. */
7200 if (p->infd < 0 || p->outfd < 0)
7201 return Qnil;
7203 setup_process_coding_systems (process);
7205 return Qnil;
7208 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
7209 Sprocess_filter_multibyte_p, 1, 1, 0,
7210 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7211 (Lisp_Object process)
7213 CHECK_PROCESS (process);
7214 struct Lisp_Process *p = XPROCESS (process);
7215 if (p->infd < 0)
7216 return Qnil;
7217 struct coding_system *coding = proc_decode_coding_system[p->infd];
7218 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
7224 # ifdef HAVE_GPM
7226 void
7227 add_gpm_wait_descriptor (int desc)
7229 add_keyboard_wait_descriptor (desc);
7232 void
7233 delete_gpm_wait_descriptor (int desc)
7235 delete_keyboard_wait_descriptor (desc);
7238 # endif
7240 # ifdef USABLE_SIGIO
7242 /* Return true if *MASK has a bit set
7243 that corresponds to one of the keyboard input descriptors. */
7245 static bool
7246 keyboard_bit_set (fd_set *mask)
7248 int fd;
7250 for (fd = 0; fd <= max_input_desc; fd++)
7251 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
7252 && !FD_ISSET (fd, &non_keyboard_wait_mask))
7253 return 1;
7255 return 0;
7257 # endif
7259 #else /* not subprocesses */
7261 /* Defined in msdos.c. */
7262 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
7263 struct timespec *, void *);
7265 /* Implementation of wait_reading_process_output, assuming that there
7266 are no subprocesses. Used only by the MS-DOS build.
7268 Wait for timeout to elapse and/or keyboard input to be available.
7270 TIME_LIMIT is:
7271 timeout in seconds
7272 If negative, gobble data immediately available but don't wait for any.
7274 NSECS is:
7275 an additional duration to wait, measured in nanoseconds
7276 If TIME_LIMIT is zero, then:
7277 If NSECS == 0, there is no limit.
7278 If NSECS > 0, the timeout consists of NSECS only.
7279 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7281 READ_KBD is:
7282 0 to ignore keyboard input, or
7283 1 to return when input is available, or
7284 -1 means caller will actually read the input, so don't throw to
7285 the quit handler.
7287 see full version for other parameters. We know that wait_proc will
7288 always be NULL, since `subprocesses' isn't defined.
7290 DO_DISPLAY means redisplay should be done to show subprocess
7291 output that arrives.
7293 Return -1 signifying we got no output and did not try. */
7296 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
7297 bool do_display,
7298 Lisp_Object wait_for_cell,
7299 struct Lisp_Process *wait_proc, int just_wait_proc)
7301 register int nfds;
7302 struct timespec end_time, timeout;
7303 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
7305 if (TYPE_MAXIMUM (time_t) < time_limit)
7306 time_limit = TYPE_MAXIMUM (time_t);
7308 if (time_limit < 0 || nsecs < 0)
7309 wait = MINIMUM;
7310 else if (time_limit > 0 || nsecs > 0)
7312 wait = TIMEOUT;
7313 end_time = timespec_add (current_timespec (),
7314 make_timespec (time_limit, nsecs));
7316 else
7317 wait = INFINITY;
7319 /* Turn off periodic alarms (in case they are in use)
7320 and then turn off any other atimers,
7321 because the select emulator uses alarms. */
7322 stop_polling ();
7323 turn_on_atimers (0);
7325 while (1)
7327 bool timeout_reduced_for_timers = false;
7328 fd_set waitchannels;
7329 int xerrno;
7331 /* If calling from keyboard input, do not quit
7332 since we want to return C-g as an input character.
7333 Otherwise, do pending quit if requested. */
7334 if (read_kbd >= 0)
7335 QUIT;
7337 /* Exit now if the cell we're waiting for became non-nil. */
7338 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7339 break;
7341 /* Compute time from now till when time limit is up. */
7342 /* Exit if already run out. */
7343 if (wait == TIMEOUT)
7345 struct timespec now = current_timespec ();
7346 if (timespec_cmp (end_time, now) <= 0)
7347 break;
7348 timeout = timespec_sub (end_time, now);
7350 else
7351 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
7353 /* If our caller will not immediately handle keyboard events,
7354 run timer events directly.
7355 (Callers that will immediately read keyboard events
7356 call timer_delay on their own.) */
7357 if (NILP (wait_for_cell))
7359 struct timespec timer_delay;
7363 unsigned old_timers_run = timers_run;
7364 timer_delay = timer_check ();
7365 if (timers_run != old_timers_run && do_display)
7366 /* We must retry, since a timer may have requeued itself
7367 and that could alter the time delay. */
7368 redisplay_preserve_echo_area (14);
7369 else
7370 break;
7372 while (!detect_input_pending ());
7374 /* If there is unread keyboard input, also return. */
7375 if (read_kbd != 0
7376 && requeued_events_pending_p ())
7377 break;
7379 if (timespec_valid_p (timer_delay))
7381 if (timespec_cmp (timer_delay, timeout) < 0)
7383 timeout = timer_delay;
7384 timeout_reduced_for_timers = true;
7389 /* Cause C-g and alarm signals to take immediate action,
7390 and cause input available signals to zero out timeout. */
7391 if (read_kbd < 0)
7392 set_waiting_for_input (&timeout);
7394 /* If a frame has been newly mapped and needs updating,
7395 reprocess its display stuff. */
7396 if (frame_garbaged && do_display)
7398 clear_waiting_for_input ();
7399 redisplay_preserve_echo_area (15);
7400 if (read_kbd < 0)
7401 set_waiting_for_input (&timeout);
7404 /* Wait till there is something to do. */
7405 FD_ZERO (&waitchannels);
7406 if (read_kbd && detect_input_pending ())
7407 nfds = 0;
7408 else
7410 if (read_kbd || !NILP (wait_for_cell))
7411 FD_SET (0, &waitchannels);
7412 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7415 xerrno = errno;
7417 /* Make C-g and alarm signals set flags again. */
7418 clear_waiting_for_input ();
7420 /* If we woke up due to SIGWINCH, actually change size now. */
7421 do_pending_window_change (0);
7423 if (wait < INFINITY && nfds == 0 && ! timeout_reduced_for_timers)
7424 /* We waited the full specified time, so return now. */
7425 break;
7427 if (nfds == -1)
7429 /* If the system call was interrupted, then go around the
7430 loop again. */
7431 if (xerrno == EINTR)
7432 FD_ZERO (&waitchannels);
7433 else
7434 report_file_errno ("Failed select", Qnil, xerrno);
7437 /* Check for keyboard input. */
7439 if (read_kbd
7440 && detect_input_pending_run_timers (do_display))
7442 swallow_events (do_display);
7443 if (detect_input_pending_run_timers (do_display))
7444 break;
7447 /* If there is unread keyboard input, also return. */
7448 if (read_kbd
7449 && requeued_events_pending_p ())
7450 break;
7452 /* If wait_for_cell. check for keyboard input
7453 but don't run any timers.
7454 ??? (It seems wrong to me to check for keyboard
7455 input at all when wait_for_cell, but the code
7456 has been this way since July 1994.
7457 Try changing this after version 19.31.) */
7458 if (! NILP (wait_for_cell)
7459 && detect_input_pending ())
7461 swallow_events (do_display);
7462 if (detect_input_pending ())
7463 break;
7466 /* Exit now if the cell we're waiting for became non-nil. */
7467 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7468 break;
7471 start_polling ();
7473 return -1;
7476 #endif /* not subprocesses */
7478 /* The following functions are needed even if async subprocesses are
7479 not supported. Some of them are no-op stubs in that case. */
7481 #ifdef HAVE_TIMERFD
7483 /* Add FD, which is a descriptor returned by timerfd_create,
7484 to the set of non-keyboard input descriptors. */
7486 void
7487 add_timer_wait_descriptor (int fd)
7489 FD_SET (fd, &input_wait_mask);
7490 FD_SET (fd, &non_keyboard_wait_mask);
7491 FD_SET (fd, &non_process_wait_mask);
7492 fd_callback_info[fd].func = timerfd_callback;
7493 fd_callback_info[fd].data = NULL;
7494 fd_callback_info[fd].condition |= FOR_READ;
7495 if (fd > max_input_desc)
7496 max_input_desc = fd;
7499 #endif /* HAVE_TIMERFD */
7501 /* If program file NAME starts with /: for quoting a magic
7502 name, remove that, preserving the multibyteness of NAME. */
7504 Lisp_Object
7505 remove_slash_colon (Lisp_Object name)
7507 return
7508 ((SBYTES (name) > 2 && SREF (name, 0) == '/' && SREF (name, 1) == ':')
7509 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
7510 SBYTES (name) - 2, STRING_MULTIBYTE (name))
7511 : name);
7514 /* Add DESC to the set of keyboard input descriptors. */
7516 void
7517 add_keyboard_wait_descriptor (int desc)
7519 #ifdef subprocesses /* Actually means "not MSDOS". */
7520 FD_SET (desc, &input_wait_mask);
7521 FD_SET (desc, &non_process_wait_mask);
7522 if (desc > max_input_desc)
7523 max_input_desc = desc;
7524 #endif
7527 /* From now on, do not expect DESC to give keyboard input. */
7529 void
7530 delete_keyboard_wait_descriptor (int desc)
7532 #ifdef subprocesses
7533 FD_CLR (desc, &input_wait_mask);
7534 FD_CLR (desc, &non_process_wait_mask);
7535 delete_input_desc (desc);
7536 #endif
7539 /* Setup coding systems of PROCESS. */
7541 void
7542 setup_process_coding_systems (Lisp_Object process)
7544 #ifdef subprocesses
7545 struct Lisp_Process *p = XPROCESS (process);
7546 int inch = p->infd;
7547 int outch = p->outfd;
7548 Lisp_Object coding_system;
7550 if (inch < 0 || outch < 0)
7551 return;
7553 if (!proc_decode_coding_system[inch])
7554 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7555 coding_system = p->decode_coding_system;
7556 if (EQ (p->filter, Qinternal_default_process_filter)
7557 && BUFFERP (p->buffer))
7559 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7560 coding_system = raw_text_coding_system (coding_system);
7562 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7564 if (!proc_encode_coding_system[outch])
7565 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7566 setup_coding_system (p->encode_coding_system,
7567 proc_encode_coding_system[outch]);
7568 #endif
7571 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7572 doc: /* Return the (or a) live process associated with BUFFER.
7573 BUFFER may be a buffer or the name of one.
7574 Return nil if all processes associated with BUFFER have been
7575 deleted or killed. */)
7576 (register Lisp_Object buffer)
7578 #ifdef subprocesses
7579 register Lisp_Object buf, tail, proc;
7581 if (NILP (buffer)) return Qnil;
7582 buf = Fget_buffer (buffer);
7583 if (NILP (buf)) return Qnil;
7585 FOR_EACH_PROCESS (tail, proc)
7586 if (EQ (XPROCESS (proc)->buffer, buf))
7587 return proc;
7588 #endif /* subprocesses */
7589 return Qnil;
7592 DEFUN ("process-inherit-coding-system-flag",
7593 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7594 1, 1, 0,
7595 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7596 If this flag is t, `buffer-file-coding-system' of the buffer
7597 associated with PROCESS will inherit the coding system used to decode
7598 the process output. */)
7599 (register Lisp_Object process)
7601 #ifdef subprocesses
7602 CHECK_PROCESS (process);
7603 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7604 #else
7605 /* Ignore the argument and return the value of
7606 inherit-process-coding-system. */
7607 return inherit_process_coding_system ? Qt : Qnil;
7608 #endif
7611 /* Kill all processes associated with `buffer'.
7612 If `buffer' is nil, kill all processes. */
7614 void
7615 kill_buffer_processes (Lisp_Object buffer)
7617 #ifdef subprocesses
7618 Lisp_Object tail, proc;
7620 FOR_EACH_PROCESS (tail, proc)
7621 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7623 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7624 Fdelete_process (proc);
7625 else if (XPROCESS (proc)->infd >= 0)
7626 process_send_signal (proc, SIGHUP, Qnil, 1);
7628 #else /* subprocesses */
7629 /* Since we have no subprocesses, this does nothing. */
7630 #endif /* subprocesses */
7633 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7634 Swaiting_for_user_input_p, 0, 0, 0,
7635 doc: /* Return non-nil if Emacs is waiting for input from the user.
7636 This is intended for use by asynchronous process output filters and sentinels. */)
7637 (void)
7639 #ifdef subprocesses
7640 return (waiting_for_user_input_p ? Qt : Qnil);
7641 #else
7642 return Qnil;
7643 #endif
7646 /* Stop reading input from keyboard sources. */
7648 void
7649 hold_keyboard_input (void)
7651 kbd_is_on_hold = 1;
7654 /* Resume reading input from keyboard sources. */
7656 void
7657 unhold_keyboard_input (void)
7659 kbd_is_on_hold = 0;
7662 /* Return true if keyboard input is on hold, zero otherwise. */
7664 bool
7665 kbd_on_hold_p (void)
7667 return kbd_is_on_hold;
7671 /* Enumeration of and access to system processes a-la ps(1). */
7673 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7674 0, 0, 0,
7675 doc: /* Return a list of numerical process IDs of all running processes.
7676 If this functionality is unsupported, return nil.
7678 See `process-attributes' for getting attributes of a process given its ID. */)
7679 (void)
7681 return list_system_processes ();
7684 DEFUN ("process-attributes", Fprocess_attributes,
7685 Sprocess_attributes, 1, 1, 0,
7686 doc: /* Return attributes of the process given by its PID, a number.
7688 Value is an alist where each element is a cons cell of the form
7690 (KEY . VALUE)
7692 If this functionality is unsupported, the value is nil.
7694 See `list-system-processes' for getting a list of all process IDs.
7696 The KEYs of the attributes that this function may return are listed
7697 below, together with the type of the associated VALUE (in parentheses).
7698 Not all platforms support all of these attributes; unsupported
7699 attributes will not appear in the returned alist.
7700 Unless explicitly indicated otherwise, numbers can have either
7701 integer or floating point values.
7703 euid -- Effective user User ID of the process (number)
7704 user -- User name corresponding to euid (string)
7705 egid -- Effective user Group ID of the process (number)
7706 group -- Group name corresponding to egid (string)
7707 comm -- Command name (executable name only) (string)
7708 state -- Process state code, such as "S", "R", or "T" (string)
7709 ppid -- Parent process ID (number)
7710 pgrp -- Process group ID (number)
7711 sess -- Session ID, i.e. process ID of session leader (number)
7712 ttname -- Controlling tty name (string)
7713 tpgid -- ID of foreground process group on the process's tty (number)
7714 minflt -- number of minor page faults (number)
7715 majflt -- number of major page faults (number)
7716 cminflt -- cumulative number of minor page faults (number)
7717 cmajflt -- cumulative number of major page faults (number)
7718 utime -- user time used by the process, in (current-time) format,
7719 which is a list of integers (HIGH LOW USEC PSEC)
7720 stime -- system time used by the process (current-time)
7721 time -- sum of utime and stime (current-time)
7722 cutime -- user time used by the process and its children (current-time)
7723 cstime -- system time used by the process and its children (current-time)
7724 ctime -- sum of cutime and cstime (current-time)
7725 pri -- priority of the process (number)
7726 nice -- nice value of the process (number)
7727 thcount -- process thread count (number)
7728 start -- time the process started (current-time)
7729 vsize -- virtual memory size of the process in KB's (number)
7730 rss -- resident set size of the process in KB's (number)
7731 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7732 pcpu -- percents of CPU time used by the process (floating-point number)
7733 pmem -- percents of total physical memory used by process's resident set
7734 (floating-point number)
7735 args -- command line which invoked the process (string). */)
7736 ( Lisp_Object pid)
7738 return system_process_attributes (pid);
7741 #ifdef subprocesses
7742 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7743 Invoke this after init_process_emacs, and after glib and/or GNUstep
7744 futz with the SIGCHLD handler, but before Emacs forks any children.
7745 This function's caller should block SIGCHLD. */
7747 void
7748 catch_child_signal (void)
7750 struct sigaction action, old_action;
7751 sigset_t oldset;
7752 emacs_sigaction_init (&action, deliver_child_signal);
7753 block_child_signal (&oldset);
7754 sigaction (SIGCHLD, &action, &old_action);
7755 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7756 || ! (old_action.sa_flags & SA_SIGINFO));
7758 if (old_action.sa_handler != deliver_child_signal)
7759 lib_child_handler
7760 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7761 ? dummy_handler
7762 : old_action.sa_handler);
7763 unblock_child_signal (&oldset);
7765 #endif /* subprocesses */
7768 /* This is not called "init_process" because that is the name of a
7769 Mach system call, so it would cause problems on Darwin systems. */
7770 void
7771 init_process_emacs (int sockfd)
7773 #ifdef subprocesses
7774 int i;
7776 inhibit_sentinels = 0;
7778 #ifndef CANNOT_DUMP
7779 if (! noninteractive || initialized)
7780 #endif
7782 #if defined HAVE_GLIB && !defined WINDOWSNT
7783 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7784 this should always fail, but is enough to initialize glib's
7785 private SIGCHLD handler, allowing catch_child_signal to copy
7786 it into lib_child_handler. */
7787 g_source_unref (g_child_watch_source_new (getpid ()));
7788 #endif
7789 catch_child_signal ();
7792 #ifdef HAVE_SETRLIMIT
7793 /* Don't allocate more than FD_SETSIZE file descriptors. */
7794 struct rlimit rlim;
7795 if (getrlimit (RLIMIT_NOFILE, &rlim) == 0 && FD_SETSIZE < rlim.rlim_cur)
7797 rlim.rlim_cur = FD_SETSIZE;
7798 setrlimit (RLIMIT_NOFILE, &rlim);
7800 #endif
7802 FD_ZERO (&input_wait_mask);
7803 FD_ZERO (&non_keyboard_wait_mask);
7804 FD_ZERO (&non_process_wait_mask);
7805 FD_ZERO (&write_mask);
7806 max_process_desc = max_input_desc = -1;
7807 external_sock_fd = sockfd;
7808 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7810 FD_ZERO (&connect_wait_mask);
7811 num_pending_connects = 0;
7813 process_output_delay_count = 0;
7814 process_output_skip = 0;
7816 /* Don't do this, it caused infinite select loops. The display
7817 method should call add_keyboard_wait_descriptor on stdin if it
7818 needs that. */
7819 #if 0
7820 FD_SET (0, &input_wait_mask);
7821 #endif
7823 Vprocess_alist = Qnil;
7824 deleted_pid_list = Qnil;
7825 for (i = 0; i < FD_SETSIZE; i++)
7827 chan_process[i] = Qnil;
7828 proc_buffered_char[i] = -1;
7830 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7831 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7832 #ifdef DATAGRAM_SOCKETS
7833 memset (datagram_address, 0, sizeof datagram_address);
7834 #endif
7836 #if defined (DARWIN_OS)
7837 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7838 processes. As such, we only change the default value. */
7839 if (initialized)
7841 char const *release = (STRINGP (Voperating_system_release)
7842 ? SSDATA (Voperating_system_release)
7843 : 0);
7844 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7845 Vprocess_connection_type = Qnil;
7848 #endif
7849 #endif /* subprocesses */
7850 kbd_is_on_hold = 0;
7853 void
7854 syms_of_process (void)
7856 #ifdef subprocesses
7858 DEFSYM (Qprocessp, "processp");
7859 DEFSYM (Qrun, "run");
7860 DEFSYM (Qstop, "stop");
7861 DEFSYM (Qsignal, "signal");
7863 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7864 here again. */
7866 DEFSYM (Qopen, "open");
7867 DEFSYM (Qclosed, "closed");
7868 DEFSYM (Qconnect, "connect");
7869 DEFSYM (Qfailed, "failed");
7870 DEFSYM (Qlisten, "listen");
7871 DEFSYM (Qlocal, "local");
7872 DEFSYM (Qipv4, "ipv4");
7873 #ifdef AF_INET6
7874 DEFSYM (Qipv6, "ipv6");
7875 #endif
7876 DEFSYM (Qdatagram, "datagram");
7877 DEFSYM (Qseqpacket, "seqpacket");
7879 DEFSYM (QCport, ":port");
7880 DEFSYM (QCspeed, ":speed");
7881 DEFSYM (QCprocess, ":process");
7883 DEFSYM (QCbytesize, ":bytesize");
7884 DEFSYM (QCstopbits, ":stopbits");
7885 DEFSYM (QCparity, ":parity");
7886 DEFSYM (Qodd, "odd");
7887 DEFSYM (Qeven, "even");
7888 DEFSYM (QCflowcontrol, ":flowcontrol");
7889 DEFSYM (Qhw, "hw");
7890 DEFSYM (Qsw, "sw");
7891 DEFSYM (QCsummary, ":summary");
7893 DEFSYM (Qreal, "real");
7894 DEFSYM (Qnetwork, "network");
7895 DEFSYM (Qserial, "serial");
7896 DEFSYM (Qpipe, "pipe");
7897 DEFSYM (QCbuffer, ":buffer");
7898 DEFSYM (QChost, ":host");
7899 DEFSYM (QCservice, ":service");
7900 DEFSYM (QClocal, ":local");
7901 DEFSYM (QCremote, ":remote");
7902 DEFSYM (QCcoding, ":coding");
7903 DEFSYM (QCserver, ":server");
7904 DEFSYM (QCnowait, ":nowait");
7905 DEFSYM (QCsentinel, ":sentinel");
7906 DEFSYM (QCuse_external_socket, ":use-external-socket");
7907 DEFSYM (QCtls_parameters, ":tls-parameters");
7908 DEFSYM (Qnsm_verify_connection, "nsm-verify-connection");
7909 DEFSYM (QClog, ":log");
7910 DEFSYM (QCnoquery, ":noquery");
7911 DEFSYM (QCstop, ":stop");
7912 DEFSYM (QCplist, ":plist");
7913 DEFSYM (QCcommand, ":command");
7914 DEFSYM (QCconnection_type, ":connection-type");
7915 DEFSYM (QCstderr, ":stderr");
7916 DEFSYM (Qpty, "pty");
7917 DEFSYM (Qpipe, "pipe");
7919 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7921 staticpro (&Vprocess_alist);
7922 staticpro (&deleted_pid_list);
7924 #endif /* subprocesses */
7926 DEFSYM (QCname, ":name");
7927 DEFSYM (QCtype, ":type");
7929 DEFSYM (Qeuid, "euid");
7930 DEFSYM (Qegid, "egid");
7931 DEFSYM (Quser, "user");
7932 DEFSYM (Qgroup, "group");
7933 DEFSYM (Qcomm, "comm");
7934 DEFSYM (Qstate, "state");
7935 DEFSYM (Qppid, "ppid");
7936 DEFSYM (Qpgrp, "pgrp");
7937 DEFSYM (Qsess, "sess");
7938 DEFSYM (Qttname, "ttname");
7939 DEFSYM (Qtpgid, "tpgid");
7940 DEFSYM (Qminflt, "minflt");
7941 DEFSYM (Qmajflt, "majflt");
7942 DEFSYM (Qcminflt, "cminflt");
7943 DEFSYM (Qcmajflt, "cmajflt");
7944 DEFSYM (Qutime, "utime");
7945 DEFSYM (Qstime, "stime");
7946 DEFSYM (Qtime, "time");
7947 DEFSYM (Qcutime, "cutime");
7948 DEFSYM (Qcstime, "cstime");
7949 DEFSYM (Qctime, "ctime");
7950 #ifdef subprocesses
7951 DEFSYM (Qinternal_default_process_sentinel,
7952 "internal-default-process-sentinel");
7953 DEFSYM (Qinternal_default_process_filter,
7954 "internal-default-process-filter");
7955 #endif
7956 DEFSYM (Qpri, "pri");
7957 DEFSYM (Qnice, "nice");
7958 DEFSYM (Qthcount, "thcount");
7959 DEFSYM (Qstart, "start");
7960 DEFSYM (Qvsize, "vsize");
7961 DEFSYM (Qrss, "rss");
7962 DEFSYM (Qetime, "etime");
7963 DEFSYM (Qpcpu, "pcpu");
7964 DEFSYM (Qpmem, "pmem");
7965 DEFSYM (Qargs, "args");
7967 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7968 doc: /* Non-nil means delete processes immediately when they exit.
7969 A value of nil means don't delete them until `list-processes' is run. */);
7971 delete_exited_processes = 1;
7973 #ifdef subprocesses
7974 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7975 doc: /* Control type of device used to communicate with subprocesses.
7976 Values are nil to use a pipe, or t or `pty' to use a pty.
7977 The value has no effect if the system has no ptys or if all ptys are busy:
7978 then a pipe is used in any case.
7979 The value takes effect when `start-process' is called. */);
7980 Vprocess_connection_type = Qt;
7982 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7983 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7984 On some systems, when Emacs reads the output from a subprocess, the output data
7985 is read in very small blocks, potentially resulting in very poor performance.
7986 This behavior can be remedied to some extent by setting this variable to a
7987 non-nil value, as it will automatically delay reading from such processes, to
7988 allow them to produce more output before Emacs tries to read it.
7989 If the value is t, the delay is reset after each write to the process; any other
7990 non-nil value means that the delay is not reset on write.
7991 The variable takes effect when `start-process' is called. */);
7992 Vprocess_adaptive_read_buffering = Qt;
7994 defsubr (&Sprocessp);
7995 defsubr (&Sget_process);
7996 defsubr (&Sdelete_process);
7997 defsubr (&Sprocess_status);
7998 defsubr (&Sprocess_exit_status);
7999 defsubr (&Sprocess_id);
8000 defsubr (&Sprocess_name);
8001 defsubr (&Sprocess_tty_name);
8002 defsubr (&Sprocess_command);
8003 defsubr (&Sset_process_buffer);
8004 defsubr (&Sprocess_buffer);
8005 defsubr (&Sprocess_mark);
8006 defsubr (&Sset_process_filter);
8007 defsubr (&Sprocess_filter);
8008 defsubr (&Sset_process_sentinel);
8009 defsubr (&Sprocess_sentinel);
8010 defsubr (&Sset_process_window_size);
8011 defsubr (&Sset_process_inherit_coding_system_flag);
8012 defsubr (&Sset_process_query_on_exit_flag);
8013 defsubr (&Sprocess_query_on_exit_flag);
8014 defsubr (&Sprocess_contact);
8015 defsubr (&Sprocess_plist);
8016 defsubr (&Sset_process_plist);
8017 defsubr (&Sprocess_list);
8018 defsubr (&Smake_process);
8019 defsubr (&Smake_pipe_process);
8020 defsubr (&Sserial_process_configure);
8021 defsubr (&Smake_serial_process);
8022 defsubr (&Sset_network_process_option);
8023 defsubr (&Smake_network_process);
8024 defsubr (&Sformat_network_address);
8025 defsubr (&Snetwork_interface_list);
8026 defsubr (&Snetwork_interface_info);
8027 #ifdef DATAGRAM_SOCKETS
8028 defsubr (&Sprocess_datagram_address);
8029 defsubr (&Sset_process_datagram_address);
8030 #endif
8031 defsubr (&Saccept_process_output);
8032 defsubr (&Sprocess_send_region);
8033 defsubr (&Sprocess_send_string);
8034 defsubr (&Sinterrupt_process);
8035 defsubr (&Skill_process);
8036 defsubr (&Squit_process);
8037 defsubr (&Sstop_process);
8038 defsubr (&Scontinue_process);
8039 defsubr (&Sprocess_running_child_p);
8040 defsubr (&Sprocess_send_eof);
8041 defsubr (&Ssignal_process);
8042 defsubr (&Swaiting_for_user_input_p);
8043 defsubr (&Sprocess_type);
8044 defsubr (&Sinternal_default_process_sentinel);
8045 defsubr (&Sinternal_default_process_filter);
8046 defsubr (&Sset_process_coding_system);
8047 defsubr (&Sprocess_coding_system);
8048 defsubr (&Sset_process_filter_multibyte);
8049 defsubr (&Sprocess_filter_multibyte_p);
8052 Lisp_Object subfeatures = Qnil;
8053 const struct socket_options *sopt;
8055 #define ADD_SUBFEATURE(key, val) \
8056 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8058 ADD_SUBFEATURE (QCnowait, Qt);
8059 #ifdef DATAGRAM_SOCKETS
8060 ADD_SUBFEATURE (QCtype, Qdatagram);
8061 #endif
8062 #ifdef HAVE_SEQPACKET
8063 ADD_SUBFEATURE (QCtype, Qseqpacket);
8064 #endif
8065 #ifdef HAVE_LOCAL_SOCKETS
8066 ADD_SUBFEATURE (QCfamily, Qlocal);
8067 #endif
8068 ADD_SUBFEATURE (QCfamily, Qipv4);
8069 #ifdef AF_INET6
8070 ADD_SUBFEATURE (QCfamily, Qipv6);
8071 #endif
8072 #ifdef HAVE_GETSOCKNAME
8073 ADD_SUBFEATURE (QCservice, Qt);
8074 #endif
8075 ADD_SUBFEATURE (QCserver, Qt);
8077 for (sopt = socket_options; sopt->name; sopt++)
8078 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
8080 Fprovide (intern_c_string ("make-network-process"), subfeatures);
8083 #endif /* subprocesses */
8085 defsubr (&Sget_buffer_process);
8086 defsubr (&Sprocess_inherit_coding_system_flag);
8087 defsubr (&Slist_system_processes);
8088 defsubr (&Sprocess_attributes);