ibuffer-decompose-filter: Avoid side effects on error
[emacs.git] / src / process.c
blob8ab73bd9ae67c2ab96fc310e8faeed9c96b4a799
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 <stdlib.h>
26 #include <errno.h>
27 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
28 #include <sys/file.h>
29 #include <sys/stat.h>
30 #include <unistd.h>
31 #include <fcntl.h>
33 #include "lisp.h"
35 /* Only MS-DOS does not define `subprocesses'. */
36 #ifdef subprocesses
38 #include <sys/socket.h>
39 #include <netdb.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
43 #ifdef HAVE_SETRLIMIT
44 # include <sys/resource.h>
46 /* If NOFILE_LIMIT.rlim_cur is greater than FD_SETSIZE, then
47 NOFILE_LIMIT is the initial limit on the number of open files,
48 which should be restored in child processes. */
49 static struct rlimit nofile_limit;
50 #endif
52 /* Are local (unix) sockets supported? */
53 #if defined (HAVE_SYS_UN_H)
54 #if !defined (AF_LOCAL) && defined (AF_UNIX)
55 #define AF_LOCAL AF_UNIX
56 #endif
57 #ifdef AF_LOCAL
58 #define HAVE_LOCAL_SOCKETS
59 #include <sys/un.h>
60 #endif
61 #endif
63 #include <sys/ioctl.h>
64 #if defined (HAVE_NET_IF_H)
65 #include <net/if.h>
66 #endif /* HAVE_NET_IF_H */
68 #if defined (HAVE_IFADDRS_H)
69 /* Must be after net/if.h */
70 #include <ifaddrs.h>
72 /* We only use structs from this header when we use getifaddrs. */
73 #if defined (HAVE_NET_IF_DL_H)
74 #include <net/if_dl.h>
75 #endif
77 #endif
79 #ifdef NEED_BSDTTY
80 #include <bsdtty.h>
81 #endif
83 #ifdef USG5_4
84 # include <sys/stream.h>
85 # include <sys/stropts.h>
86 #endif
88 #ifdef HAVE_UTIL_H
89 #include <util.h>
90 #endif
92 #ifdef HAVE_PTY_H
93 #include <pty.h>
94 #endif
96 #include <c-ctype.h>
97 #include <flexmember.h>
98 #include <sig2str.h>
99 #include <verify.h>
101 #endif /* subprocesses */
103 #include "systime.h"
104 #include "systty.h"
106 #include "window.h"
107 #include "character.h"
108 #include "buffer.h"
109 #include "coding.h"
110 #include "process.h"
111 #include "frame.h"
112 #include "termopts.h"
113 #include "keyboard.h"
114 #include "blockinput.h"
115 #include "atimer.h"
116 #include "sysselect.h"
117 #include "syssignal.h"
118 #include "syswait.h"
119 #ifdef HAVE_GNUTLS
120 #include "gnutls.h"
121 #endif
123 #ifdef HAVE_WINDOW_SYSTEM
124 #include TERM_HEADER
125 #endif /* HAVE_WINDOW_SYSTEM */
127 #ifdef HAVE_GLIB
128 #include "xgselect.h"
129 #ifndef WINDOWSNT
130 #include <glib.h>
131 #endif
132 #endif
134 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
135 /* This is 0.1s in nanoseconds. */
136 #define ASYNC_RETRY_NSEC 100000000
137 #endif
139 #ifdef WINDOWSNT
140 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
141 struct timespec *, void *);
142 #endif
144 /* Work around GCC 4.3.0 bug with strict overflow checking; see
145 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
146 This bug appears to be fixed in GCC 5.1, so don't work around it there. */
147 #if GNUC_PREREQ (4, 3, 0) && ! GNUC_PREREQ (5, 1, 0)
148 # pragma GCC diagnostic ignored "-Wstrict-overflow"
149 #endif
151 /* True if keyboard input is on hold, zero otherwise. */
153 static bool kbd_is_on_hold;
155 /* Nonzero means don't run process sentinels. This is used
156 when exiting. */
157 bool inhibit_sentinels;
159 #ifdef subprocesses
161 #ifndef SOCK_CLOEXEC
162 # define SOCK_CLOEXEC 0
163 #endif
164 #ifndef SOCK_NONBLOCK
165 # define SOCK_NONBLOCK 0
166 #endif
168 /* True if ERRNUM represents an error where the system call would
169 block if a blocking variant were used. */
170 static bool
171 would_block (int errnum)
173 #ifdef EWOULDBLOCK
174 if (EWOULDBLOCK != EAGAIN && errnum == EWOULDBLOCK)
175 return true;
176 #endif
177 return errnum == EAGAIN;
180 #ifndef HAVE_ACCEPT4
182 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
184 static int
185 close_on_exec (int fd)
187 if (0 <= fd)
188 fcntl (fd, F_SETFD, FD_CLOEXEC);
189 return fd;
192 # undef accept4
193 # define accept4(sockfd, addr, addrlen, flags) \
194 process_accept4 (sockfd, addr, addrlen, flags)
195 static int
196 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
198 return close_on_exec (accept (sockfd, addr, addrlen));
201 static int
202 process_socket (int domain, int type, int protocol)
204 return close_on_exec (socket (domain, type, protocol));
206 # undef socket
207 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
208 #endif
210 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
211 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
212 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
213 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
214 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
215 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
217 /* Number of events of change of status of a process. */
218 static EMACS_INT process_tick;
219 /* Number of events for which the user or sentinel has been notified. */
220 static EMACS_INT update_tick;
222 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
223 this system. We need to read full packets, so we need a
224 "non-destructive" select. So we require either native select,
225 or emulation of select using FIONREAD. */
227 #ifndef BROKEN_DATAGRAM_SOCKETS
228 # if defined HAVE_SELECT || defined USABLE_FIONREAD
229 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
230 # define DATAGRAM_SOCKETS
231 # endif
232 # endif
233 #endif
235 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
236 # define HAVE_SEQPACKET
237 #endif
239 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
240 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
241 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
243 /* Number of processes which have a non-zero read_output_delay,
244 and therefore might be delayed for adaptive read buffering. */
246 static int process_output_delay_count;
248 /* True if any process has non-nil read_output_skip. */
250 static bool process_output_skip;
252 static void start_process_unwind (Lisp_Object);
253 static void create_process (Lisp_Object, char **, Lisp_Object);
254 #ifdef USABLE_SIGIO
255 static bool keyboard_bit_set (fd_set *);
256 #endif
257 static void deactivate_process (Lisp_Object);
258 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
259 static int read_process_output (Lisp_Object, int);
260 static void create_pty (Lisp_Object);
261 static void exec_sentinel (Lisp_Object, Lisp_Object);
263 /* Mask of bits indicating the descriptors that we wait for input on. */
265 static fd_set input_wait_mask;
267 /* Mask that excludes keyboard input descriptor(s). */
269 static fd_set non_keyboard_wait_mask;
271 /* Mask that excludes process input descriptor(s). */
273 static fd_set non_process_wait_mask;
275 /* Mask for selecting for write. */
277 static fd_set write_mask;
279 /* Mask of bits indicating the descriptors that we wait for connect to
280 complete on. Once they complete, they are removed from this mask
281 and added to the input_wait_mask and non_keyboard_wait_mask. */
283 static fd_set connect_wait_mask;
285 /* Number of bits set in connect_wait_mask. */
286 static int num_pending_connects;
288 /* The largest descriptor currently in use for a process object; -1 if none. */
289 static int max_process_desc;
291 /* The largest descriptor currently in use for input; -1 if none. */
292 static int max_input_desc;
294 /* Set the external socket descriptor for Emacs to use when
295 `make-network-process' is called with a non-nil
296 `:use-external-socket' option. The value should be either -1, or
297 the file descriptor of a socket that is already bound. */
298 static int external_sock_fd;
300 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
301 static Lisp_Object chan_process[FD_SETSIZE];
302 static void wait_for_socket_fds (Lisp_Object, char const *);
304 /* Alist of elements (NAME . PROCESS). */
305 static Lisp_Object Vprocess_alist;
307 /* Buffered-ahead input char from process, indexed by channel.
308 -1 means empty (no char is buffered).
309 Used on sys V where the only way to tell if there is any
310 output from the process is to read at least one char.
311 Always -1 on systems that support FIONREAD. */
313 static int proc_buffered_char[FD_SETSIZE];
315 /* Table of `struct coding-system' for each process. */
316 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
317 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
319 #ifdef DATAGRAM_SOCKETS
320 /* Table of `partner address' for datagram sockets. */
321 static struct sockaddr_and_len {
322 struct sockaddr *sa;
323 ptrdiff_t len;
324 } datagram_address[FD_SETSIZE];
325 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
326 #define DATAGRAM_CONN_P(proc) \
327 (PROCESSP (proc) && \
328 XPROCESS (proc)->infd >= 0 && \
329 datagram_address[XPROCESS (proc)->infd].sa != 0)
330 #else
331 #define DATAGRAM_CONN_P(proc) (0)
332 #endif
334 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
335 a `for' loop which iterates over processes from Vprocess_alist. */
337 #define FOR_EACH_PROCESS(list_var, proc_var) \
338 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
340 /* These setters are used only in this file, so they can be private. */
341 static void
342 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
344 p->buffer = val;
346 static void
347 pset_command (struct Lisp_Process *p, Lisp_Object val)
349 p->command = val;
351 static void
352 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
354 p->decode_coding_system = val;
356 static void
357 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
359 p->decoding_buf = val;
361 static void
362 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
364 p->encode_coding_system = val;
366 static void
367 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
369 p->encoding_buf = val;
371 static void
372 pset_filter (struct Lisp_Process *p, Lisp_Object val)
374 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
376 static void
377 pset_log (struct Lisp_Process *p, Lisp_Object val)
379 p->log = val;
381 static void
382 pset_mark (struct Lisp_Process *p, Lisp_Object val)
384 p->mark = val;
386 static void
387 pset_name (struct Lisp_Process *p, Lisp_Object val)
389 p->name = val;
391 static void
392 pset_plist (struct Lisp_Process *p, Lisp_Object val)
394 p->plist = val;
396 static void
397 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
399 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
401 static void
402 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
404 p->tty_name = val;
406 static void
407 pset_type (struct Lisp_Process *p, Lisp_Object val)
409 p->type = val;
411 static void
412 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
414 p->write_queue = val;
416 static void
417 pset_stderrproc (struct Lisp_Process *p, Lisp_Object val)
419 p->stderrproc = val;
423 static Lisp_Object
424 make_lisp_proc (struct Lisp_Process *p)
426 return make_lisp_ptr (p, Lisp_Vectorlike);
429 static struct fd_callback_data
431 fd_callback func;
432 void *data;
433 #define FOR_READ 1
434 #define FOR_WRITE 2
435 int condition; /* Mask of the defines above. */
436 } fd_callback_info[FD_SETSIZE];
439 /* Add a file descriptor FD to be monitored for when read is possible.
440 When read is possible, call FUNC with argument DATA. */
442 void
443 add_read_fd (int fd, fd_callback func, void *data)
445 add_keyboard_wait_descriptor (fd);
447 fd_callback_info[fd].func = func;
448 fd_callback_info[fd].data = data;
449 fd_callback_info[fd].condition |= FOR_READ;
452 /* Stop monitoring file descriptor FD for when read is possible. */
454 void
455 delete_read_fd (int fd)
457 delete_keyboard_wait_descriptor (fd);
459 fd_callback_info[fd].condition &= ~FOR_READ;
460 if (fd_callback_info[fd].condition == 0)
462 fd_callback_info[fd].func = 0;
463 fd_callback_info[fd].data = 0;
467 /* Add a file descriptor FD to be monitored for when write is possible.
468 When write is possible, call FUNC with argument DATA. */
470 void
471 add_write_fd (int fd, fd_callback func, void *data)
473 FD_SET (fd, &write_mask);
474 if (fd > max_input_desc)
475 max_input_desc = fd;
477 fd_callback_info[fd].func = func;
478 fd_callback_info[fd].data = data;
479 fd_callback_info[fd].condition |= FOR_WRITE;
482 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
484 static void
485 delete_input_desc (int fd)
487 if (fd == max_input_desc)
490 fd--;
491 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
492 || FD_ISSET (fd, &write_mask)));
494 max_input_desc = fd;
498 /* Stop monitoring file descriptor FD for when write is possible. */
500 void
501 delete_write_fd (int fd)
503 FD_CLR (fd, &write_mask);
504 fd_callback_info[fd].condition &= ~FOR_WRITE;
505 if (fd_callback_info[fd].condition == 0)
507 fd_callback_info[fd].func = 0;
508 fd_callback_info[fd].data = 0;
509 delete_input_desc (fd);
514 /* Compute the Lisp form of the process status, p->status, from
515 the numeric status that was returned by `wait'. */
517 static Lisp_Object status_convert (int);
519 static void
520 update_status (struct Lisp_Process *p)
522 eassert (p->raw_status_new);
523 pset_status (p, status_convert (p->raw_status));
524 p->raw_status_new = 0;
527 /* Convert a process status word in Unix format to
528 the list that we use internally. */
530 static Lisp_Object
531 status_convert (int w)
533 if (WIFSTOPPED (w))
534 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
535 else if (WIFEXITED (w))
536 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
537 WCOREDUMP (w) ? Qt : Qnil));
538 else if (WIFSIGNALED (w))
539 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
540 WCOREDUMP (w) ? Qt : Qnil));
541 else
542 return Qrun;
545 /* True if STATUS is that of a process attempting connection. */
547 static bool
548 connecting_status (Lisp_Object status)
550 return CONSP (status) && EQ (XCAR (status), Qconnect);
553 /* Given a status-list, extract the three pieces of information
554 and store them individually through the three pointers. */
556 static void
557 decode_status (Lisp_Object l, Lisp_Object *symbol, Lisp_Object *code,
558 bool *coredump)
560 Lisp_Object tem;
562 if (connecting_status (l))
563 l = XCAR (l);
565 if (SYMBOLP (l))
567 *symbol = l;
568 *code = make_number (0);
569 *coredump = 0;
571 else
573 *symbol = XCAR (l);
574 tem = XCDR (l);
575 *code = XCAR (tem);
576 tem = XCDR (tem);
577 *coredump = !NILP (tem);
581 /* Return a string describing a process status list. */
583 static Lisp_Object
584 status_message (struct Lisp_Process *p)
586 Lisp_Object status = p->status;
587 Lisp_Object symbol, code;
588 bool coredump;
589 Lisp_Object string;
591 decode_status (status, &symbol, &code, &coredump);
593 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
595 char const *signame;
596 synchronize_system_messages_locale ();
597 signame = strsignal (XFASTINT (code));
598 if (signame == 0)
599 string = build_string ("unknown");
600 else
602 int c1, c2;
604 string = build_unibyte_string (signame);
605 if (! NILP (Vlocale_coding_system))
606 string = (code_convert_string_norecord
607 (string, Vlocale_coding_system, 0));
608 c1 = STRING_CHAR (SDATA (string));
609 c2 = downcase (c1);
610 if (c1 != c2)
611 Faset (string, make_number (0), make_number (c2));
613 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
614 return concat2 (string, suffix);
616 else if (EQ (symbol, Qexit))
618 if (NETCONN1_P (p))
619 return build_string (XFASTINT (code) == 0
620 ? "deleted\n"
621 : "connection broken by remote peer\n");
622 if (XFASTINT (code) == 0)
623 return build_string ("finished\n");
624 AUTO_STRING (prefix, "exited abnormally with code ");
625 string = Fnumber_to_string (code);
626 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
627 return concat3 (prefix, string, suffix);
629 else if (EQ (symbol, Qfailed))
631 AUTO_STRING (format, "failed with code %s\n");
632 return CALLN (Fformat, format, code);
634 else
635 return Fcopy_sequence (Fsymbol_name (symbol));
638 enum { PTY_NAME_SIZE = 24 };
640 /* Open an available pty, returning a file descriptor.
641 Store into PTY_NAME the file name of the terminal corresponding to the pty.
642 Return -1 on failure. */
644 static int
645 allocate_pty (char pty_name[PTY_NAME_SIZE])
647 #ifdef HAVE_PTYS
648 int fd;
650 #ifdef PTY_ITERATION
651 PTY_ITERATION
652 #else
653 register int c, i;
654 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
655 for (i = 0; i < 16; i++)
656 #endif
658 #ifdef PTY_NAME_SPRINTF
659 PTY_NAME_SPRINTF
660 #else
661 sprintf (pty_name, "/dev/pty%c%x", c, i);
662 #endif /* no PTY_NAME_SPRINTF */
664 #ifdef PTY_OPEN
665 PTY_OPEN;
666 #else /* no PTY_OPEN */
667 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
668 #endif /* no PTY_OPEN */
670 if (fd >= 0)
672 #ifdef PTY_TTY_NAME_SPRINTF
673 PTY_TTY_NAME_SPRINTF
674 #else
675 sprintf (pty_name, "/dev/tty%c%x", c, i);
676 #endif /* no PTY_TTY_NAME_SPRINTF */
678 /* Set FD's close-on-exec flag. This is needed even if
679 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
680 doesn't require support for that combination.
681 Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
682 doesn't work if the close-on-exec flag is set (Bug#20555).
683 Multithreaded platforms where posix_openpt ignores
684 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
685 have a race condition between the PTY_OPEN and here. */
686 fcntl (fd, F_SETFD, FD_CLOEXEC);
688 /* Check to make certain that both sides are available.
689 This avoids a nasty yet stupid bug in rlogins. */
690 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
692 emacs_close (fd);
693 continue;
695 setup_pty (fd);
696 return fd;
699 #endif /* HAVE_PTYS */
700 return -1;
703 /* Allocate basically initialized process. */
705 static struct Lisp_Process *
706 allocate_process (void)
708 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
711 static Lisp_Object
712 make_process (Lisp_Object name)
714 struct Lisp_Process *p = allocate_process ();
715 /* Initialize Lisp data. Note that allocate_process initializes all
716 Lisp data to nil, so do it only for slots which should not be nil. */
717 pset_status (p, Qrun);
718 pset_mark (p, Fmake_marker ());
720 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
721 non-Lisp data, so do it only for slots which should not be zero. */
722 p->infd = -1;
723 p->outfd = -1;
724 for (int i = 0; i < PROCESS_OPEN_FDS; i++)
725 p->open_fd[i] = -1;
727 #ifdef HAVE_GNUTLS
728 verify (GNUTLS_STAGE_EMPTY == 0);
729 eassert (p->gnutls_initstage == GNUTLS_STAGE_EMPTY);
730 eassert (NILP (p->gnutls_boot_parameters));
731 #endif
733 /* If name is already in use, modify it until it is unused. */
735 Lisp_Object name1 = name;
736 for (printmax_t i = 1; ; i++)
738 Lisp_Object tem = Fget_process (name1);
739 if (NILP (tem))
740 break;
741 char const suffix_fmt[] = "<%"pMd">";
742 char suffix[sizeof suffix_fmt + INT_STRLEN_BOUND (printmax_t)];
743 AUTO_STRING_WITH_LEN (lsuffix, suffix, sprintf (suffix, suffix_fmt, i));
744 name1 = concat2 (name, lsuffix);
746 name = name1;
747 pset_name (p, name);
748 pset_sentinel (p, Qinternal_default_process_sentinel);
749 pset_filter (p, Qinternal_default_process_filter);
750 Lisp_Object val;
751 XSETPROCESS (val, p);
752 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
753 return val;
756 static void
757 remove_process (register Lisp_Object proc)
759 register Lisp_Object pair;
761 pair = Frassq (proc, Vprocess_alist);
762 Vprocess_alist = Fdelq (pair, Vprocess_alist);
764 deactivate_process (proc);
767 #ifdef HAVE_GETADDRINFO_A
768 static void
769 free_dns_request (Lisp_Object proc)
771 struct Lisp_Process *p = XPROCESS (proc);
773 if (p->dns_request->ar_result)
774 freeaddrinfo (p->dns_request->ar_result);
775 xfree (p->dns_request);
776 p->dns_request = NULL;
778 #endif
781 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
782 doc: /* Return t if OBJECT is a process. */)
783 (Lisp_Object object)
785 return PROCESSP (object) ? Qt : Qnil;
788 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
789 doc: /* Return the process named NAME, or nil if there is none. */)
790 (register Lisp_Object name)
792 if (PROCESSP (name))
793 return name;
794 CHECK_STRING (name);
795 return Fcdr (Fassoc (name, Vprocess_alist));
798 /* This is how commands for the user decode process arguments. It
799 accepts a process, a process name, a buffer, a buffer name, or nil.
800 Buffers denote the first process in the buffer, and nil denotes the
801 current buffer. */
803 static Lisp_Object
804 get_process (register Lisp_Object name)
806 register Lisp_Object proc, obj;
807 if (STRINGP (name))
809 obj = Fget_process (name);
810 if (NILP (obj))
811 obj = Fget_buffer (name);
812 if (NILP (obj))
813 error ("Process %s does not exist", SDATA (name));
815 else if (NILP (name))
816 obj = Fcurrent_buffer ();
817 else
818 obj = name;
820 /* Now obj should be either a buffer object or a process object. */
821 if (BUFFERP (obj))
823 if (NILP (BVAR (XBUFFER (obj), name)))
824 error ("Attempt to get process for a dead buffer");
825 proc = Fget_buffer_process (obj);
826 if (NILP (proc))
827 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
829 else
831 CHECK_PROCESS (obj);
832 proc = obj;
834 return proc;
838 /* Fdelete_process promises to immediately forget about the process, but in
839 reality, Emacs needs to remember those processes until they have been
840 treated by the SIGCHLD handler and waitpid has been invoked on them;
841 otherwise they might fill up the kernel's process table.
843 Some processes created by call-process are also put onto this list.
845 Members of this list are (process-ID . filename) pairs. The
846 process-ID is a number; the filename, if a string, is a file that
847 needs to be removed after the process exits. */
848 static Lisp_Object deleted_pid_list;
850 void
851 record_deleted_pid (pid_t pid, Lisp_Object filename)
853 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
854 /* GC treated elements set to nil. */
855 Fdelq (Qnil, deleted_pid_list));
859 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
860 doc: /* Delete PROCESS: kill it and forget about it immediately.
861 PROCESS may be a process, a buffer, the name of a process or buffer, or
862 nil, indicating the current buffer's process. */)
863 (register Lisp_Object process)
865 register struct Lisp_Process *p;
867 process = get_process (process);
868 p = XPROCESS (process);
870 #ifdef HAVE_GETADDRINFO_A
871 if (p->dns_request)
873 /* Cancel the request. Unless shutting down, wait until
874 completion. Free the request if completely canceled. */
876 bool canceled = gai_cancel (p->dns_request) != EAI_NOTCANCELED;
877 if (!canceled && !inhibit_sentinels)
879 struct gaicb const *req = p->dns_request;
880 while (gai_suspend (&req, 1, NULL) != 0)
881 continue;
882 canceled = true;
884 if (canceled)
885 free_dns_request (process);
887 #endif
889 p->raw_status_new = 0;
890 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
892 pset_status (p, list2 (Qexit, make_number (0)));
893 p->tick = ++process_tick;
894 status_notify (p, NULL);
895 redisplay_preserve_echo_area (13);
897 else
899 if (p->alive)
900 record_kill_process (p, Qnil);
902 if (p->infd >= 0)
904 /* Update P's status, since record_kill_process will make the
905 SIGCHLD handler update deleted_pid_list, not *P. */
906 Lisp_Object symbol;
907 if (p->raw_status_new)
908 update_status (p);
909 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
910 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
911 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
913 p->tick = ++process_tick;
914 status_notify (p, NULL);
915 redisplay_preserve_echo_area (13);
918 remove_process (process);
919 return Qnil;
922 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
923 doc: /* Return the status of PROCESS.
924 The returned value is one of the following symbols:
925 run -- for a process that is running.
926 stop -- for a process stopped but continuable.
927 exit -- for a process that has exited.
928 signal -- for a process that has got a fatal signal.
929 open -- for a network stream connection that is open.
930 listen -- for a network stream server that is listening.
931 closed -- for a network stream connection that is closed.
932 connect -- when waiting for a non-blocking connection to complete.
933 failed -- when a non-blocking connection has failed.
934 nil -- if arg is a process name and no such process exists.
935 PROCESS may be a process, a buffer, the name of a process, or
936 nil, indicating the current buffer's process. */)
937 (register Lisp_Object process)
939 register struct Lisp_Process *p;
940 register Lisp_Object status;
942 if (STRINGP (process))
943 process = Fget_process (process);
944 else
945 process = get_process (process);
947 if (NILP (process))
948 return process;
950 p = XPROCESS (process);
951 if (p->raw_status_new)
952 update_status (p);
953 status = p->status;
954 if (CONSP (status))
955 status = XCAR (status);
956 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
958 if (EQ (status, Qexit))
959 status = Qclosed;
960 else if (EQ (p->command, Qt))
961 status = Qstop;
962 else if (EQ (status, Qrun))
963 status = Qopen;
965 return status;
968 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
969 1, 1, 0,
970 doc: /* Return the exit status of PROCESS or the signal number that killed it.
971 If PROCESS has not yet exited or died, return 0. */)
972 (register Lisp_Object process)
974 CHECK_PROCESS (process);
975 if (XPROCESS (process)->raw_status_new)
976 update_status (XPROCESS (process));
977 if (CONSP (XPROCESS (process)->status))
978 return XCAR (XCDR (XPROCESS (process)->status));
979 return make_number (0);
982 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
983 doc: /* Return the process id of PROCESS.
984 This is the pid of the external process which PROCESS uses or talks to.
985 For a network, serial, and pipe connections, this value is nil. */)
986 (register Lisp_Object process)
988 pid_t pid;
990 CHECK_PROCESS (process);
991 pid = XPROCESS (process)->pid;
992 return (pid ? make_fixnum_or_float (pid) : Qnil);
995 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
996 doc: /* Return the name of PROCESS, as a string.
997 This is the name of the program invoked in PROCESS,
998 possibly modified to make it unique among process names. */)
999 (register Lisp_Object process)
1001 CHECK_PROCESS (process);
1002 return XPROCESS (process)->name;
1005 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
1006 doc: /* Return the command that was executed to start PROCESS.
1007 This is a list of strings, the first string being the program executed
1008 and the rest of the strings being the arguments given to it.
1009 For a network or serial or pipe connection, this is nil (process is running)
1010 or t (process is stopped). */)
1011 (register Lisp_Object process)
1013 CHECK_PROCESS (process);
1014 return XPROCESS (process)->command;
1017 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
1018 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
1019 This is the terminal that the process itself reads and writes on,
1020 not the name of the pty that Emacs uses to talk with that terminal. */)
1021 (register Lisp_Object process)
1023 CHECK_PROCESS (process);
1024 return XPROCESS (process)->tty_name;
1027 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1028 2, 2, 0,
1029 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1030 Return BUFFER. */)
1031 (register Lisp_Object process, Lisp_Object buffer)
1033 struct Lisp_Process *p;
1035 CHECK_PROCESS (process);
1036 if (!NILP (buffer))
1037 CHECK_BUFFER (buffer);
1038 p = XPROCESS (process);
1039 pset_buffer (p, buffer);
1040 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1041 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1042 setup_process_coding_systems (process);
1043 return buffer;
1046 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1047 1, 1, 0,
1048 doc: /* Return the buffer PROCESS is associated with.
1049 The default process filter inserts output from PROCESS into this buffer. */)
1050 (register Lisp_Object process)
1052 CHECK_PROCESS (process);
1053 return XPROCESS (process)->buffer;
1056 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1057 1, 1, 0,
1058 doc: /* Return the marker for the end of the last output from PROCESS. */)
1059 (register Lisp_Object process)
1061 CHECK_PROCESS (process);
1062 return XPROCESS (process)->mark;
1065 static void
1066 set_process_filter_masks (struct Lisp_Process *p)
1068 if (EQ (p->filter, Qt) && !EQ (p->status, Qlisten))
1070 FD_CLR (p->infd, &input_wait_mask);
1071 FD_CLR (p->infd, &non_keyboard_wait_mask);
1073 else if (EQ (p->filter, Qt)
1074 /* Network or serial process not stopped: */
1075 && !EQ (p->command, Qt))
1077 FD_SET (p->infd, &input_wait_mask);
1078 FD_SET (p->infd, &non_keyboard_wait_mask);
1082 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1083 2, 2, 0,
1084 doc: /* Give PROCESS the filter function FILTER; nil means default.
1085 A value of t means stop accepting output from the process.
1087 When a process has a non-default filter, its buffer is not used for output.
1088 Instead, each time it does output, the entire string of output is
1089 passed to the filter.
1091 The filter gets two arguments: the process and the string of output.
1092 The string argument is normally a multibyte string, except:
1093 - if the process's input coding system is no-conversion or raw-text,
1094 it is a unibyte string (the non-converted input), or else
1095 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1096 string (the result of converting the decoded input multibyte
1097 string to unibyte with `string-make-unibyte'). */)
1098 (Lisp_Object process, Lisp_Object filter)
1100 CHECK_PROCESS (process);
1101 struct Lisp_Process *p = XPROCESS (process);
1103 /* Don't signal an error if the process's input file descriptor
1104 is closed. This could make debugging Lisp more difficult,
1105 for example when doing something like
1107 (setq process (start-process ...))
1108 (debug)
1109 (set-process-filter process ...) */
1111 if (NILP (filter))
1112 filter = Qinternal_default_process_filter;
1114 pset_filter (p, filter);
1116 if (p->infd >= 0)
1117 set_process_filter_masks (p);
1119 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1120 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1121 setup_process_coding_systems (process);
1122 return filter;
1125 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1126 1, 1, 0,
1127 doc: /* Return the filter function of PROCESS.
1128 See `set-process-filter' for more info on filter functions. */)
1129 (register Lisp_Object process)
1131 CHECK_PROCESS (process);
1132 return XPROCESS (process)->filter;
1135 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1136 2, 2, 0,
1137 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1138 The sentinel is called as a function when the process changes state.
1139 It gets two arguments: the process, and a string describing the change. */)
1140 (register Lisp_Object process, Lisp_Object sentinel)
1142 struct Lisp_Process *p;
1144 CHECK_PROCESS (process);
1145 p = XPROCESS (process);
1147 if (NILP (sentinel))
1148 sentinel = Qinternal_default_process_sentinel;
1150 pset_sentinel (p, sentinel);
1151 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1152 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1153 return sentinel;
1156 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1157 1, 1, 0,
1158 doc: /* Return the sentinel of PROCESS.
1159 See `set-process-sentinel' for more info on sentinels. */)
1160 (register Lisp_Object process)
1162 CHECK_PROCESS (process);
1163 return XPROCESS (process)->sentinel;
1166 DEFUN ("set-process-window-size", Fset_process_window_size,
1167 Sset_process_window_size, 3, 3, 0,
1168 doc: /* Tell PROCESS that it has logical window size WIDTH by HEIGHT.
1169 Value is t if PROCESS was successfully told about the window size,
1170 nil otherwise. */)
1171 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1173 CHECK_PROCESS (process);
1175 /* All known platforms store window sizes as 'unsigned short'. */
1176 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1177 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1179 if (NETCONN_P (process)
1180 || XPROCESS (process)->infd < 0
1181 || (set_window_size (XPROCESS (process)->infd,
1182 XINT (height), XINT (width))
1183 < 0))
1184 return Qnil;
1185 else
1186 return Qt;
1189 DEFUN ("set-process-inherit-coding-system-flag",
1190 Fset_process_inherit_coding_system_flag,
1191 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1192 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1193 If the second argument FLAG is non-nil, then the variable
1194 `buffer-file-coding-system' of the buffer associated with PROCESS
1195 will be bound to the value of the coding system used to decode
1196 the process output.
1198 This is useful when the coding system specified for the process buffer
1199 leaves either the character code conversion or the end-of-line conversion
1200 unspecified, or if the coding system used to decode the process output
1201 is more appropriate for saving the process buffer.
1203 Binding the variable `inherit-process-coding-system' to non-nil before
1204 starting the process is an alternative way of setting the inherit flag
1205 for the process which will run.
1207 This function returns FLAG. */)
1208 (register Lisp_Object process, Lisp_Object flag)
1210 CHECK_PROCESS (process);
1211 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1212 return flag;
1215 DEFUN ("set-process-query-on-exit-flag",
1216 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1217 2, 2, 0,
1218 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1219 If the second argument FLAG is non-nil, Emacs will query the user before
1220 exiting or killing a buffer if PROCESS is running. This function
1221 returns FLAG. */)
1222 (register Lisp_Object process, Lisp_Object flag)
1224 CHECK_PROCESS (process);
1225 XPROCESS (process)->kill_without_query = NILP (flag);
1226 return flag;
1229 DEFUN ("process-query-on-exit-flag",
1230 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1231 1, 1, 0,
1232 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1233 (register Lisp_Object process)
1235 CHECK_PROCESS (process);
1236 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1239 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1240 1, 2, 0,
1241 doc: /* Return the contact info of PROCESS; t for a real child.
1242 For a network or serial or pipe connection, the value depends on the
1243 optional KEY arg. If KEY is nil, value is a cons cell of the form
1244 \(HOST SERVICE) for a network connection or (PORT SPEED) for a serial
1245 connection; it is t for a pipe connection. If KEY is t, the complete
1246 contact information for the connection is returned, else the specific
1247 value for the keyword KEY is returned. See `make-network-process',
1248 `make-serial-process', or `make pipe-process' for the list of keywords.
1249 If PROCESS is a non-blocking network process that hasn't been fully
1250 set up yet, this function will block until socket setup has completed. */)
1251 (Lisp_Object process, Lisp_Object key)
1253 Lisp_Object contact;
1255 CHECK_PROCESS (process);
1256 contact = XPROCESS (process)->childp;
1258 #ifdef DATAGRAM_SOCKETS
1260 if (NETCONN_P (process))
1261 wait_for_socket_fds (process, "process-contact");
1263 if (DATAGRAM_CONN_P (process)
1264 && (EQ (key, Qt) || EQ (key, QCremote)))
1265 contact = Fplist_put (contact, QCremote,
1266 Fprocess_datagram_address (process));
1267 #endif
1269 if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1270 || EQ (key, Qt))
1271 return contact;
1272 if (NILP (key) && NETCONN_P (process))
1273 return list2 (Fplist_get (contact, QChost),
1274 Fplist_get (contact, QCservice));
1275 if (NILP (key) && SERIALCONN_P (process))
1276 return list2 (Fplist_get (contact, QCport),
1277 Fplist_get (contact, QCspeed));
1278 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1279 if the pipe process is useful for purposes other than receiving
1280 stderr. */
1281 if (NILP (key) && PIPECONN_P (process))
1282 return Qt;
1283 return Fplist_get (contact, key);
1286 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1287 1, 1, 0,
1288 doc: /* Return the plist of PROCESS. */)
1289 (register Lisp_Object process)
1291 CHECK_PROCESS (process);
1292 return XPROCESS (process)->plist;
1295 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1296 2, 2, 0,
1297 doc: /* Replace the plist of PROCESS with PLIST. Return PLIST. */)
1298 (Lisp_Object process, Lisp_Object plist)
1300 CHECK_PROCESS (process);
1301 CHECK_LIST (plist);
1303 pset_plist (XPROCESS (process), plist);
1304 return plist;
1307 #if 0 /* Turned off because we don't currently record this info
1308 in the process. Perhaps add it. */
1309 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1310 doc: /* Return the connection type of PROCESS.
1311 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1312 a socket connection. */)
1313 (Lisp_Object process)
1315 return XPROCESS (process)->type;
1317 #endif
1319 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1320 doc: /* Return the connection type of PROCESS.
1321 The value is either the symbol `real', `network', `serial', or `pipe'.
1322 PROCESS may be a process, a buffer, the name of a process or buffer, or
1323 nil, indicating the current buffer's process. */)
1324 (Lisp_Object process)
1326 Lisp_Object proc;
1327 proc = get_process (process);
1328 return XPROCESS (proc)->type;
1331 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1332 1, 2, 0,
1333 doc: /* Convert network ADDRESS from internal format to a string.
1334 A 4 or 5 element vector represents an IPv4 address (with port number).
1335 An 8 or 9 element vector represents an IPv6 address (with port number).
1336 If optional second argument OMIT-PORT is non-nil, don't include a port
1337 number in the string, even when present in ADDRESS.
1338 Return nil if format of ADDRESS is invalid. */)
1339 (Lisp_Object address, Lisp_Object omit_port)
1341 if (NILP (address))
1342 return Qnil;
1344 if (STRINGP (address)) /* AF_LOCAL */
1345 return address;
1347 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1349 register struct Lisp_Vector *p = XVECTOR (address);
1350 ptrdiff_t size = p->header.size;
1351 Lisp_Object args[10];
1352 int nargs, i;
1353 char const *format;
1355 if (size == 4 || (size == 5 && !NILP (omit_port)))
1357 format = "%d.%d.%d.%d";
1358 nargs = 4;
1360 else if (size == 5)
1362 format = "%d.%d.%d.%d:%d";
1363 nargs = 5;
1365 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1367 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1368 nargs = 8;
1370 else if (size == 9)
1372 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1373 nargs = 9;
1375 else
1376 return Qnil;
1378 AUTO_STRING (format_obj, format);
1379 args[0] = format_obj;
1381 for (i = 0; i < nargs; i++)
1383 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1384 return Qnil;
1386 if (nargs <= 5 /* IPv4 */
1387 && i < 4 /* host, not port */
1388 && XINT (p->contents[i]) > 255)
1389 return Qnil;
1391 args[i + 1] = p->contents[i];
1394 return Fformat (nargs + 1, args);
1397 if (CONSP (address))
1399 AUTO_STRING (format, "<Family %d>");
1400 return CALLN (Fformat, format, Fcar (address));
1403 return Qnil;
1406 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1407 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1408 (void)
1410 return Fmapcar (Qcdr, Vprocess_alist);
1413 /* Starting asynchronous inferior processes. */
1415 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1416 doc: /* Start a program in a subprocess. Return the process object for it.
1418 This is similar to `start-process', but arguments are specified as
1419 keyword/argument pairs. The following arguments are defined:
1421 :name NAME -- NAME is name for process. It is modified if necessary
1422 to make it unique.
1424 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1425 with the process. Process output goes at end of that buffer, unless
1426 you specify an output stream or filter function to handle the output.
1427 BUFFER may be also nil, meaning that this process is not associated
1428 with any buffer.
1430 :command COMMAND -- COMMAND is a list starting with the program file
1431 name, followed by strings to give to the program as arguments.
1433 :coding CODING -- If CODING is a symbol, it specifies the coding
1434 system used for both reading and writing for this process. If CODING
1435 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1436 ENCODING is used for writing.
1438 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1439 the process is running. If BOOL is not given, query before exiting.
1441 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1442 In the stopped state, a process does not accept incoming data, but you
1443 can send outgoing data. The stopped state is cleared by
1444 `continue-process' and set by `stop-process'.
1446 :connection-type TYPE -- TYPE is control type of device used to
1447 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1448 to use a pty, or nil to use the default specified through
1449 `process-connection-type'.
1451 :filter FILTER -- Install FILTER as the process filter.
1453 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1455 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1456 to the standard error of subprocess. Specifying this implies
1457 `:connection-type' is set to `pipe'.
1459 usage: (make-process &rest ARGS) */)
1460 (ptrdiff_t nargs, Lisp_Object *args)
1462 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1463 Lisp_Object xstderr, stderrproc;
1464 ptrdiff_t count = SPECPDL_INDEX ();
1466 if (nargs == 0)
1467 return Qnil;
1469 /* Save arguments for process-contact and clone-process. */
1470 contact = Flist (nargs, args);
1472 buffer = Fplist_get (contact, QCbuffer);
1473 if (!NILP (buffer))
1474 buffer = Fget_buffer_create (buffer);
1476 /* Make sure that the child will be able to chdir to the current
1477 buffer's current directory, or its unhandled equivalent. We
1478 can't just have the child check for an error when it does the
1479 chdir, since it's in a vfork. */
1480 current_dir = encode_current_directory ();
1482 name = Fplist_get (contact, QCname);
1483 CHECK_STRING (name);
1485 command = Fplist_get (contact, QCcommand);
1486 if (CONSP (command))
1487 program = XCAR (command);
1488 else
1489 program = Qnil;
1491 if (!NILP (program))
1492 CHECK_STRING (program);
1494 stderrproc = Qnil;
1495 xstderr = Fplist_get (contact, QCstderr);
1496 if (PROCESSP (xstderr))
1498 if (!PIPECONN_P (xstderr))
1499 error ("Process is not a pipe process");
1500 stderrproc = xstderr;
1502 else if (!NILP (xstderr))
1504 CHECK_STRING (program);
1505 stderrproc = CALLN (Fmake_pipe_process,
1506 QCname,
1507 concat2 (name, build_string (" stderr")),
1508 QCbuffer,
1509 Fget_buffer_create (xstderr));
1512 proc = make_process (name);
1513 record_unwind_protect (start_process_unwind, proc);
1515 pset_childp (XPROCESS (proc), Qt);
1516 eassert (NILP (XPROCESS (proc)->plist));
1517 pset_type (XPROCESS (proc), Qreal);
1518 pset_buffer (XPROCESS (proc), buffer);
1519 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1520 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1521 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1523 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
1524 XPROCESS (proc)->kill_without_query = 1;
1525 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1526 pset_command (XPROCESS (proc), Qt);
1528 tem = Fplist_get (contact, QCconnection_type);
1529 if (EQ (tem, Qpty))
1530 XPROCESS (proc)->pty_flag = true;
1531 else if (EQ (tem, Qpipe))
1532 XPROCESS (proc)->pty_flag = false;
1533 else if (NILP (tem))
1534 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1535 else
1536 report_file_error ("Unknown connection type", tem);
1538 if (!NILP (stderrproc))
1540 pset_stderrproc (XPROCESS (proc), stderrproc);
1542 XPROCESS (proc)->pty_flag = false;
1545 #ifdef HAVE_GNUTLS
1546 /* AKA GNUTLS_INITSTAGE(proc). */
1547 verify (GNUTLS_STAGE_EMPTY == 0);
1548 eassert (XPROCESS (proc)->gnutls_initstage == GNUTLS_STAGE_EMPTY);
1549 eassert (NILP (XPROCESS (proc)->gnutls_cred_type));
1550 #endif
1552 XPROCESS (proc)->adaptive_read_buffering
1553 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1554 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1556 /* Make the process marker point into the process buffer (if any). */
1557 if (BUFFERP (buffer))
1558 set_marker_both (XPROCESS (proc)->mark, buffer,
1559 BUF_ZV (XBUFFER (buffer)),
1560 BUF_ZV_BYTE (XBUFFER (buffer)));
1562 USE_SAFE_ALLOCA;
1565 /* Decide coding systems for communicating with the process. Here
1566 we don't setup the structure coding_system nor pay attention to
1567 unibyte mode. They are done in create_process. */
1569 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1570 Lisp_Object coding_systems = Qt;
1571 Lisp_Object val, *args2;
1573 tem = Fplist_get (contact, QCcoding);
1574 if (!NILP (tem))
1576 val = tem;
1577 if (CONSP (val))
1578 val = XCAR (val);
1580 else
1581 val = Vcoding_system_for_read;
1582 if (NILP (val))
1584 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1585 Lisp_Object tem2;
1586 SAFE_ALLOCA_LISP (args2, nargs2);
1587 ptrdiff_t i = 0;
1588 args2[i++] = Qstart_process;
1589 args2[i++] = name;
1590 args2[i++] = buffer;
1591 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1592 args2[i++] = XCAR (tem2);
1593 if (!NILP (program))
1594 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1595 if (CONSP (coding_systems))
1596 val = XCAR (coding_systems);
1597 else if (CONSP (Vdefault_process_coding_system))
1598 val = XCAR (Vdefault_process_coding_system);
1600 pset_decode_coding_system (XPROCESS (proc), val);
1602 if (!NILP (tem))
1604 val = tem;
1605 if (CONSP (val))
1606 val = XCDR (val);
1608 else
1609 val = Vcoding_system_for_write;
1610 if (NILP (val))
1612 if (EQ (coding_systems, Qt))
1614 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1615 Lisp_Object tem2;
1616 SAFE_ALLOCA_LISP (args2, nargs2);
1617 ptrdiff_t i = 0;
1618 args2[i++] = Qstart_process;
1619 args2[i++] = name;
1620 args2[i++] = buffer;
1621 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1622 args2[i++] = XCAR (tem2);
1623 if (!NILP (program))
1624 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1626 if (CONSP (coding_systems))
1627 val = XCDR (coding_systems);
1628 else if (CONSP (Vdefault_process_coding_system))
1629 val = XCDR (Vdefault_process_coding_system);
1631 pset_encode_coding_system (XPROCESS (proc), val);
1632 /* Note: At this moment, the above coding system may leave
1633 text-conversion or eol-conversion unspecified. They will be
1634 decided after we read output from the process and decode it by
1635 some coding system, or just before we actually send a text to
1636 the process. */
1640 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1641 eassert (XPROCESS (proc)->decoding_carryover == 0);
1642 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1644 XPROCESS (proc)->inherit_coding_system_flag
1645 = !(NILP (buffer) || !inherit_process_coding_system);
1647 if (!NILP (program))
1649 Lisp_Object program_args = XCDR (command);
1651 /* If program file name is not absolute, search our path for it.
1652 Put the name we will really use in TEM. */
1653 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1654 && !(SCHARS (program) > 1
1655 && IS_DEVICE_SEP (SREF (program, 1))))
1657 tem = Qnil;
1658 openp (Vexec_path, program, Vexec_suffixes, &tem,
1659 make_number (X_OK), false);
1660 if (NILP (tem))
1661 report_file_error ("Searching for program", program);
1662 tem = Fexpand_file_name (tem, Qnil);
1664 else
1666 if (!NILP (Ffile_directory_p (program)))
1667 error ("Specified program for new process is a directory");
1668 tem = program;
1671 /* Remove "/:" from TEM. */
1672 tem = remove_slash_colon (tem);
1674 Lisp_Object arg_encoding = Qnil;
1676 /* Encode the file name and put it in NEW_ARGV.
1677 That's where the child will use it to execute the program. */
1678 tem = list1 (ENCODE_FILE (tem));
1679 ptrdiff_t new_argc = 1;
1681 /* Here we encode arguments by the coding system used for sending
1682 data to the process. We don't support using different coding
1683 systems for encoding arguments and for encoding data sent to the
1684 process. */
1686 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1688 Lisp_Object arg = XCAR (tem2);
1689 CHECK_STRING (arg);
1690 if (STRING_MULTIBYTE (arg))
1692 if (NILP (arg_encoding))
1693 arg_encoding = (complement_process_encoding_system
1694 (XPROCESS (proc)->encode_coding_system));
1695 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1697 tem = Fcons (arg, tem);
1698 new_argc++;
1701 /* Now that everything is encoded we can collect the strings into
1702 NEW_ARGV. */
1703 char **new_argv;
1704 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1705 new_argv[new_argc] = 0;
1707 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1709 new_argv[i] = SSDATA (XCAR (tem));
1710 tem = XCDR (tem);
1713 create_process (proc, new_argv, current_dir);
1715 else
1716 create_pty (proc);
1718 SAFE_FREE ();
1719 return unbind_to (count, proc);
1722 /* If PROC doesn't have its pid set, then an error was signaled and
1723 the process wasn't started successfully, so remove it. */
1724 static void
1725 start_process_unwind (Lisp_Object proc)
1727 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1728 remove_process (proc);
1731 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1733 static void
1734 close_process_fd (int *fd_addr)
1736 int fd = *fd_addr;
1737 if (0 <= fd)
1739 *fd_addr = -1;
1740 emacs_close (fd);
1744 /* Indexes of file descriptors in open_fds. */
1745 enum
1747 /* The pipe from Emacs to its subprocess. */
1748 SUBPROCESS_STDIN,
1749 WRITE_TO_SUBPROCESS,
1751 /* The main pipe from the subprocess to Emacs. */
1752 READ_FROM_SUBPROCESS,
1753 SUBPROCESS_STDOUT,
1755 /* The pipe from the subprocess to Emacs that is closed when the
1756 subprocess execs. */
1757 READ_FROM_EXEC_MONITOR,
1758 EXEC_MONITOR_OUTPUT
1761 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1763 static void
1764 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1766 struct Lisp_Process *p = XPROCESS (process);
1767 int inchannel, outchannel;
1768 pid_t pid;
1769 int vfork_errno;
1770 int forkin, forkout, forkerr = -1;
1771 bool pty_flag = 0;
1772 char pty_name[PTY_NAME_SIZE];
1773 Lisp_Object lisp_pty_name = Qnil;
1774 sigset_t oldset;
1776 inchannel = outchannel = -1;
1778 if (p->pty_flag)
1779 outchannel = inchannel = allocate_pty (pty_name);
1781 if (inchannel >= 0)
1783 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1784 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1785 /* On most USG systems it does not work to open the pty's tty here,
1786 then close it and reopen it in the child. */
1787 /* Don't let this terminal become our controlling terminal
1788 (in case we don't have one). */
1789 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1790 if (forkin < 0)
1791 report_file_error ("Opening pty", Qnil);
1792 p->open_fd[SUBPROCESS_STDIN] = forkin;
1793 #else
1794 forkin = forkout = -1;
1795 #endif /* not USG, or USG_SUBTTY_WORKS */
1796 pty_flag = 1;
1797 lisp_pty_name = build_string (pty_name);
1799 else
1801 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1802 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1803 report_file_error ("Creating pipe", Qnil);
1804 forkin = p->open_fd[SUBPROCESS_STDIN];
1805 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1806 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1807 forkout = p->open_fd[SUBPROCESS_STDOUT];
1809 if (!NILP (p->stderrproc))
1811 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
1813 forkerr = pp->open_fd[SUBPROCESS_STDOUT];
1815 /* Close unnecessary file descriptors. */
1816 close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
1817 close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
1821 #ifndef WINDOWSNT
1822 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1823 report_file_error ("Creating pipe", Qnil);
1824 #endif
1826 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1827 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1829 /* Record this as an active process, with its channels. */
1830 chan_process[inchannel] = process;
1831 p->infd = inchannel;
1832 p->outfd = outchannel;
1834 /* Previously we recorded the tty descriptor used in the subprocess.
1835 It was only used for getting the foreground tty process, so now
1836 we just reopen the device (see emacs_get_tty_pgrp) as this is
1837 more portable (see USG_SUBTTY_WORKS above). */
1839 p->pty_flag = pty_flag;
1840 pset_status (p, Qrun);
1842 if (!EQ (p->command, Qt))
1844 FD_SET (inchannel, &input_wait_mask);
1845 FD_SET (inchannel, &non_keyboard_wait_mask);
1848 if (inchannel > max_process_desc)
1849 max_process_desc = inchannel;
1851 /* This may signal an error. */
1852 setup_process_coding_systems (process);
1854 block_input ();
1855 block_child_signal (&oldset);
1857 #ifndef WINDOWSNT
1858 /* vfork, and prevent local vars from being clobbered by the vfork. */
1859 Lisp_Object volatile current_dir_volatile = current_dir;
1860 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1861 char **volatile new_argv_volatile = new_argv;
1862 int volatile forkin_volatile = forkin;
1863 int volatile forkout_volatile = forkout;
1864 int volatile forkerr_volatile = forkerr;
1865 struct Lisp_Process *p_volatile = p;
1867 pid = vfork ();
1869 current_dir = current_dir_volatile;
1870 lisp_pty_name = lisp_pty_name_volatile;
1871 new_argv = new_argv_volatile;
1872 forkin = forkin_volatile;
1873 forkout = forkout_volatile;
1874 forkerr = forkerr_volatile;
1875 p = p_volatile;
1877 pty_flag = p->pty_flag;
1879 if (pid == 0)
1880 #endif /* not WINDOWSNT */
1882 /* Make the pty be the controlling terminal of the process. */
1883 #ifdef HAVE_PTYS
1884 /* First, disconnect its current controlling terminal. */
1885 if (pty_flag)
1886 setsid ();
1887 /* Make the pty's terminal the controlling terminal. */
1888 if (pty_flag && forkin >= 0)
1890 #ifdef TIOCSCTTY
1891 /* We ignore the return value
1892 because faith@cs.unc.edu says that is necessary on Linux. */
1893 ioctl (forkin, TIOCSCTTY, 0);
1894 #endif
1896 #if defined (LDISC1)
1897 if (pty_flag && forkin >= 0)
1899 struct termios t;
1900 tcgetattr (forkin, &t);
1901 t.c_lflag = LDISC1;
1902 if (tcsetattr (forkin, TCSANOW, &t) < 0)
1903 emacs_perror ("create_process/tcsetattr LDISC1");
1905 #else
1906 #if defined (NTTYDISC) && defined (TIOCSETD)
1907 if (pty_flag && forkin >= 0)
1909 /* Use new line discipline. */
1910 int ldisc = NTTYDISC;
1911 ioctl (forkin, TIOCSETD, &ldisc);
1913 #endif
1914 #endif
1915 #ifdef TIOCNOTTY
1916 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1917 can do TIOCSPGRP only to the process's controlling tty. */
1918 if (pty_flag)
1920 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1921 I can't test it since I don't have 4.3. */
1922 int j = emacs_open (DEV_TTY, O_RDWR, 0);
1923 if (j >= 0)
1925 ioctl (j, TIOCNOTTY, 0);
1926 emacs_close (j);
1929 #endif /* TIOCNOTTY */
1931 #if !defined (DONT_REOPEN_PTY)
1932 /*** There is a suggestion that this ought to be a
1933 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1934 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1935 that system does seem to need this code, even though
1936 both TIOCSCTTY is defined. */
1937 /* Now close the pty (if we had it open) and reopen it.
1938 This makes the pty the controlling terminal of the subprocess. */
1939 if (pty_flag)
1942 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1943 would work? */
1944 if (forkin >= 0)
1945 emacs_close (forkin);
1946 forkout = forkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1948 if (forkin < 0)
1950 emacs_perror (SSDATA (lisp_pty_name));
1951 _exit (EXIT_CANCELED);
1955 #endif /* not DONT_REOPEN_PTY */
1957 #ifdef SETUP_SLAVE_PTY
1958 if (pty_flag)
1960 SETUP_SLAVE_PTY;
1962 #endif /* SETUP_SLAVE_PTY */
1963 #endif /* HAVE_PTYS */
1965 signal (SIGINT, SIG_DFL);
1966 signal (SIGQUIT, SIG_DFL);
1967 #ifdef SIGPROF
1968 signal (SIGPROF, SIG_DFL);
1969 #endif
1971 /* Emacs ignores SIGPIPE, but the child should not. */
1972 signal (SIGPIPE, SIG_DFL);
1974 /* Stop blocking SIGCHLD in the child. */
1975 unblock_child_signal (&oldset);
1977 if (pty_flag)
1978 child_setup_tty (forkout);
1980 if (forkerr < 0)
1981 forkerr = forkout;
1982 #ifdef WINDOWSNT
1983 pid = child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1984 #else /* not WINDOWSNT */
1985 child_setup (forkin, forkout, forkerr, new_argv, 1, current_dir);
1986 #endif /* not WINDOWSNT */
1989 /* Back in the parent process. */
1991 vfork_errno = errno;
1992 p->pid = pid;
1993 if (pid >= 0)
1994 p->alive = 1;
1996 /* Stop blocking in the parent. */
1997 unblock_child_signal (&oldset);
1998 unblock_input ();
2000 if (pid < 0)
2001 report_file_errno ("Doing vfork", Qnil, vfork_errno);
2002 else
2004 /* vfork succeeded. */
2006 /* Close the pipe ends that the child uses, or the child's pty. */
2007 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
2008 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
2010 #ifdef WINDOWSNT
2011 register_child (pid, inchannel);
2012 #endif /* WINDOWSNT */
2014 pset_tty_name (p, lisp_pty_name);
2016 #ifndef WINDOWSNT
2017 /* Wait for child_setup to complete in case that vfork is
2018 actually defined as fork. The descriptor
2019 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2020 of a pipe is closed at the child side either by close-on-exec
2021 on successful execve or the _exit call in child_setup. */
2023 char dummy;
2025 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
2026 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
2027 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
2029 #endif
2030 if (!NILP (p->stderrproc))
2032 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2033 close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
2038 static void
2039 create_pty (Lisp_Object process)
2041 struct Lisp_Process *p = XPROCESS (process);
2042 char pty_name[PTY_NAME_SIZE];
2043 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
2045 if (pty_fd >= 0)
2047 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
2048 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2049 /* On most USG systems it does not work to open the pty's tty here,
2050 then close it and reopen it in the child. */
2051 /* Don't let this terminal become our controlling terminal
2052 (in case we don't have one). */
2053 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2054 if (forkout < 0)
2055 report_file_error ("Opening pty", Qnil);
2056 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2057 #if defined (DONT_REOPEN_PTY)
2058 /* In the case that vfork is defined as fork, the parent process
2059 (Emacs) may send some data before the child process completes
2060 tty options setup. So we setup tty before forking. */
2061 child_setup_tty (forkout);
2062 #endif /* DONT_REOPEN_PTY */
2063 #endif /* not USG, or USG_SUBTTY_WORKS */
2065 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2067 /* Record this as an active process, with its channels.
2068 As a result, child_setup will close Emacs's side of the pipes. */
2069 chan_process[pty_fd] = process;
2070 p->infd = pty_fd;
2071 p->outfd = pty_fd;
2073 /* Previously we recorded the tty descriptor used in the subprocess.
2074 It was only used for getting the foreground tty process, so now
2075 we just reopen the device (see emacs_get_tty_pgrp) as this is
2076 more portable (see USG_SUBTTY_WORKS above). */
2078 p->pty_flag = 1;
2079 pset_status (p, Qrun);
2080 setup_process_coding_systems (process);
2082 FD_SET (pty_fd, &input_wait_mask);
2083 FD_SET (pty_fd, &non_keyboard_wait_mask);
2084 if (pty_fd > max_process_desc)
2085 max_process_desc = pty_fd;
2087 pset_tty_name (p, build_string (pty_name));
2090 p->pid = -2;
2093 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2094 0, MANY, 0,
2095 doc: /* Create and return a bidirectional pipe process.
2097 In Emacs, pipes are represented by process objects, so input and
2098 output work as for subprocesses, and `delete-process' closes a pipe.
2099 However, a pipe process has no process id, it cannot be signaled,
2100 and the status codes are different from normal processes.
2102 Arguments are specified as keyword/argument pairs. The following
2103 arguments are defined:
2105 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2107 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2108 with the process. Process output goes at the end of that buffer,
2109 unless you specify an output stream or filter function to handle the
2110 output. If BUFFER is not given, the value of NAME is used.
2112 :coding CODING -- If CODING is a symbol, it specifies the coding
2113 system used for both reading and writing for this process. If CODING
2114 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2115 ENCODING is used for writing.
2117 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2118 the process is running. If BOOL is not given, query before exiting.
2120 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2121 In the stopped state, a pipe process does not accept incoming data,
2122 but you can send outgoing data. The stopped state is cleared by
2123 `continue-process' and set by `stop-process'.
2125 :filter FILTER -- Install FILTER as the process filter.
2127 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2129 usage: (make-pipe-process &rest ARGS) */)
2130 (ptrdiff_t nargs, Lisp_Object *args)
2132 Lisp_Object proc, contact;
2133 struct Lisp_Process *p;
2134 Lisp_Object name, buffer;
2135 Lisp_Object tem;
2136 ptrdiff_t specpdl_count;
2137 int inchannel, outchannel;
2139 if (nargs == 0)
2140 return Qnil;
2142 contact = Flist (nargs, args);
2144 name = Fplist_get (contact, QCname);
2145 CHECK_STRING (name);
2146 proc = make_process (name);
2147 specpdl_count = SPECPDL_INDEX ();
2148 record_unwind_protect (remove_process, proc);
2149 p = XPROCESS (proc);
2151 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2152 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2153 report_file_error ("Creating pipe", Qnil);
2154 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2155 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2157 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2158 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2160 #ifdef WINDOWSNT
2161 register_aux_fd (inchannel);
2162 #endif
2164 /* Record this as an active process, with its channels. */
2165 chan_process[inchannel] = proc;
2166 p->infd = inchannel;
2167 p->outfd = outchannel;
2169 if (inchannel > max_process_desc)
2170 max_process_desc = inchannel;
2172 buffer = Fplist_get (contact, QCbuffer);
2173 if (NILP (buffer))
2174 buffer = name;
2175 buffer = Fget_buffer_create (buffer);
2176 pset_buffer (p, buffer);
2178 pset_childp (p, contact);
2179 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2180 pset_type (p, Qpipe);
2181 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2182 pset_filter (p, Fplist_get (contact, QCfilter));
2183 eassert (NILP (p->log));
2184 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2185 p->kill_without_query = 1;
2186 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2187 pset_command (p, Qt);
2188 eassert (! p->pty_flag);
2190 if (!EQ (p->command, Qt))
2192 FD_SET (inchannel, &input_wait_mask);
2193 FD_SET (inchannel, &non_keyboard_wait_mask);
2195 p->adaptive_read_buffering
2196 = (NILP (Vprocess_adaptive_read_buffering) ? 0
2197 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2199 /* Make the process marker point into the process buffer (if any). */
2200 if (BUFFERP (buffer))
2201 set_marker_both (p->mark, buffer,
2202 BUF_ZV (XBUFFER (buffer)),
2203 BUF_ZV_BYTE (XBUFFER (buffer)));
2206 /* Setup coding systems for communicating with the network stream. */
2208 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2209 Lisp_Object coding_systems = Qt;
2210 Lisp_Object val;
2212 tem = Fplist_get (contact, QCcoding);
2213 val = Qnil;
2214 if (!NILP (tem))
2216 val = tem;
2217 if (CONSP (val))
2218 val = XCAR (val);
2220 else if (!NILP (Vcoding_system_for_read))
2221 val = Vcoding_system_for_read;
2222 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2223 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2224 /* We dare not decode end-of-line format by setting VAL to
2225 Qraw_text, because the existing Emacs Lisp libraries
2226 assume that they receive bare code including a sequence of
2227 CR LF. */
2228 val = Qnil;
2229 else
2231 if (CONSP (coding_systems))
2232 val = XCAR (coding_systems);
2233 else if (CONSP (Vdefault_process_coding_system))
2234 val = XCAR (Vdefault_process_coding_system);
2235 else
2236 val = Qnil;
2238 pset_decode_coding_system (p, val);
2240 if (!NILP (tem))
2242 val = tem;
2243 if (CONSP (val))
2244 val = XCDR (val);
2246 else if (!NILP (Vcoding_system_for_write))
2247 val = Vcoding_system_for_write;
2248 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2249 val = Qnil;
2250 else
2252 if (CONSP (coding_systems))
2253 val = XCDR (coding_systems);
2254 else if (CONSP (Vdefault_process_coding_system))
2255 val = XCDR (Vdefault_process_coding_system);
2256 else
2257 val = Qnil;
2259 pset_encode_coding_system (p, val);
2261 /* This may signal an error. */
2262 setup_process_coding_systems (proc);
2264 specpdl_ptr = specpdl + specpdl_count;
2266 return proc;
2270 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2271 The address family of sa is not included in the result. */
2273 Lisp_Object
2274 conv_sockaddr_to_lisp (struct sockaddr *sa, ptrdiff_t len)
2276 Lisp_Object address;
2277 ptrdiff_t i;
2278 unsigned char *cp;
2279 struct Lisp_Vector *p;
2281 /* Workaround for a bug in getsockname on BSD: Names bound to
2282 sockets in the UNIX domain are inaccessible; getsockname returns
2283 a zero length name. */
2284 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2285 return empty_unibyte_string;
2287 switch (sa->sa_family)
2289 case AF_INET:
2291 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2292 len = sizeof (sin->sin_addr) + 1;
2293 address = Fmake_vector (make_number (len), Qnil);
2294 p = XVECTOR (address);
2295 p->contents[--len] = make_number (ntohs (sin->sin_port));
2296 cp = (unsigned char *) &sin->sin_addr;
2297 break;
2299 #ifdef AF_INET6
2300 case AF_INET6:
2302 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2303 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2304 len = sizeof (sin6->sin6_addr) / 2 + 1;
2305 address = Fmake_vector (make_number (len), Qnil);
2306 p = XVECTOR (address);
2307 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2308 for (i = 0; i < len; i++)
2309 p->contents[i] = make_number (ntohs (ip6[i]));
2310 return address;
2312 #endif
2313 #ifdef HAVE_LOCAL_SOCKETS
2314 case AF_LOCAL:
2316 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2317 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2318 /* If the first byte is NUL, the name is a Linux abstract
2319 socket name, and the name can contain embedded NULs. If
2320 it's not, we have a NUL-terminated string. Be careful not
2321 to walk past the end of the object looking for the name
2322 terminator, however. */
2323 if (name_length > 0 && sockun->sun_path[0] != '\0')
2325 const char *terminator
2326 = memchr (sockun->sun_path, '\0', name_length);
2328 if (terminator)
2329 name_length = terminator - (const char *) sockun->sun_path;
2332 return make_unibyte_string (sockun->sun_path, name_length);
2334 #endif
2335 default:
2336 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2337 address = Fcons (make_number (sa->sa_family),
2338 Fmake_vector (make_number (len), Qnil));
2339 p = XVECTOR (XCDR (address));
2340 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2341 break;
2344 i = 0;
2345 while (i < len)
2346 p->contents[i++] = make_number (*cp++);
2348 return address;
2351 /* Convert an internal struct addrinfo to a Lisp object. */
2353 static Lisp_Object
2354 conv_addrinfo_to_lisp (struct addrinfo *res)
2356 Lisp_Object protocol = make_number (res->ai_protocol);
2357 eassert (XINT (protocol) == res->ai_protocol);
2358 return Fcons (protocol, conv_sockaddr_to_lisp (res->ai_addr, res->ai_addrlen));
2362 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2364 static ptrdiff_t
2365 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2367 struct Lisp_Vector *p;
2369 if (VECTORP (address))
2371 p = XVECTOR (address);
2372 if (p->header.size == 5)
2374 *familyp = AF_INET;
2375 return sizeof (struct sockaddr_in);
2377 #ifdef AF_INET6
2378 else if (p->header.size == 9)
2380 *familyp = AF_INET6;
2381 return sizeof (struct sockaddr_in6);
2383 #endif
2385 #ifdef HAVE_LOCAL_SOCKETS
2386 else if (STRINGP (address))
2388 *familyp = AF_LOCAL;
2389 return sizeof (struct sockaddr_un);
2391 #endif
2392 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2393 && VECTORP (XCDR (address)))
2395 struct sockaddr *sa;
2396 p = XVECTOR (XCDR (address));
2397 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2398 return 0;
2399 *familyp = XINT (XCAR (address));
2400 return p->header.size + sizeof (sa->sa_family);
2402 return 0;
2405 /* Convert an address object (vector or string) to an internal sockaddr.
2407 The address format has been basically validated by
2408 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2409 it could have come from user data. So if FAMILY is not valid,
2410 we return after zeroing *SA. */
2412 static void
2413 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2415 register struct Lisp_Vector *p;
2416 register unsigned char *cp = NULL;
2417 register int i;
2418 EMACS_INT hostport;
2420 memset (sa, 0, len);
2422 if (VECTORP (address))
2424 p = XVECTOR (address);
2425 if (family == AF_INET)
2427 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2428 len = sizeof (sin->sin_addr) + 1;
2429 hostport = XINT (p->contents[--len]);
2430 sin->sin_port = htons (hostport);
2431 cp = (unsigned char *)&sin->sin_addr;
2432 sa->sa_family = family;
2434 #ifdef AF_INET6
2435 else if (family == AF_INET6)
2437 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2438 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2439 len = sizeof (sin6->sin6_addr) / 2 + 1;
2440 hostport = XINT (p->contents[--len]);
2441 sin6->sin6_port = htons (hostport);
2442 for (i = 0; i < len; i++)
2443 if (INTEGERP (p->contents[i]))
2445 int j = XFASTINT (p->contents[i]) & 0xffff;
2446 ip6[i] = ntohs (j);
2448 sa->sa_family = family;
2449 return;
2451 #endif
2452 else
2453 return;
2455 else if (STRINGP (address))
2457 #ifdef HAVE_LOCAL_SOCKETS
2458 if (family == AF_LOCAL)
2460 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2461 cp = SDATA (address);
2462 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2463 sockun->sun_path[i] = *cp++;
2464 sa->sa_family = family;
2466 #endif
2467 return;
2469 else
2471 p = XVECTOR (XCDR (address));
2472 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2475 for (i = 0; i < len; i++)
2476 if (INTEGERP (p->contents[i]))
2477 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2480 #ifdef DATAGRAM_SOCKETS
2481 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2482 1, 1, 0,
2483 doc: /* Get the current datagram address associated with PROCESS.
2484 If PROCESS is a non-blocking network process that hasn't been fully
2485 set up yet, this function will block until socket setup has completed. */)
2486 (Lisp_Object process)
2488 int channel;
2490 CHECK_PROCESS (process);
2492 if (NETCONN_P (process))
2493 wait_for_socket_fds (process, "process-datagram-address");
2495 if (!DATAGRAM_CONN_P (process))
2496 return Qnil;
2498 channel = XPROCESS (process)->infd;
2499 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2500 datagram_address[channel].len);
2503 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2504 2, 2, 0,
2505 doc: /* Set the datagram address for PROCESS to ADDRESS.
2506 Return nil upon error setting address, ADDRESS otherwise.
2508 If PROCESS is a non-blocking network process that hasn't been fully
2509 set up yet, this function will block until socket setup has completed. */)
2510 (Lisp_Object process, Lisp_Object address)
2512 int channel;
2513 int family;
2514 ptrdiff_t len;
2516 CHECK_PROCESS (process);
2518 if (NETCONN_P (process))
2519 wait_for_socket_fds (process, "set-process-datagram-address");
2521 if (!DATAGRAM_CONN_P (process))
2522 return Qnil;
2524 channel = XPROCESS (process)->infd;
2526 len = get_lisp_to_sockaddr_size (address, &family);
2527 if (len == 0 || datagram_address[channel].len != len)
2528 return Qnil;
2529 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2530 return address;
2532 #endif
2535 static const struct socket_options {
2536 /* The name of this option. Should be lowercase version of option
2537 name without SO_ prefix. */
2538 const char *name;
2539 /* Option level SOL_... */
2540 int optlevel;
2541 /* Option number SO_... */
2542 int optnum;
2543 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2544 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2545 } socket_options[] =
2547 #ifdef SO_BINDTODEVICE
2548 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2549 #endif
2550 #ifdef SO_BROADCAST
2551 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2552 #endif
2553 #ifdef SO_DONTROUTE
2554 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2555 #endif
2556 #ifdef SO_KEEPALIVE
2557 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2558 #endif
2559 #ifdef SO_LINGER
2560 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2561 #endif
2562 #ifdef SO_OOBINLINE
2563 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2564 #endif
2565 #ifdef SO_PRIORITY
2566 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2567 #endif
2568 #ifdef SO_REUSEADDR
2569 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2570 #endif
2571 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2574 /* Set option OPT to value VAL on socket S.
2576 Return (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2577 Signals an error if setting a known option fails.
2580 static int
2581 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2583 char *name;
2584 const struct socket_options *sopt;
2585 int ret = 0;
2587 CHECK_SYMBOL (opt);
2589 name = SSDATA (SYMBOL_NAME (opt));
2590 for (sopt = socket_options; sopt->name; sopt++)
2591 if (strcmp (name, sopt->name) == 0)
2592 break;
2594 switch (sopt->opttype)
2596 case SOPT_BOOL:
2598 int optval;
2599 optval = NILP (val) ? 0 : 1;
2600 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2601 &optval, sizeof (optval));
2602 break;
2605 case SOPT_INT:
2607 int optval;
2608 if (TYPE_RANGED_INTEGERP (int, val))
2609 optval = XINT (val);
2610 else
2611 error ("Bad option value for %s", name);
2612 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2613 &optval, sizeof (optval));
2614 break;
2617 #ifdef SO_BINDTODEVICE
2618 case SOPT_IFNAME:
2620 char devname[IFNAMSIZ + 1];
2622 /* This is broken, at least in the Linux 2.4 kernel.
2623 To unbind, the arg must be a zero integer, not the empty string.
2624 This should work on all systems. KFS. 2003-09-23. */
2625 memset (devname, 0, sizeof devname);
2626 if (STRINGP (val))
2628 char *arg = SSDATA (val);
2629 int len = min (strlen (arg), IFNAMSIZ);
2630 memcpy (devname, arg, len);
2632 else if (!NILP (val))
2633 error ("Bad option value for %s", name);
2634 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2635 devname, IFNAMSIZ);
2636 break;
2638 #endif
2640 #ifdef SO_LINGER
2641 case SOPT_LINGER:
2643 struct linger linger;
2645 linger.l_onoff = 1;
2646 linger.l_linger = 0;
2647 if (TYPE_RANGED_INTEGERP (int, val))
2648 linger.l_linger = XINT (val);
2649 else
2650 linger.l_onoff = NILP (val) ? 0 : 1;
2651 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2652 &linger, sizeof (linger));
2653 break;
2655 #endif
2657 default:
2658 return 0;
2661 if (ret < 0)
2663 int setsockopt_errno = errno;
2664 report_file_errno ("Cannot set network option", list2 (opt, val),
2665 setsockopt_errno);
2668 return (1 << sopt->optbit);
2672 DEFUN ("set-network-process-option",
2673 Fset_network_process_option, Sset_network_process_option,
2674 3, 4, 0,
2675 doc: /* For network process PROCESS set option OPTION to value VALUE.
2676 See `make-network-process' for a list of options and values.
2677 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2678 OPTION is not a supported option, return nil instead; otherwise return t.
2680 If PROCESS is a non-blocking network process that hasn't been fully
2681 set up yet, this function will block until socket setup has completed. */)
2682 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2684 int s;
2685 struct Lisp_Process *p;
2687 CHECK_PROCESS (process);
2688 p = XPROCESS (process);
2689 if (!NETCONN1_P (p))
2690 error ("Process is not a network process");
2692 wait_for_socket_fds (process, "set-network-process-option");
2694 s = p->infd;
2695 if (s < 0)
2696 error ("Process is not running");
2698 if (set_socket_option (s, option, value))
2700 pset_childp (p, Fplist_put (p->childp, option, value));
2701 return Qt;
2704 if (NILP (no_error))
2705 error ("Unknown or unsupported option");
2707 return Qnil;
2711 DEFUN ("serial-process-configure",
2712 Fserial_process_configure,
2713 Sserial_process_configure,
2714 0, MANY, 0,
2715 doc: /* Configure speed, bytesize, etc. of a serial process.
2717 Arguments are specified as keyword/argument pairs. Attributes that
2718 are not given are re-initialized from the process's current
2719 configuration (available via the function `process-contact') or set to
2720 reasonable default values. The following arguments are defined:
2722 :process PROCESS
2723 :name NAME
2724 :buffer BUFFER
2725 :port PORT
2726 -- Any of these arguments can be given to identify the process that is
2727 to be configured. If none of these arguments is given, the current
2728 buffer's process is used.
2730 :speed SPEED -- SPEED is the speed of the serial port in bits per
2731 second, also called baud rate. Any value can be given for SPEED, but
2732 most serial ports work only at a few defined values between 1200 and
2733 115200, with 9600 being the most common value. If SPEED is nil, the
2734 serial port is not configured any further, i.e., all other arguments
2735 are ignored. This may be useful for special serial ports such as
2736 Bluetooth-to-serial converters which can only be configured through AT
2737 commands. A value of nil for SPEED can be used only when passed
2738 through `make-serial-process' or `serial-term'.
2740 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2741 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2743 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2744 `odd' (use odd parity), or the symbol `even' (use even parity). If
2745 PARITY is not given, no parity is used.
2747 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2748 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2749 is not given or nil, 1 stopbit is used.
2751 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2752 flowcontrol to be used, which is either nil (don't use flowcontrol),
2753 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2754 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2755 flowcontrol is used.
2757 `serial-process-configure' is called by `make-serial-process' for the
2758 initial configuration of the serial port.
2760 Examples:
2762 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2764 \(serial-process-configure
2765 :buffer "COM1" :stopbits 1 :parity \\='odd :flowcontrol \\='hw)
2767 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2769 usage: (serial-process-configure &rest ARGS) */)
2770 (ptrdiff_t nargs, Lisp_Object *args)
2772 struct Lisp_Process *p;
2773 Lisp_Object contact = Qnil;
2774 Lisp_Object proc = Qnil;
2776 contact = Flist (nargs, args);
2778 proc = Fplist_get (contact, QCprocess);
2779 if (NILP (proc))
2780 proc = Fplist_get (contact, QCname);
2781 if (NILP (proc))
2782 proc = Fplist_get (contact, QCbuffer);
2783 if (NILP (proc))
2784 proc = Fplist_get (contact, QCport);
2785 proc = get_process (proc);
2786 p = XPROCESS (proc);
2787 if (!EQ (p->type, Qserial))
2788 error ("Not a serial process");
2790 if (NILP (Fplist_get (p->childp, QCspeed)))
2791 return Qnil;
2793 serial_configure (p, contact);
2794 return Qnil;
2797 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2798 0, MANY, 0,
2799 doc: /* Create and return a serial port process.
2801 In Emacs, serial port connections are represented by process objects,
2802 so input and output work as for subprocesses, and `delete-process'
2803 closes a serial port connection. However, a serial process has no
2804 process id, it cannot be signaled, and the status codes are different
2805 from normal processes.
2807 `make-serial-process' creates a process and a buffer, on which you
2808 probably want to use `process-send-string'. Try \\[serial-term] for
2809 an interactive terminal. See below for examples.
2811 Arguments are specified as keyword/argument pairs. The following
2812 arguments are defined:
2814 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2815 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2816 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2817 the backslashes in strings).
2819 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2820 which this function calls.
2822 :name NAME -- NAME is the name of the process. If NAME is not given,
2823 the value of PORT is used.
2825 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2826 with the process. Process output goes at the end of that buffer,
2827 unless you specify an output stream or filter function to handle the
2828 output. If BUFFER is not given, the value of NAME is used.
2830 :coding CODING -- If CODING is a symbol, it specifies the coding
2831 system used for both reading and writing for this process. If CODING
2832 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2833 ENCODING is used for writing.
2835 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2836 the process is running. If BOOL is not given, query before exiting.
2838 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2839 In the stopped state, a serial process does not accept incoming data,
2840 but you can send outgoing data. The stopped state is cleared by
2841 `continue-process' and set by `stop-process'.
2843 :filter FILTER -- Install FILTER as the process filter.
2845 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2847 :plist PLIST -- Install PLIST as the initial plist of the process.
2849 :bytesize
2850 :parity
2851 :stopbits
2852 :flowcontrol
2853 -- This function calls `serial-process-configure' to handle these
2854 arguments.
2856 The original argument list, possibly modified by later configuration,
2857 is available via the function `process-contact'.
2859 Examples:
2861 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2863 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2865 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity \\='odd)
2867 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2869 usage: (make-serial-process &rest ARGS) */)
2870 (ptrdiff_t nargs, Lisp_Object *args)
2872 int fd = -1;
2873 Lisp_Object proc, contact, port;
2874 struct Lisp_Process *p;
2875 Lisp_Object name, buffer;
2876 Lisp_Object tem, val;
2877 ptrdiff_t specpdl_count;
2879 if (nargs == 0)
2880 return Qnil;
2882 contact = Flist (nargs, args);
2884 port = Fplist_get (contact, QCport);
2885 if (NILP (port))
2886 error ("No port specified");
2887 CHECK_STRING (port);
2889 if (NILP (Fplist_member (contact, QCspeed)))
2890 error (":speed not specified");
2891 if (!NILP (Fplist_get (contact, QCspeed)))
2892 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2894 name = Fplist_get (contact, QCname);
2895 if (NILP (name))
2896 name = port;
2897 CHECK_STRING (name);
2898 proc = make_process (name);
2899 specpdl_count = SPECPDL_INDEX ();
2900 record_unwind_protect (remove_process, proc);
2901 p = XPROCESS (proc);
2903 fd = serial_open (port);
2904 p->open_fd[SUBPROCESS_STDIN] = fd;
2905 p->infd = fd;
2906 p->outfd = fd;
2907 if (fd > max_process_desc)
2908 max_process_desc = fd;
2909 chan_process[fd] = proc;
2911 buffer = Fplist_get (contact, QCbuffer);
2912 if (NILP (buffer))
2913 buffer = name;
2914 buffer = Fget_buffer_create (buffer);
2915 pset_buffer (p, buffer);
2917 pset_childp (p, contact);
2918 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2919 pset_type (p, Qserial);
2920 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2921 pset_filter (p, Fplist_get (contact, QCfilter));
2922 eassert (NILP (p->log));
2923 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2924 p->kill_without_query = 1;
2925 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2926 pset_command (p, Qt);
2927 eassert (! p->pty_flag);
2929 if (!EQ (p->command, Qt))
2931 FD_SET (fd, &input_wait_mask);
2932 FD_SET (fd, &non_keyboard_wait_mask);
2935 if (BUFFERP (buffer))
2937 set_marker_both (p->mark, buffer,
2938 BUF_ZV (XBUFFER (buffer)),
2939 BUF_ZV_BYTE (XBUFFER (buffer)));
2942 tem = Fplist_member (contact, QCcoding);
2943 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2944 tem = Qnil;
2946 val = Qnil;
2947 if (!NILP (tem))
2949 val = XCAR (XCDR (tem));
2950 if (CONSP (val))
2951 val = XCAR (val);
2953 else if (!NILP (Vcoding_system_for_read))
2954 val = Vcoding_system_for_read;
2955 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2956 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2957 val = Qnil;
2958 pset_decode_coding_system (p, val);
2960 val = Qnil;
2961 if (!NILP (tem))
2963 val = XCAR (XCDR (tem));
2964 if (CONSP (val))
2965 val = XCDR (val);
2967 else if (!NILP (Vcoding_system_for_write))
2968 val = Vcoding_system_for_write;
2969 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2970 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2971 val = Qnil;
2972 pset_encode_coding_system (p, val);
2974 setup_process_coding_systems (proc);
2975 pset_decoding_buf (p, empty_unibyte_string);
2976 eassert (p->decoding_carryover == 0);
2977 pset_encoding_buf (p, empty_unibyte_string);
2978 p->inherit_coding_system_flag
2979 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2981 Fserial_process_configure (nargs, args);
2983 specpdl_ptr = specpdl + specpdl_count;
2985 return proc;
2988 static void
2989 set_network_socket_coding_system (Lisp_Object proc, Lisp_Object host,
2990 Lisp_Object service, Lisp_Object name)
2992 Lisp_Object tem;
2993 struct Lisp_Process *p = XPROCESS (proc);
2994 Lisp_Object contact = p->childp;
2995 Lisp_Object coding_systems = Qt;
2996 Lisp_Object val;
2998 tem = Fplist_member (contact, QCcoding);
2999 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3000 tem = Qnil; /* No error message (too late!). */
3002 /* Setup coding systems for communicating with the network stream. */
3003 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3005 if (!NILP (tem))
3007 val = XCAR (XCDR (tem));
3008 if (CONSP (val))
3009 val = XCAR (val);
3011 else if (!NILP (Vcoding_system_for_read))
3012 val = Vcoding_system_for_read;
3013 else if ((!NILP (p->buffer)
3014 && NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
3015 || (NILP (p->buffer)
3016 && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3017 /* We dare not decode end-of-line format by setting VAL to
3018 Qraw_text, because the existing Emacs Lisp libraries
3019 assume that they receive bare code including a sequence of
3020 CR LF. */
3021 val = Qnil;
3022 else
3024 if (NILP (host) || NILP (service))
3025 coding_systems = Qnil;
3026 else
3027 coding_systems = CALLN (Ffind_operation_coding_system,
3028 Qopen_network_stream, name, p->buffer,
3029 host, service);
3030 if (CONSP (coding_systems))
3031 val = XCAR (coding_systems);
3032 else if (CONSP (Vdefault_process_coding_system))
3033 val = XCAR (Vdefault_process_coding_system);
3034 else
3035 val = Qnil;
3037 pset_decode_coding_system (p, val);
3039 if (!NILP (tem))
3041 val = XCAR (XCDR (tem));
3042 if (CONSP (val))
3043 val = XCDR (val);
3045 else if (!NILP (Vcoding_system_for_write))
3046 val = Vcoding_system_for_write;
3047 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3048 val = Qnil;
3049 else
3051 if (EQ (coding_systems, Qt))
3053 if (NILP (host) || NILP (service))
3054 coding_systems = Qnil;
3055 else
3056 coding_systems = CALLN (Ffind_operation_coding_system,
3057 Qopen_network_stream, name, p->buffer,
3058 host, service);
3060 if (CONSP (coding_systems))
3061 val = XCDR (coding_systems);
3062 else if (CONSP (Vdefault_process_coding_system))
3063 val = XCDR (Vdefault_process_coding_system);
3064 else
3065 val = Qnil;
3067 pset_encode_coding_system (p, val);
3069 pset_decoding_buf (p, empty_unibyte_string);
3070 p->decoding_carryover = 0;
3071 pset_encoding_buf (p, empty_unibyte_string);
3073 p->inherit_coding_system_flag
3074 = !(!NILP (tem) || NILP (p->buffer) || !inherit_process_coding_system);
3077 #ifdef HAVE_GNUTLS
3078 static void
3079 finish_after_tls_connection (Lisp_Object proc)
3081 struct Lisp_Process *p = XPROCESS (proc);
3082 Lisp_Object contact = p->childp;
3083 Lisp_Object result = Qt;
3085 if (!NILP (Ffboundp (Qnsm_verify_connection)))
3086 result = call3 (Qnsm_verify_connection,
3087 proc,
3088 Fplist_get (contact, QChost),
3089 Fplist_get (contact, QCservice));
3091 if (NILP (result))
3093 pset_status (p, list2 (Qfailed,
3094 build_string ("The Network Security Manager stopped the connections")));
3095 deactivate_process (proc);
3097 else if (p->outfd < 0)
3099 /* The counterparty may have closed the connection (especially
3100 if the NSM prompt above take a long time), so recheck the file
3101 descriptor here. */
3102 pset_status (p, Qfailed);
3103 deactivate_process (proc);
3105 else if (! FD_ISSET (p->outfd, &connect_wait_mask))
3107 /* If we cleared the connection wait mask before we did the TLS
3108 setup, then we have to say that the process is finally "open"
3109 here. */
3110 pset_status (p, Qrun);
3111 /* Execute the sentinel here. If we had relied on status_notify
3112 to do it later, it will read input from the process before
3113 calling the sentinel. */
3114 exec_sentinel (proc, build_string ("open\n"));
3117 #endif
3119 static void
3120 connect_network_socket (Lisp_Object proc, Lisp_Object addrinfos,
3121 Lisp_Object use_external_socket_p)
3123 ptrdiff_t count = SPECPDL_INDEX ();
3124 int s = -1, outch, inch;
3125 int xerrno = 0;
3126 int family;
3127 struct sockaddr *sa = NULL;
3128 int ret;
3129 ptrdiff_t addrlen;
3130 struct Lisp_Process *p = XPROCESS (proc);
3131 Lisp_Object contact = p->childp;
3132 int optbits = 0;
3133 int socket_to_use = -1;
3135 if (!NILP (use_external_socket_p))
3137 socket_to_use = external_sock_fd;
3139 /* Ensure we don't consume the external socket twice. */
3140 external_sock_fd = -1;
3143 /* Do this in case we never enter the while-loop below. */
3144 s = -1;
3146 while (!NILP (addrinfos))
3148 Lisp_Object addrinfo = XCAR (addrinfos);
3149 addrinfos = XCDR (addrinfos);
3150 int protocol = XINT (XCAR (addrinfo));
3151 Lisp_Object ip_address = XCDR (addrinfo);
3153 #ifdef WINDOWSNT
3154 retry_connect:
3155 #endif
3157 addrlen = get_lisp_to_sockaddr_size (ip_address, &family);
3158 if (sa)
3159 free (sa);
3160 sa = xmalloc (addrlen);
3161 conv_lisp_to_sockaddr (family, ip_address, sa, addrlen);
3163 s = socket_to_use;
3164 if (s < 0)
3166 int socktype = p->socktype | SOCK_CLOEXEC;
3167 if (p->is_non_blocking_client)
3168 socktype |= SOCK_NONBLOCK;
3169 s = socket (family, socktype, protocol);
3170 if (s < 0)
3172 xerrno = errno;
3173 continue;
3177 if (p->is_non_blocking_client && ! (SOCK_NONBLOCK && socket_to_use < 0))
3179 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3180 if (ret < 0)
3182 xerrno = errno;
3183 emacs_close (s);
3184 s = -1;
3185 if (0 <= socket_to_use)
3186 break;
3187 continue;
3191 #ifdef DATAGRAM_SOCKETS
3192 if (!p->is_server && p->socktype == SOCK_DGRAM)
3193 break;
3194 #endif /* DATAGRAM_SOCKETS */
3196 /* Make us close S if quit. */
3197 record_unwind_protect_int (close_file_unwind, s);
3199 /* Parse network options in the arg list. We simply ignore anything
3200 which isn't a known option (including other keywords). An error
3201 is signaled if setting a known option fails. */
3203 Lisp_Object params = contact, key, val;
3205 while (!NILP (params))
3207 key = XCAR (params);
3208 params = XCDR (params);
3209 val = XCAR (params);
3210 params = XCDR (params);
3211 optbits |= set_socket_option (s, key, val);
3215 if (p->is_server)
3217 /* Configure as a server socket. */
3219 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3220 explicit :reuseaddr key to override this. */
3221 #ifdef HAVE_LOCAL_SOCKETS
3222 if (family != AF_LOCAL)
3223 #endif
3224 if (!(optbits & (1 << OPIX_REUSEADDR)))
3226 int optval = 1;
3227 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3228 report_file_error ("Cannot set reuse option on server socket", Qnil);
3231 /* If passed a socket descriptor, it should be already bound. */
3232 if (socket_to_use < 0 && bind (s, sa, addrlen) != 0)
3233 report_file_error ("Cannot bind server socket", Qnil);
3235 #ifdef HAVE_GETSOCKNAME
3236 if (p->port == 0)
3238 struct sockaddr_in sa1;
3239 socklen_t len1 = sizeof (sa1);
3240 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3242 Lisp_Object service;
3243 service = make_number (ntohs (sa1.sin_port));
3244 contact = Fplist_put (contact, QCservice, service);
3245 /* Save the port number so that we can stash it in
3246 the process object later. */
3247 ((struct sockaddr_in *)sa)->sin_port = sa1.sin_port;
3250 #endif
3252 if (p->socktype != SOCK_DGRAM && listen (s, p->backlog))
3253 report_file_error ("Cannot listen on server socket", Qnil);
3255 break;
3258 immediate_quit = 1;
3259 QUIT;
3261 ret = connect (s, sa, addrlen);
3262 xerrno = errno;
3264 if (ret == 0 || xerrno == EISCONN)
3266 /* The unwind-protect will be discarded afterwards.
3267 Likewise for immediate_quit. */
3268 break;
3271 if (p->is_non_blocking_client && xerrno == EINPROGRESS)
3272 break;
3274 #ifndef WINDOWSNT
3275 if (xerrno == EINTR)
3277 /* Unlike most other syscalls connect() cannot be called
3278 again. (That would return EALREADY.) The proper way to
3279 wait for completion is pselect(). */
3280 int sc;
3281 socklen_t len;
3282 fd_set fdset;
3283 retry_select:
3284 FD_ZERO (&fdset);
3285 FD_SET (s, &fdset);
3286 QUIT;
3287 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3288 if (sc == -1)
3290 if (errno == EINTR)
3291 goto retry_select;
3292 else
3293 report_file_error ("Failed select", Qnil);
3295 eassert (sc > 0);
3297 len = sizeof xerrno;
3298 eassert (FD_ISSET (s, &fdset));
3299 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3300 report_file_error ("Failed getsockopt", Qnil);
3301 if (xerrno == 0)
3302 break;
3303 if (NILP (addrinfos))
3304 report_file_errno ("Failed connect", Qnil, xerrno);
3306 #endif /* !WINDOWSNT */
3308 immediate_quit = 0;
3310 /* Discard the unwind protect closing S. */
3311 specpdl_ptr = specpdl + count;
3312 emacs_close (s);
3313 s = -1;
3314 if (0 <= socket_to_use)
3315 break;
3317 #ifdef WINDOWSNT
3318 if (xerrno == EINTR)
3319 goto retry_connect;
3320 #endif
3323 if (s >= 0)
3325 #ifdef DATAGRAM_SOCKETS
3326 if (p->socktype == SOCK_DGRAM)
3328 if (datagram_address[s].sa)
3329 emacs_abort ();
3331 datagram_address[s].sa = xmalloc (addrlen);
3332 datagram_address[s].len = addrlen;
3333 if (p->is_server)
3335 Lisp_Object remote;
3336 memset (datagram_address[s].sa, 0, addrlen);
3337 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3339 int rfamily;
3340 ptrdiff_t rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3341 if (rlen != 0 && rfamily == family
3342 && rlen == addrlen)
3343 conv_lisp_to_sockaddr (rfamily, remote,
3344 datagram_address[s].sa, rlen);
3347 else
3348 memcpy (datagram_address[s].sa, sa, addrlen);
3350 #endif
3352 contact = Fplist_put (contact, p->is_server? QClocal: QCremote,
3353 conv_sockaddr_to_lisp (sa, addrlen));
3354 #ifdef HAVE_GETSOCKNAME
3355 if (!p->is_server)
3357 struct sockaddr_in sa1;
3358 socklen_t len1 = sizeof (sa1);
3359 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3360 contact = Fplist_put (contact, QClocal,
3361 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3363 #endif
3366 immediate_quit = 0;
3368 if (s < 0)
3370 /* If non-blocking got this far - and failed - assume non-blocking is
3371 not supported after all. This is probably a wrong assumption, but
3372 the normal blocking calls to open-network-stream handles this error
3373 better. */
3374 if (p->is_non_blocking_client)
3375 return;
3377 report_file_errno ((p->is_server
3378 ? "make server process failed"
3379 : "make client process failed"),
3380 contact, xerrno);
3383 inch = s;
3384 outch = s;
3386 chan_process[inch] = proc;
3388 fcntl (inch, F_SETFL, O_NONBLOCK);
3390 p = XPROCESS (proc);
3391 p->open_fd[SUBPROCESS_STDIN] = inch;
3392 p->infd = inch;
3393 p->outfd = outch;
3395 /* Discard the unwind protect for closing S, if any. */
3396 specpdl_ptr = specpdl + count;
3398 if (p->is_server && p->socktype != SOCK_DGRAM)
3399 pset_status (p, Qlisten);
3401 /* Make the process marker point into the process buffer (if any). */
3402 if (BUFFERP (p->buffer))
3403 set_marker_both (p->mark, p->buffer,
3404 BUF_ZV (XBUFFER (p->buffer)),
3405 BUF_ZV_BYTE (XBUFFER (p->buffer)));
3407 if (p->is_non_blocking_client)
3409 /* We may get here if connect did succeed immediately. However,
3410 in that case, we still need to signal this like a non-blocking
3411 connection. */
3412 if (! (connecting_status (p->status)
3413 && EQ (XCDR (p->status), addrinfos)))
3414 pset_status (p, Fcons (Qconnect, addrinfos));
3415 if (!FD_ISSET (inch, &connect_wait_mask))
3417 FD_SET (inch, &connect_wait_mask);
3418 FD_SET (inch, &write_mask);
3419 num_pending_connects++;
3422 else
3423 /* A server may have a client filter setting of Qt, but it must
3424 still listen for incoming connects unless it is stopped. */
3425 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3426 || (EQ (p->status, Qlisten) && NILP (p->command)))
3428 FD_SET (inch, &input_wait_mask);
3429 FD_SET (inch, &non_keyboard_wait_mask);
3432 if (inch > max_process_desc)
3433 max_process_desc = inch;
3435 /* Set up the masks based on the process filter. */
3436 set_process_filter_masks (p);
3438 setup_process_coding_systems (proc);
3440 #ifdef HAVE_GNUTLS
3441 /* Continue the asynchronous connection. */
3442 if (!NILP (p->gnutls_boot_parameters))
3444 Lisp_Object boot, params = p->gnutls_boot_parameters;
3446 boot = Fgnutls_boot (proc, XCAR (params), XCDR (params));
3447 p->gnutls_boot_parameters = Qnil;
3449 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
3450 /* Run sentinels, etc. */
3451 finish_after_tls_connection (proc);
3452 else if (p->gnutls_initstage != GNUTLS_STAGE_HANDSHAKE_TRIED)
3454 deactivate_process (proc);
3455 if (NILP (boot))
3456 pset_status (p, list2 (Qfailed,
3457 build_string ("TLS negotiation failed")));
3458 else
3459 pset_status (p, list2 (Qfailed, boot));
3462 #endif
3466 /* Create a network stream/datagram client/server process. Treated
3467 exactly like a normal process when reading and writing. Primary
3468 differences are in status display and process deletion. A network
3469 connection has no PID; you cannot signal it. All you can do is
3470 stop/continue it and deactivate/close it via delete-process. */
3472 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
3473 0, MANY, 0,
3474 doc: /* Create and return a network server or client process.
3476 In Emacs, network connections are represented by process objects, so
3477 input and output work as for subprocesses and `delete-process' closes
3478 a network connection. However, a network process has no process id,
3479 it cannot be signaled, and the status codes are different from normal
3480 processes.
3482 Arguments are specified as keyword/argument pairs. The following
3483 arguments are defined:
3485 :name NAME -- NAME is name for process. It is modified if necessary
3486 to make it unique.
3488 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3489 with the process. Process output goes at end of that buffer, unless
3490 you specify an output stream or filter function to handle the output.
3491 BUFFER may be also nil, meaning that this process is not associated
3492 with any buffer.
3494 :host HOST -- HOST is name of the host to connect to, or its IP
3495 address. The symbol `local' specifies the local host. If specified
3496 for a server process, it must be a valid name or address for the local
3497 host, and only clients connecting to that address will be accepted.
3499 :service SERVICE -- SERVICE is name of the service desired, or an
3500 integer specifying a port number to connect to. If SERVICE is t,
3501 a random port number is selected for the server. A port number can
3502 be specified as an integer string, e.g., "80", as well as an integer.
3504 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3505 stream type connection, `datagram' creates a datagram type connection,
3506 `seqpacket' creates a reliable datagram connection.
3508 :family FAMILY -- FAMILY is the address (and protocol) family for the
3509 service specified by HOST and SERVICE. The default (nil) is to use
3510 whatever address family (IPv4 or IPv6) that is defined for the host
3511 and port number specified by HOST and SERVICE. Other address families
3512 supported are:
3513 local -- for a local (i.e. UNIX) address specified by SERVICE.
3514 ipv4 -- use IPv4 address family only.
3515 ipv6 -- use IPv6 address family only.
3517 :local ADDRESS -- ADDRESS is the local address used for the connection.
3518 This parameter is ignored when opening a client process. When specified
3519 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3521 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3522 connection. This parameter is ignored when opening a stream server
3523 process. For a datagram server process, it specifies the initial
3524 setting of the remote datagram address. When specified for a client
3525 process, the FAMILY, HOST, and SERVICE args are ignored.
3527 The format of ADDRESS depends on the address family:
3528 - An IPv4 address is represented as an vector of integers [A B C D P]
3529 corresponding to numeric IP address A.B.C.D and port number P.
3530 - A local address is represented as a string with the address in the
3531 local address space.
3532 - An "unsupported family" address is represented by a cons (F . AV)
3533 where F is the family number and AV is a vector containing the socket
3534 address data with one element per address data byte. Do not rely on
3535 this format in portable code, as it may depend on implementation
3536 defined constants, data sizes, and data structure alignment.
3538 :coding CODING -- If CODING is a symbol, it specifies the coding
3539 system used for both reading and writing for this process. If CODING
3540 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3541 ENCODING is used for writing.
3543 :nowait BOOL -- If NOWAIT is non-nil for a stream type client
3544 process, return without waiting for the connection to complete;
3545 instead, the sentinel function will be called with second arg matching
3546 "open" (if successful) or "failed" when the connect completes.
3547 Default is to use a blocking connect (i.e. wait) for stream type
3548 connections.
3550 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3551 running when Emacs is exited.
3553 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3554 In the stopped state, a server process does not accept new
3555 connections, and a client process does not handle incoming traffic.
3556 The stopped state is cleared by `continue-process' and set by
3557 `stop-process'.
3559 :filter FILTER -- Install FILTER as the process filter.
3561 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3562 process filter are multibyte, otherwise they are unibyte.
3563 If this keyword is not specified, the strings are multibyte if
3564 the default value of `enable-multibyte-characters' is non-nil.
3566 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3568 :log LOG -- Install LOG as the server process log function. This
3569 function is called when the server accepts a network connection from a
3570 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3571 is the server process, CLIENT is the new process for the connection,
3572 and MESSAGE is a string.
3574 :plist PLIST -- Install PLIST as the new process's initial plist.
3576 :tls-parameters LIST -- is a list that should be supplied if you're
3577 opening a TLS connection. The first element is the TLS type (either
3578 `gnutls-x509pki' or `gnutls-anon'), and the remaining elements should
3579 be a keyword list accepted by gnutls-boot (as returned by
3580 `gnutls-boot-parameters').
3582 :server QLEN -- if QLEN is non-nil, create a server process for the
3583 specified FAMILY, SERVICE, and connection type (stream or datagram).
3584 If QLEN is an integer, it is used as the max. length of the server's
3585 pending connection queue (also known as the backlog); the default
3586 queue length is 5. Default is to create a client process.
3588 The following network options can be specified for this connection:
3590 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3591 :dontroute BOOL -- Only send to directly connected hosts.
3592 :keepalive BOOL -- Send keep-alive messages on network stream.
3593 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3594 :oobinline BOOL -- Place out-of-band data in receive data stream.
3595 :priority INT -- Set protocol defined priority for sent packets.
3596 :reuseaddr BOOL -- Allow reusing a recently used local address
3597 (this is allowed by default for a server process).
3598 :bindtodevice NAME -- bind to interface NAME. Using this may require
3599 special privileges on some systems.
3600 :use-external-socket BOOL -- Use any pre-allocated sockets that have
3601 been passed to Emacs. If Emacs wasn't
3602 passed a socket, this option is silently
3603 ignored.
3606 Consult the relevant system programmer's manual pages for more
3607 information on using these options.
3610 A server process will listen for and accept connections from clients.
3611 When a client connection is accepted, a new network process is created
3612 for the connection with the following parameters:
3614 - The client's process name is constructed by concatenating the server
3615 process's NAME and a client identification string.
3616 - If the FILTER argument is non-nil, the client process will not get a
3617 separate process buffer; otherwise, the client's process buffer is a newly
3618 created buffer named after the server process's BUFFER name or process
3619 NAME concatenated with the client identification string.
3620 - The connection type and the process filter and sentinel parameters are
3621 inherited from the server process's TYPE, FILTER and SENTINEL.
3622 - The client process's contact info is set according to the client's
3623 addressing information (typically an IP address and a port number).
3624 - The client process's plist is initialized from the server's plist.
3626 Notice that the FILTER and SENTINEL args are never used directly by
3627 the server process. Also, the BUFFER argument is not used directly by
3628 the server process, but via the optional :log function, accepted (and
3629 failed) connections may be logged in the server process's buffer.
3631 The original argument list, modified with the actual connection
3632 information, is available via the `process-contact' function.
3634 usage: (make-network-process &rest ARGS) */)
3635 (ptrdiff_t nargs, Lisp_Object *args)
3637 Lisp_Object proc;
3638 Lisp_Object contact;
3639 struct Lisp_Process *p;
3640 const char *portstring;
3641 ptrdiff_t portstringlen ATTRIBUTE_UNUSED;
3642 char portbuf[INT_BUFSIZE_BOUND (EMACS_INT)];
3643 #ifdef HAVE_LOCAL_SOCKETS
3644 struct sockaddr_un address_un;
3645 #endif
3646 EMACS_INT port = 0;
3647 Lisp_Object tem;
3648 Lisp_Object name, buffer, host, service, address;
3649 Lisp_Object filter, sentinel, use_external_socket_p;
3650 Lisp_Object addrinfos = Qnil;
3651 int socktype;
3652 int family = -1;
3653 enum { any_protocol = 0 };
3654 #ifdef HAVE_GETADDRINFO_A
3655 struct gaicb *dns_request = NULL;
3656 #endif
3657 ptrdiff_t count = SPECPDL_INDEX ();
3659 if (nargs == 0)
3660 return Qnil;
3662 /* Save arguments for process-contact and clone-process. */
3663 contact = Flist (nargs, args);
3665 #ifdef WINDOWSNT
3666 /* Ensure socket support is loaded if available. */
3667 init_winsock (TRUE);
3668 #endif
3670 /* :type TYPE (nil: stream, datagram */
3671 tem = Fplist_get (contact, QCtype);
3672 if (NILP (tem))
3673 socktype = SOCK_STREAM;
3674 #ifdef DATAGRAM_SOCKETS
3675 else if (EQ (tem, Qdatagram))
3676 socktype = SOCK_DGRAM;
3677 #endif
3678 #ifdef HAVE_SEQPACKET
3679 else if (EQ (tem, Qseqpacket))
3680 socktype = SOCK_SEQPACKET;
3681 #endif
3682 else
3683 error ("Unsupported connection type");
3685 name = Fplist_get (contact, QCname);
3686 buffer = Fplist_get (contact, QCbuffer);
3687 filter = Fplist_get (contact, QCfilter);
3688 sentinel = Fplist_get (contact, QCsentinel);
3689 use_external_socket_p = Fplist_get (contact, QCuse_external_socket);
3691 CHECK_STRING (name);
3693 /* :local ADDRESS or :remote ADDRESS */
3694 tem = Fplist_get (contact, QCserver);
3695 if (NILP (tem))
3696 address = Fplist_get (contact, QCremote);
3697 else
3698 address = Fplist_get (contact, QClocal);
3699 if (!NILP (address))
3701 host = service = Qnil;
3703 if (!get_lisp_to_sockaddr_size (address, &family))
3704 error ("Malformed :address");
3706 addrinfos = list1 (Fcons (make_number (any_protocol), address));
3707 goto open_socket;
3710 /* :family FAMILY -- nil (for Inet), local, or integer. */
3711 tem = Fplist_get (contact, QCfamily);
3712 if (NILP (tem))
3714 #ifdef AF_INET6
3715 family = AF_UNSPEC;
3716 #else
3717 family = AF_INET;
3718 #endif
3720 #ifdef HAVE_LOCAL_SOCKETS
3721 else if (EQ (tem, Qlocal))
3722 family = AF_LOCAL;
3723 #endif
3724 #ifdef AF_INET6
3725 else if (EQ (tem, Qipv6))
3726 family = AF_INET6;
3727 #endif
3728 else if (EQ (tem, Qipv4))
3729 family = AF_INET;
3730 else if (TYPE_RANGED_INTEGERP (int, tem))
3731 family = XINT (tem);
3732 else
3733 error ("Unknown address family");
3735 /* :service SERVICE -- string, integer (port number), or t (random port). */
3736 service = Fplist_get (contact, QCservice);
3738 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3739 host = Fplist_get (contact, QChost);
3740 if (NILP (host))
3742 /* The "connection" function gets it bind info from the address we're
3743 given, so use this dummy address if nothing is specified. */
3744 #ifdef HAVE_LOCAL_SOCKETS
3745 if (family != AF_LOCAL)
3746 #endif
3747 host = build_string ("127.0.0.1");
3749 else
3751 if (EQ (host, Qlocal))
3752 /* Depending on setup, "localhost" may map to different IPv4 and/or
3753 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3754 host = build_string ("127.0.0.1");
3755 CHECK_STRING (host);
3758 #ifdef HAVE_LOCAL_SOCKETS
3759 if (family == AF_LOCAL)
3761 if (!NILP (host))
3763 message (":family local ignores the :host property");
3764 contact = Fplist_put (contact, QChost, Qnil);
3765 host = Qnil;
3767 CHECK_STRING (service);
3768 if (sizeof address_un.sun_path <= SBYTES (service))
3769 error ("Service name too long");
3770 addrinfos = list1 (Fcons (make_number (any_protocol), service));
3771 goto open_socket;
3773 #endif
3775 /* Slow down polling to every ten seconds.
3776 Some kernels have a bug which causes retrying connect to fail
3777 after a connect. Polling can interfere with gethostbyname too. */
3778 #ifdef POLL_FOR_INPUT
3779 if (socktype != SOCK_DGRAM)
3781 record_unwind_protect_void (run_all_atimers);
3782 bind_polling_period (10);
3784 #endif
3786 if (!NILP (host))
3788 /* SERVICE can either be a string or int.
3789 Convert to a C string for later use by getaddrinfo. */
3790 if (EQ (service, Qt))
3792 portstring = "0";
3793 portstringlen = 1;
3795 else if (INTEGERP (service))
3797 portstring = portbuf;
3798 portstringlen = sprintf (portbuf, "%"pI"d", XINT (service));
3800 else
3802 CHECK_STRING (service);
3803 portstring = SSDATA (service);
3804 portstringlen = SBYTES (service);
3808 #ifdef HAVE_GETADDRINFO_A
3809 if (!NILP (host) && !NILP (Fplist_get (contact, QCnowait)))
3811 ptrdiff_t hostlen = SBYTES (host);
3812 struct req
3814 struct gaicb gaicb;
3815 struct addrinfo hints;
3816 char str[FLEXIBLE_ARRAY_MEMBER];
3817 } *req = xmalloc (FLEXSIZEOF (struct req, str,
3818 hostlen + 1 + portstringlen + 1));
3819 dns_request = &req->gaicb;
3820 dns_request->ar_name = req->str;
3821 dns_request->ar_service = req->str + hostlen + 1;
3822 dns_request->ar_request = &req->hints;
3823 dns_request->ar_result = NULL;
3824 memset (&req->hints, 0, sizeof req->hints);
3825 req->hints.ai_family = family;
3826 req->hints.ai_socktype = socktype;
3827 strcpy (req->str, SSDATA (host));
3828 strcpy (req->str + hostlen + 1, portstring);
3830 int ret = getaddrinfo_a (GAI_NOWAIT, &dns_request, 1, NULL);
3831 if (ret)
3832 error ("%s/%s getaddrinfo_a error %d", SSDATA (host), portstring, ret);
3834 goto open_socket;
3836 #endif /* HAVE_GETADDRINFO_A */
3838 /* If we have a host, use getaddrinfo to resolve both host and service.
3839 Otherwise, use getservbyname to lookup the service. */
3841 if (!NILP (host))
3843 struct addrinfo *res, *lres;
3844 int ret;
3846 immediate_quit = 1;
3847 QUIT;
3849 struct addrinfo hints;
3850 memset (&hints, 0, sizeof hints);
3851 hints.ai_family = family;
3852 hints.ai_socktype = socktype;
3854 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3855 if (ret)
3856 #ifdef HAVE_GAI_STRERROR
3858 synchronize_system_messages_locale ();
3859 char const *str = gai_strerror (ret);
3860 if (! NILP (Vlocale_coding_system))
3861 str = SSDATA (code_convert_string_norecord
3862 (build_string (str), Vlocale_coding_system, 0));
3863 error ("%s/%s %s", SSDATA (host), portstring, str);
3865 #else
3866 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3867 #endif
3868 immediate_quit = 0;
3870 for (lres = res; lres; lres = lres->ai_next)
3871 addrinfos = Fcons (conv_addrinfo_to_lisp (lres), addrinfos);
3873 addrinfos = Fnreverse (addrinfos);
3875 freeaddrinfo (res);
3877 goto open_socket;
3880 /* No hostname has been specified (e.g., a local server process). */
3882 if (EQ (service, Qt))
3883 port = 0;
3884 else if (INTEGERP (service))
3885 port = XINT (service);
3886 else
3888 CHECK_STRING (service);
3890 port = -1;
3891 if (SBYTES (service) != 0)
3893 /* Allow the service to be a string containing the port number,
3894 because that's allowed if you have getaddrbyname. */
3895 char *service_end;
3896 long int lport = strtol (SSDATA (service), &service_end, 10);
3897 if (service_end == SSDATA (service) + SBYTES (service))
3898 port = lport;
3899 else
3901 struct servent *svc_info
3902 = getservbyname (SSDATA (service),
3903 socktype == SOCK_DGRAM ? "udp" : "tcp");
3904 if (svc_info)
3905 port = ntohs (svc_info->s_port);
3910 if (! (0 <= port && port < 1 << 16))
3912 AUTO_STRING (unknown_service, "Unknown service: %s");
3913 xsignal1 (Qerror, CALLN (Fformat, unknown_service, service));
3916 open_socket:
3918 if (!NILP (buffer))
3919 buffer = Fget_buffer_create (buffer);
3921 /* Unwind bind_polling_period. */
3922 unbind_to (count, Qnil);
3924 proc = make_process (name);
3925 record_unwind_protect (remove_process, proc);
3926 p = XPROCESS (proc);
3927 pset_childp (p, contact);
3928 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3929 pset_type (p, Qnetwork);
3931 pset_buffer (p, buffer);
3932 pset_sentinel (p, sentinel);
3933 pset_filter (p, filter);
3934 pset_log (p, Fplist_get (contact, QClog));
3935 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3936 p->kill_without_query = 1;
3937 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3938 pset_command (p, Qt);
3939 eassert (p->pid == 0);
3940 p->backlog = 5;
3941 eassert (! p->is_non_blocking_client);
3942 eassert (! p->is_server);
3943 p->port = port;
3944 p->socktype = socktype;
3945 #ifdef HAVE_GETADDRINFO_A
3946 eassert (! p->dns_request);
3947 #endif
3948 #ifdef HAVE_GNUTLS
3949 tem = Fplist_get (contact, QCtls_parameters);
3950 CHECK_LIST (tem);
3951 p->gnutls_boot_parameters = tem;
3952 #endif
3954 set_network_socket_coding_system (proc, host, service, name);
3956 /* :server BOOL */
3957 tem = Fplist_get (contact, QCserver);
3958 if (!NILP (tem))
3960 /* Don't support network sockets when non-blocking mode is
3961 not available, since a blocked Emacs is not useful. */
3962 p->is_server = true;
3963 if (TYPE_RANGED_INTEGERP (int, tem))
3964 p->backlog = XINT (tem);
3967 /* :nowait BOOL */
3968 if (!p->is_server && socktype != SOCK_DGRAM
3969 && !NILP (Fplist_get (contact, QCnowait)))
3970 p->is_non_blocking_client = true;
3972 bool postpone_connection = false;
3973 #ifdef HAVE_GETADDRINFO_A
3974 /* With async address resolution, the list of addresses is empty, so
3975 postpone connecting to the server. */
3976 if (!p->is_server && NILP (addrinfos))
3978 p->dns_request = dns_request;
3979 p->status = list1 (Qconnect);
3980 postpone_connection = true;
3982 #endif
3983 if (! postpone_connection)
3984 connect_network_socket (proc, addrinfos, use_external_socket_p);
3986 specpdl_ptr = specpdl + count;
3987 return proc;
3991 #ifdef HAVE_NET_IF_H
3993 #ifdef SIOCGIFCONF
3994 static Lisp_Object
3995 network_interface_list (void)
3997 struct ifconf ifconf;
3998 struct ifreq *ifreq;
3999 void *buf = NULL;
4000 ptrdiff_t buf_size = 512;
4001 int s;
4002 Lisp_Object res;
4003 ptrdiff_t count;
4005 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4006 if (s < 0)
4007 return Qnil;
4008 count = SPECPDL_INDEX ();
4009 record_unwind_protect_int (close_file_unwind, s);
4013 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
4014 ifconf.ifc_buf = buf;
4015 ifconf.ifc_len = buf_size;
4016 if (ioctl (s, SIOCGIFCONF, &ifconf))
4018 emacs_close (s);
4019 xfree (buf);
4020 return Qnil;
4023 while (ifconf.ifc_len == buf_size);
4025 res = unbind_to (count, Qnil);
4026 ifreq = ifconf.ifc_req;
4027 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
4029 struct ifreq *ifq = ifreq;
4030 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
4031 #define SIZEOF_IFREQ(sif) \
4032 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
4033 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
4035 int len = SIZEOF_IFREQ (ifq);
4036 #else
4037 int len = sizeof (*ifreq);
4038 #endif
4039 char namebuf[sizeof (ifq->ifr_name) + 1];
4040 ifreq = (struct ifreq *) ((char *) ifreq + len);
4042 if (ifq->ifr_addr.sa_family != AF_INET)
4043 continue;
4045 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
4046 namebuf[sizeof (ifq->ifr_name)] = 0;
4047 res = Fcons (Fcons (build_string (namebuf),
4048 conv_sockaddr_to_lisp (&ifq->ifr_addr,
4049 sizeof (struct sockaddr))),
4050 res);
4053 xfree (buf);
4054 return res;
4056 #endif /* SIOCGIFCONF */
4058 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
4060 struct ifflag_def {
4061 int flag_bit;
4062 const char *flag_sym;
4065 static const struct ifflag_def ifflag_table[] = {
4066 #ifdef IFF_UP
4067 { IFF_UP, "up" },
4068 #endif
4069 #ifdef IFF_BROADCAST
4070 { IFF_BROADCAST, "broadcast" },
4071 #endif
4072 #ifdef IFF_DEBUG
4073 { IFF_DEBUG, "debug" },
4074 #endif
4075 #ifdef IFF_LOOPBACK
4076 { IFF_LOOPBACK, "loopback" },
4077 #endif
4078 #ifdef IFF_POINTOPOINT
4079 { IFF_POINTOPOINT, "pointopoint" },
4080 #endif
4081 #ifdef IFF_RUNNING
4082 { IFF_RUNNING, "running" },
4083 #endif
4084 #ifdef IFF_NOARP
4085 { IFF_NOARP, "noarp" },
4086 #endif
4087 #ifdef IFF_PROMISC
4088 { IFF_PROMISC, "promisc" },
4089 #endif
4090 #ifdef IFF_NOTRAILERS
4091 #ifdef NS_IMPL_COCOA
4092 /* Really means smart, notrailers is obsolete. */
4093 { IFF_NOTRAILERS, "smart" },
4094 #else
4095 { IFF_NOTRAILERS, "notrailers" },
4096 #endif
4097 #endif
4098 #ifdef IFF_ALLMULTI
4099 { IFF_ALLMULTI, "allmulti" },
4100 #endif
4101 #ifdef IFF_MASTER
4102 { IFF_MASTER, "master" },
4103 #endif
4104 #ifdef IFF_SLAVE
4105 { IFF_SLAVE, "slave" },
4106 #endif
4107 #ifdef IFF_MULTICAST
4108 { IFF_MULTICAST, "multicast" },
4109 #endif
4110 #ifdef IFF_PORTSEL
4111 { IFF_PORTSEL, "portsel" },
4112 #endif
4113 #ifdef IFF_AUTOMEDIA
4114 { IFF_AUTOMEDIA, "automedia" },
4115 #endif
4116 #ifdef IFF_DYNAMIC
4117 { IFF_DYNAMIC, "dynamic" },
4118 #endif
4119 #ifdef IFF_OACTIVE
4120 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
4121 #endif
4122 #ifdef IFF_SIMPLEX
4123 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
4124 #endif
4125 #ifdef IFF_LINK0
4126 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
4127 #endif
4128 #ifdef IFF_LINK1
4129 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
4130 #endif
4131 #ifdef IFF_LINK2
4132 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
4133 #endif
4134 { 0, 0 }
4137 static Lisp_Object
4138 network_interface_info (Lisp_Object ifname)
4140 struct ifreq rq;
4141 Lisp_Object res = Qnil;
4142 Lisp_Object elt;
4143 int s;
4144 bool any = 0;
4145 ptrdiff_t count;
4146 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
4147 && defined HAVE_GETIFADDRS && defined LLADDR)
4148 struct ifaddrs *ifap;
4149 #endif
4151 CHECK_STRING (ifname);
4153 if (sizeof rq.ifr_name <= SBYTES (ifname))
4154 error ("interface name too long");
4155 lispstpcpy (rq.ifr_name, ifname);
4157 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
4158 if (s < 0)
4159 return Qnil;
4160 count = SPECPDL_INDEX ();
4161 record_unwind_protect_int (close_file_unwind, s);
4163 elt = Qnil;
4164 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4165 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4167 int flags = rq.ifr_flags;
4168 const struct ifflag_def *fp;
4169 int fnum;
4171 /* If flags is smaller than int (i.e. short) it may have the high bit set
4172 due to IFF_MULTICAST. In that case, sign extending it into
4173 an int is wrong. */
4174 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
4175 flags = (unsigned short) rq.ifr_flags;
4177 any = 1;
4178 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4180 if (flags & fp->flag_bit)
4182 elt = Fcons (intern (fp->flag_sym), elt);
4183 flags -= fp->flag_bit;
4186 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
4188 if (flags & 1)
4190 elt = Fcons (make_number (fnum), elt);
4194 #endif
4195 res = Fcons (elt, res);
4197 elt = Qnil;
4198 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4199 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4201 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4202 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4203 int n;
4205 any = 1;
4206 for (n = 0; n < 6; n++)
4207 p->contents[n] = make_number (((unsigned char *)
4208 &rq.ifr_hwaddr.sa_data[0])
4209 [n]);
4210 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4212 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4213 if (getifaddrs (&ifap) != -1)
4215 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4216 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4217 struct ifaddrs *it;
4219 for (it = ifap; it != NULL; it = it->ifa_next)
4221 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
4222 unsigned char linkaddr[6];
4223 int n;
4225 if (it->ifa_addr->sa_family != AF_LINK
4226 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4227 || sdl->sdl_alen != 6)
4228 continue;
4230 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4231 for (n = 0; n < 6; n++)
4232 p->contents[n] = make_number (linkaddr[n]);
4234 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4235 break;
4238 #ifdef HAVE_FREEIFADDRS
4239 freeifaddrs (ifap);
4240 #endif
4242 #endif /* HAVE_GETIFADDRS && LLADDR */
4244 res = Fcons (elt, res);
4246 elt = Qnil;
4247 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4248 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4250 any = 1;
4251 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4252 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4253 #else
4254 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4255 #endif
4257 #endif
4258 res = Fcons (elt, res);
4260 elt = Qnil;
4261 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4262 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4264 any = 1;
4265 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4267 #endif
4268 res = Fcons (elt, res);
4270 elt = Qnil;
4271 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4272 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4274 any = 1;
4275 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4277 #endif
4278 res = Fcons (elt, res);
4280 return unbind_to (count, any ? res : Qnil);
4282 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4283 #endif /* defined (HAVE_NET_IF_H) */
4285 DEFUN ("network-interface-list", Fnetwork_interface_list,
4286 Snetwork_interface_list, 0, 0, 0,
4287 doc: /* Return an alist of all network interfaces and their network address.
4288 Each element is a cons, the car of which is a string containing the
4289 interface name, and the cdr is the network address in internal
4290 format; see the description of ADDRESS in `make-network-process'.
4292 If the information is not available, return nil. */)
4293 (void)
4295 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4296 return network_interface_list ();
4297 #else
4298 return Qnil;
4299 #endif
4302 DEFUN ("network-interface-info", Fnetwork_interface_info,
4303 Snetwork_interface_info, 1, 1, 0,
4304 doc: /* Return information about network interface named IFNAME.
4305 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4306 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4307 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4308 FLAGS is the current flags of the interface.
4310 Data that is unavailable is returned as nil. */)
4311 (Lisp_Object ifname)
4313 #if ((defined HAVE_NET_IF_H \
4314 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4315 || defined SIOCGIFFLAGS)) \
4316 || defined WINDOWSNT)
4317 return network_interface_info (ifname);
4318 #else
4319 return Qnil;
4320 #endif
4323 /* Turn off input and output for process PROC. */
4325 static void
4326 deactivate_process (Lisp_Object proc)
4328 int inchannel;
4329 struct Lisp_Process *p = XPROCESS (proc);
4330 int i;
4332 #ifdef HAVE_GNUTLS
4333 /* Delete GnuTLS structures in PROC, if any. */
4334 emacs_gnutls_deinit (proc);
4335 #endif /* HAVE_GNUTLS */
4337 if (p->read_output_delay > 0)
4339 if (--process_output_delay_count < 0)
4340 process_output_delay_count = 0;
4341 p->read_output_delay = 0;
4342 p->read_output_skip = 0;
4345 /* Beware SIGCHLD hereabouts. */
4347 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4348 close_process_fd (&p->open_fd[i]);
4350 inchannel = p->infd;
4351 if (inchannel >= 0)
4353 p->infd = -1;
4354 p->outfd = -1;
4355 #ifdef DATAGRAM_SOCKETS
4356 if (DATAGRAM_CHAN_P (inchannel))
4358 xfree (datagram_address[inchannel].sa);
4359 datagram_address[inchannel].sa = 0;
4360 datagram_address[inchannel].len = 0;
4362 #endif
4363 chan_process[inchannel] = Qnil;
4364 FD_CLR (inchannel, &input_wait_mask);
4365 FD_CLR (inchannel, &non_keyboard_wait_mask);
4366 if (FD_ISSET (inchannel, &connect_wait_mask))
4368 FD_CLR (inchannel, &connect_wait_mask);
4369 FD_CLR (inchannel, &write_mask);
4370 if (--num_pending_connects < 0)
4371 emacs_abort ();
4373 if (inchannel == max_process_desc)
4375 /* We just closed the highest-numbered process input descriptor,
4376 so recompute the highest-numbered one now. */
4377 int i = inchannel;
4379 i--;
4380 while (0 <= i && NILP (chan_process[i]));
4382 max_process_desc = i;
4388 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4389 0, 4, 0,
4390 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4391 It is given to their filter functions.
4392 Optional argument PROCESS means do not return until output has been
4393 received from PROCESS.
4395 Optional second argument SECONDS and third argument MILLISEC
4396 specify a timeout; return after that much time even if there is
4397 no subprocess output. If SECONDS is a floating point number,
4398 it specifies a fractional number of seconds to wait.
4399 The MILLISEC argument is obsolete and should be avoided.
4401 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4402 from PROCESS only, suspending reading output from other processes.
4403 If JUST-THIS-ONE is an integer, don't run any timers either.
4404 Return non-nil if we received any output from PROCESS (or, if PROCESS
4405 is nil, from any process) before the timeout expired. */)
4406 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4408 intmax_t secs;
4409 int nsecs;
4411 if (! NILP (process))
4412 CHECK_PROCESS (process);
4413 else
4414 just_this_one = Qnil;
4416 if (!NILP (millisec))
4417 { /* Obsolete calling convention using integers rather than floats. */
4418 CHECK_NUMBER (millisec);
4419 if (NILP (seconds))
4420 seconds = make_float (XINT (millisec) / 1000.0);
4421 else
4423 CHECK_NUMBER (seconds);
4424 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4428 secs = 0;
4429 nsecs = -1;
4431 if (!NILP (seconds))
4433 if (INTEGERP (seconds))
4435 if (XINT (seconds) > 0)
4437 secs = XINT (seconds);
4438 nsecs = 0;
4441 else if (FLOATP (seconds))
4443 if (XFLOAT_DATA (seconds) > 0)
4445 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4446 secs = min (t.tv_sec, WAIT_READING_MAX);
4447 nsecs = t.tv_nsec;
4450 else
4451 wrong_type_argument (Qnumberp, seconds);
4453 else if (! NILP (process))
4454 nsecs = 0;
4456 return
4457 ((wait_reading_process_output (secs, nsecs, 0, 0,
4458 Qnil,
4459 !NILP (process) ? XPROCESS (process) : NULL,
4460 (NILP (just_this_one) ? 0
4461 : !INTEGERP (just_this_one) ? 1 : -1))
4462 <= 0)
4463 ? Qnil : Qt);
4466 /* Accept a connection for server process SERVER on CHANNEL. */
4468 static EMACS_INT connect_counter = 0;
4470 static void
4471 server_accept_connection (Lisp_Object server, int channel)
4473 Lisp_Object proc, caller, name, buffer;
4474 Lisp_Object contact, host, service;
4475 struct Lisp_Process *ps = XPROCESS (server);
4476 struct Lisp_Process *p;
4477 int s;
4478 union u_sockaddr {
4479 struct sockaddr sa;
4480 struct sockaddr_in in;
4481 #ifdef AF_INET6
4482 struct sockaddr_in6 in6;
4483 #endif
4484 #ifdef HAVE_LOCAL_SOCKETS
4485 struct sockaddr_un un;
4486 #endif
4487 } saddr;
4488 socklen_t len = sizeof saddr;
4489 ptrdiff_t count;
4491 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4493 if (s < 0)
4495 int code = errno;
4496 if (!would_block (code) && !NILP (ps->log))
4497 call3 (ps->log, server, Qnil,
4498 concat3 (build_string ("accept failed with code"),
4499 Fnumber_to_string (make_number (code)),
4500 build_string ("\n")));
4501 return;
4504 count = SPECPDL_INDEX ();
4505 record_unwind_protect_int (close_file_unwind, s);
4507 connect_counter++;
4509 /* Setup a new process to handle the connection. */
4511 /* Generate a unique identification of the caller, and build contact
4512 information for this process. */
4513 host = Qt;
4514 service = Qnil;
4515 switch (saddr.sa.sa_family)
4517 case AF_INET:
4519 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4521 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4522 host = CALLN (Fformat, ipv4_format,
4523 make_number (ip[0]), make_number (ip[1]),
4524 make_number (ip[2]), make_number (ip[3]));
4525 service = make_number (ntohs (saddr.in.sin_port));
4526 AUTO_STRING (caller_format, " <%s:%d>");
4527 caller = CALLN (Fformat, caller_format, host, service);
4529 break;
4531 #ifdef AF_INET6
4532 case AF_INET6:
4534 Lisp_Object args[9];
4535 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4536 int i;
4538 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4539 args[0] = ipv6_format;
4540 for (i = 0; i < 8; i++)
4541 args[i + 1] = make_number (ntohs (ip6[i]));
4542 host = CALLMANY (Fformat, args);
4543 service = make_number (ntohs (saddr.in.sin_port));
4544 AUTO_STRING (caller_format, " <[%s]:%d>");
4545 caller = CALLN (Fformat, caller_format, host, service);
4547 break;
4548 #endif
4550 #ifdef HAVE_LOCAL_SOCKETS
4551 case AF_LOCAL:
4552 #endif
4553 default:
4554 caller = Fnumber_to_string (make_number (connect_counter));
4555 AUTO_STRING (space_less_than, " <");
4556 AUTO_STRING (greater_than, ">");
4557 caller = concat3 (space_less_than, caller, greater_than);
4558 break;
4561 /* Create a new buffer name for this process if it doesn't have a
4562 filter. The new buffer name is based on the buffer name or
4563 process name of the server process concatenated with the caller
4564 identification. */
4566 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4567 || EQ (ps->filter, Qt)))
4568 buffer = Qnil;
4569 else
4571 buffer = ps->buffer;
4572 if (!NILP (buffer))
4573 buffer = Fbuffer_name (buffer);
4574 else
4575 buffer = ps->name;
4576 if (!NILP (buffer))
4578 buffer = concat2 (buffer, caller);
4579 buffer = Fget_buffer_create (buffer);
4583 /* Generate a unique name for the new server process. Combine the
4584 server process name with the caller identification. */
4586 name = concat2 (ps->name, caller);
4587 proc = make_process (name);
4589 chan_process[s] = proc;
4591 fcntl (s, F_SETFL, O_NONBLOCK);
4593 p = XPROCESS (proc);
4595 /* Build new contact information for this setup. */
4596 contact = Fcopy_sequence (ps->childp);
4597 contact = Fplist_put (contact, QCserver, Qnil);
4598 contact = Fplist_put (contact, QChost, host);
4599 if (!NILP (service))
4600 contact = Fplist_put (contact, QCservice, service);
4601 contact = Fplist_put (contact, QCremote,
4602 conv_sockaddr_to_lisp (&saddr.sa, len));
4603 #ifdef HAVE_GETSOCKNAME
4604 len = sizeof saddr;
4605 if (getsockname (s, &saddr.sa, &len) == 0)
4606 contact = Fplist_put (contact, QClocal,
4607 conv_sockaddr_to_lisp (&saddr.sa, len));
4608 #endif
4610 pset_childp (p, contact);
4611 pset_plist (p, Fcopy_sequence (ps->plist));
4612 pset_type (p, Qnetwork);
4614 pset_buffer (p, buffer);
4615 pset_sentinel (p, ps->sentinel);
4616 pset_filter (p, ps->filter);
4617 eassert (NILP (p->command));
4618 eassert (p->pid == 0);
4620 /* Discard the unwind protect for closing S. */
4621 specpdl_ptr = specpdl + count;
4623 p->open_fd[SUBPROCESS_STDIN] = s;
4624 p->infd = s;
4625 p->outfd = s;
4626 pset_status (p, Qrun);
4628 /* Client processes for accepted connections are not stopped initially. */
4629 if (!EQ (p->filter, Qt))
4631 FD_SET (s, &input_wait_mask);
4632 FD_SET (s, &non_keyboard_wait_mask);
4635 if (s > max_process_desc)
4636 max_process_desc = s;
4638 /* Setup coding system for new process based on server process.
4639 This seems to be the proper thing to do, as the coding system
4640 of the new process should reflect the settings at the time the
4641 server socket was opened; not the current settings. */
4643 pset_decode_coding_system (p, ps->decode_coding_system);
4644 pset_encode_coding_system (p, ps->encode_coding_system);
4645 setup_process_coding_systems (proc);
4647 pset_decoding_buf (p, empty_unibyte_string);
4648 eassert (p->decoding_carryover == 0);
4649 pset_encoding_buf (p, empty_unibyte_string);
4651 p->inherit_coding_system_flag
4652 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4654 AUTO_STRING (dash, "-");
4655 AUTO_STRING (nl, "\n");
4656 Lisp_Object host_string = STRINGP (host) ? host : dash;
4658 if (!NILP (ps->log))
4660 AUTO_STRING (accept_from, "accept from ");
4661 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4664 AUTO_STRING (open_from, "open from ");
4665 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4668 #ifdef HAVE_GETADDRINFO_A
4669 static Lisp_Object
4670 check_for_dns (Lisp_Object proc)
4672 struct Lisp_Process *p = XPROCESS (proc);
4673 Lisp_Object addrinfos = Qnil;
4675 /* Sanity check. */
4676 if (! p->dns_request)
4677 return Qnil;
4679 int ret = gai_error (p->dns_request);
4680 if (ret == EAI_INPROGRESS)
4681 return Qt;
4683 /* We got a response. */
4684 if (ret == 0)
4686 struct addrinfo *res;
4688 for (res = p->dns_request->ar_result; res; res = res->ai_next)
4689 addrinfos = Fcons (conv_addrinfo_to_lisp (res), addrinfos);
4691 addrinfos = Fnreverse (addrinfos);
4693 /* The DNS lookup failed. */
4694 else if (connecting_status (p->status))
4696 deactivate_process (proc);
4697 pset_status (p, (list2
4698 (Qfailed,
4699 concat3 (build_string ("Name lookup of "),
4700 build_string (p->dns_request->ar_name),
4701 build_string (" failed")))));
4704 free_dns_request (proc);
4706 /* This process should not already be connected (or killed). */
4707 if (! connecting_status (p->status))
4708 return Qnil;
4710 return addrinfos;
4713 #endif /* HAVE_GETADDRINFO_A */
4715 static void
4716 wait_for_socket_fds (Lisp_Object process, char const *name)
4718 while (XPROCESS (process)->infd < 0
4719 && connecting_status (XPROCESS (process)->status))
4721 add_to_log ("Waiting for socket from %s...", build_string (name));
4722 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4726 static void
4727 wait_while_connecting (Lisp_Object process)
4729 while (connecting_status (XPROCESS (process)->status))
4731 add_to_log ("Waiting for connection...");
4732 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4736 static void
4737 wait_for_tls_negotiation (Lisp_Object process)
4739 #ifdef HAVE_GNUTLS
4740 while (XPROCESS (process)->gnutls_p
4741 && XPROCESS (process)->gnutls_initstage != GNUTLS_STAGE_READY)
4743 add_to_log ("Waiting for TLS...");
4744 wait_reading_process_output (0, 20 * 1000 * 1000, 0, 0, Qnil, NULL, 0);
4746 #endif
4749 /* This variable is different from waiting_for_input in keyboard.c.
4750 It is used to communicate to a lisp process-filter/sentinel (via the
4751 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4752 for user-input when that process-filter was called.
4753 waiting_for_input cannot be used as that is by definition 0 when
4754 lisp code is being evalled.
4755 This is also used in record_asynch_buffer_change.
4756 For that purpose, this must be 0
4757 when not inside wait_reading_process_output. */
4758 static int waiting_for_user_input_p;
4760 static void
4761 wait_reading_process_output_unwind (int data)
4763 waiting_for_user_input_p = data;
4766 /* This is here so breakpoints can be put on it. */
4767 static void
4768 wait_reading_process_output_1 (void)
4772 /* Read and dispose of subprocess output while waiting for timeout to
4773 elapse and/or keyboard input to be available.
4775 TIME_LIMIT is:
4776 timeout in seconds
4777 If negative, gobble data immediately available but don't wait for any.
4779 NSECS is:
4780 an additional duration to wait, measured in nanoseconds
4781 If TIME_LIMIT is zero, then:
4782 If NSECS == 0, there is no limit.
4783 If NSECS > 0, the timeout consists of NSECS only.
4784 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4786 READ_KBD is:
4787 0 to ignore keyboard input, or
4788 1 to return when input is available, or
4789 -1 meaning caller will actually read the input, so don't throw to
4790 the quit handler, or
4792 DO_DISPLAY means redisplay should be done to show subprocess
4793 output that arrives.
4795 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4796 (and gobble terminal input into the buffer if any arrives).
4798 If WAIT_PROC is specified, wait until something arrives from that
4799 process.
4801 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4802 (suspending output from other processes). A negative value
4803 means don't run any timers either.
4805 Return positive if we received input from WAIT_PROC (or from any
4806 process if WAIT_PROC is null), zero if we attempted to receive
4807 input but got none, and negative if we didn't even try. */
4810 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4811 bool do_display,
4812 Lisp_Object wait_for_cell,
4813 struct Lisp_Process *wait_proc, int just_wait_proc)
4815 int channel, nfds;
4816 fd_set Available;
4817 fd_set Writeok;
4818 bool check_write;
4819 int check_delay;
4820 bool no_avail;
4821 int xerrno;
4822 Lisp_Object proc;
4823 struct timespec timeout, end_time, timer_delay;
4824 struct timespec got_output_end_time = invalid_timespec ();
4825 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
4826 int got_some_output = -1;
4827 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4828 bool retry_for_async;
4829 #endif
4830 ptrdiff_t count = SPECPDL_INDEX ();
4832 /* Close to the current time if known, an invalid timespec otherwise. */
4833 struct timespec now = invalid_timespec ();
4835 FD_ZERO (&Available);
4836 FD_ZERO (&Writeok);
4838 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4839 && !(CONSP (wait_proc->status)
4840 && EQ (XCAR (wait_proc->status), Qexit)))
4841 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4843 record_unwind_protect_int (wait_reading_process_output_unwind,
4844 waiting_for_user_input_p);
4845 waiting_for_user_input_p = read_kbd;
4847 if (TYPE_MAXIMUM (time_t) < time_limit)
4848 time_limit = TYPE_MAXIMUM (time_t);
4850 if (time_limit < 0 || nsecs < 0)
4851 wait = MINIMUM;
4852 else if (time_limit > 0 || nsecs > 0)
4854 wait = TIMEOUT;
4855 now = current_timespec ();
4856 end_time = timespec_add (now, make_timespec (time_limit, nsecs));
4858 else
4859 wait = INFINITY;
4861 while (1)
4863 bool process_skipped = false;
4865 /* If calling from keyboard input, do not quit
4866 since we want to return C-g as an input character.
4867 Otherwise, do pending quit if requested. */
4868 if (read_kbd >= 0)
4869 QUIT;
4870 else if (pending_signals)
4871 process_pending_signals ();
4873 /* Exit now if the cell we're waiting for became non-nil. */
4874 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4875 break;
4877 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
4879 Lisp_Object process_list_head, aproc;
4880 struct Lisp_Process *p;
4882 retry_for_async = false;
4883 FOR_EACH_PROCESS(process_list_head, aproc)
4885 p = XPROCESS (aproc);
4887 if (! wait_proc || p == wait_proc)
4889 #ifdef HAVE_GETADDRINFO_A
4890 /* Check for pending DNS requests. */
4891 if (p->dns_request)
4893 Lisp_Object addrinfos = check_for_dns (aproc);
4894 if (!NILP (addrinfos) && !EQ (addrinfos, Qt))
4895 connect_network_socket (aproc, addrinfos, Qnil);
4896 else
4897 retry_for_async = true;
4899 #endif
4900 #ifdef HAVE_GNUTLS
4901 /* Continue TLS negotiation. */
4902 if (p->gnutls_initstage == GNUTLS_STAGE_HANDSHAKE_TRIED
4903 && p->is_non_blocking_client)
4905 gnutls_try_handshake (p);
4906 p->gnutls_handshakes_tried++;
4908 if (p->gnutls_initstage == GNUTLS_STAGE_READY)
4910 gnutls_verify_boot (aproc, Qnil);
4911 finish_after_tls_connection (aproc);
4913 else
4915 retry_for_async = true;
4916 if (p->gnutls_handshakes_tried
4917 > GNUTLS_EMACS_HANDSHAKES_LIMIT)
4919 deactivate_process (aproc);
4920 pset_status (p, list2 (Qfailed,
4921 build_string ("TLS negotiation failed")));
4925 #endif
4929 #endif /* GETADDRINFO_A or GNUTLS */
4931 /* Compute time from now till when time limit is up. */
4932 /* Exit if already run out. */
4933 if (wait == TIMEOUT)
4935 if (!timespec_valid_p (now))
4936 now = current_timespec ();
4937 if (timespec_cmp (end_time, now) <= 0)
4938 break;
4939 timeout = timespec_sub (end_time, now);
4941 else
4942 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
4944 /* Normally we run timers here.
4945 But not if wait_for_cell; in those cases,
4946 the wait is supposed to be short,
4947 and those callers cannot handle running arbitrary Lisp code here. */
4948 if (NILP (wait_for_cell)
4949 && just_wait_proc >= 0)
4953 unsigned old_timers_run = timers_run;
4954 struct buffer *old_buffer = current_buffer;
4955 Lisp_Object old_window = selected_window;
4957 timer_delay = timer_check ();
4959 /* If a timer has run, this might have changed buffers
4960 an alike. Make read_key_sequence aware of that. */
4961 if (timers_run != old_timers_run
4962 && (old_buffer != current_buffer
4963 || !EQ (old_window, selected_window))
4964 && waiting_for_user_input_p == -1)
4965 record_asynch_buffer_change ();
4967 if (timers_run != old_timers_run && do_display)
4968 /* We must retry, since a timer may have requeued itself
4969 and that could alter the time_delay. */
4970 redisplay_preserve_echo_area (9);
4971 else
4972 break;
4974 while (!detect_input_pending ());
4976 /* If there is unread keyboard input, also return. */
4977 if (read_kbd != 0
4978 && requeued_events_pending_p ())
4979 break;
4981 /* This is so a breakpoint can be put here. */
4982 if (!timespec_valid_p (timer_delay))
4983 wait_reading_process_output_1 ();
4986 /* Cause C-g and alarm signals to take immediate action,
4987 and cause input available signals to zero out timeout.
4989 It is important that we do this before checking for process
4990 activity. If we get a SIGCHLD after the explicit checks for
4991 process activity, timeout is the only way we will know. */
4992 if (read_kbd < 0)
4993 set_waiting_for_input (&timeout);
4995 /* If status of something has changed, and no input is
4996 available, notify the user of the change right away. After
4997 this explicit check, we'll let the SIGCHLD handler zap
4998 timeout to get our attention. */
4999 if (update_tick != process_tick)
5001 fd_set Atemp;
5002 fd_set Ctemp;
5004 if (kbd_on_hold_p ())
5005 FD_ZERO (&Atemp);
5006 else
5007 Atemp = input_wait_mask;
5008 Ctemp = write_mask;
5010 timeout = make_timespec (0, 0);
5011 if ((pselect (max (max_process_desc, max_input_desc) + 1,
5012 &Atemp,
5013 (num_pending_connects > 0 ? &Ctemp : NULL),
5014 NULL, &timeout, NULL)
5015 <= 0))
5017 /* It's okay for us to do this and then continue with
5018 the loop, since timeout has already been zeroed out. */
5019 clear_waiting_for_input ();
5020 got_some_output = status_notify (NULL, wait_proc);
5021 if (do_display) redisplay_preserve_echo_area (13);
5025 /* Don't wait for output from a non-running process. Just
5026 read whatever data has already been received. */
5027 if (wait_proc && wait_proc->raw_status_new)
5028 update_status (wait_proc);
5029 if (wait_proc
5030 && ! EQ (wait_proc->status, Qrun)
5031 && ! connecting_status (wait_proc->status))
5033 bool read_some_bytes = false;
5035 clear_waiting_for_input ();
5037 /* If data can be read from the process, do so until exhausted. */
5038 if (wait_proc->infd >= 0)
5040 XSETPROCESS (proc, wait_proc);
5042 while (true)
5044 int nread = read_process_output (proc, wait_proc->infd);
5045 if (nread < 0)
5047 if (errno == EIO || would_block (errno))
5048 break;
5050 else
5052 if (got_some_output < nread)
5053 got_some_output = nread;
5054 if (nread == 0)
5055 break;
5056 read_some_bytes = true;
5061 if (read_some_bytes && do_display)
5062 redisplay_preserve_echo_area (10);
5064 break;
5067 /* Wait till there is something to do. */
5069 if (wait_proc && just_wait_proc)
5071 if (wait_proc->infd < 0) /* Terminated. */
5072 break;
5073 FD_SET (wait_proc->infd, &Available);
5074 check_delay = 0;
5075 check_write = 0;
5077 else if (!NILP (wait_for_cell))
5079 Available = non_process_wait_mask;
5080 check_delay = 0;
5081 check_write = 0;
5083 else
5085 if (! read_kbd)
5086 Available = non_keyboard_wait_mask;
5087 else
5088 Available = input_wait_mask;
5089 Writeok = write_mask;
5090 check_delay = wait_proc ? 0 : process_output_delay_count;
5091 check_write = true;
5094 /* If frame size has changed or the window is newly mapped,
5095 redisplay now, before we start to wait. There is a race
5096 condition here; if a SIGIO arrives between now and the select
5097 and indicates that a frame is trashed, the select may block
5098 displaying a trashed screen. */
5099 if (frame_garbaged && do_display)
5101 clear_waiting_for_input ();
5102 redisplay_preserve_echo_area (11);
5103 if (read_kbd < 0)
5104 set_waiting_for_input (&timeout);
5107 /* Skip the `select' call if input is available and we're
5108 waiting for keyboard input or a cell change (which can be
5109 triggered by processing X events). In the latter case, set
5110 nfds to 1 to avoid breaking the loop. */
5111 no_avail = 0;
5112 if ((read_kbd || !NILP (wait_for_cell))
5113 && detect_input_pending ())
5115 nfds = read_kbd ? 0 : 1;
5116 no_avail = 1;
5117 FD_ZERO (&Available);
5119 else
5121 /* Set the timeout for adaptive read buffering if any
5122 process has non-zero read_output_skip and non-zero
5123 read_output_delay, and we are not reading output for a
5124 specific process. It is not executed if
5125 Vprocess_adaptive_read_buffering is nil. */
5126 if (process_output_skip && check_delay > 0)
5128 int adaptive_nsecs = timeout.tv_nsec;
5129 if (timeout.tv_sec > 0 || adaptive_nsecs > READ_OUTPUT_DELAY_MAX)
5130 adaptive_nsecs = READ_OUTPUT_DELAY_MAX;
5131 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
5133 proc = chan_process[channel];
5134 if (NILP (proc))
5135 continue;
5136 /* Find minimum non-zero read_output_delay among the
5137 processes with non-zero read_output_skip. */
5138 if (XPROCESS (proc)->read_output_delay > 0)
5140 check_delay--;
5141 if (!XPROCESS (proc)->read_output_skip)
5142 continue;
5143 FD_CLR (channel, &Available);
5144 process_skipped = true;
5145 XPROCESS (proc)->read_output_skip = 0;
5146 if (XPROCESS (proc)->read_output_delay < adaptive_nsecs)
5147 adaptive_nsecs = XPROCESS (proc)->read_output_delay;
5150 timeout = make_timespec (0, adaptive_nsecs);
5151 process_output_skip = 0;
5154 /* If we've got some output and haven't limited our timeout
5155 with adaptive read buffering, limit it. */
5156 if (got_some_output > 0 && !process_skipped
5157 && (timeout.tv_sec
5158 || timeout.tv_nsec > READ_OUTPUT_DELAY_INCREMENT))
5159 timeout = make_timespec (0, READ_OUTPUT_DELAY_INCREMENT);
5162 if (NILP (wait_for_cell) && just_wait_proc >= 0
5163 && timespec_valid_p (timer_delay)
5164 && timespec_cmp (timer_delay, timeout) < 0)
5166 if (!timespec_valid_p (now))
5167 now = current_timespec ();
5168 struct timespec timeout_abs = timespec_add (now, timeout);
5169 if (!timespec_valid_p (got_output_end_time)
5170 || timespec_cmp (timeout_abs, got_output_end_time) < 0)
5171 got_output_end_time = timeout_abs;
5172 timeout = timer_delay;
5174 else
5175 got_output_end_time = invalid_timespec ();
5177 /* NOW can become inaccurate if time can pass during pselect. */
5178 if (timeout.tv_sec > 0 || timeout.tv_nsec > 0)
5179 now = invalid_timespec ();
5181 #if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
5182 if (retry_for_async
5183 && (timeout.tv_sec > 0 || timeout.tv_nsec > ASYNC_RETRY_NSEC))
5185 timeout.tv_sec = 0;
5186 timeout.tv_nsec = ASYNC_RETRY_NSEC;
5188 #endif
5190 #if defined (HAVE_NS)
5191 nfds = ns_select
5192 #elif defined (HAVE_GLIB)
5193 nfds = xg_select
5194 #else
5195 nfds = pselect
5196 #endif
5197 (max (max_process_desc, max_input_desc) + 1,
5198 &Available,
5199 (check_write ? &Writeok : 0),
5200 NULL, &timeout, NULL);
5202 #ifdef HAVE_GNUTLS
5203 /* GnuTLS buffers data internally. In lowat mode it leaves
5204 some data in the TCP buffers so that select works, but
5205 with custom pull/push functions we need to check if some
5206 data is available in the buffers manually. */
5207 if (nfds == 0)
5209 fd_set tls_available;
5210 int set = 0;
5212 FD_ZERO (&tls_available);
5213 if (! wait_proc)
5215 /* We're not waiting on a specific process, so loop
5216 through all the channels and check for data.
5217 This is a workaround needed for some versions of
5218 the gnutls library -- 2.12.14 has been confirmed
5219 to need it. See
5220 http://comments.gmane.org/gmane.emacs.devel/145074 */
5221 for (channel = 0; channel < FD_SETSIZE; ++channel)
5222 if (! NILP (chan_process[channel]))
5224 struct Lisp_Process *p =
5225 XPROCESS (chan_process[channel]);
5226 if (p && p->gnutls_p && p->gnutls_state
5227 && ((emacs_gnutls_record_check_pending
5228 (p->gnutls_state))
5229 > 0))
5231 nfds++;
5232 eassert (p->infd == channel);
5233 FD_SET (p->infd, &tls_available);
5234 set++;
5238 else
5240 /* Check this specific channel. */
5241 if (wait_proc->gnutls_p /* Check for valid process. */
5242 && wait_proc->gnutls_state
5243 /* Do we have pending data? */
5244 && ((emacs_gnutls_record_check_pending
5245 (wait_proc->gnutls_state))
5246 > 0))
5248 nfds = 1;
5249 eassert (0 <= wait_proc->infd);
5250 /* Set to Available. */
5251 FD_SET (wait_proc->infd, &tls_available);
5252 set++;
5255 if (set)
5256 Available = tls_available;
5258 #endif
5261 xerrno = errno;
5263 /* Make C-g and alarm signals set flags again. */
5264 clear_waiting_for_input ();
5266 /* If we woke up due to SIGWINCH, actually change size now. */
5267 do_pending_window_change (0);
5269 if (nfds == 0)
5271 /* Exit the main loop if we've passed the requested timeout,
5272 or aren't skipping processes and got some output and
5273 haven't lowered our timeout due to timers or SIGIO and
5274 have waited a long amount of time due to repeated
5275 timers. */
5276 struct timespec huge_timespec
5277 = make_timespec (TYPE_MAXIMUM (time_t), 2 * TIMESPEC_RESOLUTION);
5278 struct timespec cmp_time = huge_timespec;
5279 if (wait < TIMEOUT)
5280 break;
5281 if (wait == TIMEOUT)
5282 cmp_time = end_time;
5283 if (!process_skipped && got_some_output > 0
5284 && (timeout.tv_sec > 0 || timeout.tv_nsec > 0))
5286 if (!timespec_valid_p (got_output_end_time))
5287 break;
5288 if (timespec_cmp (got_output_end_time, cmp_time) < 0)
5289 cmp_time = got_output_end_time;
5291 if (timespec_cmp (cmp_time, huge_timespec) < 0)
5293 now = current_timespec ();
5294 if (timespec_cmp (cmp_time, now) <= 0)
5295 break;
5299 if (nfds < 0)
5301 if (xerrno == EINTR)
5302 no_avail = 1;
5303 else if (xerrno == EBADF)
5304 emacs_abort ();
5305 else
5306 report_file_errno ("Failed select", Qnil, xerrno);
5309 /* Check for keyboard input. */
5310 /* If there is any, return immediately
5311 to give it higher priority than subprocesses. */
5313 if (read_kbd != 0)
5315 unsigned old_timers_run = timers_run;
5316 struct buffer *old_buffer = current_buffer;
5317 Lisp_Object old_window = selected_window;
5318 bool leave = false;
5320 if (detect_input_pending_run_timers (do_display))
5322 swallow_events (do_display);
5323 if (detect_input_pending_run_timers (do_display))
5324 leave = true;
5327 /* If a timer has run, this might have changed buffers
5328 an alike. Make read_key_sequence aware of that. */
5329 if (timers_run != old_timers_run
5330 && waiting_for_user_input_p == -1
5331 && (old_buffer != current_buffer
5332 || !EQ (old_window, selected_window)))
5333 record_asynch_buffer_change ();
5335 if (leave)
5336 break;
5339 /* If there is unread keyboard input, also return. */
5340 if (read_kbd != 0
5341 && requeued_events_pending_p ())
5342 break;
5344 /* If we are not checking for keyboard input now,
5345 do process events (but don't run any timers).
5346 This is so that X events will be processed.
5347 Otherwise they may have to wait until polling takes place.
5348 That would causes delays in pasting selections, for example.
5350 (We used to do this only if wait_for_cell.) */
5351 if (read_kbd == 0 && detect_input_pending ())
5353 swallow_events (do_display);
5354 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5355 if (detect_input_pending ())
5356 break;
5357 #endif
5360 /* Exit now if the cell we're waiting for became non-nil. */
5361 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5362 break;
5364 #ifdef USABLE_SIGIO
5365 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5366 go read it. This can happen with X on BSD after logging out.
5367 In that case, there really is no input and no SIGIO,
5368 but select says there is input. */
5370 if (read_kbd && interrupt_input
5371 && keyboard_bit_set (&Available) && ! noninteractive)
5372 handle_input_available_signal (SIGIO);
5373 #endif
5375 /* If checking input just got us a size-change event from X,
5376 obey it now if we should. */
5377 if (read_kbd || ! NILP (wait_for_cell))
5378 do_pending_window_change (0);
5380 /* Check for data from a process. */
5381 if (no_avail || nfds == 0)
5382 continue;
5384 for (channel = 0; channel <= max_input_desc; ++channel)
5386 struct fd_callback_data *d = &fd_callback_info[channel];
5387 if (d->func
5388 && ((d->condition & FOR_READ
5389 && FD_ISSET (channel, &Available))
5390 || (d->condition & FOR_WRITE
5391 && FD_ISSET (channel, &write_mask))))
5392 d->func (channel, d->data);
5395 for (channel = 0; channel <= max_process_desc; channel++)
5397 if (FD_ISSET (channel, &Available)
5398 && FD_ISSET (channel, &non_keyboard_wait_mask)
5399 && !FD_ISSET (channel, &non_process_wait_mask))
5401 int nread;
5403 /* If waiting for this channel, arrange to return as
5404 soon as no more input to be processed. No more
5405 waiting. */
5406 proc = chan_process[channel];
5407 if (NILP (proc))
5408 continue;
5410 /* If this is a server stream socket, accept connection. */
5411 if (EQ (XPROCESS (proc)->status, Qlisten))
5413 server_accept_connection (proc, channel);
5414 continue;
5417 /* Read data from the process, starting with our
5418 buffered-ahead character if we have one. */
5420 nread = read_process_output (proc, channel);
5421 if ((!wait_proc || wait_proc == XPROCESS (proc))
5422 && got_some_output < nread)
5423 got_some_output = nread;
5424 if (nread > 0)
5426 /* Vacuum up any leftovers without waiting. */
5427 if (wait_proc == XPROCESS (proc))
5428 wait = MINIMUM;
5429 /* Since read_process_output can run a filter,
5430 which can call accept-process-output,
5431 don't try to read from any other processes
5432 before doing the select again. */
5433 FD_ZERO (&Available);
5435 if (do_display)
5436 redisplay_preserve_echo_area (12);
5438 else if (nread == -1 && would_block (errno))
5440 #ifdef WINDOWSNT
5441 /* FIXME: Is this special case still needed? */
5442 /* Note that we cannot distinguish between no input
5443 available now and a closed pipe.
5444 With luck, a closed pipe will be accompanied by
5445 subprocess termination and SIGCHLD. */
5446 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5447 && !PIPECONN_P (proc))
5449 #endif
5450 #ifdef HAVE_PTYS
5451 /* On some OSs with ptys, when the process on one end of
5452 a pty exits, the other end gets an error reading with
5453 errno = EIO instead of getting an EOF (0 bytes read).
5454 Therefore, if we get an error reading and errno =
5455 EIO, just continue, because the child process has
5456 exited and should clean itself up soon (e.g. when we
5457 get a SIGCHLD). */
5458 else if (nread == -1 && errno == EIO)
5460 struct Lisp_Process *p = XPROCESS (proc);
5462 /* Clear the descriptor now, so we only raise the
5463 signal once. */
5464 FD_CLR (channel, &input_wait_mask);
5465 FD_CLR (channel, &non_keyboard_wait_mask);
5467 if (p->pid == -2)
5469 /* If the EIO occurs on a pty, the SIGCHLD handler's
5470 waitpid call will not find the process object to
5471 delete. Do it here. */
5472 p->tick = ++process_tick;
5473 pset_status (p, Qfailed);
5476 #endif /* HAVE_PTYS */
5477 /* If we can detect process termination, don't consider the
5478 process gone just because its pipe is closed. */
5479 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5480 && !PIPECONN_P (proc))
5482 else if (nread == 0 && PIPECONN_P (proc))
5484 /* Preserve status of processes already terminated. */
5485 XPROCESS (proc)->tick = ++process_tick;
5486 deactivate_process (proc);
5487 if (EQ (XPROCESS (proc)->status, Qrun))
5488 pset_status (XPROCESS (proc),
5489 list2 (Qexit, make_number (0)));
5491 else
5493 /* Preserve status of processes already terminated. */
5494 XPROCESS (proc)->tick = ++process_tick;
5495 deactivate_process (proc);
5496 if (XPROCESS (proc)->raw_status_new)
5497 update_status (XPROCESS (proc));
5498 if (EQ (XPROCESS (proc)->status, Qrun))
5499 pset_status (XPROCESS (proc),
5500 list2 (Qexit, make_number (256)));
5503 if (FD_ISSET (channel, &Writeok)
5504 && FD_ISSET (channel, &connect_wait_mask))
5506 struct Lisp_Process *p;
5508 FD_CLR (channel, &connect_wait_mask);
5509 FD_CLR (channel, &write_mask);
5510 if (--num_pending_connects < 0)
5511 emacs_abort ();
5513 proc = chan_process[channel];
5514 if (NILP (proc))
5515 continue;
5517 p = XPROCESS (proc);
5519 #ifndef WINDOWSNT
5521 socklen_t xlen = sizeof (xerrno);
5522 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5523 xerrno = errno;
5525 #else
5526 /* On MS-Windows, getsockopt clears the error for the
5527 entire process, which may not be the right thing; see
5528 w32.c. Use getpeername instead. */
5530 struct sockaddr pname;
5531 socklen_t pnamelen = sizeof (pname);
5533 /* If connection failed, getpeername will fail. */
5534 xerrno = 0;
5535 if (getpeername (channel, &pname, &pnamelen) < 0)
5537 /* Obtain connect failure code through error slippage. */
5538 char dummy;
5539 xerrno = errno;
5540 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5541 xerrno = errno;
5544 #endif
5545 if (xerrno)
5547 Lisp_Object addrinfos
5548 = connecting_status (p->status) ? XCDR (p->status) : Qnil;
5549 if (!NILP (addrinfos))
5550 XSETCDR (p->status, XCDR (addrinfos));
5551 else
5553 p->tick = ++process_tick;
5554 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5556 deactivate_process (proc);
5557 if (!NILP (addrinfos))
5558 connect_network_socket (proc, addrinfos, Qnil);
5560 else
5562 #ifdef HAVE_GNUTLS
5563 /* If we have an incompletely set up TLS connection,
5564 then defer the sentinel signaling until
5565 later. */
5566 if (NILP (p->gnutls_boot_parameters)
5567 && !p->gnutls_p)
5568 #endif
5570 pset_status (p, Qrun);
5571 /* Execute the sentinel here. If we had relied on
5572 status_notify to do it later, it will read input
5573 from the process before calling the sentinel. */
5574 exec_sentinel (proc, build_string ("open\n"));
5577 if (0 <= p->infd && !EQ (p->filter, Qt)
5578 && !EQ (p->command, Qt))
5580 FD_SET (p->infd, &input_wait_mask);
5581 FD_SET (p->infd, &non_keyboard_wait_mask);
5585 } /* End for each file descriptor. */
5586 } /* End while exit conditions not met. */
5588 unbind_to (count, Qnil);
5590 /* If calling from keyboard input, do not quit
5591 since we want to return C-g as an input character.
5592 Otherwise, do pending quit if requested. */
5593 if (read_kbd >= 0)
5595 /* Prevent input_pending from remaining set if we quit. */
5596 clear_input_pending ();
5597 QUIT;
5600 return got_some_output;
5603 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5605 static Lisp_Object
5606 read_process_output_call (Lisp_Object fun_and_args)
5608 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5611 static Lisp_Object
5612 read_process_output_error_handler (Lisp_Object error_val)
5614 cmd_error_internal (error_val, "error in process filter: ");
5615 Vinhibit_quit = Qt;
5616 update_echo_area ();
5617 Fsleep_for (make_number (2), Qnil);
5618 return Qt;
5621 static void
5622 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5623 ssize_t nbytes,
5624 struct coding_system *coding);
5626 /* Read pending output from the process channel,
5627 starting with our buffered-ahead character if we have one.
5628 Yield number of decoded characters read.
5630 This function reads at most 4096 characters.
5631 If you want to read all available subprocess output,
5632 you must call it repeatedly until it returns zero.
5634 The characters read are decoded according to PROC's coding-system
5635 for decoding. */
5637 static int
5638 read_process_output (Lisp_Object proc, int channel)
5640 ssize_t nbytes;
5641 struct Lisp_Process *p = XPROCESS (proc);
5642 struct coding_system *coding = proc_decode_coding_system[channel];
5643 int carryover = p->decoding_carryover;
5644 enum { readmax = 4096 };
5645 ptrdiff_t count = SPECPDL_INDEX ();
5646 Lisp_Object odeactivate;
5647 char chars[sizeof coding->carryover + readmax];
5649 if (carryover)
5650 /* See the comment above. */
5651 memcpy (chars, SDATA (p->decoding_buf), carryover);
5653 #ifdef DATAGRAM_SOCKETS
5654 /* We have a working select, so proc_buffered_char is always -1. */
5655 if (DATAGRAM_CHAN_P (channel))
5657 socklen_t len = datagram_address[channel].len;
5658 nbytes = recvfrom (channel, chars + carryover, readmax,
5659 0, datagram_address[channel].sa, &len);
5661 else
5662 #endif
5664 bool buffered = proc_buffered_char[channel] >= 0;
5665 if (buffered)
5667 chars[carryover] = proc_buffered_char[channel];
5668 proc_buffered_char[channel] = -1;
5670 #ifdef HAVE_GNUTLS
5671 if (p->gnutls_p && p->gnutls_state)
5672 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5673 readmax - buffered);
5674 else
5675 #endif
5676 nbytes = emacs_read (channel, chars + carryover + buffered,
5677 readmax - buffered);
5678 if (nbytes > 0 && p->adaptive_read_buffering)
5680 int delay = p->read_output_delay;
5681 if (nbytes < 256)
5683 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5685 if (delay == 0)
5686 process_output_delay_count++;
5687 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5690 else if (delay > 0 && nbytes == readmax - buffered)
5692 delay -= READ_OUTPUT_DELAY_INCREMENT;
5693 if (delay == 0)
5694 process_output_delay_count--;
5696 p->read_output_delay = delay;
5697 if (delay)
5699 p->read_output_skip = 1;
5700 process_output_skip = 1;
5703 nbytes += buffered;
5704 nbytes += buffered && nbytes <= 0;
5707 p->decoding_carryover = 0;
5709 /* At this point, NBYTES holds number of bytes just received
5710 (including the one in proc_buffered_char[channel]). */
5711 if (nbytes <= 0)
5713 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5714 return nbytes;
5715 coding->mode |= CODING_MODE_LAST_BLOCK;
5718 /* Now set NBYTES how many bytes we must decode. */
5719 nbytes += carryover;
5721 odeactivate = Vdeactivate_mark;
5722 /* There's no good reason to let process filters change the current
5723 buffer, and many callers of accept-process-output, sit-for, and
5724 friends don't expect current-buffer to be changed from under them. */
5725 record_unwind_current_buffer ();
5727 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5729 /* Handling the process output should not deactivate the mark. */
5730 Vdeactivate_mark = odeactivate;
5732 unbind_to (count, Qnil);
5733 return nbytes;
5736 static void
5737 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5738 ssize_t nbytes,
5739 struct coding_system *coding)
5741 Lisp_Object outstream = p->filter;
5742 Lisp_Object text;
5743 bool outer_running_asynch_code = running_asynch_code;
5744 int waiting = waiting_for_user_input_p;
5746 #if 0
5747 Lisp_Object obuffer, okeymap;
5748 XSETBUFFER (obuffer, current_buffer);
5749 okeymap = BVAR (current_buffer, keymap);
5750 #endif
5752 /* We inhibit quit here instead of just catching it so that
5753 hitting ^G when a filter happens to be running won't screw
5754 it up. */
5755 specbind (Qinhibit_quit, Qt);
5756 specbind (Qlast_nonmenu_event, Qt);
5758 /* In case we get recursively called,
5759 and we already saved the match data nonrecursively,
5760 save the same match data in safely recursive fashion. */
5761 if (outer_running_asynch_code)
5763 Lisp_Object tem;
5764 /* Don't clobber the CURRENT match data, either! */
5765 tem = Fmatch_data (Qnil, Qnil, Qnil);
5766 restore_search_regs ();
5767 record_unwind_save_match_data ();
5768 Fset_match_data (tem, Qt);
5771 /* For speed, if a search happens within this code,
5772 save the match data in a special nonrecursive fashion. */
5773 running_asynch_code = 1;
5775 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5776 text = coding->dst_object;
5777 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5778 /* A new coding system might be found. */
5779 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5781 pset_decode_coding_system (p, Vlast_coding_system_used);
5783 /* Don't call setup_coding_system for
5784 proc_decode_coding_system[channel] here. It is done in
5785 detect_coding called via decode_coding above. */
5787 /* If a coding system for encoding is not yet decided, we set
5788 it as the same as coding-system for decoding.
5790 But, before doing that we must check if
5791 proc_encode_coding_system[p->outfd] surely points to a
5792 valid memory because p->outfd will be changed once EOF is
5793 sent to the process. */
5794 if (NILP (p->encode_coding_system) && p->outfd >= 0
5795 && proc_encode_coding_system[p->outfd])
5797 pset_encode_coding_system
5798 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5799 setup_coding_system (p->encode_coding_system,
5800 proc_encode_coding_system[p->outfd]);
5804 if (coding->carryover_bytes > 0)
5806 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5807 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5808 memcpy (SDATA (p->decoding_buf), coding->carryover,
5809 coding->carryover_bytes);
5810 p->decoding_carryover = coding->carryover_bytes;
5812 if (SBYTES (text) > 0)
5813 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5814 sometimes it's simply wrong to wrap (e.g. when called from
5815 accept-process-output). */
5816 internal_condition_case_1 (read_process_output_call,
5817 list3 (outstream, make_lisp_proc (p), text),
5818 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5819 read_process_output_error_handler);
5821 /* If we saved the match data nonrecursively, restore it now. */
5822 restore_search_regs ();
5823 running_asynch_code = outer_running_asynch_code;
5825 /* Restore waiting_for_user_input_p as it was
5826 when we were called, in case the filter clobbered it. */
5827 waiting_for_user_input_p = waiting;
5829 #if 0 /* Call record_asynch_buffer_change unconditionally,
5830 because we might have changed minor modes or other things
5831 that affect key bindings. */
5832 if (! EQ (Fcurrent_buffer (), obuffer)
5833 || ! EQ (current_buffer->keymap, okeymap))
5834 #endif
5835 /* But do it only if the caller is actually going to read events.
5836 Otherwise there's no need to make him wake up, and it could
5837 cause trouble (for example it would make sit_for return). */
5838 if (waiting_for_user_input_p == -1)
5839 record_asynch_buffer_change ();
5842 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5843 Sinternal_default_process_filter, 2, 2, 0,
5844 doc: /* Function used as default process filter.
5845 This inserts the process's output into its buffer, if there is one.
5846 Otherwise it discards the output. */)
5847 (Lisp_Object proc, Lisp_Object text)
5849 struct Lisp_Process *p;
5850 ptrdiff_t opoint;
5852 CHECK_PROCESS (proc);
5853 p = XPROCESS (proc);
5854 CHECK_STRING (text);
5856 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5858 Lisp_Object old_read_only;
5859 ptrdiff_t old_begv, old_zv;
5860 ptrdiff_t old_begv_byte, old_zv_byte;
5861 ptrdiff_t before, before_byte;
5862 ptrdiff_t opoint_byte;
5863 struct buffer *b;
5865 Fset_buffer (p->buffer);
5866 opoint = PT;
5867 opoint_byte = PT_BYTE;
5868 old_read_only = BVAR (current_buffer, read_only);
5869 old_begv = BEGV;
5870 old_zv = ZV;
5871 old_begv_byte = BEGV_BYTE;
5872 old_zv_byte = ZV_BYTE;
5874 bset_read_only (current_buffer, Qnil);
5876 /* Insert new output into buffer at the current end-of-output
5877 marker, thus preserving logical ordering of input and output. */
5878 if (XMARKER (p->mark)->buffer)
5879 set_point_from_marker (p->mark);
5880 else
5881 SET_PT_BOTH (ZV, ZV_BYTE);
5882 before = PT;
5883 before_byte = PT_BYTE;
5885 /* If the output marker is outside of the visible region, save
5886 the restriction and widen. */
5887 if (! (BEGV <= PT && PT <= ZV))
5888 Fwiden ();
5890 /* Adjust the multibyteness of TEXT to that of the buffer. */
5891 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5892 != ! STRING_MULTIBYTE (text))
5893 text = (STRING_MULTIBYTE (text)
5894 ? Fstring_as_unibyte (text)
5895 : Fstring_to_multibyte (text));
5896 /* Insert before markers in case we are inserting where
5897 the buffer's mark is, and the user's next command is Meta-y. */
5898 insert_from_string_before_markers (text, 0, 0,
5899 SCHARS (text), SBYTES (text), 0);
5901 /* Make sure the process marker's position is valid when the
5902 process buffer is changed in the signal_after_change above.
5903 W3 is known to do that. */
5904 if (BUFFERP (p->buffer)
5905 && (b = XBUFFER (p->buffer), b != current_buffer))
5906 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5907 else
5908 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5910 update_mode_lines = 23;
5912 /* Make sure opoint and the old restrictions
5913 float ahead of any new text just as point would. */
5914 if (opoint >= before)
5916 opoint += PT - before;
5917 opoint_byte += PT_BYTE - before_byte;
5919 if (old_begv > before)
5921 old_begv += PT - before;
5922 old_begv_byte += PT_BYTE - before_byte;
5924 if (old_zv >= before)
5926 old_zv += PT - before;
5927 old_zv_byte += PT_BYTE - before_byte;
5930 /* If the restriction isn't what it should be, set it. */
5931 if (old_begv != BEGV || old_zv != ZV)
5932 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5934 bset_read_only (current_buffer, old_read_only);
5935 SET_PT_BOTH (opoint, opoint_byte);
5937 return Qnil;
5940 /* Sending data to subprocess. */
5942 /* In send_process, when a write fails temporarily,
5943 wait_reading_process_output is called. It may execute user code,
5944 e.g. timers, that attempts to write new data to the same process.
5945 We must ensure that data is sent in the right order, and not
5946 interspersed half-completed with other writes (Bug#10815). This is
5947 handled by the write_queue element of struct process. It is a list
5948 with each entry having the form
5950 (string . (offset . length))
5952 where STRING is a lisp string, OFFSET is the offset into the
5953 string's byte sequence from which we should begin to send, and
5954 LENGTH is the number of bytes left to send. */
5956 /* Create a new entry in write_queue.
5957 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5958 BUF is a pointer to the string sequence of the input_obj or a C
5959 string in case of Qt or Qnil. */
5961 static void
5962 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5963 const char *buf, ptrdiff_t len, bool front)
5965 ptrdiff_t offset;
5966 Lisp_Object entry, obj;
5968 if (STRINGP (input_obj))
5970 offset = buf - SSDATA (input_obj);
5971 obj = input_obj;
5973 else
5975 offset = 0;
5976 obj = make_unibyte_string (buf, len);
5979 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5981 if (front)
5982 pset_write_queue (p, Fcons (entry, p->write_queue));
5983 else
5984 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5987 /* Remove the first element in the write_queue of process P, put its
5988 contents in OBJ, BUF and LEN, and return true. If the
5989 write_queue is empty, return false. */
5991 static bool
5992 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5993 const char **buf, ptrdiff_t *len)
5995 Lisp_Object entry, offset_length;
5996 ptrdiff_t offset;
5998 if (NILP (p->write_queue))
5999 return 0;
6001 entry = XCAR (p->write_queue);
6002 pset_write_queue (p, XCDR (p->write_queue));
6004 *obj = XCAR (entry);
6005 offset_length = XCDR (entry);
6007 *len = XINT (XCDR (offset_length));
6008 offset = XINT (XCAR (offset_length));
6009 *buf = SSDATA (*obj) + offset;
6011 return 1;
6014 /* Send some data to process PROC.
6015 BUF is the beginning of the data; LEN is the number of characters.
6016 OBJECT is the Lisp object that the data comes from. If OBJECT is
6017 nil or t, it means that the data comes from C string.
6019 If OBJECT is not nil, the data is encoded by PROC's coding-system
6020 for encoding before it is sent.
6022 This function can evaluate Lisp code and can garbage collect. */
6024 static void
6025 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
6026 Lisp_Object object)
6028 struct Lisp_Process *p = XPROCESS (proc);
6029 ssize_t rv;
6030 struct coding_system *coding;
6032 if (NETCONN_P (proc))
6034 wait_while_connecting (proc);
6035 wait_for_tls_negotiation (proc);
6038 if (p->raw_status_new)
6039 update_status (p);
6040 if (! EQ (p->status, Qrun))
6041 error ("Process %s not running", SDATA (p->name));
6042 if (p->outfd < 0)
6043 error ("Output file descriptor of %s is closed", SDATA (p->name));
6045 coding = proc_encode_coding_system[p->outfd];
6046 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
6048 if ((STRINGP (object) && STRING_MULTIBYTE (object))
6049 || (BUFFERP (object)
6050 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
6051 || EQ (object, Qt))
6053 pset_encode_coding_system
6054 (p, complement_process_encoding_system (p->encode_coding_system));
6055 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
6057 /* The coding system for encoding was changed to raw-text
6058 because we sent a unibyte text previously. Now we are
6059 sending a multibyte text, thus we must encode it by the
6060 original coding system specified for the current process.
6062 Another reason we come here is that the coding system
6063 was just complemented and a new one was returned by
6064 complement_process_encoding_system. */
6065 setup_coding_system (p->encode_coding_system, coding);
6066 Vlast_coding_system_used = p->encode_coding_system;
6068 coding->src_multibyte = 1;
6070 else
6072 coding->src_multibyte = 0;
6073 /* For sending a unibyte text, character code conversion should
6074 not take place but EOL conversion should. So, setup raw-text
6075 or one of the subsidiary if we have not yet done it. */
6076 if (CODING_REQUIRE_ENCODING (coding))
6078 if (CODING_REQUIRE_FLUSHING (coding))
6080 /* But, before changing the coding, we must flush out data. */
6081 coding->mode |= CODING_MODE_LAST_BLOCK;
6082 send_process (proc, "", 0, Qt);
6083 coding->mode &= CODING_MODE_LAST_BLOCK;
6085 setup_coding_system (raw_text_coding_system
6086 (Vlast_coding_system_used),
6087 coding);
6088 coding->src_multibyte = 0;
6091 coding->dst_multibyte = 0;
6093 if (CODING_REQUIRE_ENCODING (coding))
6095 coding->dst_object = Qt;
6096 if (BUFFERP (object))
6098 ptrdiff_t from_byte, from, to;
6099 ptrdiff_t save_pt, save_pt_byte;
6100 struct buffer *cur = current_buffer;
6102 set_buffer_internal (XBUFFER (object));
6103 save_pt = PT, save_pt_byte = PT_BYTE;
6105 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
6106 from = BYTE_TO_CHAR (from_byte);
6107 to = BYTE_TO_CHAR (from_byte + len);
6108 TEMP_SET_PT_BOTH (from, from_byte);
6109 encode_coding_object (coding, object, from, from_byte,
6110 to, from_byte + len, Qt);
6111 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
6112 set_buffer_internal (cur);
6114 else if (STRINGP (object))
6116 encode_coding_object (coding, object, 0, 0, SCHARS (object),
6117 SBYTES (object), Qt);
6119 else
6121 coding->dst_object = make_unibyte_string (buf, len);
6122 coding->produced = len;
6125 len = coding->produced;
6126 object = coding->dst_object;
6127 buf = SSDATA (object);
6130 /* If there is already data in the write_queue, put the new data
6131 in the back of queue. Otherwise, ignore it. */
6132 if (!NILP (p->write_queue))
6133 write_queue_push (p, object, buf, len, 0);
6135 do /* while !NILP (p->write_queue) */
6137 ptrdiff_t cur_len = -1;
6138 const char *cur_buf;
6139 Lisp_Object cur_object;
6141 /* If write_queue is empty, ignore it. */
6142 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
6144 cur_len = len;
6145 cur_buf = buf;
6146 cur_object = object;
6149 while (cur_len > 0)
6151 /* Send this batch, using one or more write calls. */
6152 ptrdiff_t written = 0;
6153 int outfd = p->outfd;
6154 #ifdef DATAGRAM_SOCKETS
6155 if (DATAGRAM_CHAN_P (outfd))
6157 rv = sendto (outfd, cur_buf, cur_len,
6158 0, datagram_address[outfd].sa,
6159 datagram_address[outfd].len);
6160 if (rv >= 0)
6161 written = rv;
6162 else if (errno == EMSGSIZE)
6163 report_file_error ("Sending datagram", proc);
6165 else
6166 #endif
6168 #ifdef HAVE_GNUTLS
6169 if (p->gnutls_p && p->gnutls_state)
6170 written = emacs_gnutls_write (p, cur_buf, cur_len);
6171 else
6172 #endif
6173 written = emacs_write_sig (outfd, cur_buf, cur_len);
6174 rv = (written ? 0 : -1);
6175 if (p->read_output_delay > 0
6176 && p->adaptive_read_buffering == 1)
6178 p->read_output_delay = 0;
6179 process_output_delay_count--;
6180 p->read_output_skip = 0;
6184 if (rv < 0)
6186 if (would_block (errno))
6187 /* Buffer is full. Wait, accepting input;
6188 that may allow the program
6189 to finish doing output and read more. */
6191 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
6192 /* A gross hack to work around a bug in FreeBSD.
6193 In the following sequence, read(2) returns
6194 bogus data:
6196 write(2) 1022 bytes
6197 write(2) 954 bytes, get EAGAIN
6198 read(2) 1024 bytes in process_read_output
6199 read(2) 11 bytes in process_read_output
6201 That is, read(2) returns more bytes than have
6202 ever been written successfully. The 1033 bytes
6203 read are the 1022 bytes written successfully
6204 after processing (for example with CRs added if
6205 the terminal is set up that way which it is
6206 here). The same bytes will be seen again in a
6207 later read(2), without the CRs. */
6209 if (errno == EAGAIN)
6211 int flags = FWRITE;
6212 ioctl (p->outfd, TIOCFLUSH, &flags);
6214 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
6216 /* Put what we should have written in wait_queue. */
6217 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
6218 wait_reading_process_output (0, 20 * 1000 * 1000,
6219 0, 0, Qnil, NULL, 0);
6220 /* Reread queue, to see what is left. */
6221 break;
6223 else if (errno == EPIPE)
6225 p->raw_status_new = 0;
6226 pset_status (p, list2 (Qexit, make_number (256)));
6227 p->tick = ++process_tick;
6228 deactivate_process (proc);
6229 error ("process %s no longer connected to pipe; closed it",
6230 SDATA (p->name));
6232 else
6233 /* This is a real error. */
6234 report_file_error ("Writing to process", proc);
6236 cur_buf += written;
6237 cur_len -= written;
6240 while (!NILP (p->write_queue));
6243 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
6244 3, 3, 0,
6245 doc: /* Send current contents of region as input to PROCESS.
6246 PROCESS may be a process, a buffer, the name of a process or buffer, or
6247 nil, indicating the current buffer's process.
6248 Called from program, takes three arguments, PROCESS, START and END.
6249 If the region is more than 500 characters long,
6250 it is sent in several bunches. This may happen even for shorter regions.
6251 Output from processes can arrive in between bunches.
6253 If PROCESS is a non-blocking network process that hasn't been fully
6254 set up yet, this function will block until socket setup has completed. */)
6255 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
6257 Lisp_Object proc = get_process (process);
6258 ptrdiff_t start_byte, end_byte;
6260 validate_region (&start, &end);
6262 start_byte = CHAR_TO_BYTE (XINT (start));
6263 end_byte = CHAR_TO_BYTE (XINT (end));
6265 if (XINT (start) < GPT && XINT (end) > GPT)
6266 move_gap_both (XINT (start), start_byte);
6268 if (NETCONN_P (proc))
6269 wait_while_connecting (proc);
6271 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
6272 end_byte - start_byte, Fcurrent_buffer ());
6274 return Qnil;
6277 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
6278 2, 2, 0,
6279 doc: /* Send PROCESS the contents of STRING as input.
6280 PROCESS may be a process, a buffer, the name of a process or buffer, or
6281 nil, indicating the current buffer's process.
6282 If STRING is more than 500 characters long,
6283 it is sent in several bunches. This may happen even for shorter strings.
6284 Output from processes can arrive in between bunches.
6286 If PROCESS is a non-blocking network process that hasn't been fully
6287 set up yet, this function will block until socket setup has completed. */)
6288 (Lisp_Object process, Lisp_Object string)
6290 CHECK_STRING (string);
6291 Lisp_Object proc = get_process (process);
6292 send_process (proc, SSDATA (string),
6293 SBYTES (string), string);
6294 return Qnil;
6297 /* Return the foreground process group for the tty/pty that
6298 the process P uses. */
6299 static pid_t
6300 emacs_get_tty_pgrp (struct Lisp_Process *p)
6302 pid_t gid = -1;
6304 #ifdef TIOCGPGRP
6305 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
6307 int fd;
6308 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6309 master side. Try the slave side. */
6310 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
6312 if (fd != -1)
6314 ioctl (fd, TIOCGPGRP, &gid);
6315 emacs_close (fd);
6318 #endif /* defined (TIOCGPGRP ) */
6320 return gid;
6323 DEFUN ("process-running-child-p", Fprocess_running_child_p,
6324 Sprocess_running_child_p, 0, 1, 0,
6325 doc: /* Return non-nil if PROCESS has given the terminal to a
6326 child. If the operating system does not make it possible to find out,
6327 return t. If we can find out, return the numeric ID of the foreground
6328 process group. */)
6329 (Lisp_Object process)
6331 /* Initialize in case ioctl doesn't exist or gives an error,
6332 in a way that will cause returning t. */
6333 Lisp_Object proc = get_process (process);
6334 struct Lisp_Process *p = XPROCESS (proc);
6336 if (!EQ (p->type, Qreal))
6337 error ("Process %s is not a subprocess",
6338 SDATA (p->name));
6339 if (p->infd < 0)
6340 error ("Process %s is not active",
6341 SDATA (p->name));
6343 pid_t gid = emacs_get_tty_pgrp (p);
6345 if (gid == p->pid)
6346 return Qnil;
6347 if (gid != -1)
6348 return make_number (gid);
6349 return Qt;
6352 /* Send a signal number SIGNO to PROCESS.
6353 If CURRENT_GROUP is t, that means send to the process group
6354 that currently owns the terminal being used to communicate with PROCESS.
6355 This is used for various commands in shell mode.
6356 If CURRENT_GROUP is lambda, that means send to the process group
6357 that currently owns the terminal, but only if it is NOT the shell itself.
6359 If NOMSG is false, insert signal-announcements into process's buffers
6360 right away.
6362 If we can, we try to signal PROCESS by sending control characters
6363 down the pty. This allows us to signal inferiors who have changed
6364 their uid, for which kill would return an EPERM error. */
6366 static void
6367 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
6368 bool nomsg)
6370 Lisp_Object proc;
6371 struct Lisp_Process *p;
6372 pid_t gid;
6373 bool no_pgrp = 0;
6375 proc = get_process (process);
6376 p = XPROCESS (proc);
6378 if (!EQ (p->type, Qreal))
6379 error ("Process %s is not a subprocess",
6380 SDATA (p->name));
6381 if (p->infd < 0)
6382 error ("Process %s is not active",
6383 SDATA (p->name));
6385 if (!p->pty_flag)
6386 current_group = Qnil;
6388 /* If we are using pgrps, get a pgrp number and make it negative. */
6389 if (NILP (current_group))
6390 /* Send the signal to the shell's process group. */
6391 gid = p->pid;
6392 else
6394 #ifdef SIGNALS_VIA_CHARACTERS
6395 /* If possible, send signals to the entire pgrp
6396 by sending an input character to it. */
6398 struct termios t;
6399 cc_t *sig_char = NULL;
6401 tcgetattr (p->infd, &t);
6403 switch (signo)
6405 case SIGINT:
6406 sig_char = &t.c_cc[VINTR];
6407 break;
6409 case SIGQUIT:
6410 sig_char = &t.c_cc[VQUIT];
6411 break;
6413 case SIGTSTP:
6414 #ifdef VSWTCH
6415 sig_char = &t.c_cc[VSWTCH];
6416 #else
6417 sig_char = &t.c_cc[VSUSP];
6418 #endif
6419 break;
6422 if (sig_char && *sig_char != CDISABLE)
6424 send_process (proc, (char *) sig_char, 1, Qnil);
6425 return;
6427 /* If we can't send the signal with a character,
6428 fall through and send it another way. */
6430 /* The code above may fall through if it can't
6431 handle the signal. */
6432 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6434 #ifdef TIOCGPGRP
6435 /* Get the current pgrp using the tty itself, if we have that.
6436 Otherwise, use the pty to get the pgrp.
6437 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6438 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6439 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6440 His patch indicates that if TIOCGPGRP returns an error, then
6441 we should just assume that p->pid is also the process group id. */
6443 gid = emacs_get_tty_pgrp (p);
6445 if (gid == -1)
6446 /* If we can't get the information, assume
6447 the shell owns the tty. */
6448 gid = p->pid;
6450 /* It is not clear whether anything really can set GID to -1.
6451 Perhaps on some system one of those ioctls can or could do so.
6452 Or perhaps this is vestigial. */
6453 if (gid == -1)
6454 no_pgrp = 1;
6455 #else /* ! defined (TIOCGPGRP) */
6456 /* Can't select pgrps on this system, so we know that
6457 the child itself heads the pgrp. */
6458 gid = p->pid;
6459 #endif /* ! defined (TIOCGPGRP) */
6461 /* If current_group is lambda, and the shell owns the terminal,
6462 don't send any signal. */
6463 if (EQ (current_group, Qlambda) && gid == p->pid)
6464 return;
6467 #ifdef SIGCONT
6468 if (signo == SIGCONT)
6470 p->raw_status_new = 0;
6471 pset_status (p, Qrun);
6472 p->tick = ++process_tick;
6473 if (!nomsg)
6475 status_notify (NULL, NULL);
6476 redisplay_preserve_echo_area (13);
6479 #endif
6481 #ifdef TIOCSIGSEND
6482 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6483 We don't know whether the bug is fixed in later HP-UX versions. */
6484 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6485 return;
6486 #endif
6488 /* If we don't have process groups, send the signal to the immediate
6489 subprocess. That isn't really right, but it's better than any
6490 obvious alternative. */
6491 pid_t pid = no_pgrp ? gid : - gid;
6493 /* Do not kill an already-reaped process, as that could kill an
6494 innocent bystander that happens to have the same process ID. */
6495 sigset_t oldset;
6496 block_child_signal (&oldset);
6497 if (p->alive)
6498 kill (pid, signo);
6499 unblock_child_signal (&oldset);
6502 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6503 doc: /* Interrupt process PROCESS.
6504 PROCESS may be a process, a buffer, or the name of a process or buffer.
6505 No arg or nil means current buffer's process.
6506 Second arg CURRENT-GROUP non-nil means send signal to
6507 the current process-group of the process's controlling terminal
6508 rather than to the process's own process group.
6509 If the process is a shell, this means interrupt current subjob
6510 rather than the shell.
6512 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6513 don't send the signal. */)
6514 (Lisp_Object process, Lisp_Object current_group)
6516 process_send_signal (process, SIGINT, current_group, 0);
6517 return process;
6520 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6521 doc: /* Kill process PROCESS. May be process or name of one.
6522 See function `interrupt-process' for more details on usage. */)
6523 (Lisp_Object process, Lisp_Object current_group)
6525 process_send_signal (process, SIGKILL, current_group, 0);
6526 return process;
6529 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6530 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6531 See function `interrupt-process' for more details on usage. */)
6532 (Lisp_Object process, Lisp_Object current_group)
6534 process_send_signal (process, SIGQUIT, current_group, 0);
6535 return process;
6538 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6539 doc: /* Stop process PROCESS. May be process or name of one.
6540 See function `interrupt-process' for more details on usage.
6541 If PROCESS is a network or serial or pipe connection, inhibit handling
6542 of incoming traffic. */)
6543 (Lisp_Object process, Lisp_Object current_group)
6545 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6546 || PIPECONN_P (process)))
6548 struct Lisp_Process *p;
6550 p = XPROCESS (process);
6551 if (NILP (p->command)
6552 && p->infd >= 0)
6554 FD_CLR (p->infd, &input_wait_mask);
6555 FD_CLR (p->infd, &non_keyboard_wait_mask);
6557 pset_command (p, Qt);
6558 return process;
6560 #ifndef SIGTSTP
6561 error ("No SIGTSTP support");
6562 #else
6563 process_send_signal (process, SIGTSTP, current_group, 0);
6564 #endif
6565 return process;
6568 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6569 doc: /* Continue process PROCESS. May be process or name of one.
6570 See function `interrupt-process' for more details on usage.
6571 If PROCESS is a network or serial process, resume handling of incoming
6572 traffic. */)
6573 (Lisp_Object process, Lisp_Object current_group)
6575 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6576 || PIPECONN_P (process)))
6578 struct Lisp_Process *p;
6580 p = XPROCESS (process);
6581 if (EQ (p->command, Qt)
6582 && p->infd >= 0
6583 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6585 FD_SET (p->infd, &input_wait_mask);
6586 FD_SET (p->infd, &non_keyboard_wait_mask);
6587 #ifdef WINDOWSNT
6588 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6589 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6590 #else /* not WINDOWSNT */
6591 tcflush (p->infd, TCIFLUSH);
6592 #endif /* not WINDOWSNT */
6594 pset_command (p, Qnil);
6595 return process;
6597 #ifdef SIGCONT
6598 process_send_signal (process, SIGCONT, current_group, 0);
6599 #else
6600 error ("No SIGCONT support");
6601 #endif
6602 return process;
6605 /* Return the integer value of the signal whose abbreviation is ABBR,
6606 or a negative number if there is no such signal. */
6607 static int
6608 abbr_to_signal (char const *name)
6610 int i, signo;
6611 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6613 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6614 name += 3;
6616 for (i = 0; i < sizeof sigbuf; i++)
6618 sigbuf[i] = c_toupper (name[i]);
6619 if (! sigbuf[i])
6620 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6623 return -1;
6626 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6627 2, 2, "sProcess (name or number): \nnSignal code: ",
6628 doc: /* Send PROCESS the signal with code SIGCODE.
6629 PROCESS may also be a number specifying the process id of the
6630 process to signal; in this case, the process need not be a child of
6631 this Emacs.
6632 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6633 (Lisp_Object process, Lisp_Object sigcode)
6635 pid_t pid;
6636 int signo;
6638 if (STRINGP (process))
6640 Lisp_Object tem = Fget_process (process);
6641 if (NILP (tem))
6643 Lisp_Object process_number
6644 = string_to_number (SSDATA (process), 10, 1);
6645 if (NUMBERP (process_number))
6646 tem = process_number;
6648 process = tem;
6650 else if (!NUMBERP (process))
6651 process = get_process (process);
6653 if (NILP (process))
6654 return process;
6656 if (NUMBERP (process))
6657 CONS_TO_INTEGER (process, pid_t, pid);
6658 else
6660 CHECK_PROCESS (process);
6661 pid = XPROCESS (process)->pid;
6662 if (pid <= 0)
6663 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6666 if (INTEGERP (sigcode))
6668 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6669 signo = XINT (sigcode);
6671 else
6673 char *name;
6675 CHECK_SYMBOL (sigcode);
6676 name = SSDATA (SYMBOL_NAME (sigcode));
6678 signo = abbr_to_signal (name);
6679 if (signo < 0)
6680 error ("Undefined signal name %s", name);
6683 return make_number (kill (pid, signo));
6686 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6687 doc: /* Make PROCESS see end-of-file in its input.
6688 EOF comes after any text already sent to it.
6689 PROCESS may be a process, a buffer, the name of a process or buffer, or
6690 nil, indicating the current buffer's process.
6691 If PROCESS is a network connection, or is a process communicating
6692 through a pipe (as opposed to a pty), then you cannot send any more
6693 text to PROCESS after you call this function.
6694 If PROCESS is a serial process, wait until all output written to the
6695 process has been transmitted to the serial port. */)
6696 (Lisp_Object process)
6698 Lisp_Object proc;
6699 struct coding_system *coding = NULL;
6700 int outfd;
6702 proc = get_process (process);
6704 if (NETCONN_P (proc))
6705 wait_while_connecting (proc);
6707 if (DATAGRAM_CONN_P (proc))
6708 return process;
6711 outfd = XPROCESS (proc)->outfd;
6712 if (outfd >= 0)
6713 coding = proc_encode_coding_system[outfd];
6715 /* Make sure the process is really alive. */
6716 if (XPROCESS (proc)->raw_status_new)
6717 update_status (XPROCESS (proc));
6718 if (! EQ (XPROCESS (proc)->status, Qrun))
6719 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6721 if (coding && CODING_REQUIRE_FLUSHING (coding))
6723 coding->mode |= CODING_MODE_LAST_BLOCK;
6724 send_process (proc, "", 0, Qnil);
6727 if (XPROCESS (proc)->pty_flag)
6728 send_process (proc, "\004", 1, Qnil);
6729 else if (EQ (XPROCESS (proc)->type, Qserial))
6731 #ifndef WINDOWSNT
6732 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6733 report_file_error ("Failed tcdrain", Qnil);
6734 #endif /* not WINDOWSNT */
6735 /* Do nothing on Windows because writes are blocking. */
6737 else
6739 struct Lisp_Process *p = XPROCESS (proc);
6740 int old_outfd = p->outfd;
6741 int new_outfd;
6743 #ifdef HAVE_SHUTDOWN
6744 /* If this is a network connection, or socketpair is used
6745 for communication with the subprocess, call shutdown to cause EOF.
6746 (In some old system, shutdown to socketpair doesn't work.
6747 Then we just can't win.) */
6748 if (0 <= old_outfd
6749 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6750 shutdown (old_outfd, 1);
6751 #endif
6752 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6753 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6754 if (new_outfd < 0)
6755 report_file_error ("Opening null device", Qnil);
6756 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6757 p->outfd = new_outfd;
6759 if (!proc_encode_coding_system[new_outfd])
6760 proc_encode_coding_system[new_outfd]
6761 = xmalloc (sizeof (struct coding_system));
6762 if (old_outfd >= 0)
6764 *proc_encode_coding_system[new_outfd]
6765 = *proc_encode_coding_system[old_outfd];
6766 memset (proc_encode_coding_system[old_outfd], 0,
6767 sizeof (struct coding_system));
6769 else
6770 setup_coding_system (p->encode_coding_system,
6771 proc_encode_coding_system[new_outfd]);
6773 return process;
6776 /* The main Emacs thread records child processes in three places:
6778 - Vprocess_alist, for asynchronous subprocesses, which are child
6779 processes visible to Lisp.
6781 - deleted_pid_list, for child processes invisible to Lisp,
6782 typically because of delete-process. These are recorded so that
6783 the processes can be reaped when they exit, so that the operating
6784 system's process table is not cluttered by zombies.
6786 - the local variable PID in Fcall_process, call_process_cleanup and
6787 call_process_kill, for synchronous subprocesses.
6788 record_unwind_protect is used to make sure this process is not
6789 forgotten: if the user interrupts call-process and the child
6790 process refuses to exit immediately even with two C-g's,
6791 call_process_kill adds PID's contents to deleted_pid_list before
6792 returning.
6794 The main Emacs thread invokes waitpid only on child processes that
6795 it creates and that have not been reaped. This avoid races on
6796 platforms such as GTK, where other threads create their own
6797 subprocesses which the main thread should not reap. For example,
6798 if the main thread attempted to reap an already-reaped child, it
6799 might inadvertently reap a GTK-created process that happened to
6800 have the same process ID. */
6802 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6803 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6804 keep track of its own children. GNUstep is similar. */
6806 static void dummy_handler (int sig) {}
6807 static signal_handler_t volatile lib_child_handler;
6809 /* Handle a SIGCHLD signal by looking for known child processes of
6810 Emacs whose status have changed. For each one found, record its
6811 new status.
6813 All we do is change the status; we do not run sentinels or print
6814 notifications. That is saved for the next time keyboard input is
6815 done, in order to avoid timing errors.
6817 ** WARNING: this can be called during garbage collection.
6818 Therefore, it must not be fooled by the presence of mark bits in
6819 Lisp objects.
6821 ** USG WARNING: Although it is not obvious from the documentation
6822 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6823 signal() before executing at least one wait(), otherwise the
6824 handler will be called again, resulting in an infinite loop. The
6825 relevant portion of the documentation reads "SIGCLD signals will be
6826 queued and the signal-catching function will be continually
6827 reentered until the queue is empty". Invoking signal() causes the
6828 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6829 Inc.
6831 ** Malloc WARNING: This should never call malloc either directly or
6832 indirectly; if it does, that is a bug. */
6834 static void
6835 handle_child_signal (int sig)
6837 Lisp_Object tail, proc;
6839 /* Find the process that signaled us, and record its status. */
6841 /* The process can have been deleted by Fdelete_process, or have
6842 been started asynchronously by Fcall_process. */
6843 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6845 bool all_pids_are_fixnums
6846 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6847 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6848 Lisp_Object head = XCAR (tail);
6849 Lisp_Object xpid;
6850 if (! CONSP (head))
6851 continue;
6852 xpid = XCAR (head);
6853 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6855 pid_t deleted_pid;
6856 if (INTEGERP (xpid))
6857 deleted_pid = XINT (xpid);
6858 else
6859 deleted_pid = XFLOAT_DATA (xpid);
6860 if (child_status_changed (deleted_pid, 0, 0))
6862 if (STRINGP (XCDR (head)))
6863 unlink (SSDATA (XCDR (head)));
6864 XSETCAR (tail, Qnil);
6869 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6870 FOR_EACH_PROCESS (tail, proc)
6872 struct Lisp_Process *p = XPROCESS (proc);
6873 int status;
6875 if (p->alive
6876 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6878 /* Change the status of the process that was found. */
6879 p->tick = ++process_tick;
6880 p->raw_status = status;
6881 p->raw_status_new = 1;
6883 /* If process has terminated, stop waiting for its output. */
6884 if (WIFSIGNALED (status) || WIFEXITED (status))
6886 bool clear_desc_flag = 0;
6887 p->alive = 0;
6888 if (p->infd >= 0)
6889 clear_desc_flag = 1;
6891 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6892 if (clear_desc_flag)
6894 FD_CLR (p->infd, &input_wait_mask);
6895 FD_CLR (p->infd, &non_keyboard_wait_mask);
6901 lib_child_handler (sig);
6902 #ifdef NS_IMPL_GNUSTEP
6903 /* NSTask in GNUstep sets its child handler each time it is called.
6904 So we must re-set ours. */
6905 catch_child_signal ();
6906 #endif
6909 static void
6910 deliver_child_signal (int sig)
6912 deliver_process_signal (sig, handle_child_signal);
6916 static Lisp_Object
6917 exec_sentinel_error_handler (Lisp_Object error_val)
6919 cmd_error_internal (error_val, "error in process sentinel: ");
6920 Vinhibit_quit = Qt;
6921 update_echo_area ();
6922 Fsleep_for (make_number (2), Qnil);
6923 return Qt;
6926 static void
6927 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6929 Lisp_Object sentinel, odeactivate;
6930 struct Lisp_Process *p = XPROCESS (proc);
6931 ptrdiff_t count = SPECPDL_INDEX ();
6932 bool outer_running_asynch_code = running_asynch_code;
6933 int waiting = waiting_for_user_input_p;
6935 if (inhibit_sentinels)
6936 return;
6938 odeactivate = Vdeactivate_mark;
6939 #if 0
6940 Lisp_Object obuffer, okeymap;
6941 XSETBUFFER (obuffer, current_buffer);
6942 okeymap = BVAR (current_buffer, keymap);
6943 #endif
6945 /* There's no good reason to let sentinels change the current
6946 buffer, and many callers of accept-process-output, sit-for, and
6947 friends don't expect current-buffer to be changed from under them. */
6948 record_unwind_current_buffer ();
6950 sentinel = p->sentinel;
6952 /* Inhibit quit so that random quits don't screw up a running filter. */
6953 specbind (Qinhibit_quit, Qt);
6954 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6956 /* In case we get recursively called,
6957 and we already saved the match data nonrecursively,
6958 save the same match data in safely recursive fashion. */
6959 if (outer_running_asynch_code)
6961 Lisp_Object tem;
6962 tem = Fmatch_data (Qnil, Qnil, Qnil);
6963 restore_search_regs ();
6964 record_unwind_save_match_data ();
6965 Fset_match_data (tem, Qt);
6968 /* For speed, if a search happens within this code,
6969 save the match data in a special nonrecursive fashion. */
6970 running_asynch_code = 1;
6972 internal_condition_case_1 (read_process_output_call,
6973 list3 (sentinel, proc, reason),
6974 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6975 exec_sentinel_error_handler);
6977 /* If we saved the match data nonrecursively, restore it now. */
6978 restore_search_regs ();
6979 running_asynch_code = outer_running_asynch_code;
6981 Vdeactivate_mark = odeactivate;
6983 /* Restore waiting_for_user_input_p as it was
6984 when we were called, in case the filter clobbered it. */
6985 waiting_for_user_input_p = waiting;
6987 #if 0
6988 if (! EQ (Fcurrent_buffer (), obuffer)
6989 || ! EQ (current_buffer->keymap, okeymap))
6990 #endif
6991 /* But do it only if the caller is actually going to read events.
6992 Otherwise there's no need to make him wake up, and it could
6993 cause trouble (for example it would make sit_for return). */
6994 if (waiting_for_user_input_p == -1)
6995 record_asynch_buffer_change ();
6997 unbind_to (count, Qnil);
7000 /* Report all recent events of a change in process status
7001 (either run the sentinel or output a message).
7002 This is usually done while Emacs is waiting for keyboard input
7003 but can be done at other times.
7005 Return positive if any input was received from WAIT_PROC (or from
7006 any process if WAIT_PROC is null), zero if input was attempted but
7007 none received, and negative if we didn't even try. */
7009 static int
7010 status_notify (struct Lisp_Process *deleting_process,
7011 struct Lisp_Process *wait_proc)
7013 Lisp_Object proc;
7014 Lisp_Object tail, msg;
7015 int got_some_output = -1;
7017 tail = Qnil;
7018 msg = Qnil;
7020 /* Set this now, so that if new processes are created by sentinels
7021 that we run, we get called again to handle their status changes. */
7022 update_tick = process_tick;
7024 FOR_EACH_PROCESS (tail, proc)
7026 Lisp_Object symbol;
7027 register struct Lisp_Process *p = XPROCESS (proc);
7029 if (p->tick != p->update_tick)
7031 p->update_tick = p->tick;
7033 /* If process is still active, read any output that remains. */
7034 while (! EQ (p->filter, Qt)
7035 && ! connecting_status (p->status)
7036 && ! EQ (p->status, Qlisten)
7037 /* Network or serial process not stopped: */
7038 && ! EQ (p->command, Qt)
7039 && p->infd >= 0
7040 && p != deleting_process)
7042 int nread = read_process_output (proc, p->infd);
7043 if ((!wait_proc || wait_proc == XPROCESS (proc))
7044 && got_some_output < nread)
7045 got_some_output = nread;
7046 if (nread <= 0)
7047 break;
7050 /* Get the text to use for the message. */
7051 if (p->raw_status_new)
7052 update_status (p);
7053 msg = status_message (p);
7055 /* If process is terminated, deactivate it or delete it. */
7056 symbol = p->status;
7057 if (CONSP (p->status))
7058 symbol = XCAR (p->status);
7060 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
7061 || EQ (symbol, Qclosed))
7063 if (delete_exited_processes)
7064 remove_process (proc);
7065 else
7066 deactivate_process (proc);
7069 /* The actions above may have further incremented p->tick.
7070 So set p->update_tick again so that an error in the sentinel will
7071 not cause this code to be run again. */
7072 p->update_tick = p->tick;
7073 /* Now output the message suitably. */
7074 exec_sentinel (proc, msg);
7075 if (BUFFERP (p->buffer))
7076 /* In case it uses %s in mode-line-format. */
7077 bset_update_mode_line (XBUFFER (p->buffer));
7079 } /* end for */
7081 return got_some_output;
7084 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
7085 Sinternal_default_process_sentinel, 2, 2, 0,
7086 doc: /* Function used as default sentinel for processes.
7087 This inserts a status message into the process's buffer, if there is one. */)
7088 (Lisp_Object proc, Lisp_Object msg)
7090 Lisp_Object buffer, symbol;
7091 struct Lisp_Process *p;
7092 CHECK_PROCESS (proc);
7093 p = XPROCESS (proc);
7094 buffer = p->buffer;
7095 symbol = p->status;
7096 if (CONSP (symbol))
7097 symbol = XCAR (symbol);
7099 if (!EQ (symbol, Qrun) && !NILP (buffer))
7101 Lisp_Object tem;
7102 struct buffer *old = current_buffer;
7103 ptrdiff_t opoint, opoint_byte;
7104 ptrdiff_t before, before_byte;
7106 /* Avoid error if buffer is deleted
7107 (probably that's why the process is dead, too). */
7108 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
7109 return Qnil;
7110 Fset_buffer (buffer);
7112 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
7113 msg = (code_convert_string_norecord
7114 (msg, Vlocale_coding_system, 1));
7116 opoint = PT;
7117 opoint_byte = PT_BYTE;
7118 /* Insert new output into buffer
7119 at the current end-of-output marker,
7120 thus preserving logical ordering of input and output. */
7121 if (XMARKER (p->mark)->buffer)
7122 Fgoto_char (p->mark);
7123 else
7124 SET_PT_BOTH (ZV, ZV_BYTE);
7126 before = PT;
7127 before_byte = PT_BYTE;
7129 tem = BVAR (current_buffer, read_only);
7130 bset_read_only (current_buffer, Qnil);
7131 insert_string ("\nProcess ");
7132 { /* FIXME: temporary kludge. */
7133 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
7134 insert_string (" ");
7135 Finsert (1, &msg);
7136 bset_read_only (current_buffer, tem);
7137 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
7139 if (opoint >= before)
7140 SET_PT_BOTH (opoint + (PT - before),
7141 opoint_byte + (PT_BYTE - before_byte));
7142 else
7143 SET_PT_BOTH (opoint, opoint_byte);
7145 set_buffer_internal (old);
7147 return Qnil;
7151 DEFUN ("set-process-coding-system", Fset_process_coding_system,
7152 Sset_process_coding_system, 1, 3, 0,
7153 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
7154 DECODING will be used to decode subprocess output and ENCODING to
7155 encode subprocess input. */)
7156 (Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
7158 CHECK_PROCESS (process);
7160 struct Lisp_Process *p = XPROCESS (process);
7162 Fcheck_coding_system (decoding);
7163 Fcheck_coding_system (encoding);
7164 encoding = coding_inherit_eol_type (encoding, Qnil);
7165 pset_decode_coding_system (p, decoding);
7166 pset_encode_coding_system (p, encoding);
7168 /* If the sockets haven't been set up yet, the final setup part of
7169 this will be called asynchronously. */
7170 if (p->infd < 0 || p->outfd < 0)
7171 return Qnil;
7173 setup_process_coding_systems (process);
7175 return Qnil;
7178 DEFUN ("process-coding-system",
7179 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
7180 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7181 (register Lisp_Object process)
7183 CHECK_PROCESS (process);
7184 return Fcons (XPROCESS (process)->decode_coding_system,
7185 XPROCESS (process)->encode_coding_system);
7188 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
7189 Sset_process_filter_multibyte, 2, 2, 0,
7190 doc: /* Set multibyteness of the strings given to PROCESS's filter.
7191 If FLAG is non-nil, the filter is given multibyte strings.
7192 If FLAG is nil, the filter is given unibyte strings. In this case,
7193 all character code conversion except for end-of-line conversion is
7194 suppressed. */)
7195 (Lisp_Object process, Lisp_Object flag)
7197 CHECK_PROCESS (process);
7199 struct Lisp_Process *p = XPROCESS (process);
7200 if (NILP (flag))
7201 pset_decode_coding_system
7202 (p, raw_text_coding_system (p->decode_coding_system));
7204 /* If the sockets haven't been set up yet, the final setup part of
7205 this will be called asynchronously. */
7206 if (p->infd < 0 || p->outfd < 0)
7207 return Qnil;
7209 setup_process_coding_systems (process);
7211 return Qnil;
7214 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
7215 Sprocess_filter_multibyte_p, 1, 1, 0,
7216 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7217 (Lisp_Object process)
7219 CHECK_PROCESS (process);
7220 struct Lisp_Process *p = XPROCESS (process);
7221 if (p->infd < 0)
7222 return Qnil;
7223 struct coding_system *coding = proc_decode_coding_system[p->infd];
7224 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
7230 # ifdef HAVE_GPM
7232 void
7233 add_gpm_wait_descriptor (int desc)
7235 add_keyboard_wait_descriptor (desc);
7238 void
7239 delete_gpm_wait_descriptor (int desc)
7241 delete_keyboard_wait_descriptor (desc);
7244 # endif
7246 # ifdef USABLE_SIGIO
7248 /* Return true if *MASK has a bit set
7249 that corresponds to one of the keyboard input descriptors. */
7251 static bool
7252 keyboard_bit_set (fd_set *mask)
7254 int fd;
7256 for (fd = 0; fd <= max_input_desc; fd++)
7257 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
7258 && !FD_ISSET (fd, &non_keyboard_wait_mask))
7259 return 1;
7261 return 0;
7263 # endif
7265 #else /* not subprocesses */
7267 /* Defined in msdos.c. */
7268 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
7269 struct timespec *, void *);
7271 /* Implementation of wait_reading_process_output, assuming that there
7272 are no subprocesses. Used only by the MS-DOS build.
7274 Wait for timeout to elapse and/or keyboard input to be available.
7276 TIME_LIMIT is:
7277 timeout in seconds
7278 If negative, gobble data immediately available but don't wait for any.
7280 NSECS is:
7281 an additional duration to wait, measured in nanoseconds
7282 If TIME_LIMIT is zero, then:
7283 If NSECS == 0, there is no limit.
7284 If NSECS > 0, the timeout consists of NSECS only.
7285 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
7287 READ_KBD is:
7288 0 to ignore keyboard input, or
7289 1 to return when input is available, or
7290 -1 means caller will actually read the input, so don't throw to
7291 the quit handler.
7293 see full version for other parameters. We know that wait_proc will
7294 always be NULL, since `subprocesses' isn't defined.
7296 DO_DISPLAY means redisplay should be done to show subprocess
7297 output that arrives.
7299 Return -1 signifying we got no output and did not try. */
7302 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
7303 bool do_display,
7304 Lisp_Object wait_for_cell,
7305 struct Lisp_Process *wait_proc, int just_wait_proc)
7307 register int nfds;
7308 struct timespec end_time, timeout;
7309 enum { MINIMUM = -1, TIMEOUT, INFINITY } wait;
7311 if (TYPE_MAXIMUM (time_t) < time_limit)
7312 time_limit = TYPE_MAXIMUM (time_t);
7314 if (time_limit < 0 || nsecs < 0)
7315 wait = MINIMUM;
7316 else if (time_limit > 0 || nsecs > 0)
7318 wait = TIMEOUT;
7319 end_time = timespec_add (current_timespec (),
7320 make_timespec (time_limit, nsecs));
7322 else
7323 wait = INFINITY;
7325 /* Turn off periodic alarms (in case they are in use)
7326 and then turn off any other atimers,
7327 because the select emulator uses alarms. */
7328 stop_polling ();
7329 turn_on_atimers (0);
7331 while (1)
7333 bool timeout_reduced_for_timers = false;
7334 fd_set waitchannels;
7335 int xerrno;
7337 /* If calling from keyboard input, do not quit
7338 since we want to return C-g as an input character.
7339 Otherwise, do pending quit if requested. */
7340 if (read_kbd >= 0)
7341 QUIT;
7343 /* Exit now if the cell we're waiting for became non-nil. */
7344 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7345 break;
7347 /* Compute time from now till when time limit is up. */
7348 /* Exit if already run out. */
7349 if (wait == TIMEOUT)
7351 struct timespec now = current_timespec ();
7352 if (timespec_cmp (end_time, now) <= 0)
7353 break;
7354 timeout = timespec_sub (end_time, now);
7356 else
7357 timeout = make_timespec (wait < TIMEOUT ? 0 : 100000, 0);
7359 /* If our caller will not immediately handle keyboard events,
7360 run timer events directly.
7361 (Callers that will immediately read keyboard events
7362 call timer_delay on their own.) */
7363 if (NILP (wait_for_cell))
7365 struct timespec timer_delay;
7369 unsigned old_timers_run = timers_run;
7370 timer_delay = timer_check ();
7371 if (timers_run != old_timers_run && do_display)
7372 /* We must retry, since a timer may have requeued itself
7373 and that could alter the time delay. */
7374 redisplay_preserve_echo_area (14);
7375 else
7376 break;
7378 while (!detect_input_pending ());
7380 /* If there is unread keyboard input, also return. */
7381 if (read_kbd != 0
7382 && requeued_events_pending_p ())
7383 break;
7385 if (timespec_valid_p (timer_delay))
7387 if (timespec_cmp (timer_delay, timeout) < 0)
7389 timeout = timer_delay;
7390 timeout_reduced_for_timers = true;
7395 /* Cause C-g and alarm signals to take immediate action,
7396 and cause input available signals to zero out timeout. */
7397 if (read_kbd < 0)
7398 set_waiting_for_input (&timeout);
7400 /* If a frame has been newly mapped and needs updating,
7401 reprocess its display stuff. */
7402 if (frame_garbaged && do_display)
7404 clear_waiting_for_input ();
7405 redisplay_preserve_echo_area (15);
7406 if (read_kbd < 0)
7407 set_waiting_for_input (&timeout);
7410 /* Wait till there is something to do. */
7411 FD_ZERO (&waitchannels);
7412 if (read_kbd && detect_input_pending ())
7413 nfds = 0;
7414 else
7416 if (read_kbd || !NILP (wait_for_cell))
7417 FD_SET (0, &waitchannels);
7418 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7421 xerrno = errno;
7423 /* Make C-g and alarm signals set flags again. */
7424 clear_waiting_for_input ();
7426 /* If we woke up due to SIGWINCH, actually change size now. */
7427 do_pending_window_change (0);
7429 if (wait < INFINITY && nfds == 0 && ! timeout_reduced_for_timers)
7430 /* We waited the full specified time, so return now. */
7431 break;
7433 if (nfds == -1)
7435 /* If the system call was interrupted, then go around the
7436 loop again. */
7437 if (xerrno == EINTR)
7438 FD_ZERO (&waitchannels);
7439 else
7440 report_file_errno ("Failed select", Qnil, xerrno);
7443 /* Check for keyboard input. */
7445 if (read_kbd
7446 && detect_input_pending_run_timers (do_display))
7448 swallow_events (do_display);
7449 if (detect_input_pending_run_timers (do_display))
7450 break;
7453 /* If there is unread keyboard input, also return. */
7454 if (read_kbd
7455 && requeued_events_pending_p ())
7456 break;
7458 /* If wait_for_cell. check for keyboard input
7459 but don't run any timers.
7460 ??? (It seems wrong to me to check for keyboard
7461 input at all when wait_for_cell, but the code
7462 has been this way since July 1994.
7463 Try changing this after version 19.31.) */
7464 if (! NILP (wait_for_cell)
7465 && detect_input_pending ())
7467 swallow_events (do_display);
7468 if (detect_input_pending ())
7469 break;
7472 /* Exit now if the cell we're waiting for became non-nil. */
7473 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7474 break;
7477 start_polling ();
7479 return -1;
7482 #endif /* not subprocesses */
7484 /* The following functions are needed even if async subprocesses are
7485 not supported. Some of them are no-op stubs in that case. */
7487 #ifdef HAVE_TIMERFD
7489 /* Add FD, which is a descriptor returned by timerfd_create,
7490 to the set of non-keyboard input descriptors. */
7492 void
7493 add_timer_wait_descriptor (int fd)
7495 FD_SET (fd, &input_wait_mask);
7496 FD_SET (fd, &non_keyboard_wait_mask);
7497 FD_SET (fd, &non_process_wait_mask);
7498 fd_callback_info[fd].func = timerfd_callback;
7499 fd_callback_info[fd].data = NULL;
7500 fd_callback_info[fd].condition |= FOR_READ;
7501 if (fd > max_input_desc)
7502 max_input_desc = fd;
7505 #endif /* HAVE_TIMERFD */
7507 /* If program file NAME starts with /: for quoting a magic
7508 name, remove that, preserving the multibyteness of NAME. */
7510 Lisp_Object
7511 remove_slash_colon (Lisp_Object name)
7513 return
7514 ((SBYTES (name) > 2 && SREF (name, 0) == '/' && SREF (name, 1) == ':')
7515 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
7516 SBYTES (name) - 2, STRING_MULTIBYTE (name))
7517 : name);
7520 /* Add DESC to the set of keyboard input descriptors. */
7522 void
7523 add_keyboard_wait_descriptor (int desc)
7525 #ifdef subprocesses /* Actually means "not MSDOS". */
7526 FD_SET (desc, &input_wait_mask);
7527 FD_SET (desc, &non_process_wait_mask);
7528 if (desc > max_input_desc)
7529 max_input_desc = desc;
7530 #endif
7533 /* From now on, do not expect DESC to give keyboard input. */
7535 void
7536 delete_keyboard_wait_descriptor (int desc)
7538 #ifdef subprocesses
7539 FD_CLR (desc, &input_wait_mask);
7540 FD_CLR (desc, &non_process_wait_mask);
7541 delete_input_desc (desc);
7542 #endif
7545 /* Setup coding systems of PROCESS. */
7547 void
7548 setup_process_coding_systems (Lisp_Object process)
7550 #ifdef subprocesses
7551 struct Lisp_Process *p = XPROCESS (process);
7552 int inch = p->infd;
7553 int outch = p->outfd;
7554 Lisp_Object coding_system;
7556 if (inch < 0 || outch < 0)
7557 return;
7559 if (!proc_decode_coding_system[inch])
7560 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7561 coding_system = p->decode_coding_system;
7562 if (EQ (p->filter, Qinternal_default_process_filter)
7563 && BUFFERP (p->buffer))
7565 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7566 coding_system = raw_text_coding_system (coding_system);
7568 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7570 if (!proc_encode_coding_system[outch])
7571 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7572 setup_coding_system (p->encode_coding_system,
7573 proc_encode_coding_system[outch]);
7574 #endif
7577 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7578 doc: /* Return the (or a) live process associated with BUFFER.
7579 BUFFER may be a buffer or the name of one.
7580 Return nil if all processes associated with BUFFER have been
7581 deleted or killed. */)
7582 (register Lisp_Object buffer)
7584 #ifdef subprocesses
7585 register Lisp_Object buf, tail, proc;
7587 if (NILP (buffer)) return Qnil;
7588 buf = Fget_buffer (buffer);
7589 if (NILP (buf)) return Qnil;
7591 FOR_EACH_PROCESS (tail, proc)
7592 if (EQ (XPROCESS (proc)->buffer, buf))
7593 return proc;
7594 #endif /* subprocesses */
7595 return Qnil;
7598 DEFUN ("process-inherit-coding-system-flag",
7599 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7600 1, 1, 0,
7601 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7602 If this flag is t, `buffer-file-coding-system' of the buffer
7603 associated with PROCESS will inherit the coding system used to decode
7604 the process output. */)
7605 (register Lisp_Object process)
7607 #ifdef subprocesses
7608 CHECK_PROCESS (process);
7609 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7610 #else
7611 /* Ignore the argument and return the value of
7612 inherit-process-coding-system. */
7613 return inherit_process_coding_system ? Qt : Qnil;
7614 #endif
7617 /* Kill all processes associated with `buffer'.
7618 If `buffer' is nil, kill all processes. */
7620 void
7621 kill_buffer_processes (Lisp_Object buffer)
7623 #ifdef subprocesses
7624 Lisp_Object tail, proc;
7626 FOR_EACH_PROCESS (tail, proc)
7627 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7629 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7630 Fdelete_process (proc);
7631 else if (XPROCESS (proc)->infd >= 0)
7632 process_send_signal (proc, SIGHUP, Qnil, 1);
7634 #else /* subprocesses */
7635 /* Since we have no subprocesses, this does nothing. */
7636 #endif /* subprocesses */
7639 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7640 Swaiting_for_user_input_p, 0, 0, 0,
7641 doc: /* Return non-nil if Emacs is waiting for input from the user.
7642 This is intended for use by asynchronous process output filters and sentinels. */)
7643 (void)
7645 #ifdef subprocesses
7646 return (waiting_for_user_input_p ? Qt : Qnil);
7647 #else
7648 return Qnil;
7649 #endif
7652 /* Stop reading input from keyboard sources. */
7654 void
7655 hold_keyboard_input (void)
7657 kbd_is_on_hold = 1;
7660 /* Resume reading input from keyboard sources. */
7662 void
7663 unhold_keyboard_input (void)
7665 kbd_is_on_hold = 0;
7668 /* Return true if keyboard input is on hold, zero otherwise. */
7670 bool
7671 kbd_on_hold_p (void)
7673 return kbd_is_on_hold;
7677 /* Enumeration of and access to system processes a-la ps(1). */
7679 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7680 0, 0, 0,
7681 doc: /* Return a list of numerical process IDs of all running processes.
7682 If this functionality is unsupported, return nil.
7684 See `process-attributes' for getting attributes of a process given its ID. */)
7685 (void)
7687 return list_system_processes ();
7690 DEFUN ("process-attributes", Fprocess_attributes,
7691 Sprocess_attributes, 1, 1, 0,
7692 doc: /* Return attributes of the process given by its PID, a number.
7694 Value is an alist where each element is a cons cell of the form
7696 (KEY . VALUE)
7698 If this functionality is unsupported, the value is nil.
7700 See `list-system-processes' for getting a list of all process IDs.
7702 The KEYs of the attributes that this function may return are listed
7703 below, together with the type of the associated VALUE (in parentheses).
7704 Not all platforms support all of these attributes; unsupported
7705 attributes will not appear in the returned alist.
7706 Unless explicitly indicated otherwise, numbers can have either
7707 integer or floating point values.
7709 euid -- Effective user User ID of the process (number)
7710 user -- User name corresponding to euid (string)
7711 egid -- Effective user Group ID of the process (number)
7712 group -- Group name corresponding to egid (string)
7713 comm -- Command name (executable name only) (string)
7714 state -- Process state code, such as "S", "R", or "T" (string)
7715 ppid -- Parent process ID (number)
7716 pgrp -- Process group ID (number)
7717 sess -- Session ID, i.e. process ID of session leader (number)
7718 ttname -- Controlling tty name (string)
7719 tpgid -- ID of foreground process group on the process's tty (number)
7720 minflt -- number of minor page faults (number)
7721 majflt -- number of major page faults (number)
7722 cminflt -- cumulative number of minor page faults (number)
7723 cmajflt -- cumulative number of major page faults (number)
7724 utime -- user time used by the process, in (current-time) format,
7725 which is a list of integers (HIGH LOW USEC PSEC)
7726 stime -- system time used by the process (current-time)
7727 time -- sum of utime and stime (current-time)
7728 cutime -- user time used by the process and its children (current-time)
7729 cstime -- system time used by the process and its children (current-time)
7730 ctime -- sum of cutime and cstime (current-time)
7731 pri -- priority of the process (number)
7732 nice -- nice value of the process (number)
7733 thcount -- process thread count (number)
7734 start -- time the process started (current-time)
7735 vsize -- virtual memory size of the process in KB's (number)
7736 rss -- resident set size of the process in KB's (number)
7737 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7738 pcpu -- percents of CPU time used by the process (floating-point number)
7739 pmem -- percents of total physical memory used by process's resident set
7740 (floating-point number)
7741 args -- command line which invoked the process (string). */)
7742 ( Lisp_Object pid)
7744 return system_process_attributes (pid);
7747 #ifdef subprocesses
7748 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7749 Invoke this after init_process_emacs, and after glib and/or GNUstep
7750 futz with the SIGCHLD handler, but before Emacs forks any children.
7751 This function's caller should block SIGCHLD. */
7753 void
7754 catch_child_signal (void)
7756 struct sigaction action, old_action;
7757 sigset_t oldset;
7758 emacs_sigaction_init (&action, deliver_child_signal);
7759 block_child_signal (&oldset);
7760 sigaction (SIGCHLD, &action, &old_action);
7761 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7762 || ! (old_action.sa_flags & SA_SIGINFO));
7764 if (old_action.sa_handler != deliver_child_signal)
7765 lib_child_handler
7766 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7767 ? dummy_handler
7768 : old_action.sa_handler);
7769 unblock_child_signal (&oldset);
7771 #endif /* subprocesses */
7773 /* Limit the number of open files to the value it had at startup. */
7775 void
7776 restore_nofile_limit (void)
7778 #ifdef HAVE_SETRLIMIT
7779 if (FD_SETSIZE < nofile_limit.rlim_cur)
7780 setrlimit (RLIMIT_NOFILE, &nofile_limit);
7781 #endif
7785 /* This is not called "init_process" because that is the name of a
7786 Mach system call, so it would cause problems on Darwin systems. */
7787 void
7788 init_process_emacs (int sockfd)
7790 #ifdef subprocesses
7791 int i;
7793 inhibit_sentinels = 0;
7795 #ifndef CANNOT_DUMP
7796 if (! noninteractive || initialized)
7797 #endif
7799 #if defined HAVE_GLIB && !defined WINDOWSNT
7800 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7801 this should always fail, but is enough to initialize glib's
7802 private SIGCHLD handler, allowing catch_child_signal to copy
7803 it into lib_child_handler. */
7804 g_source_unref (g_child_watch_source_new (getpid ()));
7805 #endif
7806 catch_child_signal ();
7809 #ifdef HAVE_SETRLIMIT
7810 /* Don't allocate more than FD_SETSIZE file descriptors for Emacs itself. */
7811 if (getrlimit (RLIMIT_NOFILE, &nofile_limit) != 0)
7812 nofile_limit.rlim_cur = 0;
7813 else if (FD_SETSIZE < nofile_limit.rlim_cur)
7815 struct rlimit rlim = nofile_limit;
7816 rlim.rlim_cur = FD_SETSIZE;
7817 if (setrlimit (RLIMIT_NOFILE, &rlim) != 0)
7818 nofile_limit.rlim_cur = 0;
7820 #endif
7822 FD_ZERO (&input_wait_mask);
7823 FD_ZERO (&non_keyboard_wait_mask);
7824 FD_ZERO (&non_process_wait_mask);
7825 FD_ZERO (&write_mask);
7826 max_process_desc = max_input_desc = -1;
7827 external_sock_fd = sockfd;
7828 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7830 FD_ZERO (&connect_wait_mask);
7831 num_pending_connects = 0;
7833 process_output_delay_count = 0;
7834 process_output_skip = 0;
7836 /* Don't do this, it caused infinite select loops. The display
7837 method should call add_keyboard_wait_descriptor on stdin if it
7838 needs that. */
7839 #if 0
7840 FD_SET (0, &input_wait_mask);
7841 #endif
7843 Vprocess_alist = Qnil;
7844 deleted_pid_list = Qnil;
7845 for (i = 0; i < FD_SETSIZE; i++)
7847 chan_process[i] = Qnil;
7848 proc_buffered_char[i] = -1;
7850 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7851 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7852 #ifdef DATAGRAM_SOCKETS
7853 memset (datagram_address, 0, sizeof datagram_address);
7854 #endif
7856 #if defined (DARWIN_OS)
7857 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7858 processes. As such, we only change the default value. */
7859 if (initialized)
7861 char const *release = (STRINGP (Voperating_system_release)
7862 ? SSDATA (Voperating_system_release)
7863 : 0);
7864 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7865 Vprocess_connection_type = Qnil;
7868 #endif
7869 #endif /* subprocesses */
7870 kbd_is_on_hold = 0;
7873 void
7874 syms_of_process (void)
7876 #ifdef subprocesses
7878 DEFSYM (Qprocessp, "processp");
7879 DEFSYM (Qrun, "run");
7880 DEFSYM (Qstop, "stop");
7881 DEFSYM (Qsignal, "signal");
7883 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7884 here again. */
7886 DEFSYM (Qopen, "open");
7887 DEFSYM (Qclosed, "closed");
7888 DEFSYM (Qconnect, "connect");
7889 DEFSYM (Qfailed, "failed");
7890 DEFSYM (Qlisten, "listen");
7891 DEFSYM (Qlocal, "local");
7892 DEFSYM (Qipv4, "ipv4");
7893 #ifdef AF_INET6
7894 DEFSYM (Qipv6, "ipv6");
7895 #endif
7896 DEFSYM (Qdatagram, "datagram");
7897 DEFSYM (Qseqpacket, "seqpacket");
7899 DEFSYM (QCport, ":port");
7900 DEFSYM (QCspeed, ":speed");
7901 DEFSYM (QCprocess, ":process");
7903 DEFSYM (QCbytesize, ":bytesize");
7904 DEFSYM (QCstopbits, ":stopbits");
7905 DEFSYM (QCparity, ":parity");
7906 DEFSYM (Qodd, "odd");
7907 DEFSYM (Qeven, "even");
7908 DEFSYM (QCflowcontrol, ":flowcontrol");
7909 DEFSYM (Qhw, "hw");
7910 DEFSYM (Qsw, "sw");
7911 DEFSYM (QCsummary, ":summary");
7913 DEFSYM (Qreal, "real");
7914 DEFSYM (Qnetwork, "network");
7915 DEFSYM (Qserial, "serial");
7916 DEFSYM (Qpipe, "pipe");
7917 DEFSYM (QCbuffer, ":buffer");
7918 DEFSYM (QChost, ":host");
7919 DEFSYM (QCservice, ":service");
7920 DEFSYM (QClocal, ":local");
7921 DEFSYM (QCremote, ":remote");
7922 DEFSYM (QCcoding, ":coding");
7923 DEFSYM (QCserver, ":server");
7924 DEFSYM (QCnowait, ":nowait");
7925 DEFSYM (QCsentinel, ":sentinel");
7926 DEFSYM (QCuse_external_socket, ":use-external-socket");
7927 DEFSYM (QCtls_parameters, ":tls-parameters");
7928 DEFSYM (Qnsm_verify_connection, "nsm-verify-connection");
7929 DEFSYM (QClog, ":log");
7930 DEFSYM (QCnoquery, ":noquery");
7931 DEFSYM (QCstop, ":stop");
7932 DEFSYM (QCplist, ":plist");
7933 DEFSYM (QCcommand, ":command");
7934 DEFSYM (QCconnection_type, ":connection-type");
7935 DEFSYM (QCstderr, ":stderr");
7936 DEFSYM (Qpty, "pty");
7937 DEFSYM (Qpipe, "pipe");
7939 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7941 staticpro (&Vprocess_alist);
7942 staticpro (&deleted_pid_list);
7944 #endif /* subprocesses */
7946 DEFSYM (QCname, ":name");
7947 DEFSYM (QCtype, ":type");
7949 DEFSYM (Qeuid, "euid");
7950 DEFSYM (Qegid, "egid");
7951 DEFSYM (Quser, "user");
7952 DEFSYM (Qgroup, "group");
7953 DEFSYM (Qcomm, "comm");
7954 DEFSYM (Qstate, "state");
7955 DEFSYM (Qppid, "ppid");
7956 DEFSYM (Qpgrp, "pgrp");
7957 DEFSYM (Qsess, "sess");
7958 DEFSYM (Qttname, "ttname");
7959 DEFSYM (Qtpgid, "tpgid");
7960 DEFSYM (Qminflt, "minflt");
7961 DEFSYM (Qmajflt, "majflt");
7962 DEFSYM (Qcminflt, "cminflt");
7963 DEFSYM (Qcmajflt, "cmajflt");
7964 DEFSYM (Qutime, "utime");
7965 DEFSYM (Qstime, "stime");
7966 DEFSYM (Qtime, "time");
7967 DEFSYM (Qcutime, "cutime");
7968 DEFSYM (Qcstime, "cstime");
7969 DEFSYM (Qctime, "ctime");
7970 #ifdef subprocesses
7971 DEFSYM (Qinternal_default_process_sentinel,
7972 "internal-default-process-sentinel");
7973 DEFSYM (Qinternal_default_process_filter,
7974 "internal-default-process-filter");
7975 #endif
7976 DEFSYM (Qpri, "pri");
7977 DEFSYM (Qnice, "nice");
7978 DEFSYM (Qthcount, "thcount");
7979 DEFSYM (Qstart, "start");
7980 DEFSYM (Qvsize, "vsize");
7981 DEFSYM (Qrss, "rss");
7982 DEFSYM (Qetime, "etime");
7983 DEFSYM (Qpcpu, "pcpu");
7984 DEFSYM (Qpmem, "pmem");
7985 DEFSYM (Qargs, "args");
7987 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7988 doc: /* Non-nil means delete processes immediately when they exit.
7989 A value of nil means don't delete them until `list-processes' is run. */);
7991 delete_exited_processes = 1;
7993 #ifdef subprocesses
7994 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7995 doc: /* Control type of device used to communicate with subprocesses.
7996 Values are nil to use a pipe, or t or `pty' to use a pty.
7997 The value has no effect if the system has no ptys or if all ptys are busy:
7998 then a pipe is used in any case.
7999 The value takes effect when `start-process' is called. */);
8000 Vprocess_connection_type = Qt;
8002 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
8003 doc: /* If non-nil, improve receive buffering by delaying after short reads.
8004 On some systems, when Emacs reads the output from a subprocess, the output data
8005 is read in very small blocks, potentially resulting in very poor performance.
8006 This behavior can be remedied to some extent by setting this variable to a
8007 non-nil value, as it will automatically delay reading from such processes, to
8008 allow them to produce more output before Emacs tries to read it.
8009 If the value is t, the delay is reset after each write to the process; any other
8010 non-nil value means that the delay is not reset on write.
8011 The variable takes effect when `start-process' is called. */);
8012 Vprocess_adaptive_read_buffering = Qt;
8014 defsubr (&Sprocessp);
8015 defsubr (&Sget_process);
8016 defsubr (&Sdelete_process);
8017 defsubr (&Sprocess_status);
8018 defsubr (&Sprocess_exit_status);
8019 defsubr (&Sprocess_id);
8020 defsubr (&Sprocess_name);
8021 defsubr (&Sprocess_tty_name);
8022 defsubr (&Sprocess_command);
8023 defsubr (&Sset_process_buffer);
8024 defsubr (&Sprocess_buffer);
8025 defsubr (&Sprocess_mark);
8026 defsubr (&Sset_process_filter);
8027 defsubr (&Sprocess_filter);
8028 defsubr (&Sset_process_sentinel);
8029 defsubr (&Sprocess_sentinel);
8030 defsubr (&Sset_process_window_size);
8031 defsubr (&Sset_process_inherit_coding_system_flag);
8032 defsubr (&Sset_process_query_on_exit_flag);
8033 defsubr (&Sprocess_query_on_exit_flag);
8034 defsubr (&Sprocess_contact);
8035 defsubr (&Sprocess_plist);
8036 defsubr (&Sset_process_plist);
8037 defsubr (&Sprocess_list);
8038 defsubr (&Smake_process);
8039 defsubr (&Smake_pipe_process);
8040 defsubr (&Sserial_process_configure);
8041 defsubr (&Smake_serial_process);
8042 defsubr (&Sset_network_process_option);
8043 defsubr (&Smake_network_process);
8044 defsubr (&Sformat_network_address);
8045 defsubr (&Snetwork_interface_list);
8046 defsubr (&Snetwork_interface_info);
8047 #ifdef DATAGRAM_SOCKETS
8048 defsubr (&Sprocess_datagram_address);
8049 defsubr (&Sset_process_datagram_address);
8050 #endif
8051 defsubr (&Saccept_process_output);
8052 defsubr (&Sprocess_send_region);
8053 defsubr (&Sprocess_send_string);
8054 defsubr (&Sinterrupt_process);
8055 defsubr (&Skill_process);
8056 defsubr (&Squit_process);
8057 defsubr (&Sstop_process);
8058 defsubr (&Scontinue_process);
8059 defsubr (&Sprocess_running_child_p);
8060 defsubr (&Sprocess_send_eof);
8061 defsubr (&Ssignal_process);
8062 defsubr (&Swaiting_for_user_input_p);
8063 defsubr (&Sprocess_type);
8064 defsubr (&Sinternal_default_process_sentinel);
8065 defsubr (&Sinternal_default_process_filter);
8066 defsubr (&Sset_process_coding_system);
8067 defsubr (&Sprocess_coding_system);
8068 defsubr (&Sset_process_filter_multibyte);
8069 defsubr (&Sprocess_filter_multibyte_p);
8072 Lisp_Object subfeatures = Qnil;
8073 const struct socket_options *sopt;
8075 #define ADD_SUBFEATURE(key, val) \
8076 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
8078 ADD_SUBFEATURE (QCnowait, Qt);
8079 #ifdef DATAGRAM_SOCKETS
8080 ADD_SUBFEATURE (QCtype, Qdatagram);
8081 #endif
8082 #ifdef HAVE_SEQPACKET
8083 ADD_SUBFEATURE (QCtype, Qseqpacket);
8084 #endif
8085 #ifdef HAVE_LOCAL_SOCKETS
8086 ADD_SUBFEATURE (QCfamily, Qlocal);
8087 #endif
8088 ADD_SUBFEATURE (QCfamily, Qipv4);
8089 #ifdef AF_INET6
8090 ADD_SUBFEATURE (QCfamily, Qipv6);
8091 #endif
8092 #ifdef HAVE_GETSOCKNAME
8093 ADD_SUBFEATURE (QCservice, Qt);
8094 #endif
8095 ADD_SUBFEATURE (QCserver, Qt);
8097 for (sopt = socket_options; sopt->name; sopt++)
8098 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
8100 Fprovide (intern_c_string ("make-network-process"), subfeatures);
8103 #endif /* subprocesses */
8105 defsubr (&Sget_buffer_process);
8106 defsubr (&Sprocess_inherit_coding_system_flag);
8107 defsubr (&Slist_system_processes);
8108 defsubr (&Sprocess_attributes);