Support debug declarations in pcase macros
[emacs.git] / src / process.c
blob3ffbbec544b6b86972379aaed02ccf0c0dea81ca
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2015 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
27 #include <sys/file.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30 #include <fcntl.h>
32 #include "lisp.h"
34 /* Only MS-DOS does not define `subprocesses'. */
35 #ifdef subprocesses
37 #include <sys/socket.h>
38 #include <netdb.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
42 /* Are local (unix) sockets supported? */
43 #if defined (HAVE_SYS_UN_H)
44 #if !defined (AF_LOCAL) && defined (AF_UNIX)
45 #define AF_LOCAL AF_UNIX
46 #endif
47 #ifdef AF_LOCAL
48 #define HAVE_LOCAL_SOCKETS
49 #include <sys/un.h>
50 #endif
51 #endif
53 #include <sys/ioctl.h>
54 #if defined (HAVE_NET_IF_H)
55 #include <net/if.h>
56 #endif /* HAVE_NET_IF_H */
58 #if defined (HAVE_IFADDRS_H)
59 /* Must be after net/if.h */
60 #include <ifaddrs.h>
62 /* We only use structs from this header when we use getifaddrs. */
63 #if defined (HAVE_NET_IF_DL_H)
64 #include <net/if_dl.h>
65 #endif
67 #endif
69 #ifdef NEED_BSDTTY
70 #include <bsdtty.h>
71 #endif
73 #ifdef USG5_4
74 # include <sys/stream.h>
75 # include <sys/stropts.h>
76 #endif
78 #ifdef HAVE_RES_INIT
79 #include <arpa/nameser.h>
80 #include <resolv.h>
81 #endif
83 #ifdef HAVE_UTIL_H
84 #include <util.h>
85 #endif
87 #ifdef HAVE_PTY_H
88 #include <pty.h>
89 #endif
91 #include <c-ctype.h>
92 #include <sig2str.h>
93 #include <verify.h>
95 #endif /* subprocesses */
97 #include "systime.h"
98 #include "systty.h"
100 #include "window.h"
101 #include "character.h"
102 #include "buffer.h"
103 #include "coding.h"
104 #include "process.h"
105 #include "frame.h"
106 #include "termhooks.h"
107 #include "termopts.h"
108 #include "commands.h"
109 #include "keyboard.h"
110 #include "blockinput.h"
111 #include "dispextern.h"
112 #include "composite.h"
113 #include "atimer.h"
114 #include "sysselect.h"
115 #include "syssignal.h"
116 #include "syswait.h"
117 #ifdef HAVE_GNUTLS
118 #include "gnutls.h"
119 #endif
121 #ifdef HAVE_WINDOW_SYSTEM
122 #include TERM_HEADER
123 #endif /* HAVE_WINDOW_SYSTEM */
125 #ifdef HAVE_GLIB
126 #include "xgselect.h"
127 #ifndef WINDOWSNT
128 #include <glib.h>
129 #endif
130 #endif
132 #ifdef WINDOWSNT
133 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
134 struct timespec *, void *);
135 #endif
137 /* Work around GCC 4.7.0 bug with strict overflow checking; see
138 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
139 These lines can be removed once the GCC bug is fixed. */
140 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
141 # pragma GCC diagnostic ignored "-Wstrict-overflow"
142 #endif
144 /* True if keyboard input is on hold, zero otherwise. */
146 static bool kbd_is_on_hold;
148 /* Nonzero means don't run process sentinels. This is used
149 when exiting. */
150 bool inhibit_sentinels;
152 #ifdef subprocesses
154 #ifndef SOCK_CLOEXEC
155 # define SOCK_CLOEXEC 0
156 #endif
158 #ifndef HAVE_ACCEPT4
160 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
162 static int
163 close_on_exec (int fd)
165 if (0 <= fd)
166 fcntl (fd, F_SETFD, FD_CLOEXEC);
167 return fd;
170 # undef accept4
171 # define accept4(sockfd, addr, addrlen, flags) \
172 process_accept4 (sockfd, addr, addrlen, flags)
173 static int
174 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
176 return close_on_exec (accept (sockfd, addr, addrlen));
179 static int
180 process_socket (int domain, int type, int protocol)
182 return close_on_exec (socket (domain, type, protocol));
184 # undef socket
185 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
186 #endif
188 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
189 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
190 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
191 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
192 #define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
193 #define PIPECONN1_P(p) (EQ (p->type, Qpipe))
195 /* Number of events of change of status of a process. */
196 static EMACS_INT process_tick;
197 /* Number of events for which the user or sentinel has been notified. */
198 static EMACS_INT update_tick;
200 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects.
201 The code can be simplified by assuming NON_BLOCKING_CONNECT once
202 Emacs starts assuming POSIX 1003.1-2001 or later. */
204 #if (defined HAVE_SELECT \
205 && (defined GNU_LINUX || defined HAVE_GETPEERNAME) \
206 && (defined EWOULDBLOCK || defined EINPROGRESS))
207 # define NON_BLOCKING_CONNECT
208 #endif
210 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
211 this system. We need to read full packets, so we need a
212 "non-destructive" select. So we require either native select,
213 or emulation of select using FIONREAD. */
215 #ifndef BROKEN_DATAGRAM_SOCKETS
216 # if defined HAVE_SELECT || defined USABLE_FIONREAD
217 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
218 # define DATAGRAM_SOCKETS
219 # endif
220 # endif
221 #endif
223 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
224 # define HAVE_SEQPACKET
225 #endif
227 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
228 #define ADAPTIVE_READ_BUFFERING
229 #endif
231 #ifdef ADAPTIVE_READ_BUFFERING
232 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
233 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
234 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
236 /* Number of processes which have a non-zero read_output_delay,
237 and therefore might be delayed for adaptive read buffering. */
239 static int process_output_delay_count;
241 /* True if any process has non-nil read_output_skip. */
243 static bool process_output_skip;
245 #else
246 #define process_output_delay_count 0
247 #endif
249 static void create_process (Lisp_Object, char **, Lisp_Object);
250 #ifdef USABLE_SIGIO
251 static bool keyboard_bit_set (fd_set *);
252 #endif
253 static void deactivate_process (Lisp_Object);
254 static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
255 static int read_process_output (Lisp_Object, int);
256 static void handle_child_signal (int);
257 static void create_pty (Lisp_Object);
259 static Lisp_Object get_process (register Lisp_Object name);
260 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
262 /* Mask of bits indicating the descriptors that we wait for input on. */
264 static fd_set input_wait_mask;
266 /* Mask that excludes keyboard input descriptor(s). */
268 static fd_set non_keyboard_wait_mask;
270 /* Mask that excludes process input descriptor(s). */
272 static fd_set non_process_wait_mask;
274 /* Mask for selecting for write. */
276 static fd_set write_mask;
278 #ifdef NON_BLOCKING_CONNECT
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;
287 #endif /* NON_BLOCKING_CONNECT */
289 /* The largest descriptor currently in use for a process object; -1 if none. */
290 static int max_process_desc;
292 /* The largest descriptor currently in use for input; -1 if none. */
293 static int max_input_desc;
295 /* Indexed by descriptor, gives the process (if any) for that descriptor. */
296 static Lisp_Object chan_process[FD_SETSIZE];
298 /* Alist of elements (NAME . PROCESS). */
299 static Lisp_Object Vprocess_alist;
301 /* Buffered-ahead input char from process, indexed by channel.
302 -1 means empty (no char is buffered).
303 Used on sys V where the only way to tell if there is any
304 output from the process is to read at least one char.
305 Always -1 on systems that support FIONREAD. */
307 static int proc_buffered_char[FD_SETSIZE];
309 /* Table of `struct coding-system' for each process. */
310 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
311 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
313 #ifdef DATAGRAM_SOCKETS
314 /* Table of `partner address' for datagram sockets. */
315 static struct sockaddr_and_len {
316 struct sockaddr *sa;
317 int len;
318 } datagram_address[FD_SETSIZE];
319 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
320 #define DATAGRAM_CONN_P(proc) \
321 (PROCESSP (proc) && \
322 XPROCESS (proc)->infd >= 0 && \
323 datagram_address[XPROCESS (proc)->infd].sa != 0)
324 #else
325 #define DATAGRAM_CHAN_P(chan) (0)
326 #define DATAGRAM_CONN_P(proc) (0)
327 #endif
329 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
330 a `for' loop which iterates over processes from Vprocess_alist. */
332 #define FOR_EACH_PROCESS(list_var, proc_var) \
333 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
335 /* These setters are used only in this file, so they can be private. */
336 static void
337 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
339 p->buffer = val;
341 static void
342 pset_command (struct Lisp_Process *p, Lisp_Object val)
344 p->command = val;
346 static void
347 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
349 p->decode_coding_system = val;
351 static void
352 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
354 p->decoding_buf = val;
356 static void
357 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
359 p->encode_coding_system = val;
361 static void
362 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
364 p->encoding_buf = val;
366 static void
367 pset_filter (struct Lisp_Process *p, Lisp_Object val)
369 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
371 static void
372 pset_log (struct Lisp_Process *p, Lisp_Object val)
374 p->log = val;
376 static void
377 pset_mark (struct Lisp_Process *p, Lisp_Object val)
379 p->mark = val;
381 static void
382 pset_name (struct Lisp_Process *p, Lisp_Object val)
384 p->name = val;
386 static void
387 pset_plist (struct Lisp_Process *p, Lisp_Object val)
389 p->plist = val;
391 static void
392 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
394 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
396 static void
397 pset_status (struct Lisp_Process *p, Lisp_Object val)
399 p->status = 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 /* Given a status-list, extract the three pieces of information
546 and store them individually through the three pointers. */
548 static void
549 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
551 Lisp_Object tem;
553 if (SYMBOLP (l))
555 *symbol = l;
556 *code = 0;
557 *coredump = 0;
559 else
561 *symbol = XCAR (l);
562 tem = XCDR (l);
563 *code = XFASTINT (XCAR (tem));
564 tem = XCDR (tem);
565 *coredump = !NILP (tem);
569 /* Return a string describing a process status list. */
571 static Lisp_Object
572 status_message (struct Lisp_Process *p)
574 Lisp_Object status = p->status;
575 Lisp_Object symbol;
576 int code;
577 bool coredump;
578 Lisp_Object string;
580 decode_status (status, &symbol, &code, &coredump);
582 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
584 char const *signame;
585 synchronize_system_messages_locale ();
586 signame = strsignal (code);
587 if (signame == 0)
588 string = build_string ("unknown");
589 else
591 int c1, c2;
593 string = build_unibyte_string (signame);
594 if (! NILP (Vlocale_coding_system))
595 string = (code_convert_string_norecord
596 (string, Vlocale_coding_system, 0));
597 c1 = STRING_CHAR (SDATA (string));
598 c2 = downcase (c1);
599 if (c1 != c2)
600 Faset (string, make_number (0), make_number (c2));
602 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
603 return concat2 (string, suffix);
605 else if (EQ (symbol, Qexit))
607 if (NETCONN1_P (p))
608 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
609 if (code == 0)
610 return build_string ("finished\n");
611 AUTO_STRING (prefix, "exited abnormally with code ");
612 string = Fnumber_to_string (make_number (code));
613 AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
614 return concat3 (prefix, string, suffix);
616 else if (EQ (symbol, Qfailed))
618 AUTO_STRING (prefix, "failed with code ");
619 string = Fnumber_to_string (make_number (code));
620 AUTO_STRING (suffix, "\n");
621 return concat3 (prefix, string, suffix);
623 else
624 return Fcopy_sequence (Fsymbol_name (symbol));
627 enum { PTY_NAME_SIZE = 24 };
629 /* Open an available pty, returning a file descriptor.
630 Store into PTY_NAME the file name of the terminal corresponding to the pty.
631 Return -1 on failure. */
633 static int
634 allocate_pty (char pty_name[PTY_NAME_SIZE])
636 #ifdef HAVE_PTYS
637 int fd;
639 #ifdef PTY_ITERATION
640 PTY_ITERATION
641 #else
642 register int c, i;
643 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
644 for (i = 0; i < 16; i++)
645 #endif
647 #ifdef PTY_NAME_SPRINTF
648 PTY_NAME_SPRINTF
649 #else
650 sprintf (pty_name, "/dev/pty%c%x", c, i);
651 #endif /* no PTY_NAME_SPRINTF */
653 #ifdef PTY_OPEN
654 PTY_OPEN;
655 #else /* no PTY_OPEN */
656 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
657 #endif /* no PTY_OPEN */
659 if (fd >= 0)
661 #ifdef PTY_OPEN
662 /* Set FD's close-on-exec flag. This is needed even if
663 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
664 doesn't require support for that combination.
665 Multithreaded platforms where posix_openpt ignores
666 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
667 have a race condition between the PTY_OPEN and here. */
668 fcntl (fd, F_SETFD, FD_CLOEXEC);
669 #endif
670 /* Check to make certain that both sides are available
671 this avoids a nasty yet stupid bug in rlogins. */
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 */
677 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
679 emacs_close (fd);
680 # ifndef __sgi
681 continue;
682 # else
683 return -1;
684 # endif /* __sgi */
686 setup_pty (fd);
687 return fd;
690 #endif /* HAVE_PTYS */
691 return -1;
694 /* Allocate basically initialized process. */
696 static struct Lisp_Process *
697 allocate_process (void)
699 return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
702 static Lisp_Object
703 make_process (Lisp_Object name)
705 register Lisp_Object val, tem, name1;
706 register struct Lisp_Process *p;
707 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
708 printmax_t i;
710 p = allocate_process ();
711 /* Initialize Lisp data. Note that allocate_process initializes all
712 Lisp data to nil, so do it only for slots which should not be nil. */
713 pset_status (p, Qrun);
714 pset_mark (p, Fmake_marker ());
716 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
717 non-Lisp data, so do it only for slots which should not be zero. */
718 p->infd = -1;
719 p->outfd = -1;
720 for (i = 0; i < PROCESS_OPEN_FDS; i++)
721 p->open_fd[i] = -1;
723 #ifdef HAVE_GNUTLS
724 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
725 #endif
727 /* If name is already in use, modify it until it is unused. */
729 name1 = name;
730 for (i = 1; ; i++)
732 tem = Fget_process (name1);
733 if (NILP (tem)) break;
734 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
736 name = name1;
737 pset_name (p, name);
738 pset_sentinel (p, Qinternal_default_process_sentinel);
739 pset_filter (p, Qinternal_default_process_filter);
740 XSETPROCESS (val, p);
741 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
742 return val;
745 static void
746 remove_process (register Lisp_Object proc)
748 register Lisp_Object pair;
750 pair = Frassq (proc, Vprocess_alist);
751 Vprocess_alist = Fdelq (pair, Vprocess_alist);
753 deactivate_process (proc);
757 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
758 doc: /* Return t if OBJECT is a process. */)
759 (Lisp_Object object)
761 return PROCESSP (object) ? Qt : Qnil;
764 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
765 doc: /* Return the process named NAME, or nil if there is none. */)
766 (register Lisp_Object name)
768 if (PROCESSP (name))
769 return name;
770 CHECK_STRING (name);
771 return Fcdr (Fassoc (name, Vprocess_alist));
774 /* This is how commands for the user decode process arguments. It
775 accepts a process, a process name, a buffer, a buffer name, or nil.
776 Buffers denote the first process in the buffer, and nil denotes the
777 current buffer. */
779 static Lisp_Object
780 get_process (register Lisp_Object name)
782 register Lisp_Object proc, obj;
783 if (STRINGP (name))
785 obj = Fget_process (name);
786 if (NILP (obj))
787 obj = Fget_buffer (name);
788 if (NILP (obj))
789 error ("Process %s does not exist", SDATA (name));
791 else if (NILP (name))
792 obj = Fcurrent_buffer ();
793 else
794 obj = name;
796 /* Now obj should be either a buffer object or a process object. */
797 if (BUFFERP (obj))
799 if (NILP (BVAR (XBUFFER (obj), name)))
800 error ("Attempt to get process for a dead buffer");
801 proc = Fget_buffer_process (obj);
802 if (NILP (proc))
803 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
805 else
807 CHECK_PROCESS (obj);
808 proc = obj;
810 return proc;
814 /* Fdelete_process promises to immediately forget about the process, but in
815 reality, Emacs needs to remember those processes until they have been
816 treated by the SIGCHLD handler and waitpid has been invoked on them;
817 otherwise they might fill up the kernel's process table.
819 Some processes created by call-process are also put onto this list.
821 Members of this list are (process-ID . filename) pairs. The
822 process-ID is a number; the filename, if a string, is a file that
823 needs to be removed after the process exits. */
824 static Lisp_Object deleted_pid_list;
826 void
827 record_deleted_pid (pid_t pid, Lisp_Object filename)
829 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
830 /* GC treated elements set to nil. */
831 Fdelq (Qnil, deleted_pid_list));
835 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
836 doc: /* Delete PROCESS: kill it and forget about it immediately.
837 PROCESS may be a process, a buffer, the name of a process or buffer, or
838 nil, indicating the current buffer's process. */)
839 (register Lisp_Object process)
841 register struct Lisp_Process *p;
843 process = get_process (process);
844 p = XPROCESS (process);
846 p->raw_status_new = 0;
847 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
849 pset_status (p, list2 (Qexit, make_number (0)));
850 p->tick = ++process_tick;
851 status_notify (p, NULL);
852 redisplay_preserve_echo_area (13);
854 else
856 if (p->alive)
857 record_kill_process (p, Qnil);
859 if (p->infd >= 0)
861 /* Update P's status, since record_kill_process will make the
862 SIGCHLD handler update deleted_pid_list, not *P. */
863 Lisp_Object symbol;
864 if (p->raw_status_new)
865 update_status (p);
866 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
867 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
868 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
870 p->tick = ++process_tick;
871 status_notify (p, NULL);
872 redisplay_preserve_echo_area (13);
875 remove_process (process);
876 return Qnil;
879 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
880 doc: /* Return the status of PROCESS.
881 The returned value is one of the following symbols:
882 run -- for a process that is running.
883 stop -- for a process stopped but continuable.
884 exit -- for a process that has exited.
885 signal -- for a process that has got a fatal signal.
886 open -- for a network stream connection that is open.
887 listen -- for a network stream server that is listening.
888 closed -- for a network stream connection that is closed.
889 connect -- when waiting for a non-blocking connection to complete.
890 failed -- when a non-blocking connection has failed.
891 nil -- if arg is a process name and no such process exists.
892 PROCESS may be a process, a buffer, the name of a process, or
893 nil, indicating the current buffer's process. */)
894 (register Lisp_Object process)
896 register struct Lisp_Process *p;
897 register Lisp_Object status;
899 if (STRINGP (process))
900 process = Fget_process (process);
901 else
902 process = get_process (process);
904 if (NILP (process))
905 return process;
907 p = XPROCESS (process);
908 if (p->raw_status_new)
909 update_status (p);
910 status = p->status;
911 if (CONSP (status))
912 status = XCAR (status);
913 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
915 if (EQ (status, Qexit))
916 status = Qclosed;
917 else if (EQ (p->command, Qt))
918 status = Qstop;
919 else if (EQ (status, Qrun))
920 status = Qopen;
922 return status;
925 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
926 1, 1, 0,
927 doc: /* Return the exit status of PROCESS or the signal number that killed it.
928 If PROCESS has not yet exited or died, return 0. */)
929 (register Lisp_Object process)
931 CHECK_PROCESS (process);
932 if (XPROCESS (process)->raw_status_new)
933 update_status (XPROCESS (process));
934 if (CONSP (XPROCESS (process)->status))
935 return XCAR (XCDR (XPROCESS (process)->status));
936 return make_number (0);
939 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
940 doc: /* Return the process id of PROCESS.
941 This is the pid of the external process which PROCESS uses or talks to.
942 For a network connection, this value is nil. */)
943 (register Lisp_Object process)
945 pid_t pid;
947 CHECK_PROCESS (process);
948 pid = XPROCESS (process)->pid;
949 return (pid ? make_fixnum_or_float (pid) : Qnil);
952 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
953 doc: /* Return the name of PROCESS, as a string.
954 This is the name of the program invoked in PROCESS,
955 possibly modified to make it unique among process names. */)
956 (register Lisp_Object process)
958 CHECK_PROCESS (process);
959 return XPROCESS (process)->name;
962 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
963 doc: /* Return the command that was executed to start PROCESS.
964 This is a list of strings, the first string being the program executed
965 and the rest of the strings being the arguments given to it.
966 For a network or serial process, this is nil (process is running) or t
967 \(process is stopped). */)
968 (register Lisp_Object process)
970 CHECK_PROCESS (process);
971 return XPROCESS (process)->command;
974 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
975 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
976 This is the terminal that the process itself reads and writes on,
977 not the name of the pty that Emacs uses to talk with that terminal. */)
978 (register Lisp_Object process)
980 CHECK_PROCESS (process);
981 return XPROCESS (process)->tty_name;
984 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
985 2, 2, 0,
986 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
987 Return BUFFER. */)
988 (register Lisp_Object process, Lisp_Object buffer)
990 struct Lisp_Process *p;
992 CHECK_PROCESS (process);
993 if (!NILP (buffer))
994 CHECK_BUFFER (buffer);
995 p = XPROCESS (process);
996 pset_buffer (p, buffer);
997 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
998 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
999 setup_process_coding_systems (process);
1000 return buffer;
1003 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1004 1, 1, 0,
1005 doc: /* Return the buffer PROCESS is associated with.
1006 The default process filter inserts output from PROCESS into this buffer. */)
1007 (register Lisp_Object process)
1009 CHECK_PROCESS (process);
1010 return XPROCESS (process)->buffer;
1013 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1014 1, 1, 0,
1015 doc: /* Return the marker for the end of the last output from PROCESS. */)
1016 (register Lisp_Object process)
1018 CHECK_PROCESS (process);
1019 return XPROCESS (process)->mark;
1022 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1023 2, 2, 0,
1024 doc: /* Give PROCESS the filter function FILTER; nil means default.
1025 A value of t means stop accepting output from the process.
1027 When a process has a non-default filter, its buffer is not used for output.
1028 Instead, each time it does output, the entire string of output is
1029 passed to the filter.
1031 The filter gets two arguments: the process and the string of output.
1032 The string argument is normally a multibyte string, except:
1033 - if the process's input coding system is no-conversion or raw-text,
1034 it is a unibyte string (the non-converted input), or else
1035 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1036 string (the result of converting the decoded input multibyte
1037 string to unibyte with `string-make-unibyte'). */)
1038 (register Lisp_Object process, Lisp_Object filter)
1040 struct Lisp_Process *p;
1042 CHECK_PROCESS (process);
1043 p = XPROCESS (process);
1045 /* Don't signal an error if the process's input file descriptor
1046 is closed. This could make debugging Lisp more difficult,
1047 for example when doing something like
1049 (setq process (start-process ...))
1050 (debug)
1051 (set-process-filter process ...) */
1053 if (NILP (filter))
1054 filter = Qinternal_default_process_filter;
1056 if (p->infd >= 0)
1058 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1060 FD_CLR (p->infd, &input_wait_mask);
1061 FD_CLR (p->infd, &non_keyboard_wait_mask);
1063 else if (EQ (p->filter, Qt)
1064 /* Network or serial process not stopped: */
1065 && !EQ (p->command, Qt))
1067 FD_SET (p->infd, &input_wait_mask);
1068 FD_SET (p->infd, &non_keyboard_wait_mask);
1072 pset_filter (p, filter);
1073 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1074 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1075 setup_process_coding_systems (process);
1076 return filter;
1079 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1080 1, 1, 0,
1081 doc: /* Return the filter function of PROCESS.
1082 See `set-process-filter' for more info on filter functions. */)
1083 (register Lisp_Object process)
1085 CHECK_PROCESS (process);
1086 return XPROCESS (process)->filter;
1089 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1090 2, 2, 0,
1091 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1092 The sentinel is called as a function when the process changes state.
1093 It gets two arguments: the process, and a string describing the change. */)
1094 (register Lisp_Object process, Lisp_Object sentinel)
1096 struct Lisp_Process *p;
1098 CHECK_PROCESS (process);
1099 p = XPROCESS (process);
1101 if (NILP (sentinel))
1102 sentinel = Qinternal_default_process_sentinel;
1104 pset_sentinel (p, sentinel);
1105 if (NETCONN1_P (p) || SERIALCONN1_P (p) || PIPECONN1_P (p))
1106 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1107 return sentinel;
1110 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1111 1, 1, 0,
1112 doc: /* Return the sentinel of PROCESS.
1113 See `set-process-sentinel' for more info on sentinels. */)
1114 (register Lisp_Object process)
1116 CHECK_PROCESS (process);
1117 return XPROCESS (process)->sentinel;
1120 DEFUN ("set-process-window-size", Fset_process_window_size,
1121 Sset_process_window_size, 3, 3, 0,
1122 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1123 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1125 CHECK_PROCESS (process);
1127 /* All known platforms store window sizes as 'unsigned short'. */
1128 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1129 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1131 if (XPROCESS (process)->infd < 0
1132 || (set_window_size (XPROCESS (process)->infd,
1133 XINT (height), XINT (width))
1134 < 0))
1135 return Qnil;
1136 else
1137 return Qt;
1140 DEFUN ("set-process-inherit-coding-system-flag",
1141 Fset_process_inherit_coding_system_flag,
1142 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1143 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1144 If the second argument FLAG is non-nil, then the variable
1145 `buffer-file-coding-system' of the buffer associated with PROCESS
1146 will be bound to the value of the coding system used to decode
1147 the process output.
1149 This is useful when the coding system specified for the process buffer
1150 leaves either the character code conversion or the end-of-line conversion
1151 unspecified, or if the coding system used to decode the process output
1152 is more appropriate for saving the process buffer.
1154 Binding the variable `inherit-process-coding-system' to non-nil before
1155 starting the process is an alternative way of setting the inherit flag
1156 for the process which will run.
1158 This function returns FLAG. */)
1159 (register Lisp_Object process, Lisp_Object flag)
1161 CHECK_PROCESS (process);
1162 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1163 return flag;
1166 DEFUN ("set-process-query-on-exit-flag",
1167 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1168 2, 2, 0,
1169 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1170 If the second argument FLAG is non-nil, Emacs will query the user before
1171 exiting or killing a buffer if PROCESS is running. This function
1172 returns FLAG. */)
1173 (register Lisp_Object process, Lisp_Object flag)
1175 CHECK_PROCESS (process);
1176 XPROCESS (process)->kill_without_query = NILP (flag);
1177 return flag;
1180 DEFUN ("process-query-on-exit-flag",
1181 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1182 1, 1, 0,
1183 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1184 (register Lisp_Object process)
1186 CHECK_PROCESS (process);
1187 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1190 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1191 1, 2, 0,
1192 doc: /* Return the contact info of PROCESS; t for a real child.
1193 For a network or serial connection, the value depends on the optional
1194 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1195 SERVICE) for a network connection or (PORT SPEED) for a serial
1196 connection. If KEY is t, the complete contact information for the
1197 connection is returned, else the specific value for the keyword KEY is
1198 returned. See `make-network-process' or `make-serial-process' for a
1199 list of keywords. */)
1200 (register Lisp_Object process, Lisp_Object key)
1202 Lisp_Object contact;
1204 CHECK_PROCESS (process);
1205 contact = XPROCESS (process)->childp;
1207 #ifdef DATAGRAM_SOCKETS
1208 if (DATAGRAM_CONN_P (process)
1209 && (EQ (key, Qt) || EQ (key, QCremote)))
1210 contact = Fplist_put (contact, QCremote,
1211 Fprocess_datagram_address (process));
1212 #endif
1214 if ((!NETCONN_P (process) && !SERIALCONN_P (process) && !PIPECONN_P (process))
1215 || EQ (key, Qt))
1216 return contact;
1217 if (NILP (key) && NETCONN_P (process))
1218 return list2 (Fplist_get (contact, QChost),
1219 Fplist_get (contact, QCservice));
1220 if (NILP (key) && SERIALCONN_P (process))
1221 return list2 (Fplist_get (contact, QCport),
1222 Fplist_get (contact, QCspeed));
1223 /* FIXME: Return a meaningful value (e.g., the child end of the pipe)
1224 if the pipe process is useful for purposes other than receiving
1225 stderr. */
1226 if (NILP (key) && PIPECONN_P (process))
1227 return Qt;
1228 return Fplist_get (contact, key);
1231 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1232 1, 1, 0,
1233 doc: /* Return the plist of PROCESS. */)
1234 (register Lisp_Object process)
1236 CHECK_PROCESS (process);
1237 return XPROCESS (process)->plist;
1240 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1241 2, 2, 0,
1242 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1243 (register Lisp_Object process, Lisp_Object plist)
1245 CHECK_PROCESS (process);
1246 CHECK_LIST (plist);
1248 pset_plist (XPROCESS (process), plist);
1249 return plist;
1252 #if 0 /* Turned off because we don't currently record this info
1253 in the process. Perhaps add it. */
1254 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1255 doc: /* Return the connection type of PROCESS.
1256 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1257 a socket connection. */)
1258 (Lisp_Object process)
1260 return XPROCESS (process)->type;
1262 #endif
1264 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1265 doc: /* Return the connection type of PROCESS.
1266 The value is either the symbol `real', `network', or `serial'.
1267 PROCESS may be a process, a buffer, the name of a process or buffer, or
1268 nil, indicating the current buffer's process. */)
1269 (Lisp_Object process)
1271 Lisp_Object proc;
1272 proc = get_process (process);
1273 return XPROCESS (proc)->type;
1276 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1277 1, 2, 0,
1278 doc: /* Convert network ADDRESS from internal format to a string.
1279 A 4 or 5 element vector represents an IPv4 address (with port number).
1280 An 8 or 9 element vector represents an IPv6 address (with port number).
1281 If optional second argument OMIT-PORT is non-nil, don't include a port
1282 number in the string, even when present in ADDRESS.
1283 Returns nil if format of ADDRESS is invalid. */)
1284 (Lisp_Object address, Lisp_Object omit_port)
1286 if (NILP (address))
1287 return Qnil;
1289 if (STRINGP (address)) /* AF_LOCAL */
1290 return address;
1292 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1294 register struct Lisp_Vector *p = XVECTOR (address);
1295 ptrdiff_t size = p->header.size;
1296 Lisp_Object args[10];
1297 int nargs, i;
1298 char const *format;
1300 if (size == 4 || (size == 5 && !NILP (omit_port)))
1302 format = "%d.%d.%d.%d";
1303 nargs = 4;
1305 else if (size == 5)
1307 format = "%d.%d.%d.%d:%d";
1308 nargs = 5;
1310 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1312 format = "%x:%x:%x:%x:%x:%x:%x:%x";
1313 nargs = 8;
1315 else if (size == 9)
1317 format = "[%x:%x:%x:%x:%x:%x:%x:%x]:%d";
1318 nargs = 9;
1320 else
1321 return Qnil;
1323 AUTO_STRING (format_obj, format);
1324 args[0] = format_obj;
1326 for (i = 0; i < nargs; i++)
1328 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1329 return Qnil;
1331 if (nargs <= 5 /* IPv4 */
1332 && i < 4 /* host, not port */
1333 && XINT (p->contents[i]) > 255)
1334 return Qnil;
1336 args[i + 1] = p->contents[i];
1339 return Fformat (nargs + 1, args);
1342 if (CONSP (address))
1344 AUTO_STRING (format, "<Family %d>");
1345 return CALLN (Fformat, format, Fcar (address));
1348 return Qnil;
1351 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1352 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1353 (void)
1355 return Fmapcar (Qcdr, Vprocess_alist);
1358 /* Starting asynchronous inferior processes. */
1360 static void start_process_unwind (Lisp_Object proc);
1362 DEFUN ("make-process", Fmake_process, Smake_process, 0, MANY, 0,
1363 doc: /* Start a program in a subprocess. Return the process object for it.
1365 This is similar to `start-process', but arguments are specified as
1366 keyword/argument pairs. The following arguments are defined:
1368 :name NAME -- NAME is name for process. It is modified if necessary
1369 to make it unique.
1371 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
1372 with the process. Process output goes at end of that buffer, unless
1373 you specify an output stream or filter function to handle the output.
1374 BUFFER may be also nil, meaning that this process is not associated
1375 with any buffer.
1377 :command COMMAND -- COMMAND is a list starting with the program file
1378 name, followed by strings to give to the program as arguments.
1380 :coding CODING -- If CODING is a symbol, it specifies the coding
1381 system used for both reading and writing for this process. If CODING
1382 is a cons (DECODING . ENCODING), DECODING is used for reading, and
1383 ENCODING is used for writing.
1385 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
1386 the process is running. If BOOL is not given, query before exiting.
1388 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
1389 In the stopped state, a process does not accept incoming data, but you
1390 can send outgoing data. The stopped state is cleared by
1391 `continue-process' and set by `stop-process'.
1393 :connection-type TYPE -- TYPE is control type of device used to
1394 communicate with subprocesses. Values are `pipe' to use a pipe, `pty'
1395 to use a pty, or nil to use the default specified through
1396 `process-connection-type'.
1398 :filter FILTER -- Install FILTER as the process filter.
1400 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
1402 :stderr STDERR -- STDERR is either a buffer or a pipe process attached
1403 to the standard error of subprocess. Specifying this implies
1404 `:connection-type' is set to `pipe'.
1406 usage: (make-process &rest ARGS) */)
1407 (ptrdiff_t nargs, Lisp_Object *args)
1409 Lisp_Object buffer, name, command, program, proc, contact, current_dir, tem;
1410 Lisp_Object xstderr, stderrproc;
1411 ptrdiff_t count = SPECPDL_INDEX ();
1412 struct gcpro gcpro1;
1413 USE_SAFE_ALLOCA;
1415 if (nargs == 0)
1416 return Qnil;
1418 /* Save arguments for process-contact and clone-process. */
1419 contact = Flist (nargs, args);
1420 GCPRO1 (contact);
1422 buffer = Fplist_get (contact, QCbuffer);
1423 if (!NILP (buffer))
1424 buffer = Fget_buffer_create (buffer);
1426 /* Make sure that the child will be able to chdir to the current
1427 buffer's current directory, or its unhandled equivalent. We
1428 can't just have the child check for an error when it does the
1429 chdir, since it's in a vfork.
1431 We have to GCPRO around this because Fexpand_file_name and
1432 Funhandled_file_name_directory might call a file name handling
1433 function. The argument list is protected by the caller, so all
1434 we really have to worry about is buffer. */
1436 struct gcpro gcpro1;
1437 GCPRO1 (buffer);
1438 current_dir = encode_current_directory ();
1439 UNGCPRO;
1442 name = Fplist_get (contact, QCname);
1443 CHECK_STRING (name);
1445 command = Fplist_get (contact, QCcommand);
1446 if (CONSP (command))
1447 program = XCAR (command);
1448 else
1449 program = Qnil;
1451 if (!NILP (program))
1452 CHECK_STRING (program);
1454 stderrproc = Qnil;
1455 xstderr = Fplist_get (contact, QCstderr);
1456 if (PROCESSP (xstderr))
1458 if (!PIPECONN_P (xstderr))
1459 error ("Process is not a pipe process");
1460 stderrproc = xstderr;
1462 else if (!NILP (xstderr))
1464 struct gcpro gcpro1, gcpro2;
1465 CHECK_STRING (program);
1466 GCPRO2 (buffer, current_dir);
1467 stderrproc = CALLN (Fmake_pipe_process,
1468 QCname,
1469 concat2 (name, build_string (" stderr")),
1470 QCbuffer,
1471 Fget_buffer_create (xstderr));
1472 UNGCPRO;
1475 proc = make_process (name);
1476 /* If an error occurs and we can't start the process, we want to
1477 remove it from the process list. This means that each error
1478 check in create_process doesn't need to call remove_process
1479 itself; it's all taken care of here. */
1480 record_unwind_protect (start_process_unwind, proc);
1482 pset_childp (XPROCESS (proc), Qt);
1483 pset_plist (XPROCESS (proc), Qnil);
1484 pset_type (XPROCESS (proc), Qreal);
1485 pset_buffer (XPROCESS (proc), buffer);
1486 pset_sentinel (XPROCESS (proc), Fplist_get (contact, QCsentinel));
1487 pset_filter (XPROCESS (proc), Fplist_get (contact, QCfilter));
1488 pset_command (XPROCESS (proc), Fcopy_sequence (command));
1490 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
1491 XPROCESS (proc)->kill_without_query = 1;
1492 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
1493 pset_command (XPROCESS (proc), Qt);
1495 tem = Fplist_get (contact, QCconnection_type);
1496 if (EQ (tem, Qpty))
1497 XPROCESS (proc)->pty_flag = true;
1498 else if (EQ (tem, Qpipe))
1499 XPROCESS (proc)->pty_flag = false;
1500 else if (NILP (tem))
1501 XPROCESS (proc)->pty_flag = !NILP (Vprocess_connection_type);
1502 else
1503 report_file_error ("Unknown connection type", tem);
1505 if (!NILP (stderrproc))
1507 pset_stderrproc (XPROCESS (proc), stderrproc);
1509 XPROCESS (proc)->pty_flag = false;
1512 #ifdef HAVE_GNUTLS
1513 /* AKA GNUTLS_INITSTAGE(proc). */
1514 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1515 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1516 #endif
1518 #ifdef ADAPTIVE_READ_BUFFERING
1519 XPROCESS (proc)->adaptive_read_buffering
1520 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1521 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1522 #endif
1524 /* Make the process marker point into the process buffer (if any). */
1525 if (BUFFERP (buffer))
1526 set_marker_both (XPROCESS (proc)->mark, buffer,
1527 BUF_ZV (XBUFFER (buffer)),
1528 BUF_ZV_BYTE (XBUFFER (buffer)));
1531 /* Decide coding systems for communicating with the process. Here
1532 we don't setup the structure coding_system nor pay attention to
1533 unibyte mode. They are done in create_process. */
1535 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1536 Lisp_Object coding_systems = Qt;
1537 Lisp_Object val, *args2;
1538 struct gcpro gcpro1, gcpro2;
1540 tem = Fplist_get (contact, QCcoding);
1541 if (!NILP (tem))
1543 val = tem;
1544 if (CONSP (val))
1545 val = XCAR (val);
1547 else
1548 val = Vcoding_system_for_read;
1549 if (NILP (val))
1551 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1552 Lisp_Object tem2;
1553 SAFE_ALLOCA_LISP (args2, nargs2);
1554 ptrdiff_t i = 0;
1555 args2[i++] = Qstart_process;
1556 args2[i++] = name;
1557 args2[i++] = buffer;
1558 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1559 args2[i++] = XCAR (tem2);
1560 GCPRO2 (proc, current_dir);
1561 if (!NILP (program))
1562 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1563 UNGCPRO;
1564 if (CONSP (coding_systems))
1565 val = XCAR (coding_systems);
1566 else if (CONSP (Vdefault_process_coding_system))
1567 val = XCAR (Vdefault_process_coding_system);
1569 pset_decode_coding_system (XPROCESS (proc), val);
1571 if (!NILP (tem))
1573 val = tem;
1574 if (CONSP (val))
1575 val = XCDR (val);
1577 else
1578 val = Vcoding_system_for_write;
1579 if (NILP (val))
1581 if (EQ (coding_systems, Qt))
1583 ptrdiff_t nargs2 = 3 + XINT (Flength (command));
1584 Lisp_Object tem2;
1585 SAFE_ALLOCA_LISP (args2, nargs2);
1586 ptrdiff_t i = 0;
1587 args2[i++] = Qstart_process;
1588 args2[i++] = name;
1589 args2[i++] = buffer;
1590 for (tem2 = command; CONSP (tem2); tem2 = XCDR (tem2))
1591 args2[i++] = XCAR (tem2);
1592 GCPRO2 (proc, current_dir);
1593 if (!NILP (program))
1594 coding_systems = Ffind_operation_coding_system (nargs2, args2);
1595 UNGCPRO;
1597 if (CONSP (coding_systems))
1598 val = XCDR (coding_systems);
1599 else if (CONSP (Vdefault_process_coding_system))
1600 val = XCDR (Vdefault_process_coding_system);
1602 pset_encode_coding_system (XPROCESS (proc), val);
1603 /* Note: At this moment, the above coding system may leave
1604 text-conversion or eol-conversion unspecified. They will be
1605 decided after we read output from the process and decode it by
1606 some coding system, or just before we actually send a text to
1607 the process. */
1611 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1612 XPROCESS (proc)->decoding_carryover = 0;
1613 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1615 XPROCESS (proc)->inherit_coding_system_flag
1616 = !(NILP (buffer) || !inherit_process_coding_system);
1618 if (!NILP (program))
1620 Lisp_Object program_args = XCDR (command);
1622 /* If program file name is not absolute, search our path for it.
1623 Put the name we will really use in TEM. */
1624 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1625 && !(SCHARS (program) > 1
1626 && IS_DEVICE_SEP (SREF (program, 1))))
1628 struct gcpro gcpro1, gcpro2;
1630 tem = Qnil;
1631 GCPRO2 (buffer, current_dir);
1632 openp (Vexec_path, program, Vexec_suffixes, &tem,
1633 make_number (X_OK), false);
1634 UNGCPRO;
1635 if (NILP (tem))
1636 report_file_error ("Searching for program", program);
1637 tem = Fexpand_file_name (tem, Qnil);
1639 else
1641 if (!NILP (Ffile_directory_p (program)))
1642 error ("Specified program for new process is a directory");
1643 tem = program;
1646 /* Remove "/:" from TEM. */
1647 tem = remove_slash_colon (tem);
1649 Lisp_Object arg_encoding = Qnil;
1650 struct gcpro gcpro1;
1651 GCPRO1 (tem);
1653 /* Encode the file name and put it in NEW_ARGV.
1654 That's where the child will use it to execute the program. */
1655 tem = list1 (ENCODE_FILE (tem));
1656 ptrdiff_t new_argc = 1;
1658 /* Here we encode arguments by the coding system used for sending
1659 data to the process. We don't support using different coding
1660 systems for encoding arguments and for encoding data sent to the
1661 process. */
1663 for (Lisp_Object tem2 = program_args; CONSP (tem2); tem2 = XCDR (tem2))
1665 Lisp_Object arg = XCAR (tem2);
1666 CHECK_STRING (arg);
1667 if (STRING_MULTIBYTE (arg))
1669 if (NILP (arg_encoding))
1670 arg_encoding = (complement_process_encoding_system
1671 (XPROCESS (proc)->encode_coding_system));
1672 arg = code_convert_string_norecord (arg, arg_encoding, 1);
1674 tem = Fcons (arg, tem);
1675 new_argc++;
1678 UNGCPRO;
1680 /* Now that everything is encoded we can collect the strings into
1681 NEW_ARGV. */
1682 char **new_argv;
1683 SAFE_NALLOCA (new_argv, 1, new_argc + 1);
1684 new_argv[new_argc] = 0;
1686 for (ptrdiff_t i = new_argc - 1; i >= 0; i--)
1688 new_argv[i] = SSDATA (XCAR (tem));
1689 tem = XCDR (tem);
1692 create_process (proc, new_argv, current_dir);
1694 else
1695 create_pty (proc);
1697 UNGCPRO;
1698 SAFE_FREE ();
1699 return unbind_to (count, proc);
1702 /* This function is the unwind_protect form for Fstart_process. If
1703 PROC doesn't have its pid set, then we know someone has signaled
1704 an error and the process wasn't started successfully, so we should
1705 remove it from the process list. */
1706 static void
1707 start_process_unwind (Lisp_Object proc)
1709 if (!PROCESSP (proc))
1710 emacs_abort ();
1712 /* Was PROC started successfully?
1713 -2 is used for a pty with no process, eg for gdb. */
1714 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1715 remove_process (proc);
1718 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1720 static void
1721 close_process_fd (int *fd_addr)
1723 int fd = *fd_addr;
1724 if (0 <= fd)
1726 *fd_addr = -1;
1727 emacs_close (fd);
1731 /* Indexes of file descriptors in open_fds. */
1732 enum
1734 /* The pipe from Emacs to its subprocess. */
1735 SUBPROCESS_STDIN,
1736 WRITE_TO_SUBPROCESS,
1738 /* The main pipe from the subprocess to Emacs. */
1739 READ_FROM_SUBPROCESS,
1740 SUBPROCESS_STDOUT,
1742 /* The pipe from the subprocess to Emacs that is closed when the
1743 subprocess execs. */
1744 READ_FROM_EXEC_MONITOR,
1745 EXEC_MONITOR_OUTPUT
1748 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1750 static void
1751 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1753 struct Lisp_Process *p = XPROCESS (process);
1754 int inchannel, outchannel;
1755 pid_t pid;
1756 int vfork_errno;
1757 int forkin, forkout, forkerr = -1;
1758 bool pty_flag = 0;
1759 char pty_name[PTY_NAME_SIZE];
1760 Lisp_Object lisp_pty_name = Qnil;
1761 sigset_t oldset;
1763 inchannel = outchannel = -1;
1765 if (p->pty_flag)
1766 outchannel = inchannel = allocate_pty (pty_name);
1768 if (inchannel >= 0)
1770 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1771 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1772 /* On most USG systems it does not work to open the pty's tty here,
1773 then close it and reopen it in the child. */
1774 /* Don't let this terminal become our controlling terminal
1775 (in case we don't have one). */
1776 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1777 if (forkin < 0)
1778 report_file_error ("Opening pty", Qnil);
1779 p->open_fd[SUBPROCESS_STDIN] = forkin;
1780 #else
1781 forkin = forkout = -1;
1782 #endif /* not USG, or USG_SUBTTY_WORKS */
1783 pty_flag = 1;
1784 lisp_pty_name = build_string (pty_name);
1786 else
1788 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1789 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1790 report_file_error ("Creating pipe", Qnil);
1791 forkin = p->open_fd[SUBPROCESS_STDIN];
1792 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1793 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1794 forkout = p->open_fd[SUBPROCESS_STDOUT];
1796 if (!NILP (p->stderrproc))
1798 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
1800 forkerr = pp->open_fd[SUBPROCESS_STDOUT];
1802 /* Close unnecessary file descriptors. */
1803 close_process_fd (&pp->open_fd[WRITE_TO_SUBPROCESS]);
1804 close_process_fd (&pp->open_fd[SUBPROCESS_STDIN]);
1808 #ifndef WINDOWSNT
1809 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1810 report_file_error ("Creating pipe", Qnil);
1811 #endif
1813 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1814 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1816 /* Record this as an active process, with its channels. */
1817 chan_process[inchannel] = process;
1818 p->infd = inchannel;
1819 p->outfd = outchannel;
1821 /* Previously we recorded the tty descriptor used in the subprocess.
1822 It was only used for getting the foreground tty process, so now
1823 we just reopen the device (see emacs_get_tty_pgrp) as this is
1824 more portable (see USG_SUBTTY_WORKS above). */
1826 p->pty_flag = pty_flag;
1827 pset_status (p, Qrun);
1829 if (!EQ (p->command, Qt))
1831 FD_SET (inchannel, &input_wait_mask);
1832 FD_SET (inchannel, &non_keyboard_wait_mask);
1835 if (inchannel > max_process_desc)
1836 max_process_desc = inchannel;
1838 /* This may signal an error. */
1839 setup_process_coding_systems (process);
1841 block_input ();
1842 block_child_signal (&oldset);
1844 #ifndef WINDOWSNT
1845 /* vfork, and prevent local vars from being clobbered by the vfork. */
1847 Lisp_Object volatile current_dir_volatile = current_dir;
1848 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1849 char **volatile new_argv_volatile = new_argv;
1850 int volatile forkin_volatile = forkin;
1851 int volatile forkout_volatile = forkout;
1852 int volatile forkerr_volatile = forkerr;
1853 struct Lisp_Process *p_volatile = p;
1855 pid = vfork ();
1857 current_dir = current_dir_volatile;
1858 lisp_pty_name = lisp_pty_name_volatile;
1859 new_argv = new_argv_volatile;
1860 forkin = forkin_volatile;
1861 forkout = forkout_volatile;
1862 forkerr = forkerr_volatile;
1863 p = p_volatile;
1865 pty_flag = p->pty_flag;
1868 if (pid == 0)
1869 #endif /* not WINDOWSNT */
1871 int xforkin = forkin;
1872 int xforkout = forkout;
1873 int xforkerr = forkerr;
1875 /* Make the pty be the controlling terminal of the process. */
1876 #ifdef HAVE_PTYS
1877 /* First, disconnect its current controlling terminal. */
1878 /* We tried doing setsid only if pty_flag, but it caused
1879 process_set_signal to fail on SGI when using a pipe. */
1880 setsid ();
1881 /* Make the pty's terminal the controlling terminal. */
1882 if (pty_flag && xforkin >= 0)
1884 #ifdef TIOCSCTTY
1885 /* We ignore the return value
1886 because faith@cs.unc.edu says that is necessary on Linux. */
1887 ioctl (xforkin, TIOCSCTTY, 0);
1888 #endif
1890 #if defined (LDISC1)
1891 if (pty_flag && xforkin >= 0)
1893 struct termios t;
1894 tcgetattr (xforkin, &t);
1895 t.c_lflag = LDISC1;
1896 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1897 emacs_perror ("create_process/tcsetattr LDISC1");
1899 #else
1900 #if defined (NTTYDISC) && defined (TIOCSETD)
1901 if (pty_flag && xforkin >= 0)
1903 /* Use new line discipline. */
1904 int ldisc = NTTYDISC;
1905 ioctl (xforkin, TIOCSETD, &ldisc);
1907 #endif
1908 #endif
1909 #ifdef TIOCNOTTY
1910 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1911 can do TIOCSPGRP only to the process's controlling tty. */
1912 if (pty_flag)
1914 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1915 I can't test it since I don't have 4.3. */
1916 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1917 if (j >= 0)
1919 ioctl (j, TIOCNOTTY, 0);
1920 emacs_close (j);
1923 #endif /* TIOCNOTTY */
1925 #if !defined (DONT_REOPEN_PTY)
1926 /*** There is a suggestion that this ought to be a
1927 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1928 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1929 that system does seem to need this code, even though
1930 both TIOCSCTTY is defined. */
1931 /* Now close the pty (if we had it open) and reopen it.
1932 This makes the pty the controlling terminal of the subprocess. */
1933 if (pty_flag)
1936 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1937 would work? */
1938 if (xforkin >= 0)
1939 emacs_close (xforkin);
1940 xforkout = xforkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1942 if (xforkin < 0)
1944 emacs_perror (SSDATA (lisp_pty_name));
1945 _exit (EXIT_CANCELED);
1949 #endif /* not DONT_REOPEN_PTY */
1951 #ifdef SETUP_SLAVE_PTY
1952 if (pty_flag)
1954 SETUP_SLAVE_PTY;
1956 #endif /* SETUP_SLAVE_PTY */
1957 #endif /* HAVE_PTYS */
1959 signal (SIGINT, SIG_DFL);
1960 signal (SIGQUIT, SIG_DFL);
1961 #ifdef SIGPROF
1962 signal (SIGPROF, SIG_DFL);
1963 #endif
1965 /* Emacs ignores SIGPIPE, but the child should not. */
1966 signal (SIGPIPE, SIG_DFL);
1968 /* Stop blocking SIGCHLD in the child. */
1969 unblock_child_signal (&oldset);
1971 if (pty_flag)
1972 child_setup_tty (xforkout);
1974 if (xforkerr < 0)
1975 xforkerr = xforkout;
1976 #ifdef WINDOWSNT
1977 pid = child_setup (xforkin, xforkout, xforkerr, new_argv, 1, current_dir);
1978 #else /* not WINDOWSNT */
1979 child_setup (xforkin, xforkout, xforkerr, new_argv, 1, current_dir);
1980 #endif /* not WINDOWSNT */
1983 /* Back in the parent process. */
1985 vfork_errno = errno;
1986 p->pid = pid;
1987 if (pid >= 0)
1988 p->alive = 1;
1990 /* Stop blocking in the parent. */
1991 unblock_child_signal (&oldset);
1992 unblock_input ();
1994 if (pid < 0)
1995 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1996 else
1998 /* vfork succeeded. */
2000 /* Close the pipe ends that the child uses, or the child's pty. */
2001 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
2002 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
2004 #ifdef WINDOWSNT
2005 register_child (pid, inchannel);
2006 #endif /* WINDOWSNT */
2008 pset_tty_name (p, lisp_pty_name);
2010 #ifndef WINDOWSNT
2011 /* Wait for child_setup to complete in case that vfork is
2012 actually defined as fork. The descriptor
2013 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
2014 of a pipe is closed at the child side either by close-on-exec
2015 on successful execve or the _exit call in child_setup. */
2017 char dummy;
2019 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
2020 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
2021 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
2023 #endif
2024 if (!NILP (p->stderrproc))
2026 struct Lisp_Process *pp = XPROCESS (p->stderrproc);
2027 close_process_fd (&pp->open_fd[SUBPROCESS_STDOUT]);
2032 static void
2033 create_pty (Lisp_Object process)
2035 struct Lisp_Process *p = XPROCESS (process);
2036 char pty_name[PTY_NAME_SIZE];
2037 int pty_fd = !p->pty_flag ? -1 : allocate_pty (pty_name);
2039 if (pty_fd >= 0)
2041 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
2042 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2043 /* On most USG systems it does not work to open the pty's tty here,
2044 then close it and reopen it in the child. */
2045 /* Don't let this terminal become our controlling terminal
2046 (in case we don't have one). */
2047 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2048 if (forkout < 0)
2049 report_file_error ("Opening pty", Qnil);
2050 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
2051 #if defined (DONT_REOPEN_PTY)
2052 /* In the case that vfork is defined as fork, the parent process
2053 (Emacs) may send some data before the child process completes
2054 tty options setup. So we setup tty before forking. */
2055 child_setup_tty (forkout);
2056 #endif /* DONT_REOPEN_PTY */
2057 #endif /* not USG, or USG_SUBTTY_WORKS */
2059 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
2061 /* Record this as an active process, with its channels.
2062 As a result, child_setup will close Emacs's side of the pipes. */
2063 chan_process[pty_fd] = process;
2064 p->infd = pty_fd;
2065 p->outfd = pty_fd;
2067 /* Previously we recorded the tty descriptor used in the subprocess.
2068 It was only used for getting the foreground tty process, so now
2069 we just reopen the device (see emacs_get_tty_pgrp) as this is
2070 more portable (see USG_SUBTTY_WORKS above). */
2072 p->pty_flag = 1;
2073 pset_status (p, Qrun);
2074 setup_process_coding_systems (process);
2076 FD_SET (pty_fd, &input_wait_mask);
2077 FD_SET (pty_fd, &non_keyboard_wait_mask);
2078 if (pty_fd > max_process_desc)
2079 max_process_desc = pty_fd;
2081 pset_tty_name (p, build_string (pty_name));
2084 p->pid = -2;
2087 DEFUN ("make-pipe-process", Fmake_pipe_process, Smake_pipe_process,
2088 0, MANY, 0,
2089 doc: /* Create and return a bidirectional pipe process.
2091 In Emacs, pipes are represented by process objects, so input and
2092 output work as for subprocesses, and `delete-process' closes a pipe.
2093 However, a pipe process has no process id, it cannot be signaled,
2094 and the status codes are different from normal processes.
2096 Arguments are specified as keyword/argument pairs. The following
2097 arguments are defined:
2099 :name NAME -- NAME is the name of the process. It is modified if necessary to make it unique.
2101 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2102 with the process. Process output goes at the end of that buffer,
2103 unless you specify an output stream or filter function to handle the
2104 output. If BUFFER is not given, the value of NAME is used.
2106 :coding CODING -- If CODING is a symbol, it specifies the coding
2107 system used for both reading and writing for this process. If CODING
2108 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2109 ENCODING is used for writing.
2111 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2112 the process is running. If BOOL is not given, query before exiting.
2114 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2115 In the stopped state, a pipe process does not accept incoming data,
2116 but you can send outgoing data. The stopped state is cleared by
2117 `continue-process' and set by `stop-process'.
2119 :filter FILTER -- Install FILTER as the process filter.
2121 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2123 usage: (make-pipe-process &rest ARGS) */)
2124 (ptrdiff_t nargs, Lisp_Object *args)
2126 Lisp_Object proc, contact;
2127 struct Lisp_Process *p;
2128 struct gcpro gcpro1;
2129 Lisp_Object name, buffer;
2130 Lisp_Object tem;
2131 ptrdiff_t specpdl_count;
2132 int inchannel, outchannel;
2134 if (nargs == 0)
2135 return Qnil;
2137 contact = Flist (nargs, args);
2138 GCPRO1 (contact);
2140 name = Fplist_get (contact, QCname);
2141 CHECK_STRING (name);
2142 proc = make_process (name);
2143 specpdl_count = SPECPDL_INDEX ();
2144 record_unwind_protect (remove_process, proc);
2145 p = XPROCESS (proc);
2147 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
2148 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
2149 report_file_error ("Creating pipe", Qnil);
2150 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
2151 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
2153 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2154 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2156 #ifdef WINDOWSNT
2157 register_aux_fd (inchannel);
2158 #endif
2160 /* Record this as an active process, with its channels. */
2161 chan_process[inchannel] = proc;
2162 p->infd = inchannel;
2163 p->outfd = outchannel;
2165 if (inchannel > max_process_desc)
2166 max_process_desc = inchannel;
2168 buffer = Fplist_get (contact, QCbuffer);
2169 if (NILP (buffer))
2170 buffer = name;
2171 buffer = Fget_buffer_create (buffer);
2172 pset_buffer (p, buffer);
2174 pset_childp (p, contact);
2175 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2176 pset_type (p, Qpipe);
2177 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2178 pset_filter (p, Fplist_get (contact, QCfilter));
2179 pset_log (p, Qnil);
2180 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2181 p->kill_without_query = 1;
2182 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2183 pset_command (p, Qt);
2184 eassert (! p->pty_flag);
2186 if (!EQ (p->command, Qt))
2188 FD_SET (inchannel, &input_wait_mask);
2189 FD_SET (inchannel, &non_keyboard_wait_mask);
2191 #ifdef ADAPTIVE_READ_BUFFERING
2192 p->adaptive_read_buffering
2193 = (NILP (Vprocess_adaptive_read_buffering) ? 0
2194 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
2195 #endif
2197 /* Make the process marker point into the process buffer (if any). */
2198 if (BUFFERP (buffer))
2199 set_marker_both (p->mark, buffer,
2200 BUF_ZV (XBUFFER (buffer)),
2201 BUF_ZV_BYTE (XBUFFER (buffer)));
2204 /* Setup coding systems for communicating with the network stream. */
2206 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2207 Lisp_Object coding_systems = Qt;
2208 Lisp_Object val;
2210 tem = Fplist_get (contact, QCcoding);
2211 val = Qnil;
2212 if (!NILP (tem))
2214 val = tem;
2215 if (CONSP (val))
2216 val = XCAR (val);
2218 else if (!NILP (Vcoding_system_for_read))
2219 val = Vcoding_system_for_read;
2220 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2221 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2222 /* We dare not decode end-of-line format by setting VAL to
2223 Qraw_text, because the existing Emacs Lisp libraries
2224 assume that they receive bare code including a sequence of
2225 CR LF. */
2226 val = Qnil;
2227 else
2229 if (CONSP (coding_systems))
2230 val = XCAR (coding_systems);
2231 else if (CONSP (Vdefault_process_coding_system))
2232 val = XCAR (Vdefault_process_coding_system);
2233 else
2234 val = Qnil;
2236 pset_decode_coding_system (p, val);
2238 if (!NILP (tem))
2240 val = tem;
2241 if (CONSP (val))
2242 val = XCDR (val);
2244 else if (!NILP (Vcoding_system_for_write))
2245 val = Vcoding_system_for_write;
2246 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
2247 val = Qnil;
2248 else
2250 if (CONSP (coding_systems))
2251 val = XCDR (coding_systems);
2252 else if (CONSP (Vdefault_process_coding_system))
2253 val = XCDR (Vdefault_process_coding_system);
2254 else
2255 val = Qnil;
2257 pset_encode_coding_system (p, val);
2259 /* This may signal an error. */
2260 setup_process_coding_systems (proc);
2262 specpdl_ptr = specpdl + specpdl_count;
2264 UNGCPRO;
2265 return proc;
2269 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2270 The address family of sa is not included in the result. */
2272 Lisp_Object
2273 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2275 Lisp_Object address;
2276 int i;
2277 unsigned char *cp;
2278 register struct Lisp_Vector *p;
2280 /* Workaround for a bug in getsockname on BSD: Names bound to
2281 sockets in the UNIX domain are inaccessible; getsockname returns
2282 a zero length name. */
2283 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2284 return empty_unibyte_string;
2286 switch (sa->sa_family)
2288 case AF_INET:
2290 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2291 len = sizeof (sin->sin_addr) + 1;
2292 address = Fmake_vector (make_number (len), Qnil);
2293 p = XVECTOR (address);
2294 p->contents[--len] = make_number (ntohs (sin->sin_port));
2295 cp = (unsigned char *) &sin->sin_addr;
2296 break;
2298 #ifdef AF_INET6
2299 case AF_INET6:
2301 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2302 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2303 len = sizeof (sin6->sin6_addr) / 2 + 1;
2304 address = Fmake_vector (make_number (len), Qnil);
2305 p = XVECTOR (address);
2306 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2307 for (i = 0; i < len; i++)
2308 p->contents[i] = make_number (ntohs (ip6[i]));
2309 return address;
2311 #endif
2312 #ifdef HAVE_LOCAL_SOCKETS
2313 case AF_LOCAL:
2315 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2316 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2317 /* If the first byte is NUL, the name is a Linux abstract
2318 socket name, and the name can contain embedded NULs. If
2319 it's not, we have a NUL-terminated string. Be careful not
2320 to walk past the end of the object looking for the name
2321 terminator, however. */
2322 if (name_length > 0 && sockun->sun_path[0] != '\0')
2324 const char *terminator
2325 = memchr (sockun->sun_path, '\0', name_length);
2327 if (terminator)
2328 name_length = terminator - (const char *) sockun->sun_path;
2331 return make_unibyte_string (sockun->sun_path, name_length);
2333 #endif
2334 default:
2335 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2336 address = Fcons (make_number (sa->sa_family),
2337 Fmake_vector (make_number (len), Qnil));
2338 p = XVECTOR (XCDR (address));
2339 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2340 break;
2343 i = 0;
2344 while (i < len)
2345 p->contents[i++] = make_number (*cp++);
2347 return address;
2351 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2353 static int
2354 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2356 register struct Lisp_Vector *p;
2358 if (VECTORP (address))
2360 p = XVECTOR (address);
2361 if (p->header.size == 5)
2363 *familyp = AF_INET;
2364 return sizeof (struct sockaddr_in);
2366 #ifdef AF_INET6
2367 else if (p->header.size == 9)
2369 *familyp = AF_INET6;
2370 return sizeof (struct sockaddr_in6);
2372 #endif
2374 #ifdef HAVE_LOCAL_SOCKETS
2375 else if (STRINGP (address))
2377 *familyp = AF_LOCAL;
2378 return sizeof (struct sockaddr_un);
2380 #endif
2381 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2382 && VECTORP (XCDR (address)))
2384 struct sockaddr *sa;
2385 p = XVECTOR (XCDR (address));
2386 if (MAX_ALLOCA - sizeof sa->sa_family < p->header.size)
2387 return 0;
2388 *familyp = XINT (XCAR (address));
2389 return p->header.size + sizeof (sa->sa_family);
2391 return 0;
2394 /* Convert an address object (vector or string) to an internal sockaddr.
2396 The address format has been basically validated by
2397 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2398 it could have come from user data. So if FAMILY is not valid,
2399 we return after zeroing *SA. */
2401 static void
2402 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2404 register struct Lisp_Vector *p;
2405 register unsigned char *cp = NULL;
2406 register int i;
2407 EMACS_INT hostport;
2409 memset (sa, 0, len);
2411 if (VECTORP (address))
2413 p = XVECTOR (address);
2414 if (family == AF_INET)
2416 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2417 len = sizeof (sin->sin_addr) + 1;
2418 hostport = XINT (p->contents[--len]);
2419 sin->sin_port = htons (hostport);
2420 cp = (unsigned char *)&sin->sin_addr;
2421 sa->sa_family = family;
2423 #ifdef AF_INET6
2424 else if (family == AF_INET6)
2426 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2427 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2428 len = sizeof (sin6->sin6_addr) + 1;
2429 hostport = XINT (p->contents[--len]);
2430 sin6->sin6_port = htons (hostport);
2431 for (i = 0; i < len; i++)
2432 if (INTEGERP (p->contents[i]))
2434 int j = XFASTINT (p->contents[i]) & 0xffff;
2435 ip6[i] = ntohs (j);
2437 sa->sa_family = family;
2438 return;
2440 #endif
2441 else
2442 return;
2444 else if (STRINGP (address))
2446 #ifdef HAVE_LOCAL_SOCKETS
2447 if (family == AF_LOCAL)
2449 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2450 cp = SDATA (address);
2451 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2452 sockun->sun_path[i] = *cp++;
2453 sa->sa_family = family;
2455 #endif
2456 return;
2458 else
2460 p = XVECTOR (XCDR (address));
2461 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2464 for (i = 0; i < len; i++)
2465 if (INTEGERP (p->contents[i]))
2466 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2469 #ifdef DATAGRAM_SOCKETS
2470 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2471 1, 1, 0,
2472 doc: /* Get the current datagram address associated with PROCESS. */)
2473 (Lisp_Object process)
2475 int channel;
2477 CHECK_PROCESS (process);
2479 if (!DATAGRAM_CONN_P (process))
2480 return Qnil;
2482 channel = XPROCESS (process)->infd;
2483 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2484 datagram_address[channel].len);
2487 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2488 2, 2, 0,
2489 doc: /* Set the datagram address for PROCESS to ADDRESS.
2490 Returns nil upon error setting address, ADDRESS otherwise. */)
2491 (Lisp_Object process, Lisp_Object address)
2493 int channel;
2494 int family, len;
2496 CHECK_PROCESS (process);
2498 if (!DATAGRAM_CONN_P (process))
2499 return Qnil;
2501 channel = XPROCESS (process)->infd;
2503 len = get_lisp_to_sockaddr_size (address, &family);
2504 if (len == 0 || datagram_address[channel].len != len)
2505 return Qnil;
2506 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2507 return address;
2509 #endif
2512 static const struct socket_options {
2513 /* The name of this option. Should be lowercase version of option
2514 name without SO_ prefix. */
2515 const char *name;
2516 /* Option level SOL_... */
2517 int optlevel;
2518 /* Option number SO_... */
2519 int optnum;
2520 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2521 enum { OPIX_NONE = 0, OPIX_MISC = 1, OPIX_REUSEADDR = 2 } optbit;
2522 } socket_options[] =
2524 #ifdef SO_BINDTODEVICE
2525 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2526 #endif
2527 #ifdef SO_BROADCAST
2528 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2529 #endif
2530 #ifdef SO_DONTROUTE
2531 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2532 #endif
2533 #ifdef SO_KEEPALIVE
2534 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2535 #endif
2536 #ifdef SO_LINGER
2537 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2538 #endif
2539 #ifdef SO_OOBINLINE
2540 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2541 #endif
2542 #ifdef SO_PRIORITY
2543 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2544 #endif
2545 #ifdef SO_REUSEADDR
2546 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2547 #endif
2548 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2551 /* Set option OPT to value VAL on socket S.
2553 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2554 Signals an error if setting a known option fails.
2557 static int
2558 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2560 char *name;
2561 const struct socket_options *sopt;
2562 int ret = 0;
2564 CHECK_SYMBOL (opt);
2566 name = SSDATA (SYMBOL_NAME (opt));
2567 for (sopt = socket_options; sopt->name; sopt++)
2568 if (strcmp (name, sopt->name) == 0)
2569 break;
2571 switch (sopt->opttype)
2573 case SOPT_BOOL:
2575 int optval;
2576 optval = NILP (val) ? 0 : 1;
2577 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2578 &optval, sizeof (optval));
2579 break;
2582 case SOPT_INT:
2584 int optval;
2585 if (TYPE_RANGED_INTEGERP (int, val))
2586 optval = XINT (val);
2587 else
2588 error ("Bad option value for %s", name);
2589 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2590 &optval, sizeof (optval));
2591 break;
2594 #ifdef SO_BINDTODEVICE
2595 case SOPT_IFNAME:
2597 char devname[IFNAMSIZ + 1];
2599 /* This is broken, at least in the Linux 2.4 kernel.
2600 To unbind, the arg must be a zero integer, not the empty string.
2601 This should work on all systems. KFS. 2003-09-23. */
2602 memset (devname, 0, sizeof devname);
2603 if (STRINGP (val))
2605 char *arg = SSDATA (val);
2606 int len = min (strlen (arg), IFNAMSIZ);
2607 memcpy (devname, arg, len);
2609 else if (!NILP (val))
2610 error ("Bad option value for %s", name);
2611 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2612 devname, IFNAMSIZ);
2613 break;
2615 #endif
2617 #ifdef SO_LINGER
2618 case SOPT_LINGER:
2620 struct linger linger;
2622 linger.l_onoff = 1;
2623 linger.l_linger = 0;
2624 if (TYPE_RANGED_INTEGERP (int, val))
2625 linger.l_linger = XINT (val);
2626 else
2627 linger.l_onoff = NILP (val) ? 0 : 1;
2628 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2629 &linger, sizeof (linger));
2630 break;
2632 #endif
2634 default:
2635 return 0;
2638 if (ret < 0)
2640 int setsockopt_errno = errno;
2641 report_file_errno ("Cannot set network option", list2 (opt, val),
2642 setsockopt_errno);
2645 return (1 << sopt->optbit);
2649 DEFUN ("set-network-process-option",
2650 Fset_network_process_option, Sset_network_process_option,
2651 3, 4, 0,
2652 doc: /* For network process PROCESS set option OPTION to value VALUE.
2653 See `make-network-process' for a list of options and values.
2654 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2655 OPTION is not a supported option, return nil instead; otherwise return t. */)
2656 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2658 int s;
2659 struct Lisp_Process *p;
2661 CHECK_PROCESS (process);
2662 p = XPROCESS (process);
2663 if (!NETCONN1_P (p))
2664 error ("Process is not a network process");
2666 s = p->infd;
2667 if (s < 0)
2668 error ("Process is not running");
2670 if (set_socket_option (s, option, value))
2672 pset_childp (p, Fplist_put (p->childp, option, value));
2673 return Qt;
2676 if (NILP (no_error))
2677 error ("Unknown or unsupported option");
2679 return Qnil;
2683 DEFUN ("serial-process-configure",
2684 Fserial_process_configure,
2685 Sserial_process_configure,
2686 0, MANY, 0,
2687 doc: /* Configure speed, bytesize, etc. of a serial process.
2689 Arguments are specified as keyword/argument pairs. Attributes that
2690 are not given are re-initialized from the process's current
2691 configuration (available via the function `process-contact') or set to
2692 reasonable default values. The following arguments are defined:
2694 :process PROCESS
2695 :name NAME
2696 :buffer BUFFER
2697 :port PORT
2698 -- Any of these arguments can be given to identify the process that is
2699 to be configured. If none of these arguments is given, the current
2700 buffer's process is used.
2702 :speed SPEED -- SPEED is the speed of the serial port in bits per
2703 second, also called baud rate. Any value can be given for SPEED, but
2704 most serial ports work only at a few defined values between 1200 and
2705 115200, with 9600 being the most common value. If SPEED is nil, the
2706 serial port is not configured any further, i.e., all other arguments
2707 are ignored. This may be useful for special serial ports such as
2708 Bluetooth-to-serial converters which can only be configured through AT
2709 commands. A value of nil for SPEED can be used only when passed
2710 through `make-serial-process' or `serial-term'.
2712 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2713 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2715 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2716 `odd' (use odd parity), or the symbol `even' (use even parity). If
2717 PARITY is not given, no parity is used.
2719 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2720 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2721 is not given or nil, 1 stopbit is used.
2723 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2724 flowcontrol to be used, which is either nil (don't use flowcontrol),
2725 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2726 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2727 flowcontrol is used.
2729 `serial-process-configure' is called by `make-serial-process' for the
2730 initial configuration of the serial port.
2732 Examples:
2734 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2736 \(serial-process-configure
2737 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2739 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2741 usage: (serial-process-configure &rest ARGS) */)
2742 (ptrdiff_t nargs, Lisp_Object *args)
2744 struct Lisp_Process *p;
2745 Lisp_Object contact = Qnil;
2746 Lisp_Object proc = Qnil;
2747 struct gcpro gcpro1;
2749 contact = Flist (nargs, args);
2750 GCPRO1 (contact);
2752 proc = Fplist_get (contact, QCprocess);
2753 if (NILP (proc))
2754 proc = Fplist_get (contact, QCname);
2755 if (NILP (proc))
2756 proc = Fplist_get (contact, QCbuffer);
2757 if (NILP (proc))
2758 proc = Fplist_get (contact, QCport);
2759 proc = get_process (proc);
2760 p = XPROCESS (proc);
2761 if (!EQ (p->type, Qserial))
2762 error ("Not a serial process");
2764 if (NILP (Fplist_get (p->childp, QCspeed)))
2766 UNGCPRO;
2767 return Qnil;
2770 serial_configure (p, contact);
2772 UNGCPRO;
2773 return Qnil;
2776 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2777 0, MANY, 0,
2778 doc: /* Create and return a serial port process.
2780 In Emacs, serial port connections are represented by process objects,
2781 so input and output work as for subprocesses, and `delete-process'
2782 closes a serial port connection. However, a serial process has no
2783 process id, it cannot be signaled, and the status codes are different
2784 from normal processes.
2786 `make-serial-process' creates a process and a buffer, on which you
2787 probably want to use `process-send-string'. Try \\[serial-term] for
2788 an interactive terminal. See below for examples.
2790 Arguments are specified as keyword/argument pairs. The following
2791 arguments are defined:
2793 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2794 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2795 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2796 the backslashes in strings).
2798 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2799 which this function calls.
2801 :name NAME -- NAME is the name of the process. If NAME is not given,
2802 the value of PORT is used.
2804 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2805 with the process. Process output goes at the end of that buffer,
2806 unless you specify an output stream or filter function to handle the
2807 output. If BUFFER is not given, the value of NAME is used.
2809 :coding CODING -- If CODING is a symbol, it specifies the coding
2810 system used for both reading and writing for this process. If CODING
2811 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2812 ENCODING is used for writing.
2814 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2815 the process is running. If BOOL is not given, query before exiting.
2817 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2818 In the stopped state, a serial process does not accept incoming data,
2819 but you can send outgoing data. The stopped state is cleared by
2820 `continue-process' and set by `stop-process'.
2822 :filter FILTER -- Install FILTER as the process filter.
2824 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2826 :plist PLIST -- Install PLIST as the initial plist of the process.
2828 :bytesize
2829 :parity
2830 :stopbits
2831 :flowcontrol
2832 -- This function calls `serial-process-configure' to handle these
2833 arguments.
2835 The original argument list, possibly modified by later configuration,
2836 is available via the function `process-contact'.
2838 Examples:
2840 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2842 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2844 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2846 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2848 usage: (make-serial-process &rest ARGS) */)
2849 (ptrdiff_t nargs, Lisp_Object *args)
2851 int fd = -1;
2852 Lisp_Object proc, contact, port;
2853 struct Lisp_Process *p;
2854 struct gcpro gcpro1;
2855 Lisp_Object name, buffer;
2856 Lisp_Object tem, val;
2857 ptrdiff_t specpdl_count;
2859 if (nargs == 0)
2860 return Qnil;
2862 contact = Flist (nargs, args);
2863 GCPRO1 (contact);
2865 port = Fplist_get (contact, QCport);
2866 if (NILP (port))
2867 error ("No port specified");
2868 CHECK_STRING (port);
2870 if (NILP (Fplist_member (contact, QCspeed)))
2871 error (":speed not specified");
2872 if (!NILP (Fplist_get (contact, QCspeed)))
2873 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2875 name = Fplist_get (contact, QCname);
2876 if (NILP (name))
2877 name = port;
2878 CHECK_STRING (name);
2879 proc = make_process (name);
2880 specpdl_count = SPECPDL_INDEX ();
2881 record_unwind_protect (remove_process, proc);
2882 p = XPROCESS (proc);
2884 fd = serial_open (port);
2885 p->open_fd[SUBPROCESS_STDIN] = fd;
2886 p->infd = fd;
2887 p->outfd = fd;
2888 if (fd > max_process_desc)
2889 max_process_desc = fd;
2890 chan_process[fd] = proc;
2892 buffer = Fplist_get (contact, QCbuffer);
2893 if (NILP (buffer))
2894 buffer = name;
2895 buffer = Fget_buffer_create (buffer);
2896 pset_buffer (p, buffer);
2898 pset_childp (p, contact);
2899 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2900 pset_type (p, Qserial);
2901 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2902 pset_filter (p, Fplist_get (contact, QCfilter));
2903 pset_log (p, Qnil);
2904 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2905 p->kill_without_query = 1;
2906 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2907 pset_command (p, Qt);
2908 eassert (! p->pty_flag);
2910 if (!EQ (p->command, Qt))
2912 FD_SET (fd, &input_wait_mask);
2913 FD_SET (fd, &non_keyboard_wait_mask);
2916 if (BUFFERP (buffer))
2918 set_marker_both (p->mark, buffer,
2919 BUF_ZV (XBUFFER (buffer)),
2920 BUF_ZV_BYTE (XBUFFER (buffer)));
2923 tem = Fplist_member (contact, QCcoding);
2924 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2925 tem = Qnil;
2927 val = Qnil;
2928 if (!NILP (tem))
2930 val = XCAR (XCDR (tem));
2931 if (CONSP (val))
2932 val = XCAR (val);
2934 else if (!NILP (Vcoding_system_for_read))
2935 val = Vcoding_system_for_read;
2936 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2937 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2938 val = Qnil;
2939 pset_decode_coding_system (p, val);
2941 val = Qnil;
2942 if (!NILP (tem))
2944 val = XCAR (XCDR (tem));
2945 if (CONSP (val))
2946 val = XCDR (val);
2948 else if (!NILP (Vcoding_system_for_write))
2949 val = Vcoding_system_for_write;
2950 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2951 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2952 val = Qnil;
2953 pset_encode_coding_system (p, val);
2955 setup_process_coding_systems (proc);
2956 pset_decoding_buf (p, empty_unibyte_string);
2957 p->decoding_carryover = 0;
2958 pset_encoding_buf (p, empty_unibyte_string);
2959 p->inherit_coding_system_flag
2960 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2962 Fserial_process_configure (nargs, args);
2964 specpdl_ptr = specpdl + specpdl_count;
2966 UNGCPRO;
2967 return proc;
2970 /* Create a network stream/datagram client/server process. Treated
2971 exactly like a normal process when reading and writing. Primary
2972 differences are in status display and process deletion. A network
2973 connection has no PID; you cannot signal it. All you can do is
2974 stop/continue it and deactivate/close it via delete-process. */
2976 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2977 0, MANY, 0,
2978 doc: /* Create and return a network server or client process.
2980 In Emacs, network connections are represented by process objects, so
2981 input and output work as for subprocesses and `delete-process' closes
2982 a network connection. However, a network process has no process id,
2983 it cannot be signaled, and the status codes are different from normal
2984 processes.
2986 Arguments are specified as keyword/argument pairs. The following
2987 arguments are defined:
2989 :name NAME -- NAME is name for process. It is modified if necessary
2990 to make it unique.
2992 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2993 with the process. Process output goes at end of that buffer, unless
2994 you specify an output stream or filter function to handle the output.
2995 BUFFER may be also nil, meaning that this process is not associated
2996 with any buffer.
2998 :host HOST -- HOST is name of the host to connect to, or its IP
2999 address. The symbol `local' specifies the local host. If specified
3000 for a server process, it must be a valid name or address for the local
3001 host, and only clients connecting to that address will be accepted.
3003 :service SERVICE -- SERVICE is name of the service desired, or an
3004 integer specifying a port number to connect to. If SERVICE is t,
3005 a random port number is selected for the server. (If Emacs was
3006 compiled with getaddrinfo, a port number can also be specified as a
3007 string, e.g. "80", as well as an integer. This is not portable.)
3009 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3010 stream type connection, `datagram' creates a datagram type connection,
3011 `seqpacket' creates a reliable datagram connection.
3013 :family FAMILY -- FAMILY is the address (and protocol) family for the
3014 service specified by HOST and SERVICE. The default (nil) is to use
3015 whatever address family (IPv4 or IPv6) that is defined for the host
3016 and port number specified by HOST and SERVICE. Other address families
3017 supported are:
3018 local -- for a local (i.e. UNIX) address specified by SERVICE.
3019 ipv4 -- use IPv4 address family only.
3020 ipv6 -- use IPv6 address family only.
3022 :local ADDRESS -- ADDRESS is the local address used for the connection.
3023 This parameter is ignored when opening a client process. When specified
3024 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3026 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3027 connection. This parameter is ignored when opening a stream server
3028 process. For a datagram server process, it specifies the initial
3029 setting of the remote datagram address. When specified for a client
3030 process, the FAMILY, HOST, and SERVICE args are ignored.
3032 The format of ADDRESS depends on the address family:
3033 - An IPv4 address is represented as an vector of integers [A B C D P]
3034 corresponding to numeric IP address A.B.C.D and port number P.
3035 - A local address is represented as a string with the address in the
3036 local address space.
3037 - An "unsupported family" address is represented by a cons (F . AV)
3038 where F is the family number and AV is a vector containing the socket
3039 address data with one element per address data byte. Do not rely on
3040 this format in portable code, as it may depend on implementation
3041 defined constants, data sizes, and data structure alignment.
3043 :coding CODING -- If CODING is a symbol, it specifies the coding
3044 system used for both reading and writing for this process. If CODING
3045 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3046 ENCODING is used for writing.
3048 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3049 return without waiting for the connection to complete; instead, the
3050 sentinel function will be called with second arg matching "open" (if
3051 successful) or "failed" when the connect completes. Default is to use
3052 a blocking connect (i.e. wait) for stream type connections.
3054 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3055 running when Emacs is exited.
3057 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3058 In the stopped state, a server process does not accept new
3059 connections, and a client process does not handle incoming traffic.
3060 The stopped state is cleared by `continue-process' and set by
3061 `stop-process'.
3063 :filter FILTER -- Install FILTER as the process filter.
3065 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3066 process filter are multibyte, otherwise they are unibyte.
3067 If this keyword is not specified, the strings are multibyte if
3068 the default value of `enable-multibyte-characters' is non-nil.
3070 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3072 :log LOG -- Install LOG as the server process log function. This
3073 function is called when the server accepts a network connection from a
3074 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3075 is the server process, CLIENT is the new process for the connection,
3076 and MESSAGE is a string.
3078 :plist PLIST -- Install PLIST as the new process's initial plist.
3080 :server QLEN -- if QLEN is non-nil, create a server process for the
3081 specified FAMILY, SERVICE, and connection type (stream or datagram).
3082 If QLEN is an integer, it is used as the max. length of the server's
3083 pending connection queue (also known as the backlog); the default
3084 queue length is 5. Default is to create a client process.
3086 The following network options can be specified for this connection:
3088 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3089 :dontroute BOOL -- Only send to directly connected hosts.
3090 :keepalive BOOL -- Send keep-alive messages on network stream.
3091 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3092 :oobinline BOOL -- Place out-of-band data in receive data stream.
3093 :priority INT -- Set protocol defined priority for sent packets.
3094 :reuseaddr BOOL -- Allow reusing a recently used local address
3095 (this is allowed by default for a server process).
3096 :bindtodevice NAME -- bind to interface NAME. Using this may require
3097 special privileges on some systems.
3099 Consult the relevant system programmer's manual pages for more
3100 information on using these options.
3103 A server process will listen for and accept connections from clients.
3104 When a client connection is accepted, a new network process is created
3105 for the connection with the following parameters:
3107 - The client's process name is constructed by concatenating the server
3108 process's NAME and a client identification string.
3109 - If the FILTER argument is non-nil, the client process will not get a
3110 separate process buffer; otherwise, the client's process buffer is a newly
3111 created buffer named after the server process's BUFFER name or process
3112 NAME concatenated with the client identification string.
3113 - The connection type and the process filter and sentinel parameters are
3114 inherited from the server process's TYPE, FILTER and SENTINEL.
3115 - The client process's contact info is set according to the client's
3116 addressing information (typically an IP address and a port number).
3117 - The client process's plist is initialized from the server's plist.
3119 Notice that the FILTER and SENTINEL args are never used directly by
3120 the server process. Also, the BUFFER argument is not used directly by
3121 the server process, but via the optional :log function, accepted (and
3122 failed) connections may be logged in the server process's buffer.
3124 The original argument list, modified with the actual connection
3125 information, is available via the `process-contact' function.
3127 usage: (make-network-process &rest ARGS) */)
3128 (ptrdiff_t nargs, Lisp_Object *args)
3130 Lisp_Object proc;
3131 Lisp_Object contact;
3132 struct Lisp_Process *p;
3133 #ifdef HAVE_GETADDRINFO
3134 struct addrinfo ai, *res, *lres;
3135 struct addrinfo hints;
3136 const char *portstring;
3137 char portbuf[128];
3138 #else /* HAVE_GETADDRINFO */
3139 struct _emacs_addrinfo
3141 int ai_family;
3142 int ai_socktype;
3143 int ai_protocol;
3144 int ai_addrlen;
3145 struct sockaddr *ai_addr;
3146 struct _emacs_addrinfo *ai_next;
3147 } ai, *res, *lres;
3148 #endif /* HAVE_GETADDRINFO */
3149 struct sockaddr_in address_in;
3150 #ifdef HAVE_LOCAL_SOCKETS
3151 struct sockaddr_un address_un;
3152 #endif
3153 int port;
3154 int ret = 0;
3155 int xerrno = 0;
3156 int s = -1, outch, inch;
3157 struct gcpro gcpro1;
3158 ptrdiff_t count = SPECPDL_INDEX ();
3159 ptrdiff_t count1;
3160 Lisp_Object colon_address; /* Either QClocal or QCremote. */
3161 Lisp_Object tem;
3162 Lisp_Object name, buffer, host, service, address;
3163 Lisp_Object filter, sentinel;
3164 bool is_non_blocking_client = 0;
3165 bool is_server = 0;
3166 int backlog = 5;
3167 int socktype;
3168 int family = -1;
3170 if (nargs == 0)
3171 return Qnil;
3173 /* Save arguments for process-contact and clone-process. */
3174 contact = Flist (nargs, args);
3175 GCPRO1 (contact);
3177 #ifdef WINDOWSNT
3178 /* Ensure socket support is loaded if available. */
3179 init_winsock (TRUE);
3180 #endif
3182 /* :type TYPE (nil: stream, datagram */
3183 tem = Fplist_get (contact, QCtype);
3184 if (NILP (tem))
3185 socktype = SOCK_STREAM;
3186 #ifdef DATAGRAM_SOCKETS
3187 else if (EQ (tem, Qdatagram))
3188 socktype = SOCK_DGRAM;
3189 #endif
3190 #ifdef HAVE_SEQPACKET
3191 else if (EQ (tem, Qseqpacket))
3192 socktype = SOCK_SEQPACKET;
3193 #endif
3194 else
3195 error ("Unsupported connection type");
3197 /* :server BOOL */
3198 tem = Fplist_get (contact, QCserver);
3199 if (!NILP (tem))
3201 /* Don't support network sockets when non-blocking mode is
3202 not available, since a blocked Emacs is not useful. */
3203 is_server = 1;
3204 if (TYPE_RANGED_INTEGERP (int, tem))
3205 backlog = XINT (tem);
3208 /* Make colon_address an alias for :local (server) or :remote (client). */
3209 colon_address = is_server ? QClocal : QCremote;
3211 /* :nowait BOOL */
3212 if (!is_server && socktype != SOCK_DGRAM
3213 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3215 #ifndef NON_BLOCKING_CONNECT
3216 error ("Non-blocking connect not supported");
3217 #else
3218 is_non_blocking_client = 1;
3219 #endif
3222 name = Fplist_get (contact, QCname);
3223 buffer = Fplist_get (contact, QCbuffer);
3224 filter = Fplist_get (contact, QCfilter);
3225 sentinel = Fplist_get (contact, QCsentinel);
3227 CHECK_STRING (name);
3229 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3230 ai.ai_socktype = socktype;
3231 ai.ai_protocol = 0;
3232 ai.ai_next = NULL;
3233 res = &ai;
3235 /* :local ADDRESS or :remote ADDRESS */
3236 address = Fplist_get (contact, colon_address);
3237 if (!NILP (address))
3239 host = service = Qnil;
3241 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3242 error ("Malformed :address");
3243 ai.ai_family = family;
3244 ai.ai_addr = alloca (ai.ai_addrlen);
3245 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3246 goto open_socket;
3249 /* :family FAMILY -- nil (for Inet), local, or integer. */
3250 tem = Fplist_get (contact, QCfamily);
3251 if (NILP (tem))
3253 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
3254 family = AF_UNSPEC;
3255 #else
3256 family = AF_INET;
3257 #endif
3259 #ifdef HAVE_LOCAL_SOCKETS
3260 else if (EQ (tem, Qlocal))
3261 family = AF_LOCAL;
3262 #endif
3263 #ifdef AF_INET6
3264 else if (EQ (tem, Qipv6))
3265 family = AF_INET6;
3266 #endif
3267 else if (EQ (tem, Qipv4))
3268 family = AF_INET;
3269 else if (TYPE_RANGED_INTEGERP (int, tem))
3270 family = XINT (tem);
3271 else
3272 error ("Unknown address family");
3274 ai.ai_family = family;
3276 /* :service SERVICE -- string, integer (port number), or t (random port). */
3277 service = Fplist_get (contact, QCservice);
3279 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3280 host = Fplist_get (contact, QChost);
3281 if (!NILP (host))
3283 if (EQ (host, Qlocal))
3284 /* Depending on setup, "localhost" may map to different IPv4 and/or
3285 IPv6 addresses, so it's better to be explicit (Bug#6781). */
3286 host = build_string ("127.0.0.1");
3287 CHECK_STRING (host);
3290 #ifdef HAVE_LOCAL_SOCKETS
3291 if (family == AF_LOCAL)
3293 if (!NILP (host))
3295 message (":family local ignores the :host \"%s\" property",
3296 SDATA (host));
3297 contact = Fplist_put (contact, QChost, Qnil);
3298 host = Qnil;
3300 CHECK_STRING (service);
3301 memset (&address_un, 0, sizeof address_un);
3302 address_un.sun_family = AF_LOCAL;
3303 if (sizeof address_un.sun_path <= SBYTES (service))
3304 error ("Service name too long");
3305 lispstpcpy (address_un.sun_path, service);
3306 ai.ai_addr = (struct sockaddr *) &address_un;
3307 ai.ai_addrlen = sizeof address_un;
3308 goto open_socket;
3310 #endif
3312 /* Slow down polling to every ten seconds.
3313 Some kernels have a bug which causes retrying connect to fail
3314 after a connect. Polling can interfere with gethostbyname too. */
3315 #ifdef POLL_FOR_INPUT
3316 if (socktype != SOCK_DGRAM)
3318 record_unwind_protect_void (run_all_atimers);
3319 bind_polling_period (10);
3321 #endif
3323 #ifdef HAVE_GETADDRINFO
3324 /* If we have a host, use getaddrinfo to resolve both host and service.
3325 Otherwise, use getservbyname to lookup the service. */
3326 if (!NILP (host))
3329 /* SERVICE can either be a string or int.
3330 Convert to a C string for later use by getaddrinfo. */
3331 if (EQ (service, Qt))
3332 portstring = "0";
3333 else if (INTEGERP (service))
3335 sprintf (portbuf, "%"pI"d", XINT (service));
3336 portstring = portbuf;
3338 else
3340 CHECK_STRING (service);
3341 portstring = SSDATA (service);
3344 immediate_quit = 1;
3345 QUIT;
3346 memset (&hints, 0, sizeof (hints));
3347 hints.ai_flags = 0;
3348 hints.ai_family = family;
3349 hints.ai_socktype = socktype;
3350 hints.ai_protocol = 0;
3352 #ifdef HAVE_RES_INIT
3353 res_init ();
3354 #endif
3356 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3357 if (ret)
3358 #ifdef HAVE_GAI_STRERROR
3359 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3360 #else
3361 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3362 #endif
3363 immediate_quit = 0;
3365 goto open_socket;
3367 #endif /* HAVE_GETADDRINFO */
3369 /* We end up here if getaddrinfo is not defined, or in case no hostname
3370 has been specified (e.g. for a local server process). */
3372 if (EQ (service, Qt))
3373 port = 0;
3374 else if (INTEGERP (service))
3375 port = htons ((unsigned short) XINT (service));
3376 else
3378 struct servent *svc_info;
3379 CHECK_STRING (service);
3380 svc_info = getservbyname (SSDATA (service),
3381 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3382 if (svc_info == 0)
3383 error ("Unknown service: %s", SDATA (service));
3384 port = svc_info->s_port;
3387 memset (&address_in, 0, sizeof address_in);
3388 address_in.sin_family = family;
3389 address_in.sin_addr.s_addr = INADDR_ANY;
3390 address_in.sin_port = port;
3392 #ifndef HAVE_GETADDRINFO
3393 if (!NILP (host))
3395 struct hostent *host_info_ptr;
3397 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3398 as it may `hang' Emacs for a very long time. */
3399 immediate_quit = 1;
3400 QUIT;
3402 #ifdef HAVE_RES_INIT
3403 res_init ();
3404 #endif
3406 host_info_ptr = gethostbyname (SDATA (host));
3407 immediate_quit = 0;
3409 if (host_info_ptr)
3411 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3412 host_info_ptr->h_length);
3413 family = host_info_ptr->h_addrtype;
3414 address_in.sin_family = family;
3416 else
3417 /* Attempt to interpret host as numeric inet address. */
3419 unsigned long numeric_addr;
3420 numeric_addr = inet_addr (SSDATA (host));
3421 if (numeric_addr == -1)
3422 error ("Unknown host \"%s\"", SDATA (host));
3424 memcpy (&address_in.sin_addr, &numeric_addr,
3425 sizeof (address_in.sin_addr));
3429 #endif /* not HAVE_GETADDRINFO */
3431 ai.ai_family = family;
3432 ai.ai_addr = (struct sockaddr *) &address_in;
3433 ai.ai_addrlen = sizeof address_in;
3435 open_socket:
3437 /* Do this in case we never enter the for-loop below. */
3438 count1 = SPECPDL_INDEX ();
3439 s = -1;
3441 for (lres = res; lres; lres = lres->ai_next)
3443 ptrdiff_t optn;
3444 int optbits;
3446 #ifdef WINDOWSNT
3447 retry_connect:
3448 #endif
3450 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3451 lres->ai_protocol);
3452 if (s < 0)
3454 xerrno = errno;
3455 continue;
3458 #ifdef DATAGRAM_SOCKETS
3459 if (!is_server && socktype == SOCK_DGRAM)
3460 break;
3461 #endif /* DATAGRAM_SOCKETS */
3463 #ifdef NON_BLOCKING_CONNECT
3464 if (is_non_blocking_client)
3466 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3467 if (ret < 0)
3469 xerrno = errno;
3470 emacs_close (s);
3471 s = -1;
3472 continue;
3475 #endif
3477 /* Make us close S if quit. */
3478 record_unwind_protect_int (close_file_unwind, s);
3480 /* Parse network options in the arg list.
3481 We simply ignore anything which isn't a known option (including other keywords).
3482 An error is signaled if setting a known option fails. */
3483 for (optn = optbits = 0; optn < nargs - 1; optn += 2)
3484 optbits |= set_socket_option (s, args[optn], args[optn + 1]);
3486 if (is_server)
3488 /* Configure as a server socket. */
3490 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3491 explicit :reuseaddr key to override this. */
3492 #ifdef HAVE_LOCAL_SOCKETS
3493 if (family != AF_LOCAL)
3494 #endif
3495 if (!(optbits & (1 << OPIX_REUSEADDR)))
3497 int optval = 1;
3498 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3499 report_file_error ("Cannot set reuse option on server socket", Qnil);
3502 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3503 report_file_error ("Cannot bind server socket", Qnil);
3505 #ifdef HAVE_GETSOCKNAME
3506 if (EQ (service, Qt))
3508 struct sockaddr_in sa1;
3509 socklen_t len1 = sizeof (sa1);
3510 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3512 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3513 service = make_number (ntohs (sa1.sin_port));
3514 contact = Fplist_put (contact, QCservice, service);
3517 #endif
3519 if (socktype != SOCK_DGRAM && listen (s, backlog))
3520 report_file_error ("Cannot listen on server socket", Qnil);
3522 break;
3525 immediate_quit = 1;
3526 QUIT;
3528 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3529 xerrno = errno;
3531 if (ret == 0 || xerrno == EISCONN)
3533 /* The unwind-protect will be discarded afterwards.
3534 Likewise for immediate_quit. */
3535 break;
3538 #ifdef NON_BLOCKING_CONNECT
3539 #ifdef EINPROGRESS
3540 if (is_non_blocking_client && xerrno == EINPROGRESS)
3541 break;
3542 #else
3543 #ifdef EWOULDBLOCK
3544 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3545 break;
3546 #endif
3547 #endif
3548 #endif
3550 #ifndef WINDOWSNT
3551 if (xerrno == EINTR)
3553 /* Unlike most other syscalls connect() cannot be called
3554 again. (That would return EALREADY.) The proper way to
3555 wait for completion is pselect(). */
3556 int sc;
3557 socklen_t len;
3558 fd_set fdset;
3559 retry_select:
3560 FD_ZERO (&fdset);
3561 FD_SET (s, &fdset);
3562 QUIT;
3563 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3564 if (sc == -1)
3566 if (errno == EINTR)
3567 goto retry_select;
3568 else
3569 report_file_error ("Failed select", Qnil);
3571 eassert (sc > 0);
3573 len = sizeof xerrno;
3574 eassert (FD_ISSET (s, &fdset));
3575 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3576 report_file_error ("Failed getsockopt", Qnil);
3577 if (xerrno)
3578 report_file_errno ("Failed connect", Qnil, xerrno);
3579 break;
3581 #endif /* !WINDOWSNT */
3583 immediate_quit = 0;
3585 /* Discard the unwind protect closing S. */
3586 specpdl_ptr = specpdl + count1;
3587 emacs_close (s);
3588 s = -1;
3590 #ifdef WINDOWSNT
3591 if (xerrno == EINTR)
3592 goto retry_connect;
3593 #endif
3596 if (s >= 0)
3598 #ifdef DATAGRAM_SOCKETS
3599 if (socktype == SOCK_DGRAM)
3601 if (datagram_address[s].sa)
3602 emacs_abort ();
3603 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3604 datagram_address[s].len = lres->ai_addrlen;
3605 if (is_server)
3607 Lisp_Object remote;
3608 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3609 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3611 int rfamily, rlen;
3612 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3613 if (rlen != 0 && rfamily == lres->ai_family
3614 && rlen == lres->ai_addrlen)
3615 conv_lisp_to_sockaddr (rfamily, remote,
3616 datagram_address[s].sa, rlen);
3619 else
3620 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3622 #endif
3623 contact = Fplist_put (contact, colon_address,
3624 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3625 #ifdef HAVE_GETSOCKNAME
3626 if (!is_server)
3628 struct sockaddr_in sa1;
3629 socklen_t len1 = sizeof (sa1);
3630 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3631 contact = Fplist_put (contact, QClocal,
3632 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3634 #endif
3637 immediate_quit = 0;
3639 #ifdef HAVE_GETADDRINFO
3640 if (res != &ai)
3642 block_input ();
3643 freeaddrinfo (res);
3644 unblock_input ();
3646 #endif
3648 if (s < 0)
3650 /* If non-blocking got this far - and failed - assume non-blocking is
3651 not supported after all. This is probably a wrong assumption, but
3652 the normal blocking calls to open-network-stream handles this error
3653 better. */
3654 if (is_non_blocking_client)
3655 return Qnil;
3657 report_file_errno ((is_server
3658 ? "make server process failed"
3659 : "make client process failed"),
3660 contact, xerrno);
3663 inch = s;
3664 outch = s;
3666 if (!NILP (buffer))
3667 buffer = Fget_buffer_create (buffer);
3668 proc = make_process (name);
3670 chan_process[inch] = proc;
3672 fcntl (inch, F_SETFL, O_NONBLOCK);
3674 p = XPROCESS (proc);
3676 pset_childp (p, contact);
3677 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3678 pset_type (p, Qnetwork);
3680 pset_buffer (p, buffer);
3681 pset_sentinel (p, sentinel);
3682 pset_filter (p, filter);
3683 pset_log (p, Fplist_get (contact, QClog));
3684 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3685 p->kill_without_query = 1;
3686 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3687 pset_command (p, Qt);
3688 p->pid = 0;
3690 p->open_fd[SUBPROCESS_STDIN] = inch;
3691 p->infd = inch;
3692 p->outfd = outch;
3694 /* Discard the unwind protect for closing S, if any. */
3695 specpdl_ptr = specpdl + count1;
3697 /* Unwind bind_polling_period and request_sigio. */
3698 unbind_to (count, Qnil);
3700 if (is_server && socktype != SOCK_DGRAM)
3701 pset_status (p, Qlisten);
3703 /* Make the process marker point into the process buffer (if any). */
3704 if (BUFFERP (buffer))
3705 set_marker_both (p->mark, buffer,
3706 BUF_ZV (XBUFFER (buffer)),
3707 BUF_ZV_BYTE (XBUFFER (buffer)));
3709 #ifdef NON_BLOCKING_CONNECT
3710 if (is_non_blocking_client)
3712 /* We may get here if connect did succeed immediately. However,
3713 in that case, we still need to signal this like a non-blocking
3714 connection. */
3715 pset_status (p, Qconnect);
3716 if (!FD_ISSET (inch, &connect_wait_mask))
3718 FD_SET (inch, &connect_wait_mask);
3719 FD_SET (inch, &write_mask);
3720 num_pending_connects++;
3723 else
3724 #endif
3725 /* A server may have a client filter setting of Qt, but it must
3726 still listen for incoming connects unless it is stopped. */
3727 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3728 || (EQ (p->status, Qlisten) && NILP (p->command)))
3730 FD_SET (inch, &input_wait_mask);
3731 FD_SET (inch, &non_keyboard_wait_mask);
3734 if (inch > max_process_desc)
3735 max_process_desc = inch;
3737 tem = Fplist_member (contact, QCcoding);
3738 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3739 tem = Qnil; /* No error message (too late!). */
3742 /* Setup coding systems for communicating with the network stream. */
3743 struct gcpro gcpro1;
3744 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3745 Lisp_Object coding_systems = Qt;
3746 Lisp_Object val;
3748 if (!NILP (tem))
3750 val = XCAR (XCDR (tem));
3751 if (CONSP (val))
3752 val = XCAR (val);
3754 else if (!NILP (Vcoding_system_for_read))
3755 val = Vcoding_system_for_read;
3756 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3757 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3758 /* We dare not decode end-of-line format by setting VAL to
3759 Qraw_text, because the existing Emacs Lisp libraries
3760 assume that they receive bare code including a sequence of
3761 CR LF. */
3762 val = Qnil;
3763 else
3765 if (NILP (host) || NILP (service))
3766 coding_systems = Qnil;
3767 else
3769 GCPRO1 (proc);
3770 coding_systems = CALLN (Ffind_operation_coding_system,
3771 Qopen_network_stream, name, buffer,
3772 host, service);
3773 UNGCPRO;
3775 if (CONSP (coding_systems))
3776 val = XCAR (coding_systems);
3777 else if (CONSP (Vdefault_process_coding_system))
3778 val = XCAR (Vdefault_process_coding_system);
3779 else
3780 val = Qnil;
3782 pset_decode_coding_system (p, val);
3784 if (!NILP (tem))
3786 val = XCAR (XCDR (tem));
3787 if (CONSP (val))
3788 val = XCDR (val);
3790 else if (!NILP (Vcoding_system_for_write))
3791 val = Vcoding_system_for_write;
3792 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3793 val = Qnil;
3794 else
3796 if (EQ (coding_systems, Qt))
3798 if (NILP (host) || NILP (service))
3799 coding_systems = Qnil;
3800 else
3802 GCPRO1 (proc);
3803 coding_systems = CALLN (Ffind_operation_coding_system,
3804 Qopen_network_stream, name, buffer,
3805 host, service);
3806 UNGCPRO;
3809 if (CONSP (coding_systems))
3810 val = XCDR (coding_systems);
3811 else if (CONSP (Vdefault_process_coding_system))
3812 val = XCDR (Vdefault_process_coding_system);
3813 else
3814 val = Qnil;
3816 pset_encode_coding_system (p, val);
3818 setup_process_coding_systems (proc);
3820 pset_decoding_buf (p, empty_unibyte_string);
3821 p->decoding_carryover = 0;
3822 pset_encoding_buf (p, empty_unibyte_string);
3824 p->inherit_coding_system_flag
3825 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3827 UNGCPRO;
3828 return proc;
3832 #ifdef HAVE_NET_IF_H
3834 #ifdef SIOCGIFCONF
3835 static Lisp_Object
3836 network_interface_list (void)
3838 struct ifconf ifconf;
3839 struct ifreq *ifreq;
3840 void *buf = NULL;
3841 ptrdiff_t buf_size = 512;
3842 int s;
3843 Lisp_Object res;
3844 ptrdiff_t count;
3846 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3847 if (s < 0)
3848 return Qnil;
3849 count = SPECPDL_INDEX ();
3850 record_unwind_protect_int (close_file_unwind, s);
3854 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3855 ifconf.ifc_buf = buf;
3856 ifconf.ifc_len = buf_size;
3857 if (ioctl (s, SIOCGIFCONF, &ifconf))
3859 emacs_close (s);
3860 xfree (buf);
3861 return Qnil;
3864 while (ifconf.ifc_len == buf_size);
3866 res = unbind_to (count, Qnil);
3867 ifreq = ifconf.ifc_req;
3868 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3870 struct ifreq *ifq = ifreq;
3871 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3872 #define SIZEOF_IFREQ(sif) \
3873 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3874 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3876 int len = SIZEOF_IFREQ (ifq);
3877 #else
3878 int len = sizeof (*ifreq);
3879 #endif
3880 char namebuf[sizeof (ifq->ifr_name) + 1];
3881 ifreq = (struct ifreq *) ((char *) ifreq + len);
3883 if (ifq->ifr_addr.sa_family != AF_INET)
3884 continue;
3886 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3887 namebuf[sizeof (ifq->ifr_name)] = 0;
3888 res = Fcons (Fcons (build_string (namebuf),
3889 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3890 sizeof (struct sockaddr))),
3891 res);
3894 xfree (buf);
3895 return res;
3897 #endif /* SIOCGIFCONF */
3899 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3901 struct ifflag_def {
3902 int flag_bit;
3903 const char *flag_sym;
3906 static const struct ifflag_def ifflag_table[] = {
3907 #ifdef IFF_UP
3908 { IFF_UP, "up" },
3909 #endif
3910 #ifdef IFF_BROADCAST
3911 { IFF_BROADCAST, "broadcast" },
3912 #endif
3913 #ifdef IFF_DEBUG
3914 { IFF_DEBUG, "debug" },
3915 #endif
3916 #ifdef IFF_LOOPBACK
3917 { IFF_LOOPBACK, "loopback" },
3918 #endif
3919 #ifdef IFF_POINTOPOINT
3920 { IFF_POINTOPOINT, "pointopoint" },
3921 #endif
3922 #ifdef IFF_RUNNING
3923 { IFF_RUNNING, "running" },
3924 #endif
3925 #ifdef IFF_NOARP
3926 { IFF_NOARP, "noarp" },
3927 #endif
3928 #ifdef IFF_PROMISC
3929 { IFF_PROMISC, "promisc" },
3930 #endif
3931 #ifdef IFF_NOTRAILERS
3932 #ifdef NS_IMPL_COCOA
3933 /* Really means smart, notrailers is obsolete. */
3934 { IFF_NOTRAILERS, "smart" },
3935 #else
3936 { IFF_NOTRAILERS, "notrailers" },
3937 #endif
3938 #endif
3939 #ifdef IFF_ALLMULTI
3940 { IFF_ALLMULTI, "allmulti" },
3941 #endif
3942 #ifdef IFF_MASTER
3943 { IFF_MASTER, "master" },
3944 #endif
3945 #ifdef IFF_SLAVE
3946 { IFF_SLAVE, "slave" },
3947 #endif
3948 #ifdef IFF_MULTICAST
3949 { IFF_MULTICAST, "multicast" },
3950 #endif
3951 #ifdef IFF_PORTSEL
3952 { IFF_PORTSEL, "portsel" },
3953 #endif
3954 #ifdef IFF_AUTOMEDIA
3955 { IFF_AUTOMEDIA, "automedia" },
3956 #endif
3957 #ifdef IFF_DYNAMIC
3958 { IFF_DYNAMIC, "dynamic" },
3959 #endif
3960 #ifdef IFF_OACTIVE
3961 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress. */
3962 #endif
3963 #ifdef IFF_SIMPLEX
3964 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions. */
3965 #endif
3966 #ifdef IFF_LINK0
3967 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit. */
3968 #endif
3969 #ifdef IFF_LINK1
3970 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit. */
3971 #endif
3972 #ifdef IFF_LINK2
3973 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit. */
3974 #endif
3975 { 0, 0 }
3978 static Lisp_Object
3979 network_interface_info (Lisp_Object ifname)
3981 struct ifreq rq;
3982 Lisp_Object res = Qnil;
3983 Lisp_Object elt;
3984 int s;
3985 bool any = 0;
3986 ptrdiff_t count;
3987 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3988 && defined HAVE_GETIFADDRS && defined LLADDR)
3989 struct ifaddrs *ifap;
3990 #endif
3992 CHECK_STRING (ifname);
3994 if (sizeof rq.ifr_name <= SBYTES (ifname))
3995 error ("interface name too long");
3996 lispstpcpy (rq.ifr_name, ifname);
3998 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3999 if (s < 0)
4000 return Qnil;
4001 count = SPECPDL_INDEX ();
4002 record_unwind_protect_int (close_file_unwind, s);
4004 elt = Qnil;
4005 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
4006 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4008 int flags = rq.ifr_flags;
4009 const struct ifflag_def *fp;
4010 int fnum;
4012 /* If flags is smaller than int (i.e. short) it may have the high bit set
4013 due to IFF_MULTICAST. In that case, sign extending it into
4014 an int is wrong. */
4015 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
4016 flags = (unsigned short) rq.ifr_flags;
4018 any = 1;
4019 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4021 if (flags & fp->flag_bit)
4023 elt = Fcons (intern (fp->flag_sym), elt);
4024 flags -= fp->flag_bit;
4027 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
4029 if (flags & 1)
4031 elt = Fcons (make_number (fnum), elt);
4035 #endif
4036 res = Fcons (elt, res);
4038 elt = Qnil;
4039 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
4040 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4042 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4043 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4044 int n;
4046 any = 1;
4047 for (n = 0; n < 6; n++)
4048 p->contents[n] = make_number (((unsigned char *)
4049 &rq.ifr_hwaddr.sa_data[0])
4050 [n]);
4051 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4053 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
4054 if (getifaddrs (&ifap) != -1)
4056 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4057 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4058 struct ifaddrs *it;
4060 for (it = ifap; it != NULL; it = it->ifa_next)
4062 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
4063 unsigned char linkaddr[6];
4064 int n;
4066 if (it->ifa_addr->sa_family != AF_LINK
4067 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
4068 || sdl->sdl_alen != 6)
4069 continue;
4071 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
4072 for (n = 0; n < 6; n++)
4073 p->contents[n] = make_number (linkaddr[n]);
4075 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
4076 break;
4079 #ifdef HAVE_FREEIFADDRS
4080 freeifaddrs (ifap);
4081 #endif
4083 #endif /* HAVE_GETIFADDRS && LLADDR */
4085 res = Fcons (elt, res);
4087 elt = Qnil;
4088 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
4089 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4091 any = 1;
4092 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4093 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4094 #else
4095 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4096 #endif
4098 #endif
4099 res = Fcons (elt, res);
4101 elt = Qnil;
4102 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4103 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4105 any = 1;
4106 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4108 #endif
4109 res = Fcons (elt, res);
4111 elt = Qnil;
4112 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
4113 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4115 any = 1;
4116 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4118 #endif
4119 res = Fcons (elt, res);
4121 return unbind_to (count, any ? res : Qnil);
4123 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
4124 #endif /* defined (HAVE_NET_IF_H) */
4126 DEFUN ("network-interface-list", Fnetwork_interface_list,
4127 Snetwork_interface_list, 0, 0, 0,
4128 doc: /* Return an alist of all network interfaces and their network address.
4129 Each element is a cons, the car of which is a string containing the
4130 interface name, and the cdr is the network address in internal
4131 format; see the description of ADDRESS in `make-network-process'.
4133 If the information is not available, return nil. */)
4134 (void)
4136 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
4137 return network_interface_list ();
4138 #else
4139 return Qnil;
4140 #endif
4143 DEFUN ("network-interface-info", Fnetwork_interface_info,
4144 Snetwork_interface_info, 1, 1, 0,
4145 doc: /* Return information about network interface named IFNAME.
4146 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4147 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4148 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
4149 FLAGS is the current flags of the interface.
4151 Data that is unavailable is returned as nil. */)
4152 (Lisp_Object ifname)
4154 #if ((defined HAVE_NET_IF_H \
4155 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
4156 || defined SIOCGIFFLAGS)) \
4157 || defined WINDOWSNT)
4158 return network_interface_info (ifname);
4159 #else
4160 return Qnil;
4161 #endif
4164 /* If program file NAME starts with /: for quoting a magic
4165 name, remove that, preserving the multibyteness of NAME. */
4167 Lisp_Object
4168 remove_slash_colon (Lisp_Object name)
4170 return
4171 ((SBYTES (name) > 2 && SREF (name, 0) == '/' && SREF (name, 1) == ':')
4172 ? make_specified_string (SSDATA (name) + 2, SCHARS (name) - 2,
4173 SBYTES (name) - 2, STRING_MULTIBYTE (name))
4174 : name);
4177 /* Turn off input and output for process PROC. */
4179 static void
4180 deactivate_process (Lisp_Object proc)
4182 int inchannel;
4183 struct Lisp_Process *p = XPROCESS (proc);
4184 int i;
4186 #ifdef HAVE_GNUTLS
4187 /* Delete GnuTLS structures in PROC, if any. */
4188 emacs_gnutls_deinit (proc);
4189 #endif /* HAVE_GNUTLS */
4191 #ifdef ADAPTIVE_READ_BUFFERING
4192 if (p->read_output_delay > 0)
4194 if (--process_output_delay_count < 0)
4195 process_output_delay_count = 0;
4196 p->read_output_delay = 0;
4197 p->read_output_skip = 0;
4199 #endif
4201 /* Beware SIGCHLD hereabouts. */
4203 for (i = 0; i < PROCESS_OPEN_FDS; i++)
4204 close_process_fd (&p->open_fd[i]);
4206 inchannel = p->infd;
4207 if (inchannel >= 0)
4209 p->infd = -1;
4210 p->outfd = -1;
4211 #ifdef DATAGRAM_SOCKETS
4212 if (DATAGRAM_CHAN_P (inchannel))
4214 xfree (datagram_address[inchannel].sa);
4215 datagram_address[inchannel].sa = 0;
4216 datagram_address[inchannel].len = 0;
4218 #endif
4219 chan_process[inchannel] = Qnil;
4220 FD_CLR (inchannel, &input_wait_mask);
4221 FD_CLR (inchannel, &non_keyboard_wait_mask);
4222 #ifdef NON_BLOCKING_CONNECT
4223 if (FD_ISSET (inchannel, &connect_wait_mask))
4225 FD_CLR (inchannel, &connect_wait_mask);
4226 FD_CLR (inchannel, &write_mask);
4227 if (--num_pending_connects < 0)
4228 emacs_abort ();
4230 #endif
4231 if (inchannel == max_process_desc)
4233 /* We just closed the highest-numbered process input descriptor,
4234 so recompute the highest-numbered one now. */
4235 int i = inchannel;
4237 i--;
4238 while (0 <= i && NILP (chan_process[i]));
4240 max_process_desc = i;
4246 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4247 0, 4, 0,
4248 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4249 It is given to their filter functions.
4250 Optional argument PROCESS means do not return until output has been
4251 received from PROCESS.
4253 Optional second argument SECONDS and third argument MILLISEC
4254 specify a timeout; return after that much time even if there is
4255 no subprocess output. If SECONDS is a floating point number,
4256 it specifies a fractional number of seconds to wait.
4257 The MILLISEC argument is obsolete and should be avoided.
4259 If optional fourth argument JUST-THIS-ONE is non-nil, accept output
4260 from PROCESS only, suspending reading output from other processes.
4261 If JUST-THIS-ONE is an integer, don't run any timers either.
4262 Return non-nil if we received any output from PROCESS (or, if PROCESS
4263 is nil, from any process) before the timeout expired. */)
4264 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4266 intmax_t secs;
4267 int nsecs;
4269 if (! NILP (process))
4270 CHECK_PROCESS (process);
4271 else
4272 just_this_one = Qnil;
4274 if (!NILP (millisec))
4275 { /* Obsolete calling convention using integers rather than floats. */
4276 CHECK_NUMBER (millisec);
4277 if (NILP (seconds))
4278 seconds = make_float (XINT (millisec) / 1000.0);
4279 else
4281 CHECK_NUMBER (seconds);
4282 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4286 secs = 0;
4287 nsecs = -1;
4289 if (!NILP (seconds))
4291 if (INTEGERP (seconds))
4293 if (XINT (seconds) > 0)
4295 secs = XINT (seconds);
4296 nsecs = 0;
4299 else if (FLOATP (seconds))
4301 if (XFLOAT_DATA (seconds) > 0)
4303 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
4304 secs = min (t.tv_sec, WAIT_READING_MAX);
4305 nsecs = t.tv_nsec;
4308 else
4309 wrong_type_argument (Qnumberp, seconds);
4311 else if (! NILP (process))
4312 nsecs = 0;
4314 return
4315 ((wait_reading_process_output (secs, nsecs, 0, 0,
4316 Qnil,
4317 !NILP (process) ? XPROCESS (process) : NULL,
4318 (NILP (just_this_one) ? 0
4319 : !INTEGERP (just_this_one) ? 1 : -1))
4320 <= 0)
4321 ? Qnil : Qt);
4324 /* Accept a connection for server process SERVER on CHANNEL. */
4326 static EMACS_INT connect_counter = 0;
4328 static void
4329 server_accept_connection (Lisp_Object server, int channel)
4331 Lisp_Object proc, caller, name, buffer;
4332 Lisp_Object contact, host, service;
4333 struct Lisp_Process *ps = XPROCESS (server);
4334 struct Lisp_Process *p;
4335 int s;
4336 union u_sockaddr {
4337 struct sockaddr sa;
4338 struct sockaddr_in in;
4339 #ifdef AF_INET6
4340 struct sockaddr_in6 in6;
4341 #endif
4342 #ifdef HAVE_LOCAL_SOCKETS
4343 struct sockaddr_un un;
4344 #endif
4345 } saddr;
4346 socklen_t len = sizeof saddr;
4347 ptrdiff_t count;
4349 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4351 if (s < 0)
4353 int code = errno;
4355 if (code == EAGAIN)
4356 return;
4357 #ifdef EWOULDBLOCK
4358 if (code == EWOULDBLOCK)
4359 return;
4360 #endif
4362 if (!NILP (ps->log))
4363 call3 (ps->log, server, Qnil,
4364 concat3 (build_string ("accept failed with code"),
4365 Fnumber_to_string (make_number (code)),
4366 build_string ("\n")));
4367 return;
4370 count = SPECPDL_INDEX ();
4371 record_unwind_protect_int (close_file_unwind, s);
4373 connect_counter++;
4375 /* Setup a new process to handle the connection. */
4377 /* Generate a unique identification of the caller, and build contact
4378 information for this process. */
4379 host = Qt;
4380 service = Qnil;
4381 switch (saddr.sa.sa_family)
4383 case AF_INET:
4385 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4387 AUTO_STRING (ipv4_format, "%d.%d.%d.%d");
4388 host = CALLN (Fformat, ipv4_format,
4389 make_number (ip[0]), make_number (ip[1]),
4390 make_number (ip[2]), make_number (ip[3]));
4391 service = make_number (ntohs (saddr.in.sin_port));
4392 AUTO_STRING (caller_format, " <%s:%d>");
4393 caller = CALLN (Fformat, caller_format, host, service);
4395 break;
4397 #ifdef AF_INET6
4398 case AF_INET6:
4400 Lisp_Object args[9];
4401 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4402 int i;
4404 AUTO_STRING (ipv6_format, "%x:%x:%x:%x:%x:%x:%x:%x");
4405 args[0] = ipv6_format;
4406 for (i = 0; i < 8; i++)
4407 args[i + 1] = make_number (ntohs (ip6[i]));
4408 host = CALLMANY (Fformat, args);
4409 service = make_number (ntohs (saddr.in.sin_port));
4410 AUTO_STRING (caller_format, " <[%s]:%d>");
4411 caller = CALLN (Fformat, caller_format, host, service);
4413 break;
4414 #endif
4416 #ifdef HAVE_LOCAL_SOCKETS
4417 case AF_LOCAL:
4418 #endif
4419 default:
4420 caller = Fnumber_to_string (make_number (connect_counter));
4421 AUTO_STRING (space_less_than, " <");
4422 AUTO_STRING (greater_than, ">");
4423 caller = concat3 (space_less_than, caller, greater_than);
4424 break;
4427 /* Create a new buffer name for this process if it doesn't have a
4428 filter. The new buffer name is based on the buffer name or
4429 process name of the server process concatenated with the caller
4430 identification. */
4432 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4433 || EQ (ps->filter, Qt)))
4434 buffer = Qnil;
4435 else
4437 buffer = ps->buffer;
4438 if (!NILP (buffer))
4439 buffer = Fbuffer_name (buffer);
4440 else
4441 buffer = ps->name;
4442 if (!NILP (buffer))
4444 buffer = concat2 (buffer, caller);
4445 buffer = Fget_buffer_create (buffer);
4449 /* Generate a unique name for the new server process. Combine the
4450 server process name with the caller identification. */
4452 name = concat2 (ps->name, caller);
4453 proc = make_process (name);
4455 chan_process[s] = proc;
4457 fcntl (s, F_SETFL, O_NONBLOCK);
4459 p = XPROCESS (proc);
4461 /* Build new contact information for this setup. */
4462 contact = Fcopy_sequence (ps->childp);
4463 contact = Fplist_put (contact, QCserver, Qnil);
4464 contact = Fplist_put (contact, QChost, host);
4465 if (!NILP (service))
4466 contact = Fplist_put (contact, QCservice, service);
4467 contact = Fplist_put (contact, QCremote,
4468 conv_sockaddr_to_lisp (&saddr.sa, len));
4469 #ifdef HAVE_GETSOCKNAME
4470 len = sizeof saddr;
4471 if (getsockname (s, &saddr.sa, &len) == 0)
4472 contact = Fplist_put (contact, QClocal,
4473 conv_sockaddr_to_lisp (&saddr.sa, len));
4474 #endif
4476 pset_childp (p, contact);
4477 pset_plist (p, Fcopy_sequence (ps->plist));
4478 pset_type (p, Qnetwork);
4480 pset_buffer (p, buffer);
4481 pset_sentinel (p, ps->sentinel);
4482 pset_filter (p, ps->filter);
4483 pset_command (p, Qnil);
4484 p->pid = 0;
4486 /* Discard the unwind protect for closing S. */
4487 specpdl_ptr = specpdl + count;
4489 p->open_fd[SUBPROCESS_STDIN] = s;
4490 p->infd = s;
4491 p->outfd = s;
4492 pset_status (p, Qrun);
4494 /* Client processes for accepted connections are not stopped initially. */
4495 if (!EQ (p->filter, Qt))
4497 FD_SET (s, &input_wait_mask);
4498 FD_SET (s, &non_keyboard_wait_mask);
4501 if (s > max_process_desc)
4502 max_process_desc = s;
4504 /* Setup coding system for new process based on server process.
4505 This seems to be the proper thing to do, as the coding system
4506 of the new process should reflect the settings at the time the
4507 server socket was opened; not the current settings. */
4509 pset_decode_coding_system (p, ps->decode_coding_system);
4510 pset_encode_coding_system (p, ps->encode_coding_system);
4511 setup_process_coding_systems (proc);
4513 pset_decoding_buf (p, empty_unibyte_string);
4514 p->decoding_carryover = 0;
4515 pset_encoding_buf (p, empty_unibyte_string);
4517 p->inherit_coding_system_flag
4518 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4520 AUTO_STRING (dash, "-");
4521 AUTO_STRING (nl, "\n");
4522 Lisp_Object host_string = STRINGP (host) ? host : dash;
4524 if (!NILP (ps->log))
4526 AUTO_STRING (accept_from, "accept from ");
4527 call3 (ps->log, server, proc, concat3 (accept_from, host_string, nl));
4530 AUTO_STRING (open_from, "open from ");
4531 exec_sentinel (proc, concat3 (open_from, host_string, nl));
4534 /* This variable is different from waiting_for_input in keyboard.c.
4535 It is used to communicate to a lisp process-filter/sentinel (via the
4536 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4537 for user-input when that process-filter was called.
4538 waiting_for_input cannot be used as that is by definition 0 when
4539 lisp code is being evalled.
4540 This is also used in record_asynch_buffer_change.
4541 For that purpose, this must be 0
4542 when not inside wait_reading_process_output. */
4543 static int waiting_for_user_input_p;
4545 static void
4546 wait_reading_process_output_unwind (int data)
4548 waiting_for_user_input_p = data;
4551 /* This is here so breakpoints can be put on it. */
4552 static void
4553 wait_reading_process_output_1 (void)
4557 /* Read and dispose of subprocess output while waiting for timeout to
4558 elapse and/or keyboard input to be available.
4560 TIME_LIMIT is:
4561 timeout in seconds
4562 If negative, gobble data immediately available but don't wait for any.
4564 NSECS is:
4565 an additional duration to wait, measured in nanoseconds
4566 If TIME_LIMIT is zero, then:
4567 If NSECS == 0, there is no limit.
4568 If NSECS > 0, the timeout consists of NSECS only.
4569 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4571 READ_KBD is:
4572 0 to ignore keyboard input, or
4573 1 to return when input is available, or
4574 -1 meaning caller will actually read the input, so don't throw to
4575 the quit handler, or
4577 DO_DISPLAY means redisplay should be done to show subprocess
4578 output that arrives.
4580 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4581 (and gobble terminal input into the buffer if any arrives).
4583 If WAIT_PROC is specified, wait until something arrives from that
4584 process.
4586 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4587 (suspending output from other processes). A negative value
4588 means don't run any timers either.
4590 Return positive if we received input from WAIT_PROC (or from any
4591 process if WAIT_PROC is null), zero if we attempted to receive
4592 input but got none, and negative if we didn't even try. */
4595 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4596 bool do_display,
4597 Lisp_Object wait_for_cell,
4598 struct Lisp_Process *wait_proc, int just_wait_proc)
4600 int channel, nfds;
4601 fd_set Available;
4602 fd_set Writeok;
4603 bool check_write;
4604 int check_delay;
4605 bool no_avail;
4606 int xerrno;
4607 Lisp_Object proc;
4608 struct timespec timeout, end_time;
4609 int got_some_input = -1;
4610 ptrdiff_t count = SPECPDL_INDEX ();
4612 FD_ZERO (&Available);
4613 FD_ZERO (&Writeok);
4615 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4616 && !(CONSP (wait_proc->status)
4617 && EQ (XCAR (wait_proc->status), Qexit)))
4618 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4620 record_unwind_protect_int (wait_reading_process_output_unwind,
4621 waiting_for_user_input_p);
4622 waiting_for_user_input_p = read_kbd;
4624 if (time_limit < 0)
4626 time_limit = 0;
4627 nsecs = -1;
4629 else if (TYPE_MAXIMUM (time_t) < time_limit)
4630 time_limit = TYPE_MAXIMUM (time_t);
4632 /* Since we may need to wait several times,
4633 compute the absolute time to return at. */
4634 if (time_limit || nsecs > 0)
4636 timeout = make_timespec (time_limit, nsecs);
4637 end_time = timespec_add (current_timespec (), timeout);
4640 while (1)
4642 bool timeout_reduced_for_timers = false;
4644 /* If calling from keyboard input, do not quit
4645 since we want to return C-g as an input character.
4646 Otherwise, do pending quit if requested. */
4647 if (read_kbd >= 0)
4648 QUIT;
4649 else if (pending_signals)
4650 process_pending_signals ();
4652 /* Exit now if the cell we're waiting for became non-nil. */
4653 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4654 break;
4656 /* After reading input, vacuum up any leftovers without waiting. */
4657 if (0 <= got_some_input)
4658 nsecs = -1;
4660 /* Compute time from now till when time limit is up. */
4661 /* Exit if already run out. */
4662 if (nsecs < 0)
4664 /* A negative timeout means
4665 gobble output available now
4666 but don't wait at all. */
4668 timeout = make_timespec (0, 0);
4670 else if (time_limit || nsecs > 0)
4672 struct timespec now = current_timespec ();
4673 if (timespec_cmp (end_time, now) <= 0)
4674 break;
4675 timeout = timespec_sub (end_time, now);
4677 else
4679 timeout = make_timespec (100000, 0);
4682 /* Normally we run timers here.
4683 But not if wait_for_cell; in those cases,
4684 the wait is supposed to be short,
4685 and those callers cannot handle running arbitrary Lisp code here. */
4686 if (NILP (wait_for_cell)
4687 && just_wait_proc >= 0)
4689 struct timespec timer_delay;
4693 unsigned old_timers_run = timers_run;
4694 struct buffer *old_buffer = current_buffer;
4695 Lisp_Object old_window = selected_window;
4697 timer_delay = timer_check ();
4699 /* If a timer has run, this might have changed buffers
4700 an alike. Make read_key_sequence aware of that. */
4701 if (timers_run != old_timers_run
4702 && (old_buffer != current_buffer
4703 || !EQ (old_window, selected_window))
4704 && waiting_for_user_input_p == -1)
4705 record_asynch_buffer_change ();
4707 if (timers_run != old_timers_run && do_display)
4708 /* We must retry, since a timer may have requeued itself
4709 and that could alter the time_delay. */
4710 redisplay_preserve_echo_area (9);
4711 else
4712 break;
4714 while (!detect_input_pending ());
4716 /* If there is unread keyboard input, also return. */
4717 if (read_kbd != 0
4718 && requeued_events_pending_p ())
4719 break;
4721 /* A negative timeout means do not wait at all. */
4722 if (nsecs >= 0)
4724 if (timespec_valid_p (timer_delay))
4726 if (timespec_cmp (timer_delay, timeout) < 0)
4728 timeout = timer_delay;
4729 timeout_reduced_for_timers = true;
4732 else
4734 /* This is so a breakpoint can be put here. */
4735 wait_reading_process_output_1 ();
4740 /* Cause C-g and alarm signals to take immediate action,
4741 and cause input available signals to zero out timeout.
4743 It is important that we do this before checking for process
4744 activity. If we get a SIGCHLD after the explicit checks for
4745 process activity, timeout is the only way we will know. */
4746 if (read_kbd < 0)
4747 set_waiting_for_input (&timeout);
4749 /* If status of something has changed, and no input is
4750 available, notify the user of the change right away. After
4751 this explicit check, we'll let the SIGCHLD handler zap
4752 timeout to get our attention. */
4753 if (update_tick != process_tick)
4755 fd_set Atemp;
4756 fd_set Ctemp;
4758 if (kbd_on_hold_p ())
4759 FD_ZERO (&Atemp);
4760 else
4761 Atemp = input_wait_mask;
4762 Ctemp = write_mask;
4764 timeout = make_timespec (0, 0);
4765 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4766 &Atemp,
4767 #ifdef NON_BLOCKING_CONNECT
4768 (num_pending_connects > 0 ? &Ctemp : NULL),
4769 #else
4770 NULL,
4771 #endif
4772 NULL, &timeout, NULL)
4773 <= 0))
4775 /* It's okay for us to do this and then continue with
4776 the loop, since timeout has already been zeroed out. */
4777 clear_waiting_for_input ();
4778 got_some_input = status_notify (NULL, wait_proc);
4779 if (do_display) redisplay_preserve_echo_area (13);
4783 /* Don't wait for output from a non-running process. Just
4784 read whatever data has already been received. */
4785 if (wait_proc && wait_proc->raw_status_new)
4786 update_status (wait_proc);
4787 if (wait_proc
4788 && wait_proc->infd >= 0
4789 && ! EQ (wait_proc->status, Qrun)
4790 && ! EQ (wait_proc->status, Qconnect))
4792 bool read_some_bytes = false;
4794 clear_waiting_for_input ();
4795 XSETPROCESS (proc, wait_proc);
4797 /* Read data from the process, until we exhaust it. */
4798 while (true)
4800 int nread = read_process_output (proc, wait_proc->infd);
4801 if (nread < 0)
4803 if (errno == EIO || errno == EAGAIN)
4804 break;
4805 #ifdef EWOULDBLOCK
4806 if (errno == EWOULDBLOCK)
4807 break;
4808 #endif
4810 else
4812 if (got_some_input < nread)
4813 got_some_input = nread;
4814 if (nread == 0)
4815 break;
4816 read_some_bytes = true;
4819 if (read_some_bytes && do_display)
4820 redisplay_preserve_echo_area (10);
4822 break;
4825 /* Wait till there is something to do. */
4827 if (wait_proc && just_wait_proc)
4829 if (wait_proc->infd < 0) /* Terminated. */
4830 break;
4831 FD_SET (wait_proc->infd, &Available);
4832 check_delay = 0;
4833 check_write = 0;
4835 else if (!NILP (wait_for_cell))
4837 Available = non_process_wait_mask;
4838 check_delay = 0;
4839 check_write = 0;
4841 else
4843 if (! read_kbd)
4844 Available = non_keyboard_wait_mask;
4845 else
4846 Available = input_wait_mask;
4847 Writeok = write_mask;
4848 check_delay = wait_proc ? 0 : process_output_delay_count;
4849 check_write = true;
4852 /* If frame size has changed or the window is newly mapped,
4853 redisplay now, before we start to wait. There is a race
4854 condition here; if a SIGIO arrives between now and the select
4855 and indicates that a frame is trashed, the select may block
4856 displaying a trashed screen. */
4857 if (frame_garbaged && do_display)
4859 clear_waiting_for_input ();
4860 redisplay_preserve_echo_area (11);
4861 if (read_kbd < 0)
4862 set_waiting_for_input (&timeout);
4865 /* Skip the `select' call if input is available and we're
4866 waiting for keyboard input or a cell change (which can be
4867 triggered by processing X events). In the latter case, set
4868 nfds to 1 to avoid breaking the loop. */
4869 no_avail = 0;
4870 if ((read_kbd || !NILP (wait_for_cell))
4871 && detect_input_pending ())
4873 nfds = read_kbd ? 0 : 1;
4874 no_avail = 1;
4875 FD_ZERO (&Available);
4878 if (!no_avail)
4881 #ifdef ADAPTIVE_READ_BUFFERING
4882 /* Set the timeout for adaptive read buffering if any
4883 process has non-zero read_output_skip and non-zero
4884 read_output_delay, and we are not reading output for a
4885 specific process. It is not executed if
4886 Vprocess_adaptive_read_buffering is nil. */
4887 if (process_output_skip && check_delay > 0)
4889 int nsecs = timeout.tv_nsec;
4890 if (timeout.tv_sec > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4891 nsecs = READ_OUTPUT_DELAY_MAX;
4892 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4894 proc = chan_process[channel];
4895 if (NILP (proc))
4896 continue;
4897 /* Find minimum non-zero read_output_delay among the
4898 processes with non-zero read_output_skip. */
4899 if (XPROCESS (proc)->read_output_delay > 0)
4901 check_delay--;
4902 if (!XPROCESS (proc)->read_output_skip)
4903 continue;
4904 FD_CLR (channel, &Available);
4905 XPROCESS (proc)->read_output_skip = 0;
4906 if (XPROCESS (proc)->read_output_delay < nsecs)
4907 nsecs = XPROCESS (proc)->read_output_delay;
4910 timeout = make_timespec (0, nsecs);
4911 process_output_skip = 0;
4913 #endif
4915 #if defined (HAVE_NS)
4916 nfds = ns_select
4917 #elif defined (HAVE_GLIB)
4918 nfds = xg_select
4919 #else
4920 nfds = pselect
4921 #endif
4922 (max (max_process_desc, max_input_desc) + 1,
4923 &Available,
4924 (check_write ? &Writeok : 0),
4925 NULL, &timeout, NULL);
4927 #ifdef HAVE_GNUTLS
4928 /* GnuTLS buffers data internally. In lowat mode it leaves
4929 some data in the TCP buffers so that select works, but
4930 with custom pull/push functions we need to check if some
4931 data is available in the buffers manually. */
4932 if (nfds == 0)
4934 if (! wait_proc)
4936 /* We're not waiting on a specific process, so loop
4937 through all the channels and check for data.
4938 This is a workaround needed for some versions of
4939 the gnutls library -- 2.12.14 has been confirmed
4940 to need it. See
4941 http://comments.gmane.org/gmane.emacs.devel/145074 */
4942 for (channel = 0; channel < FD_SETSIZE; ++channel)
4943 if (! NILP (chan_process[channel]))
4945 struct Lisp_Process *p =
4946 XPROCESS (chan_process[channel]);
4947 if (p && p->gnutls_p && p->gnutls_state
4948 && ((emacs_gnutls_record_check_pending
4949 (p->gnutls_state))
4950 > 0))
4952 nfds++;
4953 eassert (p->infd == channel);
4954 FD_SET (p->infd, &Available);
4958 else
4960 /* Check this specific channel. */
4961 if (wait_proc->gnutls_p /* Check for valid process. */
4962 && wait_proc->gnutls_state
4963 /* Do we have pending data? */
4964 && ((emacs_gnutls_record_check_pending
4965 (wait_proc->gnutls_state))
4966 > 0))
4968 nfds = 1;
4969 eassert (0 <= wait_proc->infd);
4970 /* Set to Available. */
4971 FD_SET (wait_proc->infd, &Available);
4975 #endif
4978 xerrno = errno;
4980 /* Make C-g and alarm signals set flags again. */
4981 clear_waiting_for_input ();
4983 /* If we woke up due to SIGWINCH, actually change size now. */
4984 do_pending_window_change (0);
4986 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4987 /* We waited the full specified time, so return now. */
4988 break;
4989 if (nfds < 0)
4991 if (xerrno == EINTR)
4992 no_avail = 1;
4993 else if (xerrno == EBADF)
4994 emacs_abort ();
4995 else
4996 report_file_errno ("Failed select", Qnil, xerrno);
4999 /* Check for keyboard input. */
5000 /* If there is any, return immediately
5001 to give it higher priority than subprocesses. */
5003 if (read_kbd != 0)
5005 unsigned old_timers_run = timers_run;
5006 struct buffer *old_buffer = current_buffer;
5007 Lisp_Object old_window = selected_window;
5008 bool leave = false;
5010 if (detect_input_pending_run_timers (do_display))
5012 swallow_events (do_display);
5013 if (detect_input_pending_run_timers (do_display))
5014 leave = true;
5017 /* If a timer has run, this might have changed buffers
5018 an alike. Make read_key_sequence aware of that. */
5019 if (timers_run != old_timers_run
5020 && waiting_for_user_input_p == -1
5021 && (old_buffer != current_buffer
5022 || !EQ (old_window, selected_window)))
5023 record_asynch_buffer_change ();
5025 if (leave)
5026 break;
5029 /* If there is unread keyboard input, also return. */
5030 if (read_kbd != 0
5031 && requeued_events_pending_p ())
5032 break;
5034 /* If we are not checking for keyboard input now,
5035 do process events (but don't run any timers).
5036 This is so that X events will be processed.
5037 Otherwise they may have to wait until polling takes place.
5038 That would causes delays in pasting selections, for example.
5040 (We used to do this only if wait_for_cell.) */
5041 if (read_kbd == 0 && detect_input_pending ())
5043 swallow_events (do_display);
5044 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5045 if (detect_input_pending ())
5046 break;
5047 #endif
5050 /* Exit now if the cell we're waiting for became non-nil. */
5051 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5052 break;
5054 #ifdef USABLE_SIGIO
5055 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5056 go read it. This can happen with X on BSD after logging out.
5057 In that case, there really is no input and no SIGIO,
5058 but select says there is input. */
5060 if (read_kbd && interrupt_input
5061 && keyboard_bit_set (&Available) && ! noninteractive)
5062 handle_input_available_signal (SIGIO);
5063 #endif
5065 /* If checking input just got us a size-change event from X,
5066 obey it now if we should. */
5067 if (read_kbd || ! NILP (wait_for_cell))
5068 do_pending_window_change (0);
5070 /* Check for data from a process. */
5071 if (no_avail || nfds == 0)
5072 continue;
5074 for (channel = 0; channel <= max_input_desc; ++channel)
5076 struct fd_callback_data *d = &fd_callback_info[channel];
5077 if (d->func
5078 && ((d->condition & FOR_READ
5079 && FD_ISSET (channel, &Available))
5080 || (d->condition & FOR_WRITE
5081 && FD_ISSET (channel, &write_mask))))
5082 d->func (channel, d->data);
5085 for (channel = 0; channel <= max_process_desc; channel++)
5087 if (FD_ISSET (channel, &Available)
5088 && FD_ISSET (channel, &non_keyboard_wait_mask)
5089 && !FD_ISSET (channel, &non_process_wait_mask))
5091 int nread;
5093 /* If waiting for this channel, arrange to return as
5094 soon as no more input to be processed. No more
5095 waiting. */
5096 proc = chan_process[channel];
5097 if (NILP (proc))
5098 continue;
5100 /* If this is a server stream socket, accept connection. */
5101 if (EQ (XPROCESS (proc)->status, Qlisten))
5103 server_accept_connection (proc, channel);
5104 continue;
5107 /* Read data from the process, starting with our
5108 buffered-ahead character if we have one. */
5110 nread = read_process_output (proc, channel);
5111 if ((!wait_proc || wait_proc == XPROCESS (proc)) && got_some_input < nread)
5112 got_some_input = nread;
5113 if (nread > 0)
5115 /* Since read_process_output can run a filter,
5116 which can call accept-process-output,
5117 don't try to read from any other processes
5118 before doing the select again. */
5119 FD_ZERO (&Available);
5121 if (do_display)
5122 redisplay_preserve_echo_area (12);
5124 #ifdef EWOULDBLOCK
5125 else if (nread == -1 && errno == EWOULDBLOCK)
5127 #endif
5128 else if (nread == -1 && errno == EAGAIN)
5130 #ifdef WINDOWSNT
5131 /* FIXME: Is this special case still needed? */
5132 /* Note that we cannot distinguish between no input
5133 available now and a closed pipe.
5134 With luck, a closed pipe will be accompanied by
5135 subprocess termination and SIGCHLD. */
5136 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5137 && !PIPECONN_P (proc))
5139 #endif
5140 #ifdef HAVE_PTYS
5141 /* On some OSs with ptys, when the process on one end of
5142 a pty exits, the other end gets an error reading with
5143 errno = EIO instead of getting an EOF (0 bytes read).
5144 Therefore, if we get an error reading and errno =
5145 EIO, just continue, because the child process has
5146 exited and should clean itself up soon (e.g. when we
5147 get a SIGCHLD). */
5148 else if (nread == -1 && errno == EIO)
5150 struct Lisp_Process *p = XPROCESS (proc);
5152 /* Clear the descriptor now, so we only raise the
5153 signal once. */
5154 FD_CLR (channel, &input_wait_mask);
5155 FD_CLR (channel, &non_keyboard_wait_mask);
5157 if (p->pid == -2)
5159 /* If the EIO occurs on a pty, the SIGCHLD handler's
5160 waitpid call will not find the process object to
5161 delete. Do it here. */
5162 p->tick = ++process_tick;
5163 pset_status (p, Qfailed);
5166 #endif /* HAVE_PTYS */
5167 /* If we can detect process termination, don't consider the
5168 process gone just because its pipe is closed. */
5169 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc)
5170 && !PIPECONN_P (proc))
5172 else if (nread == 0 && PIPECONN_P (proc))
5174 /* Preserve status of processes already terminated. */
5175 XPROCESS (proc)->tick = ++process_tick;
5176 deactivate_process (proc);
5177 if (EQ (XPROCESS (proc)->status, Qrun))
5178 pset_status (XPROCESS (proc),
5179 list2 (Qexit, make_number (0)));
5181 else
5183 /* Preserve status of processes already terminated. */
5184 XPROCESS (proc)->tick = ++process_tick;
5185 deactivate_process (proc);
5186 if (XPROCESS (proc)->raw_status_new)
5187 update_status (XPROCESS (proc));
5188 if (EQ (XPROCESS (proc)->status, Qrun))
5189 pset_status (XPROCESS (proc),
5190 list2 (Qexit, make_number (256)));
5193 #ifdef NON_BLOCKING_CONNECT
5194 if (FD_ISSET (channel, &Writeok)
5195 && FD_ISSET (channel, &connect_wait_mask))
5197 struct Lisp_Process *p;
5199 FD_CLR (channel, &connect_wait_mask);
5200 FD_CLR (channel, &write_mask);
5201 if (--num_pending_connects < 0)
5202 emacs_abort ();
5204 proc = chan_process[channel];
5205 if (NILP (proc))
5206 continue;
5208 p = XPROCESS (proc);
5210 #ifdef GNU_LINUX
5211 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5212 So only use it on systems where it is known to work. */
5214 socklen_t xlen = sizeof (xerrno);
5215 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5216 xerrno = errno;
5218 #else
5220 struct sockaddr pname;
5221 socklen_t pnamelen = sizeof (pname);
5223 /* If connection failed, getpeername will fail. */
5224 xerrno = 0;
5225 if (getpeername (channel, &pname, &pnamelen) < 0)
5227 /* Obtain connect failure code through error slippage. */
5228 char dummy;
5229 xerrno = errno;
5230 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5231 xerrno = errno;
5234 #endif
5235 if (xerrno)
5237 p->tick = ++process_tick;
5238 pset_status (p, list2 (Qfailed, make_number (xerrno)));
5239 deactivate_process (proc);
5241 else
5243 pset_status (p, Qrun);
5244 /* Execute the sentinel here. If we had relied on
5245 status_notify to do it later, it will read input
5246 from the process before calling the sentinel. */
5247 exec_sentinel (proc, build_string ("open\n"));
5248 if (0 <= p->infd && !EQ (p->filter, Qt)
5249 && !EQ (p->command, Qt))
5251 FD_SET (p->infd, &input_wait_mask);
5252 FD_SET (p->infd, &non_keyboard_wait_mask);
5256 #endif /* NON_BLOCKING_CONNECT */
5257 } /* End for each file descriptor. */
5258 } /* End while exit conditions not met. */
5260 unbind_to (count, Qnil);
5262 /* If calling from keyboard input, do not quit
5263 since we want to return C-g as an input character.
5264 Otherwise, do pending quit if requested. */
5265 if (read_kbd >= 0)
5267 /* Prevent input_pending from remaining set if we quit. */
5268 clear_input_pending ();
5269 QUIT;
5272 return got_some_input;
5275 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5277 static Lisp_Object
5278 read_process_output_call (Lisp_Object fun_and_args)
5280 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5283 static Lisp_Object
5284 read_process_output_error_handler (Lisp_Object error_val)
5286 cmd_error_internal (error_val, "error in process filter: ");
5287 Vinhibit_quit = Qt;
5288 update_echo_area ();
5289 Fsleep_for (make_number (2), Qnil);
5290 return Qt;
5293 static void
5294 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5295 ssize_t nbytes,
5296 struct coding_system *coding);
5298 /* Read pending output from the process channel,
5299 starting with our buffered-ahead character if we have one.
5300 Yield number of decoded characters read.
5302 This function reads at most 4096 characters.
5303 If you want to read all available subprocess output,
5304 you must call it repeatedly until it returns zero.
5306 The characters read are decoded according to PROC's coding-system
5307 for decoding. */
5309 static int
5310 read_process_output (Lisp_Object proc, int channel)
5312 ssize_t nbytes;
5313 struct Lisp_Process *p = XPROCESS (proc);
5314 struct coding_system *coding = proc_decode_coding_system[channel];
5315 int carryover = p->decoding_carryover;
5316 enum { readmax = 4096 };
5317 ptrdiff_t count = SPECPDL_INDEX ();
5318 Lisp_Object odeactivate;
5319 char chars[sizeof coding->carryover + readmax];
5321 if (carryover)
5322 /* See the comment above. */
5323 memcpy (chars, SDATA (p->decoding_buf), carryover);
5325 #ifdef DATAGRAM_SOCKETS
5326 /* We have a working select, so proc_buffered_char is always -1. */
5327 if (DATAGRAM_CHAN_P (channel))
5329 socklen_t len = datagram_address[channel].len;
5330 nbytes = recvfrom (channel, chars + carryover, readmax,
5331 0, datagram_address[channel].sa, &len);
5333 else
5334 #endif
5336 bool buffered = proc_buffered_char[channel] >= 0;
5337 if (buffered)
5339 chars[carryover] = proc_buffered_char[channel];
5340 proc_buffered_char[channel] = -1;
5342 #ifdef HAVE_GNUTLS
5343 if (p->gnutls_p && p->gnutls_state)
5344 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5345 readmax - buffered);
5346 else
5347 #endif
5348 nbytes = emacs_read (channel, chars + carryover + buffered,
5349 readmax - buffered);
5350 #ifdef ADAPTIVE_READ_BUFFERING
5351 if (nbytes > 0 && p->adaptive_read_buffering)
5353 int delay = p->read_output_delay;
5354 if (nbytes < 256)
5356 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5358 if (delay == 0)
5359 process_output_delay_count++;
5360 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5363 else if (delay > 0 && nbytes == readmax - buffered)
5365 delay -= READ_OUTPUT_DELAY_INCREMENT;
5366 if (delay == 0)
5367 process_output_delay_count--;
5369 p->read_output_delay = delay;
5370 if (delay)
5372 p->read_output_skip = 1;
5373 process_output_skip = 1;
5376 #endif
5377 nbytes += buffered;
5378 nbytes += buffered && nbytes <= 0;
5381 p->decoding_carryover = 0;
5383 /* At this point, NBYTES holds number of bytes just received
5384 (including the one in proc_buffered_char[channel]). */
5385 if (nbytes <= 0)
5387 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5388 return nbytes;
5389 coding->mode |= CODING_MODE_LAST_BLOCK;
5392 /* Now set NBYTES how many bytes we must decode. */
5393 nbytes += carryover;
5395 odeactivate = Vdeactivate_mark;
5396 /* There's no good reason to let process filters change the current
5397 buffer, and many callers of accept-process-output, sit-for, and
5398 friends don't expect current-buffer to be changed from under them. */
5399 record_unwind_current_buffer ();
5401 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5403 /* Handling the process output should not deactivate the mark. */
5404 Vdeactivate_mark = odeactivate;
5406 unbind_to (count, Qnil);
5407 return nbytes;
5410 static void
5411 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5412 ssize_t nbytes,
5413 struct coding_system *coding)
5415 Lisp_Object outstream = p->filter;
5416 Lisp_Object text;
5417 bool outer_running_asynch_code = running_asynch_code;
5418 int waiting = waiting_for_user_input_p;
5420 /* No need to gcpro these, because all we do with them later
5421 is test them for EQness, and none of them should be a string. */
5422 #if 0
5423 Lisp_Object obuffer, okeymap;
5424 XSETBUFFER (obuffer, current_buffer);
5425 okeymap = BVAR (current_buffer, keymap);
5426 #endif
5428 /* We inhibit quit here instead of just catching it so that
5429 hitting ^G when a filter happens to be running won't screw
5430 it up. */
5431 specbind (Qinhibit_quit, Qt);
5432 specbind (Qlast_nonmenu_event, Qt);
5434 /* In case we get recursively called,
5435 and we already saved the match data nonrecursively,
5436 save the same match data in safely recursive fashion. */
5437 if (outer_running_asynch_code)
5439 Lisp_Object tem;
5440 /* Don't clobber the CURRENT match data, either! */
5441 tem = Fmatch_data (Qnil, Qnil, Qnil);
5442 restore_search_regs ();
5443 record_unwind_save_match_data ();
5444 Fset_match_data (tem, Qt);
5447 /* For speed, if a search happens within this code,
5448 save the match data in a special nonrecursive fashion. */
5449 running_asynch_code = 1;
5451 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5452 text = coding->dst_object;
5453 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5454 /* A new coding system might be found. */
5455 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5457 pset_decode_coding_system (p, Vlast_coding_system_used);
5459 /* Don't call setup_coding_system for
5460 proc_decode_coding_system[channel] here. It is done in
5461 detect_coding called via decode_coding above. */
5463 /* If a coding system for encoding is not yet decided, we set
5464 it as the same as coding-system for decoding.
5466 But, before doing that we must check if
5467 proc_encode_coding_system[p->outfd] surely points to a
5468 valid memory because p->outfd will be changed once EOF is
5469 sent to the process. */
5470 if (NILP (p->encode_coding_system) && p->outfd >= 0
5471 && proc_encode_coding_system[p->outfd])
5473 pset_encode_coding_system
5474 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5475 setup_coding_system (p->encode_coding_system,
5476 proc_encode_coding_system[p->outfd]);
5480 if (coding->carryover_bytes > 0)
5482 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5483 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5484 memcpy (SDATA (p->decoding_buf), coding->carryover,
5485 coding->carryover_bytes);
5486 p->decoding_carryover = coding->carryover_bytes;
5488 if (SBYTES (text) > 0)
5489 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5490 sometimes it's simply wrong to wrap (e.g. when called from
5491 accept-process-output). */
5492 internal_condition_case_1 (read_process_output_call,
5493 list3 (outstream, make_lisp_proc (p), text),
5494 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5495 read_process_output_error_handler);
5497 /* If we saved the match data nonrecursively, restore it now. */
5498 restore_search_regs ();
5499 running_asynch_code = outer_running_asynch_code;
5501 /* Restore waiting_for_user_input_p as it was
5502 when we were called, in case the filter clobbered it. */
5503 waiting_for_user_input_p = waiting;
5505 #if 0 /* Call record_asynch_buffer_change unconditionally,
5506 because we might have changed minor modes or other things
5507 that affect key bindings. */
5508 if (! EQ (Fcurrent_buffer (), obuffer)
5509 || ! EQ (current_buffer->keymap, okeymap))
5510 #endif
5511 /* But do it only if the caller is actually going to read events.
5512 Otherwise there's no need to make him wake up, and it could
5513 cause trouble (for example it would make sit_for return). */
5514 if (waiting_for_user_input_p == -1)
5515 record_asynch_buffer_change ();
5518 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5519 Sinternal_default_process_filter, 2, 2, 0,
5520 doc: /* Function used as default process filter.
5521 This inserts the process's output into its buffer, if there is one.
5522 Otherwise it discards the output. */)
5523 (Lisp_Object proc, Lisp_Object text)
5525 struct Lisp_Process *p;
5526 ptrdiff_t opoint;
5528 CHECK_PROCESS (proc);
5529 p = XPROCESS (proc);
5530 CHECK_STRING (text);
5532 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5534 Lisp_Object old_read_only;
5535 ptrdiff_t old_begv, old_zv;
5536 ptrdiff_t old_begv_byte, old_zv_byte;
5537 ptrdiff_t before, before_byte;
5538 ptrdiff_t opoint_byte;
5539 struct buffer *b;
5541 Fset_buffer (p->buffer);
5542 opoint = PT;
5543 opoint_byte = PT_BYTE;
5544 old_read_only = BVAR (current_buffer, read_only);
5545 old_begv = BEGV;
5546 old_zv = ZV;
5547 old_begv_byte = BEGV_BYTE;
5548 old_zv_byte = ZV_BYTE;
5550 bset_read_only (current_buffer, Qnil);
5552 /* Insert new output into buffer at the current end-of-output
5553 marker, thus preserving logical ordering of input and output. */
5554 if (XMARKER (p->mark)->buffer)
5555 set_point_from_marker (p->mark);
5556 else
5557 SET_PT_BOTH (ZV, ZV_BYTE);
5558 before = PT;
5559 before_byte = PT_BYTE;
5561 /* If the output marker is outside of the visible region, save
5562 the restriction and widen. */
5563 if (! (BEGV <= PT && PT <= ZV))
5564 Fwiden ();
5566 /* Adjust the multibyteness of TEXT to that of the buffer. */
5567 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5568 != ! STRING_MULTIBYTE (text))
5569 text = (STRING_MULTIBYTE (text)
5570 ? Fstring_as_unibyte (text)
5571 : Fstring_to_multibyte (text));
5572 /* Insert before markers in case we are inserting where
5573 the buffer's mark is, and the user's next command is Meta-y. */
5574 insert_from_string_before_markers (text, 0, 0,
5575 SCHARS (text), SBYTES (text), 0);
5577 /* Make sure the process marker's position is valid when the
5578 process buffer is changed in the signal_after_change above.
5579 W3 is known to do that. */
5580 if (BUFFERP (p->buffer)
5581 && (b = XBUFFER (p->buffer), b != current_buffer))
5582 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5583 else
5584 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5586 update_mode_lines = 23;
5588 /* Make sure opoint and the old restrictions
5589 float ahead of any new text just as point would. */
5590 if (opoint >= before)
5592 opoint += PT - before;
5593 opoint_byte += PT_BYTE - before_byte;
5595 if (old_begv > before)
5597 old_begv += PT - before;
5598 old_begv_byte += PT_BYTE - before_byte;
5600 if (old_zv >= before)
5602 old_zv += PT - before;
5603 old_zv_byte += PT_BYTE - before_byte;
5606 /* If the restriction isn't what it should be, set it. */
5607 if (old_begv != BEGV || old_zv != ZV)
5608 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5610 bset_read_only (current_buffer, old_read_only);
5611 SET_PT_BOTH (opoint, opoint_byte);
5613 return Qnil;
5616 /* Sending data to subprocess. */
5618 /* In send_process, when a write fails temporarily,
5619 wait_reading_process_output is called. It may execute user code,
5620 e.g. timers, that attempts to write new data to the same process.
5621 We must ensure that data is sent in the right order, and not
5622 interspersed half-completed with other writes (Bug#10815). This is
5623 handled by the write_queue element of struct process. It is a list
5624 with each entry having the form
5626 (string . (offset . length))
5628 where STRING is a lisp string, OFFSET is the offset into the
5629 string's byte sequence from which we should begin to send, and
5630 LENGTH is the number of bytes left to send. */
5632 /* Create a new entry in write_queue.
5633 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5634 BUF is a pointer to the string sequence of the input_obj or a C
5635 string in case of Qt or Qnil. */
5637 static void
5638 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5639 const char *buf, ptrdiff_t len, bool front)
5641 ptrdiff_t offset;
5642 Lisp_Object entry, obj;
5644 if (STRINGP (input_obj))
5646 offset = buf - SSDATA (input_obj);
5647 obj = input_obj;
5649 else
5651 offset = 0;
5652 obj = make_unibyte_string (buf, len);
5655 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5657 if (front)
5658 pset_write_queue (p, Fcons (entry, p->write_queue));
5659 else
5660 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5663 /* Remove the first element in the write_queue of process P, put its
5664 contents in OBJ, BUF and LEN, and return true. If the
5665 write_queue is empty, return false. */
5667 static bool
5668 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5669 const char **buf, ptrdiff_t *len)
5671 Lisp_Object entry, offset_length;
5672 ptrdiff_t offset;
5674 if (NILP (p->write_queue))
5675 return 0;
5677 entry = XCAR (p->write_queue);
5678 pset_write_queue (p, XCDR (p->write_queue));
5680 *obj = XCAR (entry);
5681 offset_length = XCDR (entry);
5683 *len = XINT (XCDR (offset_length));
5684 offset = XINT (XCAR (offset_length));
5685 *buf = SSDATA (*obj) + offset;
5687 return 1;
5690 /* Send some data to process PROC.
5691 BUF is the beginning of the data; LEN is the number of characters.
5692 OBJECT is the Lisp object that the data comes from. If OBJECT is
5693 nil or t, it means that the data comes from C string.
5695 If OBJECT is not nil, the data is encoded by PROC's coding-system
5696 for encoding before it is sent.
5698 This function can evaluate Lisp code and can garbage collect. */
5700 static void
5701 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5702 Lisp_Object object)
5704 struct Lisp_Process *p = XPROCESS (proc);
5705 ssize_t rv;
5706 struct coding_system *coding;
5708 if (p->raw_status_new)
5709 update_status (p);
5710 if (! EQ (p->status, Qrun))
5711 error ("Process %s not running", SDATA (p->name));
5712 if (p->outfd < 0)
5713 error ("Output file descriptor of %s is closed", SDATA (p->name));
5715 coding = proc_encode_coding_system[p->outfd];
5716 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5718 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5719 || (BUFFERP (object)
5720 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5721 || EQ (object, Qt))
5723 pset_encode_coding_system
5724 (p, complement_process_encoding_system (p->encode_coding_system));
5725 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5727 /* The coding system for encoding was changed to raw-text
5728 because we sent a unibyte text previously. Now we are
5729 sending a multibyte text, thus we must encode it by the
5730 original coding system specified for the current process.
5732 Another reason we come here is that the coding system
5733 was just complemented and a new one was returned by
5734 complement_process_encoding_system. */
5735 setup_coding_system (p->encode_coding_system, coding);
5736 Vlast_coding_system_used = p->encode_coding_system;
5738 coding->src_multibyte = 1;
5740 else
5742 coding->src_multibyte = 0;
5743 /* For sending a unibyte text, character code conversion should
5744 not take place but EOL conversion should. So, setup raw-text
5745 or one of the subsidiary if we have not yet done it. */
5746 if (CODING_REQUIRE_ENCODING (coding))
5748 if (CODING_REQUIRE_FLUSHING (coding))
5750 /* But, before changing the coding, we must flush out data. */
5751 coding->mode |= CODING_MODE_LAST_BLOCK;
5752 send_process (proc, "", 0, Qt);
5753 coding->mode &= CODING_MODE_LAST_BLOCK;
5755 setup_coding_system (raw_text_coding_system
5756 (Vlast_coding_system_used),
5757 coding);
5758 coding->src_multibyte = 0;
5761 coding->dst_multibyte = 0;
5763 if (CODING_REQUIRE_ENCODING (coding))
5765 coding->dst_object = Qt;
5766 if (BUFFERP (object))
5768 ptrdiff_t from_byte, from, to;
5769 ptrdiff_t save_pt, save_pt_byte;
5770 struct buffer *cur = current_buffer;
5772 set_buffer_internal (XBUFFER (object));
5773 save_pt = PT, save_pt_byte = PT_BYTE;
5775 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5776 from = BYTE_TO_CHAR (from_byte);
5777 to = BYTE_TO_CHAR (from_byte + len);
5778 TEMP_SET_PT_BOTH (from, from_byte);
5779 encode_coding_object (coding, object, from, from_byte,
5780 to, from_byte + len, Qt);
5781 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5782 set_buffer_internal (cur);
5784 else if (STRINGP (object))
5786 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5787 SBYTES (object), Qt);
5789 else
5791 coding->dst_object = make_unibyte_string (buf, len);
5792 coding->produced = len;
5795 len = coding->produced;
5796 object = coding->dst_object;
5797 buf = SSDATA (object);
5800 /* If there is already data in the write_queue, put the new data
5801 in the back of queue. Otherwise, ignore it. */
5802 if (!NILP (p->write_queue))
5803 write_queue_push (p, object, buf, len, 0);
5805 do /* while !NILP (p->write_queue) */
5807 ptrdiff_t cur_len = -1;
5808 const char *cur_buf;
5809 Lisp_Object cur_object;
5811 /* If write_queue is empty, ignore it. */
5812 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5814 cur_len = len;
5815 cur_buf = buf;
5816 cur_object = object;
5819 while (cur_len > 0)
5821 /* Send this batch, using one or more write calls. */
5822 ptrdiff_t written = 0;
5823 int outfd = p->outfd;
5824 #ifdef DATAGRAM_SOCKETS
5825 if (DATAGRAM_CHAN_P (outfd))
5827 rv = sendto (outfd, cur_buf, cur_len,
5828 0, datagram_address[outfd].sa,
5829 datagram_address[outfd].len);
5830 if (rv >= 0)
5831 written = rv;
5832 else if (errno == EMSGSIZE)
5833 report_file_error ("Sending datagram", proc);
5835 else
5836 #endif
5838 #ifdef HAVE_GNUTLS
5839 if (p->gnutls_p && p->gnutls_state)
5840 written = emacs_gnutls_write (p, cur_buf, cur_len);
5841 else
5842 #endif
5843 written = emacs_write_sig (outfd, cur_buf, cur_len);
5844 rv = (written ? 0 : -1);
5845 #ifdef ADAPTIVE_READ_BUFFERING
5846 if (p->read_output_delay > 0
5847 && p->adaptive_read_buffering == 1)
5849 p->read_output_delay = 0;
5850 process_output_delay_count--;
5851 p->read_output_skip = 0;
5853 #endif
5856 if (rv < 0)
5858 if (errno == EAGAIN
5859 #ifdef EWOULDBLOCK
5860 || errno == EWOULDBLOCK
5861 #endif
5863 /* Buffer is full. Wait, accepting input;
5864 that may allow the program
5865 to finish doing output and read more. */
5867 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5868 /* A gross hack to work around a bug in FreeBSD.
5869 In the following sequence, read(2) returns
5870 bogus data:
5872 write(2) 1022 bytes
5873 write(2) 954 bytes, get EAGAIN
5874 read(2) 1024 bytes in process_read_output
5875 read(2) 11 bytes in process_read_output
5877 That is, read(2) returns more bytes than have
5878 ever been written successfully. The 1033 bytes
5879 read are the 1022 bytes written successfully
5880 after processing (for example with CRs added if
5881 the terminal is set up that way which it is
5882 here). The same bytes will be seen again in a
5883 later read(2), without the CRs. */
5885 if (errno == EAGAIN)
5887 int flags = FWRITE;
5888 ioctl (p->outfd, TIOCFLUSH, &flags);
5890 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5892 /* Put what we should have written in wait_queue. */
5893 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5894 wait_reading_process_output (0, 20 * 1000 * 1000,
5895 0, 0, Qnil, NULL, 0);
5896 /* Reread queue, to see what is left. */
5897 break;
5899 else if (errno == EPIPE)
5901 p->raw_status_new = 0;
5902 pset_status (p, list2 (Qexit, make_number (256)));
5903 p->tick = ++process_tick;
5904 deactivate_process (proc);
5905 error ("process %s no longer connected to pipe; closed it",
5906 SDATA (p->name));
5908 else
5909 /* This is a real error. */
5910 report_file_error ("Writing to process", proc);
5912 cur_buf += written;
5913 cur_len -= written;
5916 while (!NILP (p->write_queue));
5919 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5920 3, 3, 0,
5921 doc: /* Send current contents of region as input to PROCESS.
5922 PROCESS may be a process, a buffer, the name of a process or buffer, or
5923 nil, indicating the current buffer's process.
5924 Called from program, takes three arguments, PROCESS, START and END.
5925 If the region is more than 500 characters long,
5926 it is sent in several bunches. This may happen even for shorter regions.
5927 Output from processes can arrive in between bunches. */)
5928 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5930 Lisp_Object proc = get_process (process);
5931 ptrdiff_t start_byte, end_byte;
5933 validate_region (&start, &end);
5935 start_byte = CHAR_TO_BYTE (XINT (start));
5936 end_byte = CHAR_TO_BYTE (XINT (end));
5938 if (XINT (start) < GPT && XINT (end) > GPT)
5939 move_gap_both (XINT (start), start_byte);
5941 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5942 end_byte - start_byte, Fcurrent_buffer ());
5944 return Qnil;
5947 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5948 2, 2, 0,
5949 doc: /* Send PROCESS the contents of STRING as input.
5950 PROCESS may be a process, a buffer, the name of a process or buffer, or
5951 nil, indicating the current buffer's process.
5952 If STRING is more than 500 characters long,
5953 it is sent in several bunches. This may happen even for shorter strings.
5954 Output from processes can arrive in between bunches. */)
5955 (Lisp_Object process, Lisp_Object string)
5957 Lisp_Object proc;
5958 CHECK_STRING (string);
5959 proc = get_process (process);
5960 send_process (proc, SSDATA (string),
5961 SBYTES (string), string);
5962 return Qnil;
5965 /* Return the foreground process group for the tty/pty that
5966 the process P uses. */
5967 static pid_t
5968 emacs_get_tty_pgrp (struct Lisp_Process *p)
5970 pid_t gid = -1;
5972 #ifdef TIOCGPGRP
5973 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5975 int fd;
5976 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5977 master side. Try the slave side. */
5978 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5980 if (fd != -1)
5982 ioctl (fd, TIOCGPGRP, &gid);
5983 emacs_close (fd);
5986 #endif /* defined (TIOCGPGRP ) */
5988 return gid;
5991 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5992 Sprocess_running_child_p, 0, 1, 0,
5993 doc: /* Return non-nil if PROCESS has given the terminal to a
5994 child. If the operating system does not make it possible to find out,
5995 return t. If we can find out, return the numeric ID of the foreground
5996 process group. */)
5997 (Lisp_Object process)
5999 /* Initialize in case ioctl doesn't exist or gives an error,
6000 in a way that will cause returning t. */
6001 pid_t gid;
6002 Lisp_Object proc;
6003 struct Lisp_Process *p;
6005 proc = get_process (process);
6006 p = XPROCESS (proc);
6008 if (!EQ (p->type, Qreal))
6009 error ("Process %s is not a subprocess",
6010 SDATA (p->name));
6011 if (p->infd < 0)
6012 error ("Process %s is not active",
6013 SDATA (p->name));
6015 gid = emacs_get_tty_pgrp (p);
6017 if (gid == p->pid)
6018 return Qnil;
6019 if (gid != -1)
6020 return make_number (gid);
6021 return Qt;
6024 /* Send a signal number SIGNO to PROCESS.
6025 If CURRENT_GROUP is t, that means send to the process group
6026 that currently owns the terminal being used to communicate with PROCESS.
6027 This is used for various commands in shell mode.
6028 If CURRENT_GROUP is lambda, that means send to the process group
6029 that currently owns the terminal, but only if it is NOT the shell itself.
6031 If NOMSG is false, insert signal-announcements into process's buffers
6032 right away.
6034 If we can, we try to signal PROCESS by sending control characters
6035 down the pty. This allows us to signal inferiors who have changed
6036 their uid, for which kill would return an EPERM error. */
6038 static void
6039 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
6040 bool nomsg)
6042 Lisp_Object proc;
6043 struct Lisp_Process *p;
6044 pid_t gid;
6045 bool no_pgrp = 0;
6047 proc = get_process (process);
6048 p = XPROCESS (proc);
6050 if (!EQ (p->type, Qreal))
6051 error ("Process %s is not a subprocess",
6052 SDATA (p->name));
6053 if (p->infd < 0)
6054 error ("Process %s is not active",
6055 SDATA (p->name));
6057 if (!p->pty_flag)
6058 current_group = Qnil;
6060 /* If we are using pgrps, get a pgrp number and make it negative. */
6061 if (NILP (current_group))
6062 /* Send the signal to the shell's process group. */
6063 gid = p->pid;
6064 else
6066 #ifdef SIGNALS_VIA_CHARACTERS
6067 /* If possible, send signals to the entire pgrp
6068 by sending an input character to it. */
6070 struct termios t;
6071 cc_t *sig_char = NULL;
6073 tcgetattr (p->infd, &t);
6075 switch (signo)
6077 case SIGINT:
6078 sig_char = &t.c_cc[VINTR];
6079 break;
6081 case SIGQUIT:
6082 sig_char = &t.c_cc[VQUIT];
6083 break;
6085 case SIGTSTP:
6086 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6087 sig_char = &t.c_cc[VSWTCH];
6088 #else
6089 sig_char = &t.c_cc[VSUSP];
6090 #endif
6091 break;
6094 if (sig_char && *sig_char != CDISABLE)
6096 send_process (proc, (char *) sig_char, 1, Qnil);
6097 return;
6099 /* If we can't send the signal with a character,
6100 fall through and send it another way. */
6102 /* The code above may fall through if it can't
6103 handle the signal. */
6104 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6106 #ifdef TIOCGPGRP
6107 /* Get the current pgrp using the tty itself, if we have that.
6108 Otherwise, use the pty to get the pgrp.
6109 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6110 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6111 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6112 His patch indicates that if TIOCGPGRP returns an error, then
6113 we should just assume that p->pid is also the process group id. */
6115 gid = emacs_get_tty_pgrp (p);
6117 if (gid == -1)
6118 /* If we can't get the information, assume
6119 the shell owns the tty. */
6120 gid = p->pid;
6122 /* It is not clear whether anything really can set GID to -1.
6123 Perhaps on some system one of those ioctls can or could do so.
6124 Or perhaps this is vestigial. */
6125 if (gid == -1)
6126 no_pgrp = 1;
6127 #else /* ! defined (TIOCGPGRP) */
6128 /* Can't select pgrps on this system, so we know that
6129 the child itself heads the pgrp. */
6130 gid = p->pid;
6131 #endif /* ! defined (TIOCGPGRP) */
6133 /* If current_group is lambda, and the shell owns the terminal,
6134 don't send any signal. */
6135 if (EQ (current_group, Qlambda) && gid == p->pid)
6136 return;
6139 #ifdef SIGCONT
6140 if (signo == SIGCONT)
6142 p->raw_status_new = 0;
6143 pset_status (p, Qrun);
6144 p->tick = ++process_tick;
6145 if (!nomsg)
6147 status_notify (NULL, NULL);
6148 redisplay_preserve_echo_area (13);
6151 #endif
6153 #ifdef TIOCSIGSEND
6154 /* Work around a HP-UX 7.0 bug that mishandles signals to subjobs.
6155 We don't know whether the bug is fixed in later HP-UX versions. */
6156 if (! NILP (current_group) && ioctl (p->infd, TIOCSIGSEND, signo) != -1)
6157 return;
6158 #endif
6160 /* If we don't have process groups, send the signal to the immediate
6161 subprocess. That isn't really right, but it's better than any
6162 obvious alternative. */
6163 pid_t pid = no_pgrp ? gid : - gid;
6165 /* Do not kill an already-reaped process, as that could kill an
6166 innocent bystander that happens to have the same process ID. */
6167 sigset_t oldset;
6168 block_child_signal (&oldset);
6169 if (p->alive)
6170 kill (pid, signo);
6171 unblock_child_signal (&oldset);
6174 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6175 doc: /* Interrupt process PROCESS.
6176 PROCESS may be a process, a buffer, or the name of a process or buffer.
6177 No arg or nil means current buffer's process.
6178 Second arg CURRENT-GROUP non-nil means send signal to
6179 the current process-group of the process's controlling terminal
6180 rather than to the process's own process group.
6181 If the process is a shell, this means interrupt current subjob
6182 rather than the shell.
6184 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6185 don't send the signal. */)
6186 (Lisp_Object process, Lisp_Object current_group)
6188 process_send_signal (process, SIGINT, current_group, 0);
6189 return process;
6192 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6193 doc: /* Kill process PROCESS. May be process or name of one.
6194 See function `interrupt-process' for more details on usage. */)
6195 (Lisp_Object process, Lisp_Object current_group)
6197 process_send_signal (process, SIGKILL, current_group, 0);
6198 return process;
6201 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6202 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6203 See function `interrupt-process' for more details on usage. */)
6204 (Lisp_Object process, Lisp_Object current_group)
6206 process_send_signal (process, SIGQUIT, current_group, 0);
6207 return process;
6210 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6211 doc: /* Stop process PROCESS. May be process or name of one.
6212 See function `interrupt-process' for more details on usage.
6213 If PROCESS is a network or serial process, inhibit handling of incoming
6214 traffic. */)
6215 (Lisp_Object process, Lisp_Object current_group)
6217 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6218 || PIPECONN_P (process)))
6220 struct Lisp_Process *p;
6222 p = XPROCESS (process);
6223 if (NILP (p->command)
6224 && p->infd >= 0)
6226 FD_CLR (p->infd, &input_wait_mask);
6227 FD_CLR (p->infd, &non_keyboard_wait_mask);
6229 pset_command (p, Qt);
6230 return process;
6232 #ifndef SIGTSTP
6233 error ("No SIGTSTP support");
6234 #else
6235 process_send_signal (process, SIGTSTP, current_group, 0);
6236 #endif
6237 return process;
6240 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6241 doc: /* Continue process PROCESS. May be process or name of one.
6242 See function `interrupt-process' for more details on usage.
6243 If PROCESS is a network or serial process, resume handling of incoming
6244 traffic. */)
6245 (Lisp_Object process, Lisp_Object current_group)
6247 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)
6248 || PIPECONN_P (process)))
6250 struct Lisp_Process *p;
6252 p = XPROCESS (process);
6253 if (EQ (p->command, Qt)
6254 && p->infd >= 0
6255 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6257 FD_SET (p->infd, &input_wait_mask);
6258 FD_SET (p->infd, &non_keyboard_wait_mask);
6259 #ifdef WINDOWSNT
6260 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6261 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6262 #else /* not WINDOWSNT */
6263 tcflush (p->infd, TCIFLUSH);
6264 #endif /* not WINDOWSNT */
6266 pset_command (p, Qnil);
6267 return process;
6269 #ifdef SIGCONT
6270 process_send_signal (process, SIGCONT, current_group, 0);
6271 #else
6272 error ("No SIGCONT support");
6273 #endif
6274 return process;
6277 /* Return the integer value of the signal whose abbreviation is ABBR,
6278 or a negative number if there is no such signal. */
6279 static int
6280 abbr_to_signal (char const *name)
6282 int i, signo;
6283 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
6285 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6286 name += 3;
6288 for (i = 0; i < sizeof sigbuf; i++)
6290 sigbuf[i] = c_toupper (name[i]);
6291 if (! sigbuf[i])
6292 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
6295 return -1;
6298 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6299 2, 2, "sProcess (name or number): \nnSignal code: ",
6300 doc: /* Send PROCESS the signal with code SIGCODE.
6301 PROCESS may also be a number specifying the process id of the
6302 process to signal; in this case, the process need not be a child of
6303 this Emacs.
6304 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6305 (Lisp_Object process, Lisp_Object sigcode)
6307 pid_t pid;
6308 int signo;
6310 if (STRINGP (process))
6312 Lisp_Object tem = Fget_process (process);
6313 if (NILP (tem))
6315 Lisp_Object process_number
6316 = string_to_number (SSDATA (process), 10, 1);
6317 if (INTEGERP (process_number) || FLOATP (process_number))
6318 tem = process_number;
6320 process = tem;
6322 else if (!NUMBERP (process))
6323 process = get_process (process);
6325 if (NILP (process))
6326 return process;
6328 if (NUMBERP (process))
6329 CONS_TO_INTEGER (process, pid_t, pid);
6330 else
6332 CHECK_PROCESS (process);
6333 pid = XPROCESS (process)->pid;
6334 if (pid <= 0)
6335 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6338 if (INTEGERP (sigcode))
6340 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6341 signo = XINT (sigcode);
6343 else
6345 char *name;
6347 CHECK_SYMBOL (sigcode);
6348 name = SSDATA (SYMBOL_NAME (sigcode));
6350 signo = abbr_to_signal (name);
6351 if (signo < 0)
6352 error ("Undefined signal name %s", name);
6355 return make_number (kill (pid, signo));
6358 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6359 doc: /* Make PROCESS see end-of-file in its input.
6360 EOF comes after any text already sent to it.
6361 PROCESS may be a process, a buffer, the name of a process or buffer, or
6362 nil, indicating the current buffer's process.
6363 If PROCESS is a network connection, or is a process communicating
6364 through a pipe (as opposed to a pty), then you cannot send any more
6365 text to PROCESS after you call this function.
6366 If PROCESS is a serial process, wait until all output written to the
6367 process has been transmitted to the serial port. */)
6368 (Lisp_Object process)
6370 Lisp_Object proc;
6371 struct coding_system *coding = NULL;
6372 int outfd;
6374 if (DATAGRAM_CONN_P (process))
6375 return process;
6377 proc = get_process (process);
6378 outfd = XPROCESS (proc)->outfd;
6379 if (outfd >= 0)
6380 coding = proc_encode_coding_system[outfd];
6382 /* Make sure the process is really alive. */
6383 if (XPROCESS (proc)->raw_status_new)
6384 update_status (XPROCESS (proc));
6385 if (! EQ (XPROCESS (proc)->status, Qrun))
6386 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6388 if (coding && CODING_REQUIRE_FLUSHING (coding))
6390 coding->mode |= CODING_MODE_LAST_BLOCK;
6391 send_process (proc, "", 0, Qnil);
6394 if (XPROCESS (proc)->pty_flag)
6395 send_process (proc, "\004", 1, Qnil);
6396 else if (EQ (XPROCESS (proc)->type, Qserial))
6398 #ifndef WINDOWSNT
6399 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6400 report_file_error ("Failed tcdrain", Qnil);
6401 #endif /* not WINDOWSNT */
6402 /* Do nothing on Windows because writes are blocking. */
6404 else
6406 struct Lisp_Process *p = XPROCESS (proc);
6407 int old_outfd = p->outfd;
6408 int new_outfd;
6410 #ifdef HAVE_SHUTDOWN
6411 /* If this is a network connection, or socketpair is used
6412 for communication with the subprocess, call shutdown to cause EOF.
6413 (In some old system, shutdown to socketpair doesn't work.
6414 Then we just can't win.) */
6415 if (0 <= old_outfd
6416 && (EQ (p->type, Qnetwork) || p->infd == old_outfd))
6417 shutdown (old_outfd, 1);
6418 #endif
6419 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6420 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6421 if (new_outfd < 0)
6422 report_file_error ("Opening null device", Qnil);
6423 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6424 p->outfd = new_outfd;
6426 if (!proc_encode_coding_system[new_outfd])
6427 proc_encode_coding_system[new_outfd]
6428 = xmalloc (sizeof (struct coding_system));
6429 if (old_outfd >= 0)
6431 *proc_encode_coding_system[new_outfd]
6432 = *proc_encode_coding_system[old_outfd];
6433 memset (proc_encode_coding_system[old_outfd], 0,
6434 sizeof (struct coding_system));
6436 else
6437 setup_coding_system (p->encode_coding_system,
6438 proc_encode_coding_system[new_outfd]);
6440 return process;
6443 /* The main Emacs thread records child processes in three places:
6445 - Vprocess_alist, for asynchronous subprocesses, which are child
6446 processes visible to Lisp.
6448 - deleted_pid_list, for child processes invisible to Lisp,
6449 typically because of delete-process. These are recorded so that
6450 the processes can be reaped when they exit, so that the operating
6451 system's process table is not cluttered by zombies.
6453 - the local variable PID in Fcall_process, call_process_cleanup and
6454 call_process_kill, for synchronous subprocesses.
6455 record_unwind_protect is used to make sure this process is not
6456 forgotten: if the user interrupts call-process and the child
6457 process refuses to exit immediately even with two C-g's,
6458 call_process_kill adds PID's contents to deleted_pid_list before
6459 returning.
6461 The main Emacs thread invokes waitpid only on child processes that
6462 it creates and that have not been reaped. This avoid races on
6463 platforms such as GTK, where other threads create their own
6464 subprocesses which the main thread should not reap. For example,
6465 if the main thread attempted to reap an already-reaped child, it
6466 might inadvertently reap a GTK-created process that happened to
6467 have the same process ID. */
6469 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6470 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6471 keep track of its own children. GNUstep is similar. */
6473 static void dummy_handler (int sig) {}
6474 static signal_handler_t volatile lib_child_handler;
6476 /* Handle a SIGCHLD signal by looking for known child processes of
6477 Emacs whose status have changed. For each one found, record its
6478 new status.
6480 All we do is change the status; we do not run sentinels or print
6481 notifications. That is saved for the next time keyboard input is
6482 done, in order to avoid timing errors.
6484 ** WARNING: this can be called during garbage collection.
6485 Therefore, it must not be fooled by the presence of mark bits in
6486 Lisp objects.
6488 ** USG WARNING: Although it is not obvious from the documentation
6489 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6490 signal() before executing at least one wait(), otherwise the
6491 handler will be called again, resulting in an infinite loop. The
6492 relevant portion of the documentation reads "SIGCLD signals will be
6493 queued and the signal-catching function will be continually
6494 reentered until the queue is empty". Invoking signal() causes the
6495 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6496 Inc.
6498 ** Malloc WARNING: This should never call malloc either directly or
6499 indirectly; if it does, that is a bug. */
6501 static void
6502 handle_child_signal (int sig)
6504 Lisp_Object tail, proc;
6506 /* Find the process that signaled us, and record its status. */
6508 /* The process can have been deleted by Fdelete_process, or have
6509 been started asynchronously by Fcall_process. */
6510 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6512 bool all_pids_are_fixnums
6513 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6514 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6515 Lisp_Object head = XCAR (tail);
6516 Lisp_Object xpid;
6517 if (! CONSP (head))
6518 continue;
6519 xpid = XCAR (head);
6520 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6522 pid_t deleted_pid;
6523 if (INTEGERP (xpid))
6524 deleted_pid = XINT (xpid);
6525 else
6526 deleted_pid = XFLOAT_DATA (xpid);
6527 if (child_status_changed (deleted_pid, 0, 0))
6529 if (STRINGP (XCDR (head)))
6530 unlink (SSDATA (XCDR (head)));
6531 XSETCAR (tail, Qnil);
6536 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6537 FOR_EACH_PROCESS (tail, proc)
6539 struct Lisp_Process *p = XPROCESS (proc);
6540 int status;
6542 if (p->alive
6543 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6545 /* Change the status of the process that was found. */
6546 p->tick = ++process_tick;
6547 p->raw_status = status;
6548 p->raw_status_new = 1;
6550 /* If process has terminated, stop waiting for its output. */
6551 if (WIFSIGNALED (status) || WIFEXITED (status))
6553 bool clear_desc_flag = 0;
6554 p->alive = 0;
6555 if (p->infd >= 0)
6556 clear_desc_flag = 1;
6558 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6559 if (clear_desc_flag)
6561 FD_CLR (p->infd, &input_wait_mask);
6562 FD_CLR (p->infd, &non_keyboard_wait_mask);
6568 lib_child_handler (sig);
6569 #ifdef NS_IMPL_GNUSTEP
6570 /* NSTask in GNUstep sets its child handler each time it is called.
6571 So we must re-set ours. */
6572 catch_child_signal ();
6573 #endif
6576 static void
6577 deliver_child_signal (int sig)
6579 deliver_process_signal (sig, handle_child_signal);
6583 static Lisp_Object
6584 exec_sentinel_error_handler (Lisp_Object error_val)
6586 cmd_error_internal (error_val, "error in process sentinel: ");
6587 Vinhibit_quit = Qt;
6588 update_echo_area ();
6589 Fsleep_for (make_number (2), Qnil);
6590 return Qt;
6593 static void
6594 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6596 Lisp_Object sentinel, odeactivate;
6597 struct Lisp_Process *p = XPROCESS (proc);
6598 ptrdiff_t count = SPECPDL_INDEX ();
6599 bool outer_running_asynch_code = running_asynch_code;
6600 int waiting = waiting_for_user_input_p;
6602 if (inhibit_sentinels)
6603 return;
6605 /* No need to gcpro these, because all we do with them later
6606 is test them for EQness, and none of them should be a string. */
6607 odeactivate = Vdeactivate_mark;
6608 #if 0
6609 Lisp_Object obuffer, okeymap;
6610 XSETBUFFER (obuffer, current_buffer);
6611 okeymap = BVAR (current_buffer, keymap);
6612 #endif
6614 /* There's no good reason to let sentinels change the current
6615 buffer, and many callers of accept-process-output, sit-for, and
6616 friends don't expect current-buffer to be changed from under them. */
6617 record_unwind_current_buffer ();
6619 sentinel = p->sentinel;
6621 /* Inhibit quit so that random quits don't screw up a running filter. */
6622 specbind (Qinhibit_quit, Qt);
6623 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6625 /* In case we get recursively called,
6626 and we already saved the match data nonrecursively,
6627 save the same match data in safely recursive fashion. */
6628 if (outer_running_asynch_code)
6630 Lisp_Object tem;
6631 tem = Fmatch_data (Qnil, Qnil, Qnil);
6632 restore_search_regs ();
6633 record_unwind_save_match_data ();
6634 Fset_match_data (tem, Qt);
6637 /* For speed, if a search happens within this code,
6638 save the match data in a special nonrecursive fashion. */
6639 running_asynch_code = 1;
6641 internal_condition_case_1 (read_process_output_call,
6642 list3 (sentinel, proc, reason),
6643 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6644 exec_sentinel_error_handler);
6646 /* If we saved the match data nonrecursively, restore it now. */
6647 restore_search_regs ();
6648 running_asynch_code = outer_running_asynch_code;
6650 Vdeactivate_mark = odeactivate;
6652 /* Restore waiting_for_user_input_p as it was
6653 when we were called, in case the filter clobbered it. */
6654 waiting_for_user_input_p = waiting;
6656 #if 0
6657 if (! EQ (Fcurrent_buffer (), obuffer)
6658 || ! EQ (current_buffer->keymap, okeymap))
6659 #endif
6660 /* But do it only if the caller is actually going to read events.
6661 Otherwise there's no need to make him wake up, and it could
6662 cause trouble (for example it would make sit_for return). */
6663 if (waiting_for_user_input_p == -1)
6664 record_asynch_buffer_change ();
6666 unbind_to (count, Qnil);
6669 /* Report all recent events of a change in process status
6670 (either run the sentinel or output a message).
6671 This is usually done while Emacs is waiting for keyboard input
6672 but can be done at other times.
6674 Return positive if any input was received from WAIT_PROC (or from
6675 any process if WAIT_PROC is null), zero if input was attempted but
6676 none received, and negative if we didn't even try. */
6678 static int
6679 status_notify (struct Lisp_Process *deleting_process,
6680 struct Lisp_Process *wait_proc)
6682 Lisp_Object proc;
6683 Lisp_Object tail, msg;
6684 struct gcpro gcpro1, gcpro2;
6685 int got_some_input = -1;
6687 tail = Qnil;
6688 msg = Qnil;
6689 /* We need to gcpro tail; if read_process_output calls a filter
6690 which deletes a process and removes the cons to which tail points
6691 from Vprocess_alist, and then causes a GC, tail is an unprotected
6692 reference. */
6693 GCPRO2 (tail, msg);
6695 /* Set this now, so that if new processes are created by sentinels
6696 that we run, we get called again to handle their status changes. */
6697 update_tick = process_tick;
6699 FOR_EACH_PROCESS (tail, proc)
6701 Lisp_Object symbol;
6702 register struct Lisp_Process *p = XPROCESS (proc);
6704 if (p->tick != p->update_tick)
6706 p->update_tick = p->tick;
6708 /* If process is still active, read any output that remains. */
6709 while (! EQ (p->filter, Qt)
6710 && ! EQ (p->status, Qconnect)
6711 && ! EQ (p->status, Qlisten)
6712 /* Network or serial process not stopped: */
6713 && ! EQ (p->command, Qt)
6714 && p->infd >= 0
6715 && p != deleting_process)
6717 int nread = read_process_output (proc, p->infd);
6718 if (got_some_input < nread)
6719 got_some_input = nread;
6720 if (nread <= 0)
6721 break;
6724 /* Get the text to use for the message. */
6725 if (p->raw_status_new)
6726 update_status (p);
6727 msg = status_message (p);
6729 /* If process is terminated, deactivate it or delete it. */
6730 symbol = p->status;
6731 if (CONSP (p->status))
6732 symbol = XCAR (p->status);
6734 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6735 || EQ (symbol, Qclosed))
6737 if (delete_exited_processes)
6738 remove_process (proc);
6739 else
6740 deactivate_process (proc);
6743 /* The actions above may have further incremented p->tick.
6744 So set p->update_tick again so that an error in the sentinel will
6745 not cause this code to be run again. */
6746 p->update_tick = p->tick;
6747 /* Now output the message suitably. */
6748 exec_sentinel (proc, msg);
6750 } /* end for */
6752 update_mode_lines = 24; /* In case buffers use %s in mode-line-format. */
6753 UNGCPRO;
6754 return got_some_input;
6757 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6758 Sinternal_default_process_sentinel, 2, 2, 0,
6759 doc: /* Function used as default sentinel for processes.
6760 This inserts a status message into the process's buffer, if there is one. */)
6761 (Lisp_Object proc, Lisp_Object msg)
6763 Lisp_Object buffer, symbol;
6764 struct Lisp_Process *p;
6765 CHECK_PROCESS (proc);
6766 p = XPROCESS (proc);
6767 buffer = p->buffer;
6768 symbol = p->status;
6769 if (CONSP (symbol))
6770 symbol = XCAR (symbol);
6772 if (!EQ (symbol, Qrun) && !NILP (buffer))
6774 Lisp_Object tem;
6775 struct buffer *old = current_buffer;
6776 ptrdiff_t opoint, opoint_byte;
6777 ptrdiff_t before, before_byte;
6779 /* Avoid error if buffer is deleted
6780 (probably that's why the process is dead, too). */
6781 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6782 return Qnil;
6783 Fset_buffer (buffer);
6785 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6786 msg = (code_convert_string_norecord
6787 (msg, Vlocale_coding_system, 1));
6789 opoint = PT;
6790 opoint_byte = PT_BYTE;
6791 /* Insert new output into buffer
6792 at the current end-of-output marker,
6793 thus preserving logical ordering of input and output. */
6794 if (XMARKER (p->mark)->buffer)
6795 Fgoto_char (p->mark);
6796 else
6797 SET_PT_BOTH (ZV, ZV_BYTE);
6799 before = PT;
6800 before_byte = PT_BYTE;
6802 tem = BVAR (current_buffer, read_only);
6803 bset_read_only (current_buffer, Qnil);
6804 insert_string ("\nProcess ");
6805 { /* FIXME: temporary kludge. */
6806 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6807 insert_string (" ");
6808 Finsert (1, &msg);
6809 bset_read_only (current_buffer, tem);
6810 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6812 if (opoint >= before)
6813 SET_PT_BOTH (opoint + (PT - before),
6814 opoint_byte + (PT_BYTE - before_byte));
6815 else
6816 SET_PT_BOTH (opoint, opoint_byte);
6818 set_buffer_internal (old);
6820 return Qnil;
6824 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6825 Sset_process_coding_system, 1, 3, 0,
6826 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6827 DECODING will be used to decode subprocess output and ENCODING to
6828 encode subprocess input. */)
6829 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6831 register struct Lisp_Process *p;
6833 CHECK_PROCESS (process);
6834 p = XPROCESS (process);
6835 if (p->infd < 0)
6836 error ("Input file descriptor of %s closed", SDATA (p->name));
6837 if (p->outfd < 0)
6838 error ("Output file descriptor of %s closed", SDATA (p->name));
6839 Fcheck_coding_system (decoding);
6840 Fcheck_coding_system (encoding);
6841 encoding = coding_inherit_eol_type (encoding, Qnil);
6842 pset_decode_coding_system (p, decoding);
6843 pset_encode_coding_system (p, encoding);
6844 setup_process_coding_systems (process);
6846 return Qnil;
6849 DEFUN ("process-coding-system",
6850 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6851 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6852 (register Lisp_Object process)
6854 CHECK_PROCESS (process);
6855 return Fcons (XPROCESS (process)->decode_coding_system,
6856 XPROCESS (process)->encode_coding_system);
6859 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6860 Sset_process_filter_multibyte, 2, 2, 0,
6861 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6862 If FLAG is non-nil, the filter is given multibyte strings.
6863 If FLAG is nil, the filter is given unibyte strings. In this case,
6864 all character code conversion except for end-of-line conversion is
6865 suppressed. */)
6866 (Lisp_Object process, Lisp_Object flag)
6868 register struct Lisp_Process *p;
6870 CHECK_PROCESS (process);
6871 p = XPROCESS (process);
6872 if (NILP (flag))
6873 pset_decode_coding_system
6874 (p, raw_text_coding_system (p->decode_coding_system));
6875 setup_process_coding_systems (process);
6877 return Qnil;
6880 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6881 Sprocess_filter_multibyte_p, 1, 1, 0,
6882 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6883 (Lisp_Object process)
6885 register struct Lisp_Process *p;
6886 struct coding_system *coding;
6888 CHECK_PROCESS (process);
6889 p = XPROCESS (process);
6890 if (p->infd < 0)
6891 return Qnil;
6892 coding = proc_decode_coding_system[p->infd];
6893 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6899 # ifdef HAVE_GPM
6901 void
6902 add_gpm_wait_descriptor (int desc)
6904 add_keyboard_wait_descriptor (desc);
6907 void
6908 delete_gpm_wait_descriptor (int desc)
6910 delete_keyboard_wait_descriptor (desc);
6913 # endif
6915 # ifdef USABLE_SIGIO
6917 /* Return true if *MASK has a bit set
6918 that corresponds to one of the keyboard input descriptors. */
6920 static bool
6921 keyboard_bit_set (fd_set *mask)
6923 int fd;
6925 for (fd = 0; fd <= max_input_desc; fd++)
6926 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6927 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6928 return 1;
6930 return 0;
6932 # endif
6934 #else /* not subprocesses */
6936 /* Defined in msdos.c. */
6937 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6938 struct timespec *, void *);
6940 /* Implementation of wait_reading_process_output, assuming that there
6941 are no subprocesses. Used only by the MS-DOS build.
6943 Wait for timeout to elapse and/or keyboard input to be available.
6945 TIME_LIMIT is:
6946 timeout in seconds
6947 If negative, gobble data immediately available but don't wait for any.
6949 NSECS is:
6950 an additional duration to wait, measured in nanoseconds
6951 If TIME_LIMIT is zero, then:
6952 If NSECS == 0, there is no limit.
6953 If NSECS > 0, the timeout consists of NSECS only.
6954 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6956 READ_KBD is:
6957 0 to ignore keyboard input, or
6958 1 to return when input is available, or
6959 -1 means caller will actually read the input, so don't throw to
6960 the quit handler.
6962 see full version for other parameters. We know that wait_proc will
6963 always be NULL, since `subprocesses' isn't defined.
6965 DO_DISPLAY means redisplay should be done to show subprocess
6966 output that arrives.
6968 Return positive if we received input from WAIT_PROC (or from any
6969 process if WAIT_PROC is null), zero if we attempted to receive
6970 input but got none, and negative if we didn't even try. */
6973 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6974 bool do_display,
6975 Lisp_Object wait_for_cell,
6976 struct Lisp_Process *wait_proc, int just_wait_proc)
6978 register int nfds;
6979 struct timespec end_time, timeout;
6981 if (time_limit < 0)
6983 time_limit = 0;
6984 nsecs = -1;
6986 else if (TYPE_MAXIMUM (time_t) < time_limit)
6987 time_limit = TYPE_MAXIMUM (time_t);
6989 /* What does time_limit really mean? */
6990 if (time_limit || nsecs > 0)
6992 timeout = make_timespec (time_limit, nsecs);
6993 end_time = timespec_add (current_timespec (), timeout);
6996 /* Turn off periodic alarms (in case they are in use)
6997 and then turn off any other atimers,
6998 because the select emulator uses alarms. */
6999 stop_polling ();
7000 turn_on_atimers (0);
7002 while (1)
7004 bool timeout_reduced_for_timers = false;
7005 fd_set waitchannels;
7006 int xerrno;
7008 /* If calling from keyboard input, do not quit
7009 since we want to return C-g as an input character.
7010 Otherwise, do pending quit if requested. */
7011 if (read_kbd >= 0)
7012 QUIT;
7014 /* Exit now if the cell we're waiting for became non-nil. */
7015 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7016 break;
7018 /* Compute time from now till when time limit is up. */
7019 /* Exit if already run out. */
7020 if (nsecs < 0)
7022 /* A negative timeout means
7023 gobble output available now
7024 but don't wait at all. */
7026 timeout = make_timespec (0, 0);
7028 else if (time_limit || nsecs > 0)
7030 struct timespec now = current_timespec ();
7031 if (timespec_cmp (end_time, now) <= 0)
7032 break;
7033 timeout = timespec_sub (end_time, now);
7035 else
7037 timeout = make_timespec (100000, 0);
7040 /* If our caller will not immediately handle keyboard events,
7041 run timer events directly.
7042 (Callers that will immediately read keyboard events
7043 call timer_delay on their own.) */
7044 if (NILP (wait_for_cell))
7046 struct timespec timer_delay;
7050 unsigned old_timers_run = timers_run;
7051 timer_delay = timer_check ();
7052 if (timers_run != old_timers_run && do_display)
7053 /* We must retry, since a timer may have requeued itself
7054 and that could alter the time delay. */
7055 redisplay_preserve_echo_area (14);
7056 else
7057 break;
7059 while (!detect_input_pending ());
7061 /* If there is unread keyboard input, also return. */
7062 if (read_kbd != 0
7063 && requeued_events_pending_p ())
7064 break;
7066 if (timespec_valid_p (timer_delay) && nsecs >= 0)
7068 if (timespec_cmp (timer_delay, timeout) < 0)
7070 timeout = timer_delay;
7071 timeout_reduced_for_timers = true;
7076 /* Cause C-g and alarm signals to take immediate action,
7077 and cause input available signals to zero out timeout. */
7078 if (read_kbd < 0)
7079 set_waiting_for_input (&timeout);
7081 /* If a frame has been newly mapped and needs updating,
7082 reprocess its display stuff. */
7083 if (frame_garbaged && do_display)
7085 clear_waiting_for_input ();
7086 redisplay_preserve_echo_area (15);
7087 if (read_kbd < 0)
7088 set_waiting_for_input (&timeout);
7091 /* Wait till there is something to do. */
7092 FD_ZERO (&waitchannels);
7093 if (read_kbd && detect_input_pending ())
7094 nfds = 0;
7095 else
7097 if (read_kbd || !NILP (wait_for_cell))
7098 FD_SET (0, &waitchannels);
7099 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
7102 xerrno = errno;
7104 /* Make C-g and alarm signals set flags again. */
7105 clear_waiting_for_input ();
7107 /* If we woke up due to SIGWINCH, actually change size now. */
7108 do_pending_window_change (0);
7110 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
7111 /* We waited the full specified time, so return now. */
7112 break;
7114 if (nfds == -1)
7116 /* If the system call was interrupted, then go around the
7117 loop again. */
7118 if (xerrno == EINTR)
7119 FD_ZERO (&waitchannels);
7120 else
7121 report_file_errno ("Failed select", Qnil, xerrno);
7124 /* Check for keyboard input. */
7126 if (read_kbd
7127 && detect_input_pending_run_timers (do_display))
7129 swallow_events (do_display);
7130 if (detect_input_pending_run_timers (do_display))
7131 break;
7134 /* If there is unread keyboard input, also return. */
7135 if (read_kbd
7136 && requeued_events_pending_p ())
7137 break;
7139 /* If wait_for_cell. check for keyboard input
7140 but don't run any timers.
7141 ??? (It seems wrong to me to check for keyboard
7142 input at all when wait_for_cell, but the code
7143 has been this way since July 1994.
7144 Try changing this after version 19.31.) */
7145 if (! NILP (wait_for_cell)
7146 && detect_input_pending ())
7148 swallow_events (do_display);
7149 if (detect_input_pending ())
7150 break;
7153 /* Exit now if the cell we're waiting for became non-nil. */
7154 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7155 break;
7158 start_polling ();
7160 return -1;
7163 #endif /* not subprocesses */
7165 /* The following functions are needed even if async subprocesses are
7166 not supported. Some of them are no-op stubs in that case. */
7168 #ifdef HAVE_TIMERFD
7170 /* Add FD, which is a descriptor returned by timerfd_create,
7171 to the set of non-keyboard input descriptors. */
7173 void
7174 add_timer_wait_descriptor (int fd)
7176 FD_SET (fd, &input_wait_mask);
7177 FD_SET (fd, &non_keyboard_wait_mask);
7178 FD_SET (fd, &non_process_wait_mask);
7179 fd_callback_info[fd].func = timerfd_callback;
7180 fd_callback_info[fd].data = NULL;
7181 fd_callback_info[fd].condition |= FOR_READ;
7182 if (fd > max_input_desc)
7183 max_input_desc = fd;
7186 #endif /* HAVE_TIMERFD */
7188 /* Add DESC to the set of keyboard input descriptors. */
7190 void
7191 add_keyboard_wait_descriptor (int desc)
7193 #ifdef subprocesses /* Actually means "not MSDOS". */
7194 FD_SET (desc, &input_wait_mask);
7195 FD_SET (desc, &non_process_wait_mask);
7196 if (desc > max_input_desc)
7197 max_input_desc = desc;
7198 #endif
7201 /* From now on, do not expect DESC to give keyboard input. */
7203 void
7204 delete_keyboard_wait_descriptor (int desc)
7206 #ifdef subprocesses
7207 FD_CLR (desc, &input_wait_mask);
7208 FD_CLR (desc, &non_process_wait_mask);
7209 delete_input_desc (desc);
7210 #endif
7213 /* Setup coding systems of PROCESS. */
7215 void
7216 setup_process_coding_systems (Lisp_Object process)
7218 #ifdef subprocesses
7219 struct Lisp_Process *p = XPROCESS (process);
7220 int inch = p->infd;
7221 int outch = p->outfd;
7222 Lisp_Object coding_system;
7224 if (inch < 0 || outch < 0)
7225 return;
7227 if (!proc_decode_coding_system[inch])
7228 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
7229 coding_system = p->decode_coding_system;
7230 if (EQ (p->filter, Qinternal_default_process_filter)
7231 && BUFFERP (p->buffer))
7233 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7234 coding_system = raw_text_coding_system (coding_system);
7236 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7238 if (!proc_encode_coding_system[outch])
7239 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
7240 setup_coding_system (p->encode_coding_system,
7241 proc_encode_coding_system[outch]);
7242 #endif
7245 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7246 doc: /* Return the (or a) process associated with BUFFER.
7247 BUFFER may be a buffer or the name of one. */)
7248 (register Lisp_Object buffer)
7250 #ifdef subprocesses
7251 register Lisp_Object buf, tail, proc;
7253 if (NILP (buffer)) return Qnil;
7254 buf = Fget_buffer (buffer);
7255 if (NILP (buf)) return Qnil;
7257 FOR_EACH_PROCESS (tail, proc)
7258 if (EQ (XPROCESS (proc)->buffer, buf))
7259 return proc;
7260 #endif /* subprocesses */
7261 return Qnil;
7264 DEFUN ("process-inherit-coding-system-flag",
7265 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7266 1, 1, 0,
7267 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7268 If this flag is t, `buffer-file-coding-system' of the buffer
7269 associated with PROCESS will inherit the coding system used to decode
7270 the process output. */)
7271 (register Lisp_Object process)
7273 #ifdef subprocesses
7274 CHECK_PROCESS (process);
7275 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7276 #else
7277 /* Ignore the argument and return the value of
7278 inherit-process-coding-system. */
7279 return inherit_process_coding_system ? Qt : Qnil;
7280 #endif
7283 /* Kill all processes associated with `buffer'.
7284 If `buffer' is nil, kill all processes. */
7286 void
7287 kill_buffer_processes (Lisp_Object buffer)
7289 #ifdef subprocesses
7290 Lisp_Object tail, proc;
7292 FOR_EACH_PROCESS (tail, proc)
7293 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
7295 if (NETCONN_P (proc) || SERIALCONN_P (proc) || PIPECONN_P (proc))
7296 Fdelete_process (proc);
7297 else if (XPROCESS (proc)->infd >= 0)
7298 process_send_signal (proc, SIGHUP, Qnil, 1);
7300 #else /* subprocesses */
7301 /* Since we have no subprocesses, this does nothing. */
7302 #endif /* subprocesses */
7305 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7306 Swaiting_for_user_input_p, 0, 0, 0,
7307 doc: /* Return non-nil if Emacs is waiting for input from the user.
7308 This is intended for use by asynchronous process output filters and sentinels. */)
7309 (void)
7311 #ifdef subprocesses
7312 return (waiting_for_user_input_p ? Qt : Qnil);
7313 #else
7314 return Qnil;
7315 #endif
7318 /* Stop reading input from keyboard sources. */
7320 void
7321 hold_keyboard_input (void)
7323 kbd_is_on_hold = 1;
7326 /* Resume reading input from keyboard sources. */
7328 void
7329 unhold_keyboard_input (void)
7331 kbd_is_on_hold = 0;
7334 /* Return true if keyboard input is on hold, zero otherwise. */
7336 bool
7337 kbd_on_hold_p (void)
7339 return kbd_is_on_hold;
7343 /* Enumeration of and access to system processes a-la ps(1). */
7345 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7346 0, 0, 0,
7347 doc: /* Return a list of numerical process IDs of all running processes.
7348 If this functionality is unsupported, return nil.
7350 See `process-attributes' for getting attributes of a process given its ID. */)
7351 (void)
7353 return list_system_processes ();
7356 DEFUN ("process-attributes", Fprocess_attributes,
7357 Sprocess_attributes, 1, 1, 0,
7358 doc: /* Return attributes of the process given by its PID, a number.
7360 Value is an alist where each element is a cons cell of the form
7362 \(KEY . VALUE)
7364 If this functionality is unsupported, the value is nil.
7366 See `list-system-processes' for getting a list of all process IDs.
7368 The KEYs of the attributes that this function may return are listed
7369 below, together with the type of the associated VALUE (in parentheses).
7370 Not all platforms support all of these attributes; unsupported
7371 attributes will not appear in the returned alist.
7372 Unless explicitly indicated otherwise, numbers can have either
7373 integer or floating point values.
7375 euid -- Effective user User ID of the process (number)
7376 user -- User name corresponding to euid (string)
7377 egid -- Effective user Group ID of the process (number)
7378 group -- Group name corresponding to egid (string)
7379 comm -- Command name (executable name only) (string)
7380 state -- Process state code, such as "S", "R", or "T" (string)
7381 ppid -- Parent process ID (number)
7382 pgrp -- Process group ID (number)
7383 sess -- Session ID, i.e. process ID of session leader (number)
7384 ttname -- Controlling tty name (string)
7385 tpgid -- ID of foreground process group on the process's tty (number)
7386 minflt -- number of minor page faults (number)
7387 majflt -- number of major page faults (number)
7388 cminflt -- cumulative number of minor page faults (number)
7389 cmajflt -- cumulative number of major page faults (number)
7390 utime -- user time used by the process, in (current-time) format,
7391 which is a list of integers (HIGH LOW USEC PSEC)
7392 stime -- system time used by the process (current-time)
7393 time -- sum of utime and stime (current-time)
7394 cutime -- user time used by the process and its children (current-time)
7395 cstime -- system time used by the process and its children (current-time)
7396 ctime -- sum of cutime and cstime (current-time)
7397 pri -- priority of the process (number)
7398 nice -- nice value of the process (number)
7399 thcount -- process thread count (number)
7400 start -- time the process started (current-time)
7401 vsize -- virtual memory size of the process in KB's (number)
7402 rss -- resident set size of the process in KB's (number)
7403 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7404 pcpu -- percents of CPU time used by the process (floating-point number)
7405 pmem -- percents of total physical memory used by process's resident set
7406 (floating-point number)
7407 args -- command line which invoked the process (string). */)
7408 ( Lisp_Object pid)
7410 return system_process_attributes (pid);
7413 #ifdef subprocesses
7414 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7415 Invoke this after init_process_emacs, and after glib and/or GNUstep
7416 futz with the SIGCHLD handler, but before Emacs forks any children.
7417 This function's caller should block SIGCHLD. */
7419 void
7420 catch_child_signal (void)
7422 struct sigaction action, old_action;
7423 sigset_t oldset;
7424 emacs_sigaction_init (&action, deliver_child_signal);
7425 block_child_signal (&oldset);
7426 sigaction (SIGCHLD, &action, &old_action);
7427 eassert (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7428 || ! (old_action.sa_flags & SA_SIGINFO));
7430 if (old_action.sa_handler != deliver_child_signal)
7431 lib_child_handler
7432 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7433 ? dummy_handler
7434 : old_action.sa_handler);
7435 unblock_child_signal (&oldset);
7437 #endif /* subprocesses */
7440 /* This is not called "init_process" because that is the name of a
7441 Mach system call, so it would cause problems on Darwin systems. */
7442 void
7443 init_process_emacs (void)
7445 #ifdef subprocesses
7446 register int i;
7448 inhibit_sentinels = 0;
7450 #ifndef CANNOT_DUMP
7451 if (! noninteractive || initialized)
7452 #endif
7454 #if defined HAVE_GLIB && !defined WINDOWSNT
7455 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7456 this should always fail, but is enough to initialize glib's
7457 private SIGCHLD handler, allowing catch_child_signal to copy
7458 it into lib_child_handler. */
7459 g_source_unref (g_child_watch_source_new (getpid ()));
7460 #endif
7461 catch_child_signal ();
7464 FD_ZERO (&input_wait_mask);
7465 FD_ZERO (&non_keyboard_wait_mask);
7466 FD_ZERO (&non_process_wait_mask);
7467 FD_ZERO (&write_mask);
7468 max_process_desc = max_input_desc = -1;
7469 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7471 #ifdef NON_BLOCKING_CONNECT
7472 FD_ZERO (&connect_wait_mask);
7473 num_pending_connects = 0;
7474 #endif
7476 #ifdef ADAPTIVE_READ_BUFFERING
7477 process_output_delay_count = 0;
7478 process_output_skip = 0;
7479 #endif
7481 /* Don't do this, it caused infinite select loops. The display
7482 method should call add_keyboard_wait_descriptor on stdin if it
7483 needs that. */
7484 #if 0
7485 FD_SET (0, &input_wait_mask);
7486 #endif
7488 Vprocess_alist = Qnil;
7489 deleted_pid_list = Qnil;
7490 for (i = 0; i < FD_SETSIZE; i++)
7492 chan_process[i] = Qnil;
7493 proc_buffered_char[i] = -1;
7495 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7496 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7497 #ifdef DATAGRAM_SOCKETS
7498 memset (datagram_address, 0, sizeof datagram_address);
7499 #endif
7502 Lisp_Object subfeatures = Qnil;
7503 const struct socket_options *sopt;
7505 #define ADD_SUBFEATURE(key, val) \
7506 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7508 #ifdef NON_BLOCKING_CONNECT
7509 ADD_SUBFEATURE (QCnowait, Qt);
7510 #endif
7511 #ifdef DATAGRAM_SOCKETS
7512 ADD_SUBFEATURE (QCtype, Qdatagram);
7513 #endif
7514 #ifdef HAVE_SEQPACKET
7515 ADD_SUBFEATURE (QCtype, Qseqpacket);
7516 #endif
7517 #ifdef HAVE_LOCAL_SOCKETS
7518 ADD_SUBFEATURE (QCfamily, Qlocal);
7519 #endif
7520 ADD_SUBFEATURE (QCfamily, Qipv4);
7521 #ifdef AF_INET6
7522 ADD_SUBFEATURE (QCfamily, Qipv6);
7523 #endif
7524 #ifdef HAVE_GETSOCKNAME
7525 ADD_SUBFEATURE (QCservice, Qt);
7526 #endif
7527 ADD_SUBFEATURE (QCserver, Qt);
7529 for (sopt = socket_options; sopt->name; sopt++)
7530 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7532 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7535 #if defined (DARWIN_OS)
7536 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7537 processes. As such, we only change the default value. */
7538 if (initialized)
7540 char const *release = (STRINGP (Voperating_system_release)
7541 ? SSDATA (Voperating_system_release)
7542 : 0);
7543 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7544 Vprocess_connection_type = Qnil;
7547 #endif
7548 #endif /* subprocesses */
7549 kbd_is_on_hold = 0;
7552 void
7553 syms_of_process (void)
7555 #ifdef subprocesses
7557 DEFSYM (Qprocessp, "processp");
7558 DEFSYM (Qrun, "run");
7559 DEFSYM (Qstop, "stop");
7560 DEFSYM (Qsignal, "signal");
7562 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7563 here again. */
7565 DEFSYM (Qopen, "open");
7566 DEFSYM (Qclosed, "closed");
7567 DEFSYM (Qconnect, "connect");
7568 DEFSYM (Qfailed, "failed");
7569 DEFSYM (Qlisten, "listen");
7570 DEFSYM (Qlocal, "local");
7571 DEFSYM (Qipv4, "ipv4");
7572 #ifdef AF_INET6
7573 DEFSYM (Qipv6, "ipv6");
7574 #endif
7575 DEFSYM (Qdatagram, "datagram");
7576 DEFSYM (Qseqpacket, "seqpacket");
7578 DEFSYM (QCport, ":port");
7579 DEFSYM (QCspeed, ":speed");
7580 DEFSYM (QCprocess, ":process");
7582 DEFSYM (QCbytesize, ":bytesize");
7583 DEFSYM (QCstopbits, ":stopbits");
7584 DEFSYM (QCparity, ":parity");
7585 DEFSYM (Qodd, "odd");
7586 DEFSYM (Qeven, "even");
7587 DEFSYM (QCflowcontrol, ":flowcontrol");
7588 DEFSYM (Qhw, "hw");
7589 DEFSYM (Qsw, "sw");
7590 DEFSYM (QCsummary, ":summary");
7592 DEFSYM (Qreal, "real");
7593 DEFSYM (Qnetwork, "network");
7594 DEFSYM (Qserial, "serial");
7595 DEFSYM (Qpipe, "pipe");
7596 DEFSYM (QCbuffer, ":buffer");
7597 DEFSYM (QChost, ":host");
7598 DEFSYM (QCservice, ":service");
7599 DEFSYM (QClocal, ":local");
7600 DEFSYM (QCremote, ":remote");
7601 DEFSYM (QCcoding, ":coding");
7602 DEFSYM (QCserver, ":server");
7603 DEFSYM (QCnowait, ":nowait");
7604 DEFSYM (QCsentinel, ":sentinel");
7605 DEFSYM (QClog, ":log");
7606 DEFSYM (QCnoquery, ":noquery");
7607 DEFSYM (QCstop, ":stop");
7608 DEFSYM (QCoptions, ":options");
7609 DEFSYM (QCplist, ":plist");
7610 DEFSYM (QCcommand, ":command");
7611 DEFSYM (QCconnection_type, ":connection-type");
7612 DEFSYM (QCstderr, ":stderr");
7613 DEFSYM (Qpty, "pty");
7614 DEFSYM (Qpipe, "pipe");
7616 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7618 staticpro (&Vprocess_alist);
7619 staticpro (&deleted_pid_list);
7621 #endif /* subprocesses */
7623 DEFSYM (QCname, ":name");
7624 DEFSYM (QCtype, ":type");
7626 DEFSYM (Qeuid, "euid");
7627 DEFSYM (Qegid, "egid");
7628 DEFSYM (Quser, "user");
7629 DEFSYM (Qgroup, "group");
7630 DEFSYM (Qcomm, "comm");
7631 DEFSYM (Qstate, "state");
7632 DEFSYM (Qppid, "ppid");
7633 DEFSYM (Qpgrp, "pgrp");
7634 DEFSYM (Qsess, "sess");
7635 DEFSYM (Qttname, "ttname");
7636 DEFSYM (Qtpgid, "tpgid");
7637 DEFSYM (Qminflt, "minflt");
7638 DEFSYM (Qmajflt, "majflt");
7639 DEFSYM (Qcminflt, "cminflt");
7640 DEFSYM (Qcmajflt, "cmajflt");
7641 DEFSYM (Qutime, "utime");
7642 DEFSYM (Qstime, "stime");
7643 DEFSYM (Qtime, "time");
7644 DEFSYM (Qcutime, "cutime");
7645 DEFSYM (Qcstime, "cstime");
7646 DEFSYM (Qctime, "ctime");
7647 #ifdef subprocesses
7648 DEFSYM (Qinternal_default_process_sentinel,
7649 "internal-default-process-sentinel");
7650 DEFSYM (Qinternal_default_process_filter,
7651 "internal-default-process-filter");
7652 #endif
7653 DEFSYM (Qpri, "pri");
7654 DEFSYM (Qnice, "nice");
7655 DEFSYM (Qthcount, "thcount");
7656 DEFSYM (Qstart, "start");
7657 DEFSYM (Qvsize, "vsize");
7658 DEFSYM (Qrss, "rss");
7659 DEFSYM (Qetime, "etime");
7660 DEFSYM (Qpcpu, "pcpu");
7661 DEFSYM (Qpmem, "pmem");
7662 DEFSYM (Qargs, "args");
7664 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7665 doc: /* Non-nil means delete processes immediately when they exit.
7666 A value of nil means don't delete them until `list-processes' is run. */);
7668 delete_exited_processes = 1;
7670 #ifdef subprocesses
7671 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7672 doc: /* Control type of device used to communicate with subprocesses.
7673 Values are nil to use a pipe, or t or `pty' to use a pty.
7674 The value has no effect if the system has no ptys or if all ptys are busy:
7675 then a pipe is used in any case.
7676 The value takes effect when `start-process' is called. */);
7677 Vprocess_connection_type = Qt;
7679 #ifdef ADAPTIVE_READ_BUFFERING
7680 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7681 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7682 On some systems, when Emacs reads the output from a subprocess, the output data
7683 is read in very small blocks, potentially resulting in very poor performance.
7684 This behavior can be remedied to some extent by setting this variable to a
7685 non-nil value, as it will automatically delay reading from such processes, to
7686 allow them to produce more output before Emacs tries to read it.
7687 If the value is t, the delay is reset after each write to the process; any other
7688 non-nil value means that the delay is not reset on write.
7689 The variable takes effect when `start-process' is called. */);
7690 Vprocess_adaptive_read_buffering = Qt;
7691 #endif
7693 defsubr (&Sprocessp);
7694 defsubr (&Sget_process);
7695 defsubr (&Sdelete_process);
7696 defsubr (&Sprocess_status);
7697 defsubr (&Sprocess_exit_status);
7698 defsubr (&Sprocess_id);
7699 defsubr (&Sprocess_name);
7700 defsubr (&Sprocess_tty_name);
7701 defsubr (&Sprocess_command);
7702 defsubr (&Sset_process_buffer);
7703 defsubr (&Sprocess_buffer);
7704 defsubr (&Sprocess_mark);
7705 defsubr (&Sset_process_filter);
7706 defsubr (&Sprocess_filter);
7707 defsubr (&Sset_process_sentinel);
7708 defsubr (&Sprocess_sentinel);
7709 defsubr (&Sset_process_window_size);
7710 defsubr (&Sset_process_inherit_coding_system_flag);
7711 defsubr (&Sset_process_query_on_exit_flag);
7712 defsubr (&Sprocess_query_on_exit_flag);
7713 defsubr (&Sprocess_contact);
7714 defsubr (&Sprocess_plist);
7715 defsubr (&Sset_process_plist);
7716 defsubr (&Sprocess_list);
7717 defsubr (&Smake_process);
7718 defsubr (&Smake_pipe_process);
7719 defsubr (&Sserial_process_configure);
7720 defsubr (&Smake_serial_process);
7721 defsubr (&Sset_network_process_option);
7722 defsubr (&Smake_network_process);
7723 defsubr (&Sformat_network_address);
7724 defsubr (&Snetwork_interface_list);
7725 defsubr (&Snetwork_interface_info);
7726 #ifdef DATAGRAM_SOCKETS
7727 defsubr (&Sprocess_datagram_address);
7728 defsubr (&Sset_process_datagram_address);
7729 #endif
7730 defsubr (&Saccept_process_output);
7731 defsubr (&Sprocess_send_region);
7732 defsubr (&Sprocess_send_string);
7733 defsubr (&Sinterrupt_process);
7734 defsubr (&Skill_process);
7735 defsubr (&Squit_process);
7736 defsubr (&Sstop_process);
7737 defsubr (&Scontinue_process);
7738 defsubr (&Sprocess_running_child_p);
7739 defsubr (&Sprocess_send_eof);
7740 defsubr (&Ssignal_process);
7741 defsubr (&Swaiting_for_user_input_p);
7742 defsubr (&Sprocess_type);
7743 defsubr (&Sinternal_default_process_sentinel);
7744 defsubr (&Sinternal_default_process_filter);
7745 defsubr (&Sset_process_coding_system);
7746 defsubr (&Sprocess_coding_system);
7747 defsubr (&Sset_process_filter_multibyte);
7748 defsubr (&Sprocess_filter_multibyte_p);
7750 #endif /* subprocesses */
7752 defsubr (&Sget_buffer_process);
7753 defsubr (&Sprocess_inherit_coding_system_flag);
7754 defsubr (&Slist_system_processes);
7755 defsubr (&Sprocess_attributes);