Update copyright year to 2014 by running admin/update-copyright.
[emacs.git] / src / process.c
blob763d2fd504aa05f863f6dd1acb170f2f99903f7b
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2014 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 #ifndef SOCK_CLOEXEC
138 # define SOCK_CLOEXEC 0
139 #endif
141 #ifndef HAVE_ACCEPT4
143 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
145 static int
146 close_on_exec (int fd)
148 if (0 <= fd)
149 fcntl (fd, F_SETFD, FD_CLOEXEC);
150 return fd;
153 static int
154 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
156 return close_on_exec (accept (sockfd, addr, addrlen));
159 static int
160 process_socket (int domain, int type, int protocol)
162 return close_on_exec (socket (domain, type, protocol));
164 # undef socket
165 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
166 #endif
168 /* Work around GCC 4.7.0 bug with strict overflow checking; see
169 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
170 These lines can be removed once the GCC bug is fixed. */
171 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
172 # pragma GCC diagnostic ignored "-Wstrict-overflow"
173 #endif
175 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
176 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
177 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
178 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
179 Lisp_Object QCname, QCtype;
181 /* True if keyboard input is on hold, zero otherwise. */
183 static bool kbd_is_on_hold;
185 /* Nonzero means don't run process sentinels. This is used
186 when exiting. */
187 bool inhibit_sentinels;
189 #ifdef subprocesses
191 Lisp_Object Qprocessp;
192 static Lisp_Object Qrun, Qstop, Qsignal;
193 static Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
194 Lisp_Object Qlocal;
195 static Lisp_Object Qipv4, Qdatagram, Qseqpacket;
196 static Lisp_Object Qreal, Qnetwork, Qserial;
197 #ifdef AF_INET6
198 static Lisp_Object Qipv6;
199 #endif
200 static Lisp_Object QCport, QCprocess;
201 Lisp_Object QCspeed;
202 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
203 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
204 static Lisp_Object QCbuffer, QChost, QCservice;
205 static Lisp_Object QClocal, QCremote, QCcoding;
206 static Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
207 static Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
208 static Lisp_Object Qlast_nonmenu_event;
209 static Lisp_Object Qinternal_default_process_sentinel;
210 static Lisp_Object Qinternal_default_process_filter;
212 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
213 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
214 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
215 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
217 /* Number of events of change of status of a process. */
218 static EMACS_INT process_tick;
219 /* Number of events for which the user or sentinel has been notified. */
220 static EMACS_INT update_tick;
222 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
224 /* Only W32 has this, it really means that select can't take write mask. */
225 #ifdef BROKEN_NON_BLOCKING_CONNECT
226 #undef NON_BLOCKING_CONNECT
227 #define SELECT_CANT_DO_WRITE_MASK
228 #else
229 #ifndef NON_BLOCKING_CONNECT
230 #ifdef HAVE_SELECT
231 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
232 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
233 #define NON_BLOCKING_CONNECT
234 #endif /* EWOULDBLOCK || EINPROGRESS */
235 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
236 #endif /* HAVE_SELECT */
237 #endif /* NON_BLOCKING_CONNECT */
238 #endif /* BROKEN_NON_BLOCKING_CONNECT */
240 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
241 this system. We need to read full packets, so we need a
242 "non-destructive" select. So we require either native select,
243 or emulation of select using FIONREAD. */
245 #ifndef BROKEN_DATAGRAM_SOCKETS
246 # if defined HAVE_SELECT || defined USABLE_FIONREAD
247 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
248 # define DATAGRAM_SOCKETS
249 # endif
250 # endif
251 #endif
253 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
254 # define HAVE_SEQPACKET
255 #endif
257 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
258 #define ADAPTIVE_READ_BUFFERING
259 #endif
261 #ifdef ADAPTIVE_READ_BUFFERING
262 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
263 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
264 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
266 /* Number of processes which have a non-zero read_output_delay,
267 and therefore might be delayed for adaptive read buffering. */
269 static int process_output_delay_count;
271 /* True if any process has non-nil read_output_skip. */
273 static bool process_output_skip;
275 #else
276 #define process_output_delay_count 0
277 #endif
279 static void create_process (Lisp_Object, char **, Lisp_Object);
280 #ifdef USABLE_SIGIO
281 static bool keyboard_bit_set (fd_set *);
282 #endif
283 static void deactivate_process (Lisp_Object);
284 static void status_notify (struct Lisp_Process *);
285 static int read_process_output (Lisp_Object, int);
286 static void handle_child_signal (int);
287 static void create_pty (Lisp_Object);
289 /* If we support a window system, turn on the code to poll periodically
290 to detect C-g. It isn't actually used when doing interrupt input. */
291 #ifdef HAVE_WINDOW_SYSTEM
292 #define POLL_FOR_INPUT
293 #endif
295 static Lisp_Object get_process (register Lisp_Object name);
296 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
298 /* Mask of bits indicating the descriptors that we wait for input on. */
300 static fd_set input_wait_mask;
302 /* Mask that excludes keyboard input descriptor(s). */
304 static fd_set non_keyboard_wait_mask;
306 /* Mask that excludes process input descriptor(s). */
308 static fd_set non_process_wait_mask;
310 /* Mask for selecting for write. */
312 static fd_set write_mask;
314 #ifdef NON_BLOCKING_CONNECT
315 /* Mask of bits indicating the descriptors that we wait for connect to
316 complete on. Once they complete, they are removed from this mask
317 and added to the input_wait_mask and non_keyboard_wait_mask. */
319 static fd_set connect_wait_mask;
321 /* Number of bits set in connect_wait_mask. */
322 static int num_pending_connects;
323 #endif /* NON_BLOCKING_CONNECT */
325 /* The largest descriptor currently in use for a process object; -1 if none. */
326 static int max_process_desc;
328 /* The largest descriptor currently in use for input; -1 if none. */
329 static int max_input_desc;
331 /* Indexed by descriptor, gives the process (if any) for that descriptor */
332 static Lisp_Object chan_process[FD_SETSIZE];
334 /* Alist of elements (NAME . PROCESS) */
335 static Lisp_Object Vprocess_alist;
337 /* Buffered-ahead input char from process, indexed by channel.
338 -1 means empty (no char is buffered).
339 Used on sys V where the only way to tell if there is any
340 output from the process is to read at least one char.
341 Always -1 on systems that support FIONREAD. */
343 static int proc_buffered_char[FD_SETSIZE];
345 /* Table of `struct coding-system' for each process. */
346 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
347 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
349 #ifdef DATAGRAM_SOCKETS
350 /* Table of `partner address' for datagram sockets. */
351 static struct sockaddr_and_len {
352 struct sockaddr *sa;
353 int len;
354 } datagram_address[FD_SETSIZE];
355 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
356 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
357 #else
358 #define DATAGRAM_CHAN_P(chan) (0)
359 #define DATAGRAM_CONN_P(proc) (0)
360 #endif
362 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
363 a `for' loop which iterates over processes from Vprocess_alist. */
365 #define FOR_EACH_PROCESS(list_var, proc_var) \
366 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
368 /* These setters are used only in this file, so they can be private. */
369 static void
370 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
372 p->buffer = val;
374 static void
375 pset_command (struct Lisp_Process *p, Lisp_Object val)
377 p->command = val;
379 static void
380 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
382 p->decode_coding_system = val;
384 static void
385 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
387 p->decoding_buf = val;
389 static void
390 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
392 p->encode_coding_system = val;
394 static void
395 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
397 p->encoding_buf = val;
399 static void
400 pset_filter (struct Lisp_Process *p, Lisp_Object val)
402 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
404 static void
405 pset_log (struct Lisp_Process *p, Lisp_Object val)
407 p->log = val;
409 static void
410 pset_mark (struct Lisp_Process *p, Lisp_Object val)
412 p->mark = val;
414 static void
415 pset_name (struct Lisp_Process *p, Lisp_Object val)
417 p->name = val;
419 static void
420 pset_plist (struct Lisp_Process *p, Lisp_Object val)
422 p->plist = val;
424 static void
425 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
427 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
429 static void
430 pset_status (struct Lisp_Process *p, Lisp_Object val)
432 p->status = val;
434 static void
435 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
437 p->tty_name = val;
439 static void
440 pset_type (struct Lisp_Process *p, Lisp_Object val)
442 p->type = val;
444 static void
445 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
447 p->write_queue = val;
452 static struct fd_callback_data
454 fd_callback func;
455 void *data;
456 #define FOR_READ 1
457 #define FOR_WRITE 2
458 int condition; /* mask of the defines above. */
459 } fd_callback_info[FD_SETSIZE];
462 /* Add a file descriptor FD to be monitored for when read is possible.
463 When read is possible, call FUNC with argument DATA. */
465 void
466 add_read_fd (int fd, fd_callback func, void *data)
468 eassert (fd < FD_SETSIZE);
469 add_keyboard_wait_descriptor (fd);
471 fd_callback_info[fd].func = func;
472 fd_callback_info[fd].data = data;
473 fd_callback_info[fd].condition |= FOR_READ;
476 /* Stop monitoring file descriptor FD for when read is possible. */
478 void
479 delete_read_fd (int fd)
481 eassert (fd < FD_SETSIZE);
482 delete_keyboard_wait_descriptor (fd);
484 fd_callback_info[fd].condition &= ~FOR_READ;
485 if (fd_callback_info[fd].condition == 0)
487 fd_callback_info[fd].func = 0;
488 fd_callback_info[fd].data = 0;
492 /* Add a file descriptor FD to be monitored for when write is possible.
493 When write is possible, call FUNC with argument DATA. */
495 void
496 add_write_fd (int fd, fd_callback func, void *data)
498 eassert (fd < FD_SETSIZE);
499 FD_SET (fd, &write_mask);
500 if (fd > max_input_desc)
501 max_input_desc = fd;
503 fd_callback_info[fd].func = func;
504 fd_callback_info[fd].data = data;
505 fd_callback_info[fd].condition |= FOR_WRITE;
508 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
510 static void
511 delete_input_desc (int fd)
513 if (fd == max_input_desc)
516 fd--;
517 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
518 || FD_ISSET (fd, &write_mask)));
520 max_input_desc = fd;
524 /* Stop monitoring file descriptor FD for when write is possible. */
526 void
527 delete_write_fd (int fd)
529 eassert (fd < FD_SETSIZE);
530 FD_CLR (fd, &write_mask);
531 fd_callback_info[fd].condition &= ~FOR_WRITE;
532 if (fd_callback_info[fd].condition == 0)
534 fd_callback_info[fd].func = 0;
535 fd_callback_info[fd].data = 0;
536 delete_input_desc (fd);
541 /* Compute the Lisp form of the process status, p->status, from
542 the numeric status that was returned by `wait'. */
544 static Lisp_Object status_convert (int);
546 static void
547 update_status (struct Lisp_Process *p)
549 eassert (p->raw_status_new);
550 pset_status (p, status_convert (p->raw_status));
551 p->raw_status_new = 0;
554 /* Convert a process status word in Unix format to
555 the list that we use internally. */
557 static Lisp_Object
558 status_convert (int w)
560 if (WIFSTOPPED (w))
561 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
562 else if (WIFEXITED (w))
563 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
564 WCOREDUMP (w) ? Qt : Qnil));
565 else if (WIFSIGNALED (w))
566 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
567 WCOREDUMP (w) ? Qt : Qnil));
568 else
569 return Qrun;
572 /* Given a status-list, extract the three pieces of information
573 and store them individually through the three pointers. */
575 static void
576 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
578 Lisp_Object tem;
580 if (SYMBOLP (l))
582 *symbol = l;
583 *code = 0;
584 *coredump = 0;
586 else
588 *symbol = XCAR (l);
589 tem = XCDR (l);
590 *code = XFASTINT (XCAR (tem));
591 tem = XCDR (tem);
592 *coredump = !NILP (tem);
596 /* Return a string describing a process status list. */
598 static Lisp_Object
599 status_message (struct Lisp_Process *p)
601 Lisp_Object status = p->status;
602 Lisp_Object symbol;
603 int code;
604 bool coredump;
605 Lisp_Object string, string2;
607 decode_status (status, &symbol, &code, &coredump);
609 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
611 char const *signame;
612 synchronize_system_messages_locale ();
613 signame = strsignal (code);
614 if (signame == 0)
615 string = build_string ("unknown");
616 else
618 int c1, c2;
620 string = build_unibyte_string (signame);
621 if (! NILP (Vlocale_coding_system))
622 string = (code_convert_string_norecord
623 (string, Vlocale_coding_system, 0));
624 c1 = STRING_CHAR (SDATA (string));
625 c2 = downcase (c1);
626 if (c1 != c2)
627 Faset (string, make_number (0), make_number (c2));
629 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
630 return concat2 (string, string2);
632 else if (EQ (symbol, Qexit))
634 if (NETCONN1_P (p))
635 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
636 if (code == 0)
637 return build_string ("finished\n");
638 string = Fnumber_to_string (make_number (code));
639 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
640 return concat3 (build_string ("exited abnormally with code "),
641 string, string2);
643 else if (EQ (symbol, Qfailed))
645 string = Fnumber_to_string (make_number (code));
646 string2 = build_string ("\n");
647 return concat3 (build_string ("failed with code "),
648 string, string2);
650 else
651 return Fcopy_sequence (Fsymbol_name (symbol));
654 enum { PTY_NAME_SIZE = 24 };
656 /* Open an available pty, returning a file descriptor.
657 Store into PTY_NAME the file name of the terminal corresponding to the pty.
658 Return -1 on failure. */
660 static int
661 allocate_pty (char pty_name[PTY_NAME_SIZE])
663 #ifdef HAVE_PTYS
664 int fd;
666 #ifdef PTY_ITERATION
667 PTY_ITERATION
668 #else
669 register int c, i;
670 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
671 for (i = 0; i < 16; i++)
672 #endif
674 #ifdef PTY_NAME_SPRINTF
675 PTY_NAME_SPRINTF
676 #else
677 sprintf (pty_name, "/dev/pty%c%x", c, i);
678 #endif /* no PTY_NAME_SPRINTF */
680 #ifdef PTY_OPEN
681 PTY_OPEN;
682 #else /* no PTY_OPEN */
683 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
684 #endif /* no PTY_OPEN */
686 if (fd >= 0)
688 #ifdef PTY_OPEN
689 /* Set FD's close-on-exec flag. This is needed even if
690 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
691 doesn't require support for that combination.
692 Multithreaded platforms where posix_openpt ignores
693 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
694 have a race condition between the PTY_OPEN and here. */
695 fcntl (fd, F_SETFD, FD_CLOEXEC);
696 #endif
697 /* check to make certain that both sides are available
698 this avoids a nasty yet stupid bug in rlogins */
699 #ifdef PTY_TTY_NAME_SPRINTF
700 PTY_TTY_NAME_SPRINTF
701 #else
702 sprintf (pty_name, "/dev/tty%c%x", c, i);
703 #endif /* no PTY_TTY_NAME_SPRINTF */
704 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
706 emacs_close (fd);
707 # ifndef __sgi
708 continue;
709 # else
710 return -1;
711 # endif /* __sgi */
713 setup_pty (fd);
714 return fd;
717 #endif /* HAVE_PTYS */
718 return -1;
721 static Lisp_Object
722 make_process (Lisp_Object name)
724 register Lisp_Object val, tem, name1;
725 register struct Lisp_Process *p;
726 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
727 printmax_t i;
729 p = allocate_process ();
730 /* Initialize Lisp data. Note that allocate_process initializes all
731 Lisp data to nil, so do it only for slots which should not be nil. */
732 pset_status (p, Qrun);
733 pset_mark (p, Fmake_marker ());
735 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
736 non-Lisp data, so do it only for slots which should not be zero. */
737 p->infd = -1;
738 p->outfd = -1;
739 for (i = 0; i < PROCESS_OPEN_FDS; i++)
740 p->open_fd[i] = -1;
742 #ifdef HAVE_GNUTLS
743 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
744 #endif
746 /* If name is already in use, modify it until it is unused. */
748 name1 = name;
749 for (i = 1; ; i++)
751 tem = Fget_process (name1);
752 if (NILP (tem)) break;
753 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
755 name = name1;
756 pset_name (p, name);
757 pset_sentinel (p, Qinternal_default_process_sentinel);
758 pset_filter (p, Qinternal_default_process_filter);
759 XSETPROCESS (val, p);
760 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
761 return val;
764 static void
765 remove_process (register Lisp_Object proc)
767 register Lisp_Object pair;
769 pair = Frassq (proc, Vprocess_alist);
770 Vprocess_alist = Fdelq (pair, Vprocess_alist);
772 deactivate_process (proc);
776 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
777 doc: /* Return t if OBJECT is a process. */)
778 (Lisp_Object object)
780 return PROCESSP (object) ? Qt : Qnil;
783 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
784 doc: /* Return the process named NAME, or nil if there is none. */)
785 (register Lisp_Object name)
787 if (PROCESSP (name))
788 return name;
789 CHECK_STRING (name);
790 return Fcdr (Fassoc (name, Vprocess_alist));
793 /* This is how commands for the user decode process arguments. It
794 accepts a process, a process name, a buffer, a buffer name, or nil.
795 Buffers denote the first process in the buffer, and nil denotes the
796 current buffer. */
798 static Lisp_Object
799 get_process (register Lisp_Object name)
801 register Lisp_Object proc, obj;
802 if (STRINGP (name))
804 obj = Fget_process (name);
805 if (NILP (obj))
806 obj = Fget_buffer (name);
807 if (NILP (obj))
808 error ("Process %s does not exist", SDATA (name));
810 else if (NILP (name))
811 obj = Fcurrent_buffer ();
812 else
813 obj = name;
815 /* Now obj should be either a buffer object or a process object. */
816 if (BUFFERP (obj))
818 if (NILP (BVAR (XBUFFER (obj), name)))
819 error ("Attempt to get process for a dead buffer");
820 proc = Fget_buffer_process (obj);
821 if (NILP (proc))
822 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
824 else
826 CHECK_PROCESS (obj);
827 proc = obj;
829 return proc;
833 /* Fdelete_process promises to immediately forget about the process, but in
834 reality, Emacs needs to remember those processes until they have been
835 treated by the SIGCHLD handler and waitpid has been invoked on them;
836 otherwise they might fill up the kernel's process table.
838 Some processes created by call-process are also put onto this list.
840 Members of this list are (process-ID . filename) pairs. The
841 process-ID is a number; the filename, if a string, is a file that
842 needs to be removed after the process exits. */
843 static Lisp_Object deleted_pid_list;
845 void
846 record_deleted_pid (pid_t pid, Lisp_Object filename)
848 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
849 /* GC treated elements set to nil. */
850 Fdelq (Qnil, deleted_pid_list));
854 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
855 doc: /* Delete PROCESS: kill it and forget about it immediately.
856 PROCESS may be a process, a buffer, the name of a process or buffer, or
857 nil, indicating the current buffer's process. */)
858 (register Lisp_Object process)
860 register struct Lisp_Process *p;
862 process = get_process (process);
863 p = XPROCESS (process);
865 p->raw_status_new = 0;
866 if (NETCONN1_P (p) || SERIALCONN1_P (p))
868 pset_status (p, list2 (Qexit, make_number (0)));
869 p->tick = ++process_tick;
870 status_notify (p);
871 redisplay_preserve_echo_area (13);
873 else
875 if (p->alive)
876 record_kill_process (p, Qnil);
878 if (p->infd >= 0)
880 /* Update P's status, since record_kill_process will make the
881 SIGCHLD handler update deleted_pid_list, not *P. */
882 Lisp_Object symbol;
883 if (p->raw_status_new)
884 update_status (p);
885 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
886 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
887 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
889 p->tick = ++process_tick;
890 status_notify (p);
891 redisplay_preserve_echo_area (13);
894 remove_process (process);
895 return Qnil;
898 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
899 doc: /* Return the status of PROCESS.
900 The returned value is one of the following symbols:
901 run -- for a process that is running.
902 stop -- for a process stopped but continuable.
903 exit -- for a process that has exited.
904 signal -- for a process that has got a fatal signal.
905 open -- for a network stream connection that is open.
906 listen -- for a network stream server that is listening.
907 closed -- for a network stream connection that is closed.
908 connect -- when waiting for a non-blocking connection to complete.
909 failed -- when a non-blocking connection has failed.
910 nil -- if arg is a process name and no such process exists.
911 PROCESS may be a process, a buffer, the name of a process, or
912 nil, indicating the current buffer's process. */)
913 (register Lisp_Object process)
915 register struct Lisp_Process *p;
916 register Lisp_Object status;
918 if (STRINGP (process))
919 process = Fget_process (process);
920 else
921 process = get_process (process);
923 if (NILP (process))
924 return process;
926 p = XPROCESS (process);
927 if (p->raw_status_new)
928 update_status (p);
929 status = p->status;
930 if (CONSP (status))
931 status = XCAR (status);
932 if (NETCONN1_P (p) || SERIALCONN1_P (p))
934 if (EQ (status, Qexit))
935 status = Qclosed;
936 else if (EQ (p->command, Qt))
937 status = Qstop;
938 else if (EQ (status, Qrun))
939 status = Qopen;
941 return status;
944 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
945 1, 1, 0,
946 doc: /* Return the exit status of PROCESS or the signal number that killed it.
947 If PROCESS has not yet exited or died, return 0. */)
948 (register Lisp_Object process)
950 CHECK_PROCESS (process);
951 if (XPROCESS (process)->raw_status_new)
952 update_status (XPROCESS (process));
953 if (CONSP (XPROCESS (process)->status))
954 return XCAR (XCDR (XPROCESS (process)->status));
955 return make_number (0);
958 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
959 doc: /* Return the process id of PROCESS.
960 This is the pid of the external process which PROCESS uses or talks to.
961 For a network connection, this value is nil. */)
962 (register Lisp_Object process)
964 pid_t pid;
966 CHECK_PROCESS (process);
967 pid = XPROCESS (process)->pid;
968 return (pid ? make_fixnum_or_float (pid) : Qnil);
971 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
972 doc: /* Return the name of PROCESS, as a string.
973 This is the name of the program invoked in PROCESS,
974 possibly modified to make it unique among process names. */)
975 (register Lisp_Object process)
977 CHECK_PROCESS (process);
978 return XPROCESS (process)->name;
981 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
982 doc: /* Return the command that was executed to start PROCESS.
983 This is a list of strings, the first string being the program executed
984 and the rest of the strings being the arguments given to it.
985 For a network or serial process, this is nil (process is running) or t
986 \(process is stopped). */)
987 (register Lisp_Object process)
989 CHECK_PROCESS (process);
990 return XPROCESS (process)->command;
993 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
994 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
995 This is the terminal that the process itself reads and writes on,
996 not the name of the pty that Emacs uses to talk with that terminal. */)
997 (register Lisp_Object process)
999 CHECK_PROCESS (process);
1000 return XPROCESS (process)->tty_name;
1003 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1004 2, 2, 0,
1005 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1006 Return BUFFER. */)
1007 (register Lisp_Object process, Lisp_Object buffer)
1009 struct Lisp_Process *p;
1011 CHECK_PROCESS (process);
1012 if (!NILP (buffer))
1013 CHECK_BUFFER (buffer);
1014 p = XPROCESS (process);
1015 pset_buffer (p, buffer);
1016 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1017 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1018 setup_process_coding_systems (process);
1019 return buffer;
1022 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1023 1, 1, 0,
1024 doc: /* Return the buffer PROCESS is associated with.
1025 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
1026 (register Lisp_Object process)
1028 CHECK_PROCESS (process);
1029 return XPROCESS (process)->buffer;
1032 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1033 1, 1, 0,
1034 doc: /* Return the marker for the end of the last output from PROCESS. */)
1035 (register Lisp_Object process)
1037 CHECK_PROCESS (process);
1038 return XPROCESS (process)->mark;
1041 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1042 2, 2, 0,
1043 doc: /* Give PROCESS the filter function FILTER; nil means default.
1044 A value of t means stop accepting output from the process.
1046 When a process has a non-default filter, its buffer is not used for output.
1047 Instead, each time it does output, the entire string of output is
1048 passed to the filter.
1050 The filter gets two arguments: the process and the string of output.
1051 The string argument is normally a multibyte string, except:
1052 - if the process' input coding system is no-conversion or raw-text,
1053 it is a unibyte string (the non-converted input), or else
1054 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1055 string (the result of converting the decoded input multibyte
1056 string to unibyte with `string-make-unibyte'). */)
1057 (register Lisp_Object process, Lisp_Object filter)
1059 struct Lisp_Process *p;
1061 CHECK_PROCESS (process);
1062 p = XPROCESS (process);
1064 /* Don't signal an error if the process' input file descriptor
1065 is closed. This could make debugging Lisp more difficult,
1066 for example when doing something like
1068 (setq process (start-process ...))
1069 (debug)
1070 (set-process-filter process ...) */
1072 if (NILP (filter))
1073 filter = Qinternal_default_process_filter;
1075 if (p->infd >= 0)
1077 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1079 FD_CLR (p->infd, &input_wait_mask);
1080 FD_CLR (p->infd, &non_keyboard_wait_mask);
1082 else if (EQ (p->filter, Qt)
1083 /* Network or serial process not stopped: */
1084 && !EQ (p->command, Qt))
1086 FD_SET (p->infd, &input_wait_mask);
1087 FD_SET (p->infd, &non_keyboard_wait_mask);
1091 pset_filter (p, filter);
1092 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1093 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1094 setup_process_coding_systems (process);
1095 return filter;
1098 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1099 1, 1, 0,
1100 doc: /* Return the filter function of PROCESS.
1101 See `set-process-filter' for more info on filter functions. */)
1102 (register Lisp_Object process)
1104 CHECK_PROCESS (process);
1105 return XPROCESS (process)->filter;
1108 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1109 2, 2, 0,
1110 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1111 The sentinel is called as a function when the process changes state.
1112 It gets two arguments: the process, and a string describing the change. */)
1113 (register Lisp_Object process, Lisp_Object sentinel)
1115 struct Lisp_Process *p;
1117 CHECK_PROCESS (process);
1118 p = XPROCESS (process);
1120 if (NILP (sentinel))
1121 sentinel = Qinternal_default_process_sentinel;
1123 pset_sentinel (p, sentinel);
1124 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1125 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1126 return sentinel;
1129 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1130 1, 1, 0,
1131 doc: /* Return the sentinel of PROCESS.
1132 See `set-process-sentinel' for more info on sentinels. */)
1133 (register Lisp_Object process)
1135 CHECK_PROCESS (process);
1136 return XPROCESS (process)->sentinel;
1139 DEFUN ("set-process-window-size", Fset_process_window_size,
1140 Sset_process_window_size, 3, 3, 0,
1141 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1142 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1144 CHECK_PROCESS (process);
1146 /* All known platforms store window sizes as 'unsigned short'. */
1147 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1148 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1150 if (XPROCESS (process)->infd < 0
1151 || (set_window_size (XPROCESS (process)->infd,
1152 XINT (height), XINT (width))
1153 < 0))
1154 return Qnil;
1155 else
1156 return Qt;
1159 DEFUN ("set-process-inherit-coding-system-flag",
1160 Fset_process_inherit_coding_system_flag,
1161 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1162 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1163 If the second argument FLAG is non-nil, then the variable
1164 `buffer-file-coding-system' of the buffer associated with PROCESS
1165 will be bound to the value of the coding system used to decode
1166 the process output.
1168 This is useful when the coding system specified for the process buffer
1169 leaves either the character code conversion or the end-of-line conversion
1170 unspecified, or if the coding system used to decode the process output
1171 is more appropriate for saving the process buffer.
1173 Binding the variable `inherit-process-coding-system' to non-nil before
1174 starting the process is an alternative way of setting the inherit flag
1175 for the process which will run.
1177 This function returns FLAG. */)
1178 (register Lisp_Object process, Lisp_Object flag)
1180 CHECK_PROCESS (process);
1181 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1182 return flag;
1185 DEFUN ("set-process-query-on-exit-flag",
1186 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1187 2, 2, 0,
1188 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1189 If the second argument FLAG is non-nil, Emacs will query the user before
1190 exiting or killing a buffer if PROCESS is running. This function
1191 returns FLAG. */)
1192 (register Lisp_Object process, Lisp_Object flag)
1194 CHECK_PROCESS (process);
1195 XPROCESS (process)->kill_without_query = NILP (flag);
1196 return flag;
1199 DEFUN ("process-query-on-exit-flag",
1200 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1201 1, 1, 0,
1202 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1203 (register Lisp_Object process)
1205 CHECK_PROCESS (process);
1206 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1209 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1210 1, 2, 0,
1211 doc: /* Return the contact info of PROCESS; t for a real child.
1212 For a network or serial connection, the value depends on the optional
1213 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1214 SERVICE) for a network connection or (PORT SPEED) for a serial
1215 connection. If KEY is t, the complete contact information for the
1216 connection is returned, else the specific value for the keyword KEY is
1217 returned. See `make-network-process' or `make-serial-process' for a
1218 list of keywords. */)
1219 (register Lisp_Object process, Lisp_Object key)
1221 Lisp_Object contact;
1223 CHECK_PROCESS (process);
1224 contact = XPROCESS (process)->childp;
1226 #ifdef DATAGRAM_SOCKETS
1227 if (DATAGRAM_CONN_P (process)
1228 && (EQ (key, Qt) || EQ (key, QCremote)))
1229 contact = Fplist_put (contact, QCremote,
1230 Fprocess_datagram_address (process));
1231 #endif
1233 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1234 return contact;
1235 if (NILP (key) && NETCONN_P (process))
1236 return list2 (Fplist_get (contact, QChost),
1237 Fplist_get (contact, QCservice));
1238 if (NILP (key) && SERIALCONN_P (process))
1239 return list2 (Fplist_get (contact, QCport),
1240 Fplist_get (contact, QCspeed));
1241 return Fplist_get (contact, key);
1244 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1245 1, 1, 0,
1246 doc: /* Return the plist of PROCESS. */)
1247 (register Lisp_Object process)
1249 CHECK_PROCESS (process);
1250 return XPROCESS (process)->plist;
1253 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1254 2, 2, 0,
1255 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1256 (register Lisp_Object process, Lisp_Object plist)
1258 CHECK_PROCESS (process);
1259 CHECK_LIST (plist);
1261 pset_plist (XPROCESS (process), plist);
1262 return plist;
1265 #if 0 /* Turned off because we don't currently record this info
1266 in the process. Perhaps add it. */
1267 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1268 doc: /* Return the connection type of PROCESS.
1269 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1270 a socket connection. */)
1271 (Lisp_Object process)
1273 return XPROCESS (process)->type;
1275 #endif
1277 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1278 doc: /* Return the connection type of PROCESS.
1279 The value is either the symbol `real', `network', or `serial'.
1280 PROCESS may be a process, a buffer, the name of a process or buffer, or
1281 nil, indicating the current buffer's process. */)
1282 (Lisp_Object process)
1284 Lisp_Object proc;
1285 proc = get_process (process);
1286 return XPROCESS (proc)->type;
1289 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1290 1, 2, 0,
1291 doc: /* Convert network ADDRESS from internal format to a string.
1292 A 4 or 5 element vector represents an IPv4 address (with port number).
1293 An 8 or 9 element vector represents an IPv6 address (with port number).
1294 If optional second argument OMIT-PORT is non-nil, don't include a port
1295 number in the string, even when present in ADDRESS.
1296 Returns nil if format of ADDRESS is invalid. */)
1297 (Lisp_Object address, Lisp_Object omit_port)
1299 if (NILP (address))
1300 return Qnil;
1302 if (STRINGP (address)) /* AF_LOCAL */
1303 return address;
1305 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1307 register struct Lisp_Vector *p = XVECTOR (address);
1308 ptrdiff_t size = p->header.size;
1309 Lisp_Object args[10];
1310 int nargs, i;
1312 if (size == 4 || (size == 5 && !NILP (omit_port)))
1314 args[0] = build_string ("%d.%d.%d.%d");
1315 nargs = 4;
1317 else if (size == 5)
1319 args[0] = build_string ("%d.%d.%d.%d:%d");
1320 nargs = 5;
1322 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1324 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1325 nargs = 8;
1327 else if (size == 9)
1329 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1330 nargs = 9;
1332 else
1333 return Qnil;
1335 for (i = 0; i < nargs; i++)
1337 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1338 return Qnil;
1340 if (nargs <= 5 /* IPv4 */
1341 && i < 4 /* host, not port */
1342 && XINT (p->contents[i]) > 255)
1343 return Qnil;
1345 args[i+1] = p->contents[i];
1348 return Fformat (nargs+1, args);
1351 if (CONSP (address))
1353 Lisp_Object args[2];
1354 args[0] = build_string ("<Family %d>");
1355 args[1] = Fcar (address);
1356 return Fformat (2, args);
1359 return Qnil;
1362 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1363 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1364 (void)
1366 return Fmapcar (Qcdr, Vprocess_alist);
1369 /* Starting asynchronous inferior processes. */
1371 static void start_process_unwind (Lisp_Object proc);
1373 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1374 doc: /* Start a program in a subprocess. Return the process object for it.
1375 NAME is name for process. It is modified if necessary to make it unique.
1376 BUFFER is the buffer (or buffer name) to associate with the process.
1378 Process output (both standard output and standard error streams) goes
1379 at end of BUFFER, unless you specify an output stream or filter
1380 function to handle the output. BUFFER may also be nil, meaning that
1381 this process is not associated with any buffer.
1383 PROGRAM is the program file name. It is searched for in `exec-path'
1384 (which see). If nil, just associate a pty with the buffer. Remaining
1385 arguments are strings to give program as arguments.
1387 If you want to separate standard output from standard error, invoke
1388 the command through a shell and redirect one of them using the shell
1389 syntax.
1391 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1392 (ptrdiff_t nargs, Lisp_Object *args)
1394 Lisp_Object buffer, name, program, proc, current_dir, tem;
1395 register unsigned char **new_argv;
1396 ptrdiff_t i;
1397 ptrdiff_t count = SPECPDL_INDEX ();
1399 buffer = args[1];
1400 if (!NILP (buffer))
1401 buffer = Fget_buffer_create (buffer);
1403 /* Make sure that the child will be able to chdir to the current
1404 buffer's current directory, or its unhandled equivalent. We
1405 can't just have the child check for an error when it does the
1406 chdir, since it's in a vfork.
1408 We have to GCPRO around this because Fexpand_file_name and
1409 Funhandled_file_name_directory might call a file name handling
1410 function. The argument list is protected by the caller, so all
1411 we really have to worry about is buffer. */
1413 struct gcpro gcpro1;
1414 GCPRO1 (buffer);
1415 current_dir = encode_current_directory ();
1416 UNGCPRO;
1419 name = args[0];
1420 CHECK_STRING (name);
1422 program = args[2];
1424 if (!NILP (program))
1425 CHECK_STRING (program);
1427 proc = make_process (name);
1428 /* If an error occurs and we can't start the process, we want to
1429 remove it from the process list. This means that each error
1430 check in create_process doesn't need to call remove_process
1431 itself; it's all taken care of here. */
1432 record_unwind_protect (start_process_unwind, proc);
1434 pset_childp (XPROCESS (proc), Qt);
1435 pset_plist (XPROCESS (proc), Qnil);
1436 pset_type (XPROCESS (proc), Qreal);
1437 pset_buffer (XPROCESS (proc), buffer);
1438 pset_sentinel (XPROCESS (proc), Qinternal_default_process_sentinel);
1439 pset_filter (XPROCESS (proc), Qinternal_default_process_filter);
1440 pset_command (XPROCESS (proc), Flist (nargs - 2, args + 2));
1442 #ifdef HAVE_GNUTLS
1443 /* AKA GNUTLS_INITSTAGE(proc). */
1444 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1445 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1446 #endif
1448 #ifdef ADAPTIVE_READ_BUFFERING
1449 XPROCESS (proc)->adaptive_read_buffering
1450 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1451 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1452 #endif
1454 /* Make the process marker point into the process buffer (if any). */
1455 if (BUFFERP (buffer))
1456 set_marker_both (XPROCESS (proc)->mark, buffer,
1457 BUF_ZV (XBUFFER (buffer)),
1458 BUF_ZV_BYTE (XBUFFER (buffer)));
1461 /* Decide coding systems for communicating with the process. Here
1462 we don't setup the structure coding_system nor pay attention to
1463 unibyte mode. They are done in create_process. */
1465 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1466 Lisp_Object coding_systems = Qt;
1467 Lisp_Object val, *args2;
1468 struct gcpro gcpro1, gcpro2;
1470 val = Vcoding_system_for_read;
1471 if (NILP (val))
1473 args2 = alloca ((nargs + 1) * sizeof *args2);
1474 args2[0] = Qstart_process;
1475 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1476 GCPRO2 (proc, current_dir);
1477 if (!NILP (program))
1478 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1479 UNGCPRO;
1480 if (CONSP (coding_systems))
1481 val = XCAR (coding_systems);
1482 else if (CONSP (Vdefault_process_coding_system))
1483 val = XCAR (Vdefault_process_coding_system);
1485 pset_decode_coding_system (XPROCESS (proc), val);
1487 val = Vcoding_system_for_write;
1488 if (NILP (val))
1490 if (EQ (coding_systems, Qt))
1492 args2 = alloca ((nargs + 1) * sizeof *args2);
1493 args2[0] = Qstart_process;
1494 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1495 GCPRO2 (proc, current_dir);
1496 if (!NILP (program))
1497 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1498 UNGCPRO;
1500 if (CONSP (coding_systems))
1501 val = XCDR (coding_systems);
1502 else if (CONSP (Vdefault_process_coding_system))
1503 val = XCDR (Vdefault_process_coding_system);
1505 pset_encode_coding_system (XPROCESS (proc), val);
1506 /* Note: At this moment, the above coding system may leave
1507 text-conversion or eol-conversion unspecified. They will be
1508 decided after we read output from the process and decode it by
1509 some coding system, or just before we actually send a text to
1510 the process. */
1514 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1515 XPROCESS (proc)->decoding_carryover = 0;
1516 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1518 XPROCESS (proc)->inherit_coding_system_flag
1519 = !(NILP (buffer) || !inherit_process_coding_system);
1521 if (!NILP (program))
1523 /* If program file name is not absolute, search our path for it.
1524 Put the name we will really use in TEM. */
1525 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1526 && !(SCHARS (program) > 1
1527 && IS_DEVICE_SEP (SREF (program, 1))))
1529 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1531 tem = Qnil;
1532 GCPRO4 (name, program, buffer, current_dir);
1533 openp (Vexec_path, program, Vexec_suffixes, &tem,
1534 make_number (X_OK), false);
1535 UNGCPRO;
1536 if (NILP (tem))
1537 report_file_error ("Searching for program", program);
1538 tem = Fexpand_file_name (tem, Qnil);
1540 else
1542 if (!NILP (Ffile_directory_p (program)))
1543 error ("Specified program for new process is a directory");
1544 tem = program;
1547 /* If program file name starts with /: for quoting a magic name,
1548 discard that. */
1549 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1550 && SREF (tem, 1) == ':')
1551 tem = Fsubstring (tem, make_number (2), Qnil);
1554 Lisp_Object arg_encoding = Qnil;
1555 struct gcpro gcpro1;
1556 GCPRO1 (tem);
1558 /* Encode the file name and put it in NEW_ARGV.
1559 That's where the child will use it to execute the program. */
1560 tem = list1 (ENCODE_FILE (tem));
1562 /* Here we encode arguments by the coding system used for sending
1563 data to the process. We don't support using different coding
1564 systems for encoding arguments and for encoding data sent to the
1565 process. */
1567 for (i = 3; i < nargs; i++)
1569 tem = Fcons (args[i], tem);
1570 CHECK_STRING (XCAR (tem));
1571 if (STRING_MULTIBYTE (XCAR (tem)))
1573 if (NILP (arg_encoding))
1574 arg_encoding = (complement_process_encoding_system
1575 (XPROCESS (proc)->encode_coding_system));
1576 XSETCAR (tem,
1577 code_convert_string_norecord
1578 (XCAR (tem), arg_encoding, 1));
1582 UNGCPRO;
1585 /* Now that everything is encoded we can collect the strings into
1586 NEW_ARGV. */
1587 new_argv = alloca ((nargs - 1) * sizeof *new_argv);
1588 new_argv[nargs - 2] = 0;
1590 for (i = nargs - 2; i-- != 0; )
1592 new_argv[i] = SDATA (XCAR (tem));
1593 tem = XCDR (tem);
1596 create_process (proc, (char **) new_argv, current_dir);
1598 else
1599 create_pty (proc);
1601 return unbind_to (count, proc);
1604 /* This function is the unwind_protect form for Fstart_process. If
1605 PROC doesn't have its pid set, then we know someone has signaled
1606 an error and the process wasn't started successfully, so we should
1607 remove it from the process list. */
1608 static void
1609 start_process_unwind (Lisp_Object proc)
1611 if (!PROCESSP (proc))
1612 emacs_abort ();
1614 /* Was PROC started successfully?
1615 -2 is used for a pty with no process, eg for gdb. */
1616 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1617 remove_process (proc);
1620 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1622 static void
1623 close_process_fd (int *fd_addr)
1625 int fd = *fd_addr;
1626 if (0 <= fd)
1628 *fd_addr = -1;
1629 emacs_close (fd);
1633 /* Indexes of file descriptors in open_fds. */
1634 enum
1636 /* The pipe from Emacs to its subprocess. */
1637 SUBPROCESS_STDIN,
1638 WRITE_TO_SUBPROCESS,
1640 /* The main pipe from the subprocess to Emacs. */
1641 READ_FROM_SUBPROCESS,
1642 SUBPROCESS_STDOUT,
1644 /* The pipe from the subprocess to Emacs that is closed when the
1645 subprocess execs. */
1646 READ_FROM_EXEC_MONITOR,
1647 EXEC_MONITOR_OUTPUT
1650 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1652 static void
1653 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1655 struct Lisp_Process *p = XPROCESS (process);
1656 int inchannel, outchannel;
1657 pid_t pid;
1658 int vfork_errno;
1659 int forkin, forkout;
1660 bool pty_flag = 0;
1661 char pty_name[PTY_NAME_SIZE];
1662 Lisp_Object lisp_pty_name = Qnil;
1664 inchannel = outchannel = -1;
1666 if (!NILP (Vprocess_connection_type))
1667 outchannel = inchannel = allocate_pty (pty_name);
1669 if (inchannel >= 0)
1671 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1672 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1673 /* On most USG systems it does not work to open the pty's tty here,
1674 then close it and reopen it in the child. */
1675 /* Don't let this terminal become our controlling terminal
1676 (in case we don't have one). */
1677 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1678 if (forkin < 0)
1679 report_file_error ("Opening pty", Qnil);
1680 p->open_fd[SUBPROCESS_STDIN] = forkin;
1681 #else
1682 forkin = forkout = -1;
1683 #endif /* not USG, or USG_SUBTTY_WORKS */
1684 pty_flag = 1;
1685 lisp_pty_name = build_string (pty_name);
1687 else
1689 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1690 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1691 report_file_error ("Creating pipe", Qnil);
1692 forkin = p->open_fd[SUBPROCESS_STDIN];
1693 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1694 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1695 forkout = p->open_fd[SUBPROCESS_STDOUT];
1698 #ifndef WINDOWSNT
1699 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1700 report_file_error ("Creating pipe", Qnil);
1701 #endif
1703 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1704 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1706 /* Record this as an active process, with its channels. */
1707 chan_process[inchannel] = process;
1708 p->infd = inchannel;
1709 p->outfd = outchannel;
1711 /* Previously we recorded the tty descriptor used in the subprocess.
1712 It was only used for getting the foreground tty process, so now
1713 we just reopen the device (see emacs_get_tty_pgrp) as this is
1714 more portable (see USG_SUBTTY_WORKS above). */
1716 p->pty_flag = pty_flag;
1717 pset_status (p, Qrun);
1719 FD_SET (inchannel, &input_wait_mask);
1720 FD_SET (inchannel, &non_keyboard_wait_mask);
1721 if (inchannel > max_process_desc)
1722 max_process_desc = inchannel;
1724 /* This may signal an error. */
1725 setup_process_coding_systems (process);
1727 block_input ();
1728 block_child_signal ();
1730 #ifndef WINDOWSNT
1731 /* vfork, and prevent local vars from being clobbered by the vfork. */
1733 Lisp_Object volatile current_dir_volatile = current_dir;
1734 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1735 char **volatile new_argv_volatile = new_argv;
1736 int volatile forkin_volatile = forkin;
1737 int volatile forkout_volatile = forkout;
1738 struct Lisp_Process *p_volatile = p;
1740 pid = vfork ();
1742 current_dir = current_dir_volatile;
1743 lisp_pty_name = lisp_pty_name_volatile;
1744 new_argv = new_argv_volatile;
1745 forkin = forkin_volatile;
1746 forkout = forkout_volatile;
1747 p = p_volatile;
1749 pty_flag = p->pty_flag;
1752 if (pid == 0)
1753 #endif /* not WINDOWSNT */
1755 int xforkin = forkin;
1756 int xforkout = forkout;
1758 /* Make the pty be the controlling terminal of the process. */
1759 #ifdef HAVE_PTYS
1760 /* First, disconnect its current controlling terminal. */
1761 /* We tried doing setsid only if pty_flag, but it caused
1762 process_set_signal to fail on SGI when using a pipe. */
1763 setsid ();
1764 /* Make the pty's terminal the controlling terminal. */
1765 if (pty_flag && xforkin >= 0)
1767 #ifdef TIOCSCTTY
1768 /* We ignore the return value
1769 because faith@cs.unc.edu says that is necessary on Linux. */
1770 ioctl (xforkin, TIOCSCTTY, 0);
1771 #endif
1773 #if defined (LDISC1)
1774 if (pty_flag && xforkin >= 0)
1776 struct termios t;
1777 tcgetattr (xforkin, &t);
1778 t.c_lflag = LDISC1;
1779 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1780 emacs_perror ("create_process/tcsetattr LDISC1");
1782 #else
1783 #if defined (NTTYDISC) && defined (TIOCSETD)
1784 if (pty_flag && xforkin >= 0)
1786 /* Use new line discipline. */
1787 int ldisc = NTTYDISC;
1788 ioctl (xforkin, TIOCSETD, &ldisc);
1790 #endif
1791 #endif
1792 #ifdef TIOCNOTTY
1793 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1794 can do TIOCSPGRP only to the process's controlling tty. */
1795 if (pty_flag)
1797 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1798 I can't test it since I don't have 4.3. */
1799 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1800 if (j >= 0)
1802 ioctl (j, TIOCNOTTY, 0);
1803 emacs_close (j);
1806 #endif /* TIOCNOTTY */
1808 #if !defined (DONT_REOPEN_PTY)
1809 /*** There is a suggestion that this ought to be a
1810 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1811 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1812 that system does seem to need this code, even though
1813 both TIOCSCTTY is defined. */
1814 /* Now close the pty (if we had it open) and reopen it.
1815 This makes the pty the controlling terminal of the subprocess. */
1816 if (pty_flag)
1819 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1820 would work? */
1821 if (xforkin >= 0)
1822 emacs_close (xforkin);
1823 xforkout = xforkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1825 if (xforkin < 0)
1827 emacs_perror (SSDATA (lisp_pty_name));
1828 _exit (EXIT_CANCELED);
1832 #endif /* not DONT_REOPEN_PTY */
1834 #ifdef SETUP_SLAVE_PTY
1835 if (pty_flag)
1837 SETUP_SLAVE_PTY;
1839 #endif /* SETUP_SLAVE_PTY */
1840 #endif /* HAVE_PTYS */
1842 signal (SIGINT, SIG_DFL);
1843 signal (SIGQUIT, SIG_DFL);
1845 /* Emacs ignores SIGPIPE, but the child should not. */
1846 signal (SIGPIPE, SIG_DFL);
1848 /* Stop blocking SIGCHLD in the child. */
1849 unblock_child_signal ();
1851 if (pty_flag)
1852 child_setup_tty (xforkout);
1853 #ifdef WINDOWSNT
1854 pid = child_setup (xforkin, xforkout, xforkout, new_argv, 1, current_dir);
1855 #else /* not WINDOWSNT */
1856 child_setup (xforkin, xforkout, xforkout, new_argv, 1, current_dir);
1857 #endif /* not WINDOWSNT */
1860 /* Back in the parent process. */
1862 vfork_errno = errno;
1863 p->pid = pid;
1864 if (pid >= 0)
1865 p->alive = 1;
1867 /* Stop blocking in the parent. */
1868 unblock_child_signal ();
1869 unblock_input ();
1871 if (pid < 0)
1872 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1873 else
1875 /* vfork succeeded. */
1877 /* Close the pipe ends that the child uses, or the child's pty. */
1878 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
1879 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
1881 #ifdef WINDOWSNT
1882 register_child (pid, inchannel);
1883 #endif /* WINDOWSNT */
1885 pset_tty_name (p, lisp_pty_name);
1887 #ifndef WINDOWSNT
1888 /* Wait for child_setup to complete in case that vfork is
1889 actually defined as fork. The descriptor
1890 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1891 of a pipe is closed at the child side either by close-on-exec
1892 on successful execve or the _exit call in child_setup. */
1894 char dummy;
1896 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
1897 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
1898 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
1900 #endif
1904 static void
1905 create_pty (Lisp_Object process)
1907 struct Lisp_Process *p = XPROCESS (process);
1908 char pty_name[PTY_NAME_SIZE];
1909 int pty_fd = NILP (Vprocess_connection_type) ? -1 : allocate_pty (pty_name);
1911 if (pty_fd >= 0)
1913 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
1914 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1915 /* On most USG systems it does not work to open the pty's tty here,
1916 then close it and reopen it in the child. */
1917 /* Don't let this terminal become our controlling terminal
1918 (in case we don't have one). */
1919 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1920 if (forkout < 0)
1921 report_file_error ("Opening pty", Qnil);
1922 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
1923 #if defined (DONT_REOPEN_PTY)
1924 /* In the case that vfork is defined as fork, the parent process
1925 (Emacs) may send some data before the child process completes
1926 tty options setup. So we setup tty before forking. */
1927 child_setup_tty (forkout);
1928 #endif /* DONT_REOPEN_PTY */
1929 #endif /* not USG, or USG_SUBTTY_WORKS */
1931 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
1933 /* Record this as an active process, with its channels.
1934 As a result, child_setup will close Emacs's side of the pipes. */
1935 chan_process[pty_fd] = process;
1936 p->infd = pty_fd;
1937 p->outfd = pty_fd;
1939 /* Previously we recorded the tty descriptor used in the subprocess.
1940 It was only used for getting the foreground tty process, so now
1941 we just reopen the device (see emacs_get_tty_pgrp) as this is
1942 more portable (see USG_SUBTTY_WORKS above). */
1944 p->pty_flag = 1;
1945 pset_status (p, Qrun);
1946 setup_process_coding_systems (process);
1948 FD_SET (pty_fd, &input_wait_mask);
1949 FD_SET (pty_fd, &non_keyboard_wait_mask);
1950 if (pty_fd > max_process_desc)
1951 max_process_desc = pty_fd;
1953 pset_tty_name (p, build_string (pty_name));
1956 p->pid = -2;
1960 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1961 The address family of sa is not included in the result. */
1963 #ifndef WINDOWSNT
1964 static
1965 #endif
1966 Lisp_Object
1967 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
1969 Lisp_Object address;
1970 int i;
1971 unsigned char *cp;
1972 register struct Lisp_Vector *p;
1974 /* Workaround for a bug in getsockname on BSD: Names bound to
1975 sockets in the UNIX domain are inaccessible; getsockname returns
1976 a zero length name. */
1977 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
1978 return empty_unibyte_string;
1980 switch (sa->sa_family)
1982 case AF_INET:
1984 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
1985 len = sizeof (sin->sin_addr) + 1;
1986 address = Fmake_vector (make_number (len), Qnil);
1987 p = XVECTOR (address);
1988 p->contents[--len] = make_number (ntohs (sin->sin_port));
1989 cp = (unsigned char *) &sin->sin_addr;
1990 break;
1992 #ifdef AF_INET6
1993 case AF_INET6:
1995 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
1996 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
1997 len = sizeof (sin6->sin6_addr)/2 + 1;
1998 address = Fmake_vector (make_number (len), Qnil);
1999 p = XVECTOR (address);
2000 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2001 for (i = 0; i < len; i++)
2002 p->contents[i] = make_number (ntohs (ip6[i]));
2003 return address;
2005 #endif
2006 #ifdef HAVE_LOCAL_SOCKETS
2007 case AF_LOCAL:
2009 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2010 for (i = 0; i < sizeof (sockun->sun_path); i++)
2011 if (sockun->sun_path[i] == 0)
2012 break;
2013 return make_unibyte_string (sockun->sun_path, i);
2015 #endif
2016 default:
2017 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2018 address = Fcons (make_number (sa->sa_family),
2019 Fmake_vector (make_number (len), Qnil));
2020 p = XVECTOR (XCDR (address));
2021 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2022 break;
2025 i = 0;
2026 while (i < len)
2027 p->contents[i++] = make_number (*cp++);
2029 return address;
2033 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2035 static int
2036 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2038 register struct Lisp_Vector *p;
2040 if (VECTORP (address))
2042 p = XVECTOR (address);
2043 if (p->header.size == 5)
2045 *familyp = AF_INET;
2046 return sizeof (struct sockaddr_in);
2048 #ifdef AF_INET6
2049 else if (p->header.size == 9)
2051 *familyp = AF_INET6;
2052 return sizeof (struct sockaddr_in6);
2054 #endif
2056 #ifdef HAVE_LOCAL_SOCKETS
2057 else if (STRINGP (address))
2059 *familyp = AF_LOCAL;
2060 return sizeof (struct sockaddr_un);
2062 #endif
2063 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2064 && VECTORP (XCDR (address)))
2066 struct sockaddr *sa;
2067 *familyp = XINT (XCAR (address));
2068 p = XVECTOR (XCDR (address));
2069 return p->header.size + sizeof (sa->sa_family);
2071 return 0;
2074 /* Convert an address object (vector or string) to an internal sockaddr.
2076 The address format has been basically validated by
2077 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2078 it could have come from user data. So if FAMILY is not valid,
2079 we return after zeroing *SA. */
2081 static void
2082 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2084 register struct Lisp_Vector *p;
2085 register unsigned char *cp = NULL;
2086 register int i;
2087 EMACS_INT hostport;
2089 memset (sa, 0, len);
2091 if (VECTORP (address))
2093 p = XVECTOR (address);
2094 if (family == AF_INET)
2096 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2097 len = sizeof (sin->sin_addr) + 1;
2098 hostport = XINT (p->contents[--len]);
2099 sin->sin_port = htons (hostport);
2100 cp = (unsigned char *)&sin->sin_addr;
2101 sa->sa_family = family;
2103 #ifdef AF_INET6
2104 else if (family == AF_INET6)
2106 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2107 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2108 len = sizeof (sin6->sin6_addr) + 1;
2109 hostport = XINT (p->contents[--len]);
2110 sin6->sin6_port = htons (hostport);
2111 for (i = 0; i < len; i++)
2112 if (INTEGERP (p->contents[i]))
2114 int j = XFASTINT (p->contents[i]) & 0xffff;
2115 ip6[i] = ntohs (j);
2117 sa->sa_family = family;
2118 return;
2120 #endif
2121 else
2122 return;
2124 else if (STRINGP (address))
2126 #ifdef HAVE_LOCAL_SOCKETS
2127 if (family == AF_LOCAL)
2129 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2130 cp = SDATA (address);
2131 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2132 sockun->sun_path[i] = *cp++;
2133 sa->sa_family = family;
2135 #endif
2136 return;
2138 else
2140 p = XVECTOR (XCDR (address));
2141 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2144 for (i = 0; i < len; i++)
2145 if (INTEGERP (p->contents[i]))
2146 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2149 #ifdef DATAGRAM_SOCKETS
2150 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2151 1, 1, 0,
2152 doc: /* Get the current datagram address associated with PROCESS. */)
2153 (Lisp_Object process)
2155 int channel;
2157 CHECK_PROCESS (process);
2159 if (!DATAGRAM_CONN_P (process))
2160 return Qnil;
2162 channel = XPROCESS (process)->infd;
2163 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2164 datagram_address[channel].len);
2167 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2168 2, 2, 0,
2169 doc: /* Set the datagram address for PROCESS to ADDRESS.
2170 Returns nil upon error setting address, ADDRESS otherwise. */)
2171 (Lisp_Object process, Lisp_Object address)
2173 int channel;
2174 int family, len;
2176 CHECK_PROCESS (process);
2178 if (!DATAGRAM_CONN_P (process))
2179 return Qnil;
2181 channel = XPROCESS (process)->infd;
2183 len = get_lisp_to_sockaddr_size (address, &family);
2184 if (len == 0 || datagram_address[channel].len != len)
2185 return Qnil;
2186 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2187 return address;
2189 #endif
2192 static const struct socket_options {
2193 /* The name of this option. Should be lowercase version of option
2194 name without SO_ prefix. */
2195 const char *name;
2196 /* Option level SOL_... */
2197 int optlevel;
2198 /* Option number SO_... */
2199 int optnum;
2200 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2201 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2202 } socket_options[] =
2204 #ifdef SO_BINDTODEVICE
2205 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2206 #endif
2207 #ifdef SO_BROADCAST
2208 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2209 #endif
2210 #ifdef SO_DONTROUTE
2211 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2212 #endif
2213 #ifdef SO_KEEPALIVE
2214 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2215 #endif
2216 #ifdef SO_LINGER
2217 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2218 #endif
2219 #ifdef SO_OOBINLINE
2220 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2221 #endif
2222 #ifdef SO_PRIORITY
2223 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2224 #endif
2225 #ifdef SO_REUSEADDR
2226 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2227 #endif
2228 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2231 /* Set option OPT to value VAL on socket S.
2233 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2234 Signals an error if setting a known option fails.
2237 static int
2238 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2240 char *name;
2241 const struct socket_options *sopt;
2242 int ret = 0;
2244 CHECK_SYMBOL (opt);
2246 name = SSDATA (SYMBOL_NAME (opt));
2247 for (sopt = socket_options; sopt->name; sopt++)
2248 if (strcmp (name, sopt->name) == 0)
2249 break;
2251 switch (sopt->opttype)
2253 case SOPT_BOOL:
2255 int optval;
2256 optval = NILP (val) ? 0 : 1;
2257 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2258 &optval, sizeof (optval));
2259 break;
2262 case SOPT_INT:
2264 int optval;
2265 if (TYPE_RANGED_INTEGERP (int, val))
2266 optval = XINT (val);
2267 else
2268 error ("Bad option value for %s", name);
2269 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2270 &optval, sizeof (optval));
2271 break;
2274 #ifdef SO_BINDTODEVICE
2275 case SOPT_IFNAME:
2277 char devname[IFNAMSIZ+1];
2279 /* This is broken, at least in the Linux 2.4 kernel.
2280 To unbind, the arg must be a zero integer, not the empty string.
2281 This should work on all systems. KFS. 2003-09-23. */
2282 memset (devname, 0, sizeof devname);
2283 if (STRINGP (val))
2285 char *arg = SSDATA (val);
2286 int len = min (strlen (arg), IFNAMSIZ);
2287 memcpy (devname, arg, len);
2289 else if (!NILP (val))
2290 error ("Bad option value for %s", name);
2291 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2292 devname, IFNAMSIZ);
2293 break;
2295 #endif
2297 #ifdef SO_LINGER
2298 case SOPT_LINGER:
2300 struct linger linger;
2302 linger.l_onoff = 1;
2303 linger.l_linger = 0;
2304 if (TYPE_RANGED_INTEGERP (int, val))
2305 linger.l_linger = XINT (val);
2306 else
2307 linger.l_onoff = NILP (val) ? 0 : 1;
2308 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2309 &linger, sizeof (linger));
2310 break;
2312 #endif
2314 default:
2315 return 0;
2318 if (ret < 0)
2320 int setsockopt_errno = errno;
2321 report_file_errno ("Cannot set network option", list2 (opt, val),
2322 setsockopt_errno);
2325 return (1 << sopt->optbit);
2329 DEFUN ("set-network-process-option",
2330 Fset_network_process_option, Sset_network_process_option,
2331 3, 4, 0,
2332 doc: /* For network process PROCESS set option OPTION to value VALUE.
2333 See `make-network-process' for a list of options and values.
2334 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2335 OPTION is not a supported option, return nil instead; otherwise return t. */)
2336 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2338 int s;
2339 struct Lisp_Process *p;
2341 CHECK_PROCESS (process);
2342 p = XPROCESS (process);
2343 if (!NETCONN1_P (p))
2344 error ("Process is not a network process");
2346 s = p->infd;
2347 if (s < 0)
2348 error ("Process is not running");
2350 if (set_socket_option (s, option, value))
2352 pset_childp (p, Fplist_put (p->childp, option, value));
2353 return Qt;
2356 if (NILP (no_error))
2357 error ("Unknown or unsupported option");
2359 return Qnil;
2363 DEFUN ("serial-process-configure",
2364 Fserial_process_configure,
2365 Sserial_process_configure,
2366 0, MANY, 0,
2367 doc: /* Configure speed, bytesize, etc. of a serial process.
2369 Arguments are specified as keyword/argument pairs. Attributes that
2370 are not given are re-initialized from the process's current
2371 configuration (available via the function `process-contact') or set to
2372 reasonable default values. The following arguments are defined:
2374 :process PROCESS
2375 :name NAME
2376 :buffer BUFFER
2377 :port PORT
2378 -- Any of these arguments can be given to identify the process that is
2379 to be configured. If none of these arguments is given, the current
2380 buffer's process is used.
2382 :speed SPEED -- SPEED is the speed of the serial port in bits per
2383 second, also called baud rate. Any value can be given for SPEED, but
2384 most serial ports work only at a few defined values between 1200 and
2385 115200, with 9600 being the most common value. If SPEED is nil, the
2386 serial port is not configured any further, i.e., all other arguments
2387 are ignored. This may be useful for special serial ports such as
2388 Bluetooth-to-serial converters which can only be configured through AT
2389 commands. A value of nil for SPEED can be used only when passed
2390 through `make-serial-process' or `serial-term'.
2392 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2393 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2395 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2396 `odd' (use odd parity), or the symbol `even' (use even parity). If
2397 PARITY is not given, no parity is used.
2399 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2400 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2401 is not given or nil, 1 stopbit is used.
2403 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2404 flowcontrol to be used, which is either nil (don't use flowcontrol),
2405 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2406 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2407 flowcontrol is used.
2409 `serial-process-configure' is called by `make-serial-process' for the
2410 initial configuration of the serial port.
2412 Examples:
2414 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2416 \(serial-process-configure
2417 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2419 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2421 usage: (serial-process-configure &rest ARGS) */)
2422 (ptrdiff_t nargs, Lisp_Object *args)
2424 struct Lisp_Process *p;
2425 Lisp_Object contact = Qnil;
2426 Lisp_Object proc = Qnil;
2427 struct gcpro gcpro1;
2429 contact = Flist (nargs, args);
2430 GCPRO1 (contact);
2432 proc = Fplist_get (contact, QCprocess);
2433 if (NILP (proc))
2434 proc = Fplist_get (contact, QCname);
2435 if (NILP (proc))
2436 proc = Fplist_get (contact, QCbuffer);
2437 if (NILP (proc))
2438 proc = Fplist_get (contact, QCport);
2439 proc = get_process (proc);
2440 p = XPROCESS (proc);
2441 if (!EQ (p->type, Qserial))
2442 error ("Not a serial process");
2444 if (NILP (Fplist_get (p->childp, QCspeed)))
2446 UNGCPRO;
2447 return Qnil;
2450 serial_configure (p, contact);
2452 UNGCPRO;
2453 return Qnil;
2456 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2457 0, MANY, 0,
2458 doc: /* Create and return a serial port process.
2460 In Emacs, serial port connections are represented by process objects,
2461 so input and output work as for subprocesses, and `delete-process'
2462 closes a serial port connection. However, a serial process has no
2463 process id, it cannot be signaled, and the status codes are different
2464 from normal processes.
2466 `make-serial-process' creates a process and a buffer, on which you
2467 probably want to use `process-send-string'. Try \\[serial-term] for
2468 an interactive terminal. See below for examples.
2470 Arguments are specified as keyword/argument pairs. The following
2471 arguments are defined:
2473 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2474 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2475 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2476 the backslashes in strings).
2478 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2479 which this function calls.
2481 :name NAME -- NAME is the name of the process. If NAME is not given,
2482 the value of PORT is used.
2484 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2485 with the process. Process output goes at the end of that buffer,
2486 unless you specify an output stream or filter function to handle the
2487 output. If BUFFER is not given, the value of NAME is used.
2489 :coding CODING -- If CODING is a symbol, it specifies the coding
2490 system used for both reading and writing for this process. If CODING
2491 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2492 ENCODING is used for writing.
2494 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2495 the process is running. If BOOL is not given, query before exiting.
2497 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2498 In the stopped state, a serial process does not accept incoming data,
2499 but you can send outgoing data. The stopped state is cleared by
2500 `continue-process' and set by `stop-process'.
2502 :filter FILTER -- Install FILTER as the process filter.
2504 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2506 :plist PLIST -- Install PLIST as the initial plist of the process.
2508 :bytesize
2509 :parity
2510 :stopbits
2511 :flowcontrol
2512 -- This function calls `serial-process-configure' to handle these
2513 arguments.
2515 The original argument list, possibly modified by later configuration,
2516 is available via the function `process-contact'.
2518 Examples:
2520 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2522 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2524 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2526 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2528 usage: (make-serial-process &rest ARGS) */)
2529 (ptrdiff_t nargs, Lisp_Object *args)
2531 int fd = -1;
2532 Lisp_Object proc, contact, port;
2533 struct Lisp_Process *p;
2534 struct gcpro gcpro1;
2535 Lisp_Object name, buffer;
2536 Lisp_Object tem, val;
2537 ptrdiff_t specpdl_count;
2539 if (nargs == 0)
2540 return Qnil;
2542 contact = Flist (nargs, args);
2543 GCPRO1 (contact);
2545 port = Fplist_get (contact, QCport);
2546 if (NILP (port))
2547 error ("No port specified");
2548 CHECK_STRING (port);
2550 if (NILP (Fplist_member (contact, QCspeed)))
2551 error (":speed not specified");
2552 if (!NILP (Fplist_get (contact, QCspeed)))
2553 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2555 name = Fplist_get (contact, QCname);
2556 if (NILP (name))
2557 name = port;
2558 CHECK_STRING (name);
2559 proc = make_process (name);
2560 specpdl_count = SPECPDL_INDEX ();
2561 record_unwind_protect (remove_process, proc);
2562 p = XPROCESS (proc);
2564 fd = serial_open (port);
2565 p->open_fd[SUBPROCESS_STDIN] = fd;
2566 p->infd = fd;
2567 p->outfd = fd;
2568 if (fd > max_process_desc)
2569 max_process_desc = fd;
2570 chan_process[fd] = proc;
2572 buffer = Fplist_get (contact, QCbuffer);
2573 if (NILP (buffer))
2574 buffer = name;
2575 buffer = Fget_buffer_create (buffer);
2576 pset_buffer (p, buffer);
2578 pset_childp (p, contact);
2579 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2580 pset_type (p, Qserial);
2581 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2582 pset_filter (p, Fplist_get (contact, QCfilter));
2583 pset_log (p, Qnil);
2584 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2585 p->kill_without_query = 1;
2586 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2587 pset_command (p, Qt);
2588 eassert (! p->pty_flag);
2590 if (!EQ (p->command, Qt))
2592 FD_SET (fd, &input_wait_mask);
2593 FD_SET (fd, &non_keyboard_wait_mask);
2596 if (BUFFERP (buffer))
2598 set_marker_both (p->mark, buffer,
2599 BUF_ZV (XBUFFER (buffer)),
2600 BUF_ZV_BYTE (XBUFFER (buffer)));
2603 tem = Fplist_member (contact, QCcoding);
2604 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2605 tem = Qnil;
2607 val = Qnil;
2608 if (!NILP (tem))
2610 val = XCAR (XCDR (tem));
2611 if (CONSP (val))
2612 val = XCAR (val);
2614 else if (!NILP (Vcoding_system_for_read))
2615 val = Vcoding_system_for_read;
2616 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2617 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2618 val = Qnil;
2619 pset_decode_coding_system (p, val);
2621 val = Qnil;
2622 if (!NILP (tem))
2624 val = XCAR (XCDR (tem));
2625 if (CONSP (val))
2626 val = XCDR (val);
2628 else if (!NILP (Vcoding_system_for_write))
2629 val = Vcoding_system_for_write;
2630 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2631 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2632 val = Qnil;
2633 pset_encode_coding_system (p, val);
2635 setup_process_coding_systems (proc);
2636 pset_decoding_buf (p, empty_unibyte_string);
2637 p->decoding_carryover = 0;
2638 pset_encoding_buf (p, empty_unibyte_string);
2639 p->inherit_coding_system_flag
2640 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2642 Fserial_process_configure (nargs, args);
2644 specpdl_ptr = specpdl + specpdl_count;
2646 UNGCPRO;
2647 return proc;
2650 /* Create a network stream/datagram client/server process. Treated
2651 exactly like a normal process when reading and writing. Primary
2652 differences are in status display and process deletion. A network
2653 connection has no PID; you cannot signal it. All you can do is
2654 stop/continue it and deactivate/close it via delete-process */
2656 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2657 0, MANY, 0,
2658 doc: /* Create and return a network server or client process.
2660 In Emacs, network connections are represented by process objects, so
2661 input and output work as for subprocesses and `delete-process' closes
2662 a network connection. However, a network process has no process id,
2663 it cannot be signaled, and the status codes are different from normal
2664 processes.
2666 Arguments are specified as keyword/argument pairs. The following
2667 arguments are defined:
2669 :name NAME -- NAME is name for process. It is modified if necessary
2670 to make it unique.
2672 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2673 with the process. Process output goes at end of that buffer, unless
2674 you specify an output stream or filter function to handle the output.
2675 BUFFER may be also nil, meaning that this process is not associated
2676 with any buffer.
2678 :host HOST -- HOST is name of the host to connect to, or its IP
2679 address. The symbol `local' specifies the local host. If specified
2680 for a server process, it must be a valid name or address for the local
2681 host, and only clients connecting to that address will be accepted.
2683 :service SERVICE -- SERVICE is name of the service desired, or an
2684 integer specifying a port number to connect to. If SERVICE is t,
2685 a random port number is selected for the server. (If Emacs was
2686 compiled with getaddrinfo, a port number can also be specified as a
2687 string, e.g. "80", as well as an integer. This is not portable.)
2689 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2690 stream type connection, `datagram' creates a datagram type connection,
2691 `seqpacket' creates a reliable datagram connection.
2693 :family FAMILY -- FAMILY is the address (and protocol) family for the
2694 service specified by HOST and SERVICE. The default (nil) is to use
2695 whatever address family (IPv4 or IPv6) that is defined for the host
2696 and port number specified by HOST and SERVICE. Other address families
2697 supported are:
2698 local -- for a local (i.e. UNIX) address specified by SERVICE.
2699 ipv4 -- use IPv4 address family only.
2700 ipv6 -- use IPv6 address family only.
2702 :local ADDRESS -- ADDRESS is the local address used for the connection.
2703 This parameter is ignored when opening a client process. When specified
2704 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2706 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2707 connection. This parameter is ignored when opening a stream server
2708 process. For a datagram server process, it specifies the initial
2709 setting of the remote datagram address. When specified for a client
2710 process, the FAMILY, HOST, and SERVICE args are ignored.
2712 The format of ADDRESS depends on the address family:
2713 - An IPv4 address is represented as an vector of integers [A B C D P]
2714 corresponding to numeric IP address A.B.C.D and port number P.
2715 - A local address is represented as a string with the address in the
2716 local address space.
2717 - An "unsupported family" address is represented by a cons (F . AV)
2718 where F is the family number and AV is a vector containing the socket
2719 address data with one element per address data byte. Do not rely on
2720 this format in portable code, as it may depend on implementation
2721 defined constants, data sizes, and data structure alignment.
2723 :coding CODING -- If CODING is a symbol, it specifies the coding
2724 system used for both reading and writing for this process. If CODING
2725 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2726 ENCODING is used for writing.
2728 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2729 return without waiting for the connection to complete; instead, the
2730 sentinel function will be called with second arg matching "open" (if
2731 successful) or "failed" when the connect completes. Default is to use
2732 a blocking connect (i.e. wait) for stream type connections.
2734 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2735 running when Emacs is exited.
2737 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2738 In the stopped state, a server process does not accept new
2739 connections, and a client process does not handle incoming traffic.
2740 The stopped state is cleared by `continue-process' and set by
2741 `stop-process'.
2743 :filter FILTER -- Install FILTER as the process filter.
2745 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2746 process filter are multibyte, otherwise they are unibyte.
2747 If this keyword is not specified, the strings are multibyte if
2748 the default value of `enable-multibyte-characters' is non-nil.
2750 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2752 :log LOG -- Install LOG as the server process log function. This
2753 function is called when the server accepts a network connection from a
2754 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2755 is the server process, CLIENT is the new process for the connection,
2756 and MESSAGE is a string.
2758 :plist PLIST -- Install PLIST as the new process' initial plist.
2760 :server QLEN -- if QLEN is non-nil, create a server process for the
2761 specified FAMILY, SERVICE, and connection type (stream or datagram).
2762 If QLEN is an integer, it is used as the max. length of the server's
2763 pending connection queue (also known as the backlog); the default
2764 queue length is 5. Default is to create a client process.
2766 The following network options can be specified for this connection:
2768 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2769 :dontroute BOOL -- Only send to directly connected hosts.
2770 :keepalive BOOL -- Send keep-alive messages on network stream.
2771 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2772 :oobinline BOOL -- Place out-of-band data in receive data stream.
2773 :priority INT -- Set protocol defined priority for sent packets.
2774 :reuseaddr BOOL -- Allow reusing a recently used local address
2775 (this is allowed by default for a server process).
2776 :bindtodevice NAME -- bind to interface NAME. Using this may require
2777 special privileges on some systems.
2779 Consult the relevant system programmer's manual pages for more
2780 information on using these options.
2783 A server process will listen for and accept connections from clients.
2784 When a client connection is accepted, a new network process is created
2785 for the connection with the following parameters:
2787 - The client's process name is constructed by concatenating the server
2788 process' NAME and a client identification string.
2789 - If the FILTER argument is non-nil, the client process will not get a
2790 separate process buffer; otherwise, the client's process buffer is a newly
2791 created buffer named after the server process' BUFFER name or process
2792 NAME concatenated with the client identification string.
2793 - The connection type and the process filter and sentinel parameters are
2794 inherited from the server process' TYPE, FILTER and SENTINEL.
2795 - The client process' contact info is set according to the client's
2796 addressing information (typically an IP address and a port number).
2797 - The client process' plist is initialized from the server's plist.
2799 Notice that the FILTER and SENTINEL args are never used directly by
2800 the server process. Also, the BUFFER argument is not used directly by
2801 the server process, but via the optional :log function, accepted (and
2802 failed) connections may be logged in the server process' buffer.
2804 The original argument list, modified with the actual connection
2805 information, is available via the `process-contact' function.
2807 usage: (make-network-process &rest ARGS) */)
2808 (ptrdiff_t nargs, Lisp_Object *args)
2810 Lisp_Object proc;
2811 Lisp_Object contact;
2812 struct Lisp_Process *p;
2813 #ifdef HAVE_GETADDRINFO
2814 struct addrinfo ai, *res, *lres;
2815 struct addrinfo hints;
2816 const char *portstring;
2817 char portbuf[128];
2818 #else /* HAVE_GETADDRINFO */
2819 struct _emacs_addrinfo
2821 int ai_family;
2822 int ai_socktype;
2823 int ai_protocol;
2824 int ai_addrlen;
2825 struct sockaddr *ai_addr;
2826 struct _emacs_addrinfo *ai_next;
2827 } ai, *res, *lres;
2828 #endif /* HAVE_GETADDRINFO */
2829 struct sockaddr_in address_in;
2830 #ifdef HAVE_LOCAL_SOCKETS
2831 struct sockaddr_un address_un;
2832 #endif
2833 int port;
2834 int ret = 0;
2835 int xerrno = 0;
2836 int s = -1, outch, inch;
2837 struct gcpro gcpro1;
2838 ptrdiff_t count = SPECPDL_INDEX ();
2839 ptrdiff_t count1;
2840 Lisp_Object QCaddress; /* one of QClocal or QCremote */
2841 Lisp_Object tem;
2842 Lisp_Object name, buffer, host, service, address;
2843 Lisp_Object filter, sentinel;
2844 bool is_non_blocking_client = 0;
2845 bool is_server = 0;
2846 int backlog = 5;
2847 int socktype;
2848 int family = -1;
2850 if (nargs == 0)
2851 return Qnil;
2853 /* Save arguments for process-contact and clone-process. */
2854 contact = Flist (nargs, args);
2855 GCPRO1 (contact);
2857 #ifdef WINDOWSNT
2858 /* Ensure socket support is loaded if available. */
2859 init_winsock (TRUE);
2860 #endif
2862 /* :type TYPE (nil: stream, datagram */
2863 tem = Fplist_get (contact, QCtype);
2864 if (NILP (tem))
2865 socktype = SOCK_STREAM;
2866 #ifdef DATAGRAM_SOCKETS
2867 else if (EQ (tem, Qdatagram))
2868 socktype = SOCK_DGRAM;
2869 #endif
2870 #ifdef HAVE_SEQPACKET
2871 else if (EQ (tem, Qseqpacket))
2872 socktype = SOCK_SEQPACKET;
2873 #endif
2874 else
2875 error ("Unsupported connection type");
2877 /* :server BOOL */
2878 tem = Fplist_get (contact, QCserver);
2879 if (!NILP (tem))
2881 /* Don't support network sockets when non-blocking mode is
2882 not available, since a blocked Emacs is not useful. */
2883 is_server = 1;
2884 if (TYPE_RANGED_INTEGERP (int, tem))
2885 backlog = XINT (tem);
2888 /* Make QCaddress an alias for :local (server) or :remote (client). */
2889 QCaddress = is_server ? QClocal : QCremote;
2891 /* :nowait BOOL */
2892 if (!is_server && socktype != SOCK_DGRAM
2893 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2895 #ifndef NON_BLOCKING_CONNECT
2896 error ("Non-blocking connect not supported");
2897 #else
2898 is_non_blocking_client = 1;
2899 #endif
2902 name = Fplist_get (contact, QCname);
2903 buffer = Fplist_get (contact, QCbuffer);
2904 filter = Fplist_get (contact, QCfilter);
2905 sentinel = Fplist_get (contact, QCsentinel);
2907 CHECK_STRING (name);
2909 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2910 ai.ai_socktype = socktype;
2911 ai.ai_protocol = 0;
2912 ai.ai_next = NULL;
2913 res = &ai;
2915 /* :local ADDRESS or :remote ADDRESS */
2916 address = Fplist_get (contact, QCaddress);
2917 if (!NILP (address))
2919 host = service = Qnil;
2921 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2922 error ("Malformed :address");
2923 ai.ai_family = family;
2924 ai.ai_addr = alloca (ai.ai_addrlen);
2925 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
2926 goto open_socket;
2929 /* :family FAMILY -- nil (for Inet), local, or integer. */
2930 tem = Fplist_get (contact, QCfamily);
2931 if (NILP (tem))
2933 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
2934 family = AF_UNSPEC;
2935 #else
2936 family = AF_INET;
2937 #endif
2939 #ifdef HAVE_LOCAL_SOCKETS
2940 else if (EQ (tem, Qlocal))
2941 family = AF_LOCAL;
2942 #endif
2943 #ifdef AF_INET6
2944 else if (EQ (tem, Qipv6))
2945 family = AF_INET6;
2946 #endif
2947 else if (EQ (tem, Qipv4))
2948 family = AF_INET;
2949 else if (TYPE_RANGED_INTEGERP (int, tem))
2950 family = XINT (tem);
2951 else
2952 error ("Unknown address family");
2954 ai.ai_family = family;
2956 /* :service SERVICE -- string, integer (port number), or t (random port). */
2957 service = Fplist_get (contact, QCservice);
2959 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2960 host = Fplist_get (contact, QChost);
2961 if (!NILP (host))
2963 if (EQ (host, Qlocal))
2964 /* Depending on setup, "localhost" may map to different IPv4 and/or
2965 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
2966 host = build_string ("127.0.0.1");
2967 CHECK_STRING (host);
2970 #ifdef HAVE_LOCAL_SOCKETS
2971 if (family == AF_LOCAL)
2973 if (!NILP (host))
2975 message (":family local ignores the :host \"%s\" property",
2976 SDATA (host));
2977 contact = Fplist_put (contact, QChost, Qnil);
2978 host = Qnil;
2980 CHECK_STRING (service);
2981 memset (&address_un, 0, sizeof address_un);
2982 address_un.sun_family = AF_LOCAL;
2983 if (sizeof address_un.sun_path <= SBYTES (service))
2984 error ("Service name too long");
2985 strcpy (address_un.sun_path, SSDATA (service));
2986 ai.ai_addr = (struct sockaddr *) &address_un;
2987 ai.ai_addrlen = sizeof address_un;
2988 goto open_socket;
2990 #endif
2992 /* Slow down polling to every ten seconds.
2993 Some kernels have a bug which causes retrying connect to fail
2994 after a connect. Polling can interfere with gethostbyname too. */
2995 #ifdef POLL_FOR_INPUT
2996 if (socktype != SOCK_DGRAM)
2998 record_unwind_protect_void (run_all_atimers);
2999 bind_polling_period (10);
3001 #endif
3003 #ifdef HAVE_GETADDRINFO
3004 /* If we have a host, use getaddrinfo to resolve both host and service.
3005 Otherwise, use getservbyname to lookup the service. */
3006 if (!NILP (host))
3009 /* SERVICE can either be a string or int.
3010 Convert to a C string for later use by getaddrinfo. */
3011 if (EQ (service, Qt))
3012 portstring = "0";
3013 else if (INTEGERP (service))
3015 sprintf (portbuf, "%"pI"d", XINT (service));
3016 portstring = portbuf;
3018 else
3020 CHECK_STRING (service);
3021 portstring = SSDATA (service);
3024 immediate_quit = 1;
3025 QUIT;
3026 memset (&hints, 0, sizeof (hints));
3027 hints.ai_flags = 0;
3028 hints.ai_family = family;
3029 hints.ai_socktype = socktype;
3030 hints.ai_protocol = 0;
3032 #ifdef HAVE_RES_INIT
3033 res_init ();
3034 #endif
3036 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3037 if (ret)
3038 #ifdef HAVE_GAI_STRERROR
3039 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3040 #else
3041 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3042 #endif
3043 immediate_quit = 0;
3045 goto open_socket;
3047 #endif /* HAVE_GETADDRINFO */
3049 /* We end up here if getaddrinfo is not defined, or in case no hostname
3050 has been specified (e.g. for a local server process). */
3052 if (EQ (service, Qt))
3053 port = 0;
3054 else if (INTEGERP (service))
3055 port = htons ((unsigned short) XINT (service));
3056 else
3058 struct servent *svc_info;
3059 CHECK_STRING (service);
3060 svc_info = getservbyname (SSDATA (service),
3061 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3062 if (svc_info == 0)
3063 error ("Unknown service: %s", SDATA (service));
3064 port = svc_info->s_port;
3067 memset (&address_in, 0, sizeof address_in);
3068 address_in.sin_family = family;
3069 address_in.sin_addr.s_addr = INADDR_ANY;
3070 address_in.sin_port = port;
3072 #ifndef HAVE_GETADDRINFO
3073 if (!NILP (host))
3075 struct hostent *host_info_ptr;
3077 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3078 as it may `hang' Emacs for a very long time. */
3079 immediate_quit = 1;
3080 QUIT;
3082 #ifdef HAVE_RES_INIT
3083 res_init ();
3084 #endif
3086 host_info_ptr = gethostbyname (SDATA (host));
3087 immediate_quit = 0;
3089 if (host_info_ptr)
3091 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3092 host_info_ptr->h_length);
3093 family = host_info_ptr->h_addrtype;
3094 address_in.sin_family = family;
3096 else
3097 /* Attempt to interpret host as numeric inet address */
3099 unsigned long numeric_addr;
3100 numeric_addr = inet_addr (SSDATA (host));
3101 if (numeric_addr == -1)
3102 error ("Unknown host \"%s\"", SDATA (host));
3104 memcpy (&address_in.sin_addr, &numeric_addr,
3105 sizeof (address_in.sin_addr));
3109 #endif /* not HAVE_GETADDRINFO */
3111 ai.ai_family = family;
3112 ai.ai_addr = (struct sockaddr *) &address_in;
3113 ai.ai_addrlen = sizeof address_in;
3115 open_socket:
3117 /* Do this in case we never enter the for-loop below. */
3118 count1 = SPECPDL_INDEX ();
3119 s = -1;
3121 for (lres = res; lres; lres = lres->ai_next)
3123 ptrdiff_t optn;
3124 int optbits;
3126 #ifdef WINDOWSNT
3127 retry_connect:
3128 #endif
3130 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3131 lres->ai_protocol);
3132 if (s < 0)
3134 xerrno = errno;
3135 continue;
3138 #ifdef DATAGRAM_SOCKETS
3139 if (!is_server && socktype == SOCK_DGRAM)
3140 break;
3141 #endif /* DATAGRAM_SOCKETS */
3143 #ifdef NON_BLOCKING_CONNECT
3144 if (is_non_blocking_client)
3146 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3147 if (ret < 0)
3149 xerrno = errno;
3150 emacs_close (s);
3151 s = -1;
3152 continue;
3155 #endif
3157 /* Make us close S if quit. */
3158 record_unwind_protect_int (close_file_unwind, s);
3160 /* Parse network options in the arg list.
3161 We simply ignore anything which isn't a known option (including other keywords).
3162 An error is signaled if setting a known option fails. */
3163 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3164 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3166 if (is_server)
3168 /* Configure as a server socket. */
3170 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3171 explicit :reuseaddr key to override this. */
3172 #ifdef HAVE_LOCAL_SOCKETS
3173 if (family != AF_LOCAL)
3174 #endif
3175 if (!(optbits & (1 << OPIX_REUSEADDR)))
3177 int optval = 1;
3178 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3179 report_file_error ("Cannot set reuse option on server socket", Qnil);
3182 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3183 report_file_error ("Cannot bind server socket", Qnil);
3185 #ifdef HAVE_GETSOCKNAME
3186 if (EQ (service, Qt))
3188 struct sockaddr_in sa1;
3189 socklen_t len1 = sizeof (sa1);
3190 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3192 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3193 service = make_number (ntohs (sa1.sin_port));
3194 contact = Fplist_put (contact, QCservice, service);
3197 #endif
3199 if (socktype != SOCK_DGRAM && listen (s, backlog))
3200 report_file_error ("Cannot listen on server socket", Qnil);
3202 break;
3205 immediate_quit = 1;
3206 QUIT;
3208 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3209 xerrno = errno;
3211 if (ret == 0 || xerrno == EISCONN)
3213 /* The unwind-protect will be discarded afterwards.
3214 Likewise for immediate_quit. */
3215 break;
3218 #ifdef NON_BLOCKING_CONNECT
3219 #ifdef EINPROGRESS
3220 if (is_non_blocking_client && xerrno == EINPROGRESS)
3221 break;
3222 #else
3223 #ifdef EWOULDBLOCK
3224 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3225 break;
3226 #endif
3227 #endif
3228 #endif
3230 #ifndef WINDOWSNT
3231 if (xerrno == EINTR)
3233 /* Unlike most other syscalls connect() cannot be called
3234 again. (That would return EALREADY.) The proper way to
3235 wait for completion is pselect(). */
3236 int sc;
3237 socklen_t len;
3238 fd_set fdset;
3239 retry_select:
3240 FD_ZERO (&fdset);
3241 FD_SET (s, &fdset);
3242 QUIT;
3243 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3244 if (sc == -1)
3246 if (errno == EINTR)
3247 goto retry_select;
3248 else
3249 report_file_error ("Failed select", Qnil);
3251 eassert (sc > 0);
3253 len = sizeof xerrno;
3254 eassert (FD_ISSET (s, &fdset));
3255 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3256 report_file_error ("Failed getsockopt", Qnil);
3257 if (xerrno)
3258 report_file_errno ("Failed connect", Qnil, xerrno);
3259 break;
3261 #endif /* !WINDOWSNT */
3263 immediate_quit = 0;
3265 /* Discard the unwind protect closing S. */
3266 specpdl_ptr = specpdl + count1;
3267 emacs_close (s);
3268 s = -1;
3270 #ifdef WINDOWSNT
3271 if (xerrno == EINTR)
3272 goto retry_connect;
3273 #endif
3276 if (s >= 0)
3278 #ifdef DATAGRAM_SOCKETS
3279 if (socktype == SOCK_DGRAM)
3281 if (datagram_address[s].sa)
3282 emacs_abort ();
3283 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3284 datagram_address[s].len = lres->ai_addrlen;
3285 if (is_server)
3287 Lisp_Object remote;
3288 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3289 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3291 int rfamily, rlen;
3292 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3293 if (rlen != 0 && rfamily == lres->ai_family
3294 && rlen == lres->ai_addrlen)
3295 conv_lisp_to_sockaddr (rfamily, remote,
3296 datagram_address[s].sa, rlen);
3299 else
3300 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3302 #endif
3303 contact = Fplist_put (contact, QCaddress,
3304 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3305 #ifdef HAVE_GETSOCKNAME
3306 if (!is_server)
3308 struct sockaddr_in sa1;
3309 socklen_t len1 = sizeof (sa1);
3310 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3311 contact = Fplist_put (contact, QClocal,
3312 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3314 #endif
3317 immediate_quit = 0;
3319 #ifdef HAVE_GETADDRINFO
3320 if (res != &ai)
3322 block_input ();
3323 freeaddrinfo (res);
3324 unblock_input ();
3326 #endif
3328 if (s < 0)
3330 /* If non-blocking got this far - and failed - assume non-blocking is
3331 not supported after all. This is probably a wrong assumption, but
3332 the normal blocking calls to open-network-stream handles this error
3333 better. */
3334 if (is_non_blocking_client)
3335 return Qnil;
3337 report_file_errno ((is_server
3338 ? "make server process failed"
3339 : "make client process failed"),
3340 contact, xerrno);
3343 inch = s;
3344 outch = s;
3346 if (!NILP (buffer))
3347 buffer = Fget_buffer_create (buffer);
3348 proc = make_process (name);
3350 chan_process[inch] = proc;
3352 fcntl (inch, F_SETFL, O_NONBLOCK);
3354 p = XPROCESS (proc);
3356 pset_childp (p, contact);
3357 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3358 pset_type (p, Qnetwork);
3360 pset_buffer (p, buffer);
3361 pset_sentinel (p, sentinel);
3362 pset_filter (p, filter);
3363 pset_log (p, Fplist_get (contact, QClog));
3364 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3365 p->kill_without_query = 1;
3366 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3367 pset_command (p, Qt);
3368 p->pid = 0;
3370 p->open_fd[SUBPROCESS_STDIN] = inch;
3371 p->infd = inch;
3372 p->outfd = outch;
3374 /* Discard the unwind protect for closing S, if any. */
3375 specpdl_ptr = specpdl + count1;
3377 /* Unwind bind_polling_period and request_sigio. */
3378 unbind_to (count, Qnil);
3380 if (is_server && socktype != SOCK_DGRAM)
3381 pset_status (p, Qlisten);
3383 /* Make the process marker point into the process buffer (if any). */
3384 if (BUFFERP (buffer))
3385 set_marker_both (p->mark, buffer,
3386 BUF_ZV (XBUFFER (buffer)),
3387 BUF_ZV_BYTE (XBUFFER (buffer)));
3389 #ifdef NON_BLOCKING_CONNECT
3390 if (is_non_blocking_client)
3392 /* We may get here if connect did succeed immediately. However,
3393 in that case, we still need to signal this like a non-blocking
3394 connection. */
3395 pset_status (p, Qconnect);
3396 if (!FD_ISSET (inch, &connect_wait_mask))
3398 FD_SET (inch, &connect_wait_mask);
3399 FD_SET (inch, &write_mask);
3400 num_pending_connects++;
3403 else
3404 #endif
3405 /* A server may have a client filter setting of Qt, but it must
3406 still listen for incoming connects unless it is stopped. */
3407 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3408 || (EQ (p->status, Qlisten) && NILP (p->command)))
3410 FD_SET (inch, &input_wait_mask);
3411 FD_SET (inch, &non_keyboard_wait_mask);
3414 if (inch > max_process_desc)
3415 max_process_desc = inch;
3417 tem = Fplist_member (contact, QCcoding);
3418 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3419 tem = Qnil; /* No error message (too late!). */
3422 /* Setup coding systems for communicating with the network stream. */
3423 struct gcpro gcpro1;
3424 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3425 Lisp_Object coding_systems = Qt;
3426 Lisp_Object fargs[5], val;
3428 if (!NILP (tem))
3430 val = XCAR (XCDR (tem));
3431 if (CONSP (val))
3432 val = XCAR (val);
3434 else if (!NILP (Vcoding_system_for_read))
3435 val = Vcoding_system_for_read;
3436 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3437 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3438 /* We dare not decode end-of-line format by setting VAL to
3439 Qraw_text, because the existing Emacs Lisp libraries
3440 assume that they receive bare code including a sequence of
3441 CR LF. */
3442 val = Qnil;
3443 else
3445 if (NILP (host) || NILP (service))
3446 coding_systems = Qnil;
3447 else
3449 fargs[0] = Qopen_network_stream, fargs[1] = name,
3450 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3451 GCPRO1 (proc);
3452 coding_systems = Ffind_operation_coding_system (5, fargs);
3453 UNGCPRO;
3455 if (CONSP (coding_systems))
3456 val = XCAR (coding_systems);
3457 else if (CONSP (Vdefault_process_coding_system))
3458 val = XCAR (Vdefault_process_coding_system);
3459 else
3460 val = Qnil;
3462 pset_decode_coding_system (p, val);
3464 if (!NILP (tem))
3466 val = XCAR (XCDR (tem));
3467 if (CONSP (val))
3468 val = XCDR (val);
3470 else if (!NILP (Vcoding_system_for_write))
3471 val = Vcoding_system_for_write;
3472 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3473 val = Qnil;
3474 else
3476 if (EQ (coding_systems, Qt))
3478 if (NILP (host) || NILP (service))
3479 coding_systems = Qnil;
3480 else
3482 fargs[0] = Qopen_network_stream, fargs[1] = name,
3483 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3484 GCPRO1 (proc);
3485 coding_systems = Ffind_operation_coding_system (5, fargs);
3486 UNGCPRO;
3489 if (CONSP (coding_systems))
3490 val = XCDR (coding_systems);
3491 else if (CONSP (Vdefault_process_coding_system))
3492 val = XCDR (Vdefault_process_coding_system);
3493 else
3494 val = Qnil;
3496 pset_encode_coding_system (p, val);
3498 setup_process_coding_systems (proc);
3500 pset_decoding_buf (p, empty_unibyte_string);
3501 p->decoding_carryover = 0;
3502 pset_encoding_buf (p, empty_unibyte_string);
3504 p->inherit_coding_system_flag
3505 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3507 UNGCPRO;
3508 return proc;
3512 #ifdef HAVE_NET_IF_H
3514 #ifdef SIOCGIFCONF
3515 static Lisp_Object
3516 network_interface_list (void)
3518 struct ifconf ifconf;
3519 struct ifreq *ifreq;
3520 void *buf = NULL;
3521 ptrdiff_t buf_size = 512;
3522 int s;
3523 Lisp_Object res;
3524 ptrdiff_t count;
3526 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3527 if (s < 0)
3528 return Qnil;
3529 count = SPECPDL_INDEX ();
3530 record_unwind_protect_int (close_file_unwind, s);
3534 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3535 ifconf.ifc_buf = buf;
3536 ifconf.ifc_len = buf_size;
3537 if (ioctl (s, SIOCGIFCONF, &ifconf))
3539 emacs_close (s);
3540 xfree (buf);
3541 return Qnil;
3544 while (ifconf.ifc_len == buf_size);
3546 res = unbind_to (count, Qnil);
3547 ifreq = ifconf.ifc_req;
3548 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3550 struct ifreq *ifq = ifreq;
3551 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3552 #define SIZEOF_IFREQ(sif) \
3553 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3554 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3556 int len = SIZEOF_IFREQ (ifq);
3557 #else
3558 int len = sizeof (*ifreq);
3559 #endif
3560 char namebuf[sizeof (ifq->ifr_name) + 1];
3561 ifreq = (struct ifreq *) ((char *) ifreq + len);
3563 if (ifq->ifr_addr.sa_family != AF_INET)
3564 continue;
3566 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3567 namebuf[sizeof (ifq->ifr_name)] = 0;
3568 res = Fcons (Fcons (build_string (namebuf),
3569 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3570 sizeof (struct sockaddr))),
3571 res);
3574 xfree (buf);
3575 return res;
3577 #endif /* SIOCGIFCONF */
3579 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3581 struct ifflag_def {
3582 int flag_bit;
3583 const char *flag_sym;
3586 static const struct ifflag_def ifflag_table[] = {
3587 #ifdef IFF_UP
3588 { IFF_UP, "up" },
3589 #endif
3590 #ifdef IFF_BROADCAST
3591 { IFF_BROADCAST, "broadcast" },
3592 #endif
3593 #ifdef IFF_DEBUG
3594 { IFF_DEBUG, "debug" },
3595 #endif
3596 #ifdef IFF_LOOPBACK
3597 { IFF_LOOPBACK, "loopback" },
3598 #endif
3599 #ifdef IFF_POINTOPOINT
3600 { IFF_POINTOPOINT, "pointopoint" },
3601 #endif
3602 #ifdef IFF_RUNNING
3603 { IFF_RUNNING, "running" },
3604 #endif
3605 #ifdef IFF_NOARP
3606 { IFF_NOARP, "noarp" },
3607 #endif
3608 #ifdef IFF_PROMISC
3609 { IFF_PROMISC, "promisc" },
3610 #endif
3611 #ifdef IFF_NOTRAILERS
3612 #ifdef NS_IMPL_COCOA
3613 /* Really means smart, notrailers is obsolete */
3614 { IFF_NOTRAILERS, "smart" },
3615 #else
3616 { IFF_NOTRAILERS, "notrailers" },
3617 #endif
3618 #endif
3619 #ifdef IFF_ALLMULTI
3620 { IFF_ALLMULTI, "allmulti" },
3621 #endif
3622 #ifdef IFF_MASTER
3623 { IFF_MASTER, "master" },
3624 #endif
3625 #ifdef IFF_SLAVE
3626 { IFF_SLAVE, "slave" },
3627 #endif
3628 #ifdef IFF_MULTICAST
3629 { IFF_MULTICAST, "multicast" },
3630 #endif
3631 #ifdef IFF_PORTSEL
3632 { IFF_PORTSEL, "portsel" },
3633 #endif
3634 #ifdef IFF_AUTOMEDIA
3635 { IFF_AUTOMEDIA, "automedia" },
3636 #endif
3637 #ifdef IFF_DYNAMIC
3638 { IFF_DYNAMIC, "dynamic" },
3639 #endif
3640 #ifdef IFF_OACTIVE
3641 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3642 #endif
3643 #ifdef IFF_SIMPLEX
3644 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3645 #endif
3646 #ifdef IFF_LINK0
3647 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3648 #endif
3649 #ifdef IFF_LINK1
3650 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3651 #endif
3652 #ifdef IFF_LINK2
3653 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3654 #endif
3655 { 0, 0 }
3658 static Lisp_Object
3659 network_interface_info (Lisp_Object ifname)
3661 struct ifreq rq;
3662 Lisp_Object res = Qnil;
3663 Lisp_Object elt;
3664 int s;
3665 bool any = 0;
3666 ptrdiff_t count;
3667 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3668 && defined HAVE_GETIFADDRS && defined LLADDR)
3669 struct ifaddrs *ifap;
3670 #endif
3672 CHECK_STRING (ifname);
3674 if (sizeof rq.ifr_name <= SBYTES (ifname))
3675 error ("interface name too long");
3676 strcpy (rq.ifr_name, SSDATA (ifname));
3678 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3679 if (s < 0)
3680 return Qnil;
3681 count = SPECPDL_INDEX ();
3682 record_unwind_protect_int (close_file_unwind, s);
3684 elt = Qnil;
3685 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3686 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3688 int flags = rq.ifr_flags;
3689 const struct ifflag_def *fp;
3690 int fnum;
3692 /* If flags is smaller than int (i.e. short) it may have the high bit set
3693 due to IFF_MULTICAST. In that case, sign extending it into
3694 an int is wrong. */
3695 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3696 flags = (unsigned short) rq.ifr_flags;
3698 any = 1;
3699 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3701 if (flags & fp->flag_bit)
3703 elt = Fcons (intern (fp->flag_sym), elt);
3704 flags -= fp->flag_bit;
3707 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3709 if (flags & 1)
3711 elt = Fcons (make_number (fnum), elt);
3715 #endif
3716 res = Fcons (elt, res);
3718 elt = Qnil;
3719 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3720 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3722 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3723 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3724 int n;
3726 any = 1;
3727 for (n = 0; n < 6; n++)
3728 p->contents[n] = make_number (((unsigned char *)
3729 &rq.ifr_hwaddr.sa_data[0])
3730 [n]);
3731 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3733 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3734 if (getifaddrs (&ifap) != -1)
3736 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3737 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3738 struct ifaddrs *it;
3740 for (it = ifap; it != NULL; it = it->ifa_next)
3742 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3743 unsigned char linkaddr[6];
3744 int n;
3746 if (it->ifa_addr->sa_family != AF_LINK
3747 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3748 || sdl->sdl_alen != 6)
3749 continue;
3751 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3752 for (n = 0; n < 6; n++)
3753 p->contents[n] = make_number (linkaddr[n]);
3755 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
3756 break;
3759 #ifdef HAVE_FREEIFADDRS
3760 freeifaddrs (ifap);
3761 #endif
3763 #endif /* HAVE_GETIFADDRS && LLADDR */
3765 res = Fcons (elt, res);
3767 elt = Qnil;
3768 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3769 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3771 any = 1;
3772 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3773 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3774 #else
3775 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3776 #endif
3778 #endif
3779 res = Fcons (elt, res);
3781 elt = Qnil;
3782 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3783 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3785 any = 1;
3786 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3788 #endif
3789 res = Fcons (elt, res);
3791 elt = Qnil;
3792 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3793 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3795 any = 1;
3796 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3798 #endif
3799 res = Fcons (elt, res);
3801 return unbind_to (count, any ? res : Qnil);
3803 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
3804 #endif /* defined (HAVE_NET_IF_H) */
3806 DEFUN ("network-interface-list", Fnetwork_interface_list,
3807 Snetwork_interface_list, 0, 0, 0,
3808 doc: /* Return an alist of all network interfaces and their network address.
3809 Each element is a cons, the car of which is a string containing the
3810 interface name, and the cdr is the network address in internal
3811 format; see the description of ADDRESS in `make-network-process'.
3813 If the information is not available, return nil. */)
3814 (void)
3816 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
3817 return network_interface_list ();
3818 #else
3819 return Qnil;
3820 #endif
3823 DEFUN ("network-interface-info", Fnetwork_interface_info,
3824 Snetwork_interface_info, 1, 1, 0,
3825 doc: /* Return information about network interface named IFNAME.
3826 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3827 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3828 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3829 FLAGS is the current flags of the interface.
3831 Data that is unavailable is returned as nil. */)
3832 (Lisp_Object ifname)
3834 #if ((defined HAVE_NET_IF_H \
3835 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
3836 || defined SIOCGIFFLAGS)) \
3837 || defined WINDOWSNT)
3838 return network_interface_info (ifname);
3839 #else
3840 return Qnil;
3841 #endif
3845 /* Turn off input and output for process PROC. */
3847 static void
3848 deactivate_process (Lisp_Object proc)
3850 int inchannel;
3851 struct Lisp_Process *p = XPROCESS (proc);
3852 int i;
3854 #ifdef HAVE_GNUTLS
3855 /* Delete GnuTLS structures in PROC, if any. */
3856 emacs_gnutls_deinit (proc);
3857 #endif /* HAVE_GNUTLS */
3859 #ifdef ADAPTIVE_READ_BUFFERING
3860 if (p->read_output_delay > 0)
3862 if (--process_output_delay_count < 0)
3863 process_output_delay_count = 0;
3864 p->read_output_delay = 0;
3865 p->read_output_skip = 0;
3867 #endif
3869 /* Beware SIGCHLD hereabouts. */
3871 for (i = 0; i < PROCESS_OPEN_FDS; i++)
3872 close_process_fd (&p->open_fd[i]);
3874 inchannel = p->infd;
3875 if (inchannel >= 0)
3877 p->infd = -1;
3878 p->outfd = -1;
3879 #ifdef DATAGRAM_SOCKETS
3880 if (DATAGRAM_CHAN_P (inchannel))
3882 xfree (datagram_address[inchannel].sa);
3883 datagram_address[inchannel].sa = 0;
3884 datagram_address[inchannel].len = 0;
3886 #endif
3887 chan_process[inchannel] = Qnil;
3888 FD_CLR (inchannel, &input_wait_mask);
3889 FD_CLR (inchannel, &non_keyboard_wait_mask);
3890 #ifdef NON_BLOCKING_CONNECT
3891 if (FD_ISSET (inchannel, &connect_wait_mask))
3893 FD_CLR (inchannel, &connect_wait_mask);
3894 FD_CLR (inchannel, &write_mask);
3895 if (--num_pending_connects < 0)
3896 emacs_abort ();
3898 #endif
3899 if (inchannel == max_process_desc)
3901 /* We just closed the highest-numbered process input descriptor,
3902 so recompute the highest-numbered one now. */
3903 int i = inchannel;
3905 i--;
3906 while (0 <= i && NILP (chan_process[i]));
3908 max_process_desc = i;
3914 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3915 0, 4, 0,
3916 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3917 It is read into the process' buffers or given to their filter functions.
3918 Non-nil arg PROCESS means do not return until some output has been received
3919 from PROCESS.
3921 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
3922 and milliseconds to wait; return after that much time whether or not
3923 there is any subprocess output. If SECONDS is a floating point number,
3924 it specifies a fractional number of seconds to wait.
3925 The MILLISEC argument is obsolete and should be avoided.
3927 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
3928 from PROCESS, suspending reading output from other processes.
3929 If JUST-THIS-ONE is an integer, don't run any timers either.
3930 Return non-nil if we received any output before the timeout expired. */)
3931 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
3933 intmax_t secs;
3934 int nsecs;
3936 if (! NILP (process))
3937 CHECK_PROCESS (process);
3938 else
3939 just_this_one = Qnil;
3941 if (!NILP (millisec))
3942 { /* Obsolete calling convention using integers rather than floats. */
3943 CHECK_NUMBER (millisec);
3944 if (NILP (seconds))
3945 seconds = make_float (XINT (millisec) / 1000.0);
3946 else
3948 CHECK_NUMBER (seconds);
3949 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
3953 secs = 0;
3954 nsecs = -1;
3956 if (!NILP (seconds))
3958 if (INTEGERP (seconds))
3960 if (XINT (seconds) > 0)
3962 secs = XINT (seconds);
3963 nsecs = 0;
3966 else if (FLOATP (seconds))
3968 if (XFLOAT_DATA (seconds) > 0)
3970 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
3971 secs = min (t.tv_sec, WAIT_READING_MAX);
3972 nsecs = t.tv_nsec;
3975 else
3976 wrong_type_argument (Qnumberp, seconds);
3978 else if (! NILP (process))
3979 nsecs = 0;
3981 return
3982 (wait_reading_process_output (secs, nsecs, 0, 0,
3983 Qnil,
3984 !NILP (process) ? XPROCESS (process) : NULL,
3985 NILP (just_this_one) ? 0 :
3986 !INTEGERP (just_this_one) ? 1 : -1)
3987 ? Qt : Qnil);
3990 /* Accept a connection for server process SERVER on CHANNEL. */
3992 static EMACS_INT connect_counter = 0;
3994 static void
3995 server_accept_connection (Lisp_Object server, int channel)
3997 Lisp_Object proc, caller, name, buffer;
3998 Lisp_Object contact, host, service;
3999 struct Lisp_Process *ps= XPROCESS (server);
4000 struct Lisp_Process *p;
4001 int s;
4002 union u_sockaddr {
4003 struct sockaddr sa;
4004 struct sockaddr_in in;
4005 #ifdef AF_INET6
4006 struct sockaddr_in6 in6;
4007 #endif
4008 #ifdef HAVE_LOCAL_SOCKETS
4009 struct sockaddr_un un;
4010 #endif
4011 } saddr;
4012 socklen_t len = sizeof saddr;
4013 ptrdiff_t count;
4015 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4017 if (s < 0)
4019 int code = errno;
4021 if (code == EAGAIN)
4022 return;
4023 #ifdef EWOULDBLOCK
4024 if (code == EWOULDBLOCK)
4025 return;
4026 #endif
4028 if (!NILP (ps->log))
4029 call3 (ps->log, server, Qnil,
4030 concat3 (build_string ("accept failed with code"),
4031 Fnumber_to_string (make_number (code)),
4032 build_string ("\n")));
4033 return;
4036 count = SPECPDL_INDEX ();
4037 record_unwind_protect_int (close_file_unwind, s);
4039 connect_counter++;
4041 /* Setup a new process to handle the connection. */
4043 /* Generate a unique identification of the caller, and build contact
4044 information for this process. */
4045 host = Qt;
4046 service = Qnil;
4047 switch (saddr.sa.sa_family)
4049 case AF_INET:
4051 Lisp_Object args[5];
4052 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4053 args[0] = build_string ("%d.%d.%d.%d");
4054 args[1] = make_number (*ip++);
4055 args[2] = make_number (*ip++);
4056 args[3] = make_number (*ip++);
4057 args[4] = make_number (*ip++);
4058 host = Fformat (5, args);
4059 service = make_number (ntohs (saddr.in.sin_port));
4061 args[0] = build_string (" <%s:%d>");
4062 args[1] = host;
4063 args[2] = service;
4064 caller = Fformat (3, args);
4066 break;
4068 #ifdef AF_INET6
4069 case AF_INET6:
4071 Lisp_Object args[9];
4072 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4073 int i;
4074 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4075 for (i = 0; i < 8; i++)
4076 args[i+1] = make_number (ntohs (ip6[i]));
4077 host = Fformat (9, args);
4078 service = make_number (ntohs (saddr.in.sin_port));
4080 args[0] = build_string (" <[%s]:%d>");
4081 args[1] = host;
4082 args[2] = service;
4083 caller = Fformat (3, args);
4085 break;
4086 #endif
4088 #ifdef HAVE_LOCAL_SOCKETS
4089 case AF_LOCAL:
4090 #endif
4091 default:
4092 caller = Fnumber_to_string (make_number (connect_counter));
4093 caller = concat3 (build_string (" <"), caller, build_string (">"));
4094 break;
4097 /* Create a new buffer name for this process if it doesn't have a
4098 filter. The new buffer name is based on the buffer name or
4099 process name of the server process concatenated with the caller
4100 identification. */
4102 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4103 || EQ (ps->filter, Qt)))
4104 buffer = Qnil;
4105 else
4107 buffer = ps->buffer;
4108 if (!NILP (buffer))
4109 buffer = Fbuffer_name (buffer);
4110 else
4111 buffer = ps->name;
4112 if (!NILP (buffer))
4114 buffer = concat2 (buffer, caller);
4115 buffer = Fget_buffer_create (buffer);
4119 /* Generate a unique name for the new server process. Combine the
4120 server process name with the caller identification. */
4122 name = concat2 (ps->name, caller);
4123 proc = make_process (name);
4125 chan_process[s] = proc;
4127 fcntl (s, F_SETFL, O_NONBLOCK);
4129 p = XPROCESS (proc);
4131 /* Build new contact information for this setup. */
4132 contact = Fcopy_sequence (ps->childp);
4133 contact = Fplist_put (contact, QCserver, Qnil);
4134 contact = Fplist_put (contact, QChost, host);
4135 if (!NILP (service))
4136 contact = Fplist_put (contact, QCservice, service);
4137 contact = Fplist_put (contact, QCremote,
4138 conv_sockaddr_to_lisp (&saddr.sa, len));
4139 #ifdef HAVE_GETSOCKNAME
4140 len = sizeof saddr;
4141 if (getsockname (s, &saddr.sa, &len) == 0)
4142 contact = Fplist_put (contact, QClocal,
4143 conv_sockaddr_to_lisp (&saddr.sa, len));
4144 #endif
4146 pset_childp (p, contact);
4147 pset_plist (p, Fcopy_sequence (ps->plist));
4148 pset_type (p, Qnetwork);
4150 pset_buffer (p, buffer);
4151 pset_sentinel (p, ps->sentinel);
4152 pset_filter (p, ps->filter);
4153 pset_command (p, Qnil);
4154 p->pid = 0;
4156 /* Discard the unwind protect for closing S. */
4157 specpdl_ptr = specpdl + count;
4159 p->open_fd[SUBPROCESS_STDIN] = s;
4160 p->infd = s;
4161 p->outfd = s;
4162 pset_status (p, Qrun);
4164 /* Client processes for accepted connections are not stopped initially. */
4165 if (!EQ (p->filter, Qt))
4167 FD_SET (s, &input_wait_mask);
4168 FD_SET (s, &non_keyboard_wait_mask);
4171 if (s > max_process_desc)
4172 max_process_desc = s;
4174 /* Setup coding system for new process based on server process.
4175 This seems to be the proper thing to do, as the coding system
4176 of the new process should reflect the settings at the time the
4177 server socket was opened; not the current settings. */
4179 pset_decode_coding_system (p, ps->decode_coding_system);
4180 pset_encode_coding_system (p, ps->encode_coding_system);
4181 setup_process_coding_systems (proc);
4183 pset_decoding_buf (p, empty_unibyte_string);
4184 p->decoding_carryover = 0;
4185 pset_encoding_buf (p, empty_unibyte_string);
4187 p->inherit_coding_system_flag
4188 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4190 if (!NILP (ps->log))
4191 call3 (ps->log, server, proc,
4192 concat3 (build_string ("accept from "),
4193 (STRINGP (host) ? host : build_string ("-")),
4194 build_string ("\n")));
4196 exec_sentinel (proc,
4197 concat3 (build_string ("open from "),
4198 (STRINGP (host) ? host : build_string ("-")),
4199 build_string ("\n")));
4202 /* This variable is different from waiting_for_input in keyboard.c.
4203 It is used to communicate to a lisp process-filter/sentinel (via the
4204 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4205 for user-input when that process-filter was called.
4206 waiting_for_input cannot be used as that is by definition 0 when
4207 lisp code is being evalled.
4208 This is also used in record_asynch_buffer_change.
4209 For that purpose, this must be 0
4210 when not inside wait_reading_process_output. */
4211 static int waiting_for_user_input_p;
4213 static void
4214 wait_reading_process_output_unwind (int data)
4216 waiting_for_user_input_p = data;
4219 /* This is here so breakpoints can be put on it. */
4220 static void
4221 wait_reading_process_output_1 (void)
4225 /* Read and dispose of subprocess output while waiting for timeout to
4226 elapse and/or keyboard input to be available.
4228 TIME_LIMIT is:
4229 timeout in seconds
4230 If negative, gobble data immediately available but don't wait for any.
4232 NSECS is:
4233 an additional duration to wait, measured in nanoseconds
4234 If TIME_LIMIT is zero, then:
4235 If NSECS == 0, there is no limit.
4236 If NSECS > 0, the timeout consists of NSECS only.
4237 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4239 READ_KBD is:
4240 0 to ignore keyboard input, or
4241 1 to return when input is available, or
4242 -1 meaning caller will actually read the input, so don't throw to
4243 the quit handler, or
4245 DO_DISPLAY means redisplay should be done to show subprocess
4246 output that arrives.
4248 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4249 (and gobble terminal input into the buffer if any arrives).
4251 If WAIT_PROC is specified, wait until something arrives from that
4252 process. The return value is true if we read some input from
4253 that process.
4255 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4256 (suspending output from other processes). A negative value
4257 means don't run any timers either.
4259 If WAIT_PROC is specified, then the function returns true if we
4260 received input from that process before the timeout elapsed.
4261 Otherwise, return true if we received input from any process. */
4263 bool
4264 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4265 bool do_display,
4266 Lisp_Object wait_for_cell,
4267 struct Lisp_Process *wait_proc, int just_wait_proc)
4269 int channel, nfds;
4270 fd_set Available;
4271 fd_set Writeok;
4272 bool check_write;
4273 int check_delay;
4274 bool no_avail;
4275 int xerrno;
4276 Lisp_Object proc;
4277 struct timespec timeout, end_time;
4278 int wait_channel = -1;
4279 bool got_some_input = 0;
4280 ptrdiff_t count = SPECPDL_INDEX ();
4282 FD_ZERO (&Available);
4283 FD_ZERO (&Writeok);
4285 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4286 && !(CONSP (wait_proc->status)
4287 && EQ (XCAR (wait_proc->status), Qexit)))
4288 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4290 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4291 if (wait_proc != NULL)
4292 wait_channel = wait_proc->infd;
4294 record_unwind_protect_int (wait_reading_process_output_unwind,
4295 waiting_for_user_input_p);
4296 waiting_for_user_input_p = read_kbd;
4298 if (time_limit < 0)
4300 time_limit = 0;
4301 nsecs = -1;
4303 else if (TYPE_MAXIMUM (time_t) < time_limit)
4304 time_limit = TYPE_MAXIMUM (time_t);
4306 /* Since we may need to wait several times,
4307 compute the absolute time to return at. */
4308 if (time_limit || nsecs > 0)
4310 timeout = make_timespec (time_limit, nsecs);
4311 end_time = timespec_add (current_timespec (), timeout);
4314 while (1)
4316 bool timeout_reduced_for_timers = 0;
4318 /* If calling from keyboard input, do not quit
4319 since we want to return C-g as an input character.
4320 Otherwise, do pending quit if requested. */
4321 if (read_kbd >= 0)
4322 QUIT;
4323 else if (pending_signals)
4324 process_pending_signals ();
4326 /* Exit now if the cell we're waiting for became non-nil. */
4327 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4328 break;
4330 /* Compute time from now till when time limit is up. */
4331 /* Exit if already run out. */
4332 if (nsecs < 0)
4334 /* A negative timeout means
4335 gobble output available now
4336 but don't wait at all. */
4338 timeout = make_timespec (0, 0);
4340 else if (time_limit || nsecs > 0)
4342 struct timespec now = current_timespec ();
4343 if (timespec_cmp (end_time, now) <= 0)
4344 break;
4345 timeout = timespec_sub (end_time, now);
4347 else
4349 timeout = make_timespec (100000, 0);
4352 /* Normally we run timers here.
4353 But not if wait_for_cell; in those cases,
4354 the wait is supposed to be short,
4355 and those callers cannot handle running arbitrary Lisp code here. */
4356 if (NILP (wait_for_cell)
4357 && just_wait_proc >= 0)
4359 struct timespec timer_delay;
4363 unsigned old_timers_run = timers_run;
4364 struct buffer *old_buffer = current_buffer;
4365 Lisp_Object old_window = selected_window;
4367 timer_delay = timer_check ();
4369 /* If a timer has run, this might have changed buffers
4370 an alike. Make read_key_sequence aware of that. */
4371 if (timers_run != old_timers_run
4372 && (old_buffer != current_buffer
4373 || !EQ (old_window, selected_window))
4374 && waiting_for_user_input_p == -1)
4375 record_asynch_buffer_change ();
4377 if (timers_run != old_timers_run && do_display)
4378 /* We must retry, since a timer may have requeued itself
4379 and that could alter the time_delay. */
4380 redisplay_preserve_echo_area (9);
4381 else
4382 break;
4384 while (!detect_input_pending ());
4386 /* If there is unread keyboard input, also return. */
4387 if (read_kbd != 0
4388 && requeued_events_pending_p ())
4389 break;
4391 /* A negative timeout means do not wait at all. */
4392 if (nsecs >= 0)
4394 if (timespec_valid_p (timer_delay))
4396 if (timespec_cmp (timer_delay, timeout) < 0)
4398 timeout = timer_delay;
4399 timeout_reduced_for_timers = 1;
4402 else
4404 /* This is so a breakpoint can be put here. */
4405 wait_reading_process_output_1 ();
4410 /* Cause C-g and alarm signals to take immediate action,
4411 and cause input available signals to zero out timeout.
4413 It is important that we do this before checking for process
4414 activity. If we get a SIGCHLD after the explicit checks for
4415 process activity, timeout is the only way we will know. */
4416 if (read_kbd < 0)
4417 set_waiting_for_input (&timeout);
4419 /* If status of something has changed, and no input is
4420 available, notify the user of the change right away. After
4421 this explicit check, we'll let the SIGCHLD handler zap
4422 timeout to get our attention. */
4423 if (update_tick != process_tick)
4425 fd_set Atemp;
4426 fd_set Ctemp;
4428 if (kbd_on_hold_p ())
4429 FD_ZERO (&Atemp);
4430 else
4431 Atemp = input_wait_mask;
4432 Ctemp = write_mask;
4434 timeout = make_timespec (0, 0);
4435 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4436 &Atemp,
4437 #ifdef NON_BLOCKING_CONNECT
4438 (num_pending_connects > 0 ? &Ctemp : NULL),
4439 #else
4440 NULL,
4441 #endif
4442 NULL, &timeout, NULL)
4443 <= 0))
4445 /* It's okay for us to do this and then continue with
4446 the loop, since timeout has already been zeroed out. */
4447 clear_waiting_for_input ();
4448 status_notify (NULL);
4449 if (do_display) redisplay_preserve_echo_area (13);
4453 /* Don't wait for output from a non-running process. Just
4454 read whatever data has already been received. */
4455 if (wait_proc && wait_proc->raw_status_new)
4456 update_status (wait_proc);
4457 if (wait_proc
4458 && ! EQ (wait_proc->status, Qrun)
4459 && ! EQ (wait_proc->status, Qconnect))
4461 bool read_some_bytes = 0;
4463 clear_waiting_for_input ();
4464 XSETPROCESS (proc, wait_proc);
4466 /* Read data from the process, until we exhaust it. */
4467 while (wait_proc->infd >= 0)
4469 int nread = read_process_output (proc, wait_proc->infd);
4471 if (nread == 0)
4472 break;
4474 if (nread > 0)
4475 got_some_input = read_some_bytes = 1;
4476 else if (nread == -1 && (errno == EIO || errno == EAGAIN))
4477 break;
4478 #ifdef EWOULDBLOCK
4479 else if (nread == -1 && EWOULDBLOCK == errno)
4480 break;
4481 #endif
4483 if (read_some_bytes && do_display)
4484 redisplay_preserve_echo_area (10);
4486 break;
4489 /* Wait till there is something to do */
4491 if (wait_proc && just_wait_proc)
4493 if (wait_proc->infd < 0) /* Terminated */
4494 break;
4495 FD_SET (wait_proc->infd, &Available);
4496 check_delay = 0;
4497 check_write = 0;
4499 else if (!NILP (wait_for_cell))
4501 Available = non_process_wait_mask;
4502 check_delay = 0;
4503 check_write = 0;
4505 else
4507 if (! read_kbd)
4508 Available = non_keyboard_wait_mask;
4509 else
4510 Available = input_wait_mask;
4511 Writeok = write_mask;
4512 #ifdef SELECT_CANT_DO_WRITE_MASK
4513 check_write = 0;
4514 #else
4515 check_write = 1;
4516 #endif
4517 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4520 /* If frame size has changed or the window is newly mapped,
4521 redisplay now, before we start to wait. There is a race
4522 condition here; if a SIGIO arrives between now and the select
4523 and indicates that a frame is trashed, the select may block
4524 displaying a trashed screen. */
4525 if (frame_garbaged && do_display)
4527 clear_waiting_for_input ();
4528 redisplay_preserve_echo_area (11);
4529 if (read_kbd < 0)
4530 set_waiting_for_input (&timeout);
4533 /* Skip the `select' call if input is available and we're
4534 waiting for keyboard input or a cell change (which can be
4535 triggered by processing X events). In the latter case, set
4536 nfds to 1 to avoid breaking the loop. */
4537 no_avail = 0;
4538 if ((read_kbd || !NILP (wait_for_cell))
4539 && detect_input_pending ())
4541 nfds = read_kbd ? 0 : 1;
4542 no_avail = 1;
4545 if (!no_avail)
4548 #ifdef ADAPTIVE_READ_BUFFERING
4549 /* Set the timeout for adaptive read buffering if any
4550 process has non-zero read_output_skip and non-zero
4551 read_output_delay, and we are not reading output for a
4552 specific wait_channel. It is not executed if
4553 Vprocess_adaptive_read_buffering is nil. */
4554 if (process_output_skip && check_delay > 0)
4556 int nsecs = timeout.tv_nsec;
4557 if (timeout.tv_sec > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4558 nsecs = READ_OUTPUT_DELAY_MAX;
4559 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4561 proc = chan_process[channel];
4562 if (NILP (proc))
4563 continue;
4564 /* Find minimum non-zero read_output_delay among the
4565 processes with non-zero read_output_skip. */
4566 if (XPROCESS (proc)->read_output_delay > 0)
4568 check_delay--;
4569 if (!XPROCESS (proc)->read_output_skip)
4570 continue;
4571 FD_CLR (channel, &Available);
4572 XPROCESS (proc)->read_output_skip = 0;
4573 if (XPROCESS (proc)->read_output_delay < nsecs)
4574 nsecs = XPROCESS (proc)->read_output_delay;
4577 timeout = make_timespec (0, nsecs);
4578 process_output_skip = 0;
4580 #endif
4582 #if defined (HAVE_NS)
4583 nfds = ns_select
4584 #elif defined (HAVE_GLIB)
4585 nfds = xg_select
4586 #else
4587 nfds = pselect
4588 #endif
4589 (max (max_process_desc, max_input_desc) + 1,
4590 &Available,
4591 (check_write ? &Writeok : 0),
4592 NULL, &timeout, NULL);
4594 #ifdef HAVE_GNUTLS
4595 /* GnuTLS buffers data internally. In lowat mode it leaves
4596 some data in the TCP buffers so that select works, but
4597 with custom pull/push functions we need to check if some
4598 data is available in the buffers manually. */
4599 if (nfds == 0)
4601 if (! wait_proc)
4603 /* We're not waiting on a specific process, so loop
4604 through all the channels and check for data.
4605 This is a workaround needed for some versions of
4606 the gnutls library -- 2.12.14 has been confirmed
4607 to need it. See
4608 http://comments.gmane.org/gmane.emacs.devel/145074 */
4609 for (channel = 0; channel < FD_SETSIZE; ++channel)
4610 if (! NILP (chan_process[channel]))
4612 struct Lisp_Process *p =
4613 XPROCESS (chan_process[channel]);
4614 if (p && p->gnutls_p && p->gnutls_state && p->infd
4615 && ((emacs_gnutls_record_check_pending
4616 (p->gnutls_state))
4617 > 0))
4619 nfds++;
4620 FD_SET (p->infd, &Available);
4624 else
4626 /* Check this specific channel. */
4627 if (wait_proc->gnutls_p /* Check for valid process. */
4628 && wait_proc->gnutls_state
4629 /* Do we have pending data? */
4630 && ((emacs_gnutls_record_check_pending
4631 (wait_proc->gnutls_state))
4632 > 0))
4634 nfds = 1;
4635 /* Set to Available. */
4636 FD_SET (wait_proc->infd, &Available);
4640 #endif
4643 xerrno = errno;
4645 /* Make C-g and alarm signals set flags again */
4646 clear_waiting_for_input ();
4648 /* If we woke up due to SIGWINCH, actually change size now. */
4649 do_pending_window_change (0);
4651 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4652 /* We waited the full specified time, so return now. */
4653 break;
4654 if (nfds < 0)
4656 if (xerrno == EINTR)
4657 no_avail = 1;
4658 else if (xerrno == EBADF)
4659 emacs_abort ();
4660 else
4661 report_file_errno ("Failed select", Qnil, xerrno);
4664 if (no_avail)
4666 FD_ZERO (&Available);
4667 check_write = 0;
4670 /* Check for keyboard input */
4671 /* If there is any, return immediately
4672 to give it higher priority than subprocesses */
4674 if (read_kbd != 0)
4676 unsigned old_timers_run = timers_run;
4677 struct buffer *old_buffer = current_buffer;
4678 Lisp_Object old_window = selected_window;
4679 bool leave = 0;
4681 if (detect_input_pending_run_timers (do_display))
4683 swallow_events (do_display);
4684 if (detect_input_pending_run_timers (do_display))
4685 leave = 1;
4688 /* If a timer has run, this might have changed buffers
4689 an alike. Make read_key_sequence aware of that. */
4690 if (timers_run != old_timers_run
4691 && waiting_for_user_input_p == -1
4692 && (old_buffer != current_buffer
4693 || !EQ (old_window, selected_window)))
4694 record_asynch_buffer_change ();
4696 if (leave)
4697 break;
4700 /* If there is unread keyboard input, also return. */
4701 if (read_kbd != 0
4702 && requeued_events_pending_p ())
4703 break;
4705 /* If we are not checking for keyboard input now,
4706 do process events (but don't run any timers).
4707 This is so that X events will be processed.
4708 Otherwise they may have to wait until polling takes place.
4709 That would causes delays in pasting selections, for example.
4711 (We used to do this only if wait_for_cell.) */
4712 if (read_kbd == 0 && detect_input_pending ())
4714 swallow_events (do_display);
4715 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4716 if (detect_input_pending ())
4717 break;
4718 #endif
4721 /* Exit now if the cell we're waiting for became non-nil. */
4722 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4723 break;
4725 #ifdef USABLE_SIGIO
4726 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4727 go read it. This can happen with X on BSD after logging out.
4728 In that case, there really is no input and no SIGIO,
4729 but select says there is input. */
4731 if (read_kbd && interrupt_input
4732 && keyboard_bit_set (&Available) && ! noninteractive)
4733 handle_input_available_signal (SIGIO);
4734 #endif
4736 if (! wait_proc)
4737 got_some_input |= nfds > 0;
4739 /* If checking input just got us a size-change event from X,
4740 obey it now if we should. */
4741 if (read_kbd || ! NILP (wait_for_cell))
4742 do_pending_window_change (0);
4744 /* Check for data from a process. */
4745 if (no_avail || nfds == 0)
4746 continue;
4748 for (channel = 0; channel <= max_input_desc; ++channel)
4750 struct fd_callback_data *d = &fd_callback_info[channel];
4751 if (d->func
4752 && ((d->condition & FOR_READ
4753 && FD_ISSET (channel, &Available))
4754 || (d->condition & FOR_WRITE
4755 && FD_ISSET (channel, &write_mask))))
4756 d->func (channel, d->data);
4759 for (channel = 0; channel <= max_process_desc; channel++)
4761 if (FD_ISSET (channel, &Available)
4762 && FD_ISSET (channel, &non_keyboard_wait_mask)
4763 && !FD_ISSET (channel, &non_process_wait_mask))
4765 int nread;
4767 /* If waiting for this channel, arrange to return as
4768 soon as no more input to be processed. No more
4769 waiting. */
4770 if (wait_channel == channel)
4772 wait_channel = -1;
4773 nsecs = -1;
4774 got_some_input = 1;
4776 proc = chan_process[channel];
4777 if (NILP (proc))
4778 continue;
4780 /* If this is a server stream socket, accept connection. */
4781 if (EQ (XPROCESS (proc)->status, Qlisten))
4783 server_accept_connection (proc, channel);
4784 continue;
4787 /* Read data from the process, starting with our
4788 buffered-ahead character if we have one. */
4790 nread = read_process_output (proc, channel);
4791 if (nread > 0)
4793 /* Since read_process_output can run a filter,
4794 which can call accept-process-output,
4795 don't try to read from any other processes
4796 before doing the select again. */
4797 FD_ZERO (&Available);
4799 if (do_display)
4800 redisplay_preserve_echo_area (12);
4802 #ifdef EWOULDBLOCK
4803 else if (nread == -1 && errno == EWOULDBLOCK)
4805 #endif
4806 else if (nread == -1 && errno == EAGAIN)
4808 #ifdef WINDOWSNT
4809 /* FIXME: Is this special case still needed? */
4810 /* Note that we cannot distinguish between no input
4811 available now and a closed pipe.
4812 With luck, a closed pipe will be accompanied by
4813 subprocess termination and SIGCHLD. */
4814 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4816 #endif
4817 #ifdef HAVE_PTYS
4818 /* On some OSs with ptys, when the process on one end of
4819 a pty exits, the other end gets an error reading with
4820 errno = EIO instead of getting an EOF (0 bytes read).
4821 Therefore, if we get an error reading and errno =
4822 EIO, just continue, because the child process has
4823 exited and should clean itself up soon (e.g. when we
4824 get a SIGCHLD). */
4825 else if (nread == -1 && errno == EIO)
4827 struct Lisp_Process *p = XPROCESS (proc);
4829 /* Clear the descriptor now, so we only raise the
4830 signal once. */
4831 FD_CLR (channel, &input_wait_mask);
4832 FD_CLR (channel, &non_keyboard_wait_mask);
4834 if (p->pid == -2)
4836 /* If the EIO occurs on a pty, the SIGCHLD handler's
4837 waitpid call will not find the process object to
4838 delete. Do it here. */
4839 p->tick = ++process_tick;
4840 pset_status (p, Qfailed);
4843 #endif /* HAVE_PTYS */
4844 /* If we can detect process termination, don't consider the
4845 process gone just because its pipe is closed. */
4846 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4848 else
4850 /* Preserve status of processes already terminated. */
4851 XPROCESS (proc)->tick = ++process_tick;
4852 deactivate_process (proc);
4853 if (XPROCESS (proc)->raw_status_new)
4854 update_status (XPROCESS (proc));
4855 if (EQ (XPROCESS (proc)->status, Qrun))
4856 pset_status (XPROCESS (proc),
4857 list2 (Qexit, make_number (256)));
4860 #ifdef NON_BLOCKING_CONNECT
4861 if (FD_ISSET (channel, &Writeok)
4862 && FD_ISSET (channel, &connect_wait_mask))
4864 struct Lisp_Process *p;
4866 FD_CLR (channel, &connect_wait_mask);
4867 FD_CLR (channel, &write_mask);
4868 if (--num_pending_connects < 0)
4869 emacs_abort ();
4871 proc = chan_process[channel];
4872 if (NILP (proc))
4873 continue;
4875 p = XPROCESS (proc);
4877 #ifdef GNU_LINUX
4878 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4879 So only use it on systems where it is known to work. */
4881 socklen_t xlen = sizeof (xerrno);
4882 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4883 xerrno = errno;
4885 #else
4887 struct sockaddr pname;
4888 socklen_t pnamelen = sizeof (pname);
4890 /* If connection failed, getpeername will fail. */
4891 xerrno = 0;
4892 if (getpeername (channel, &pname, &pnamelen) < 0)
4894 /* Obtain connect failure code through error slippage. */
4895 char dummy;
4896 xerrno = errno;
4897 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
4898 xerrno = errno;
4901 #endif
4902 if (xerrno)
4904 p->tick = ++process_tick;
4905 pset_status (p, list2 (Qfailed, make_number (xerrno)));
4906 deactivate_process (proc);
4908 else
4910 pset_status (p, Qrun);
4911 /* Execute the sentinel here. If we had relied on
4912 status_notify to do it later, it will read input
4913 from the process before calling the sentinel. */
4914 exec_sentinel (proc, build_string ("open\n"));
4915 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
4917 FD_SET (p->infd, &input_wait_mask);
4918 FD_SET (p->infd, &non_keyboard_wait_mask);
4922 #endif /* NON_BLOCKING_CONNECT */
4923 } /* End for each file descriptor. */
4924 } /* End while exit conditions not met. */
4926 unbind_to (count, Qnil);
4928 /* If calling from keyboard input, do not quit
4929 since we want to return C-g as an input character.
4930 Otherwise, do pending quit if requested. */
4931 if (read_kbd >= 0)
4933 /* Prevent input_pending from remaining set if we quit. */
4934 clear_input_pending ();
4935 QUIT;
4938 return got_some_input;
4941 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4943 static Lisp_Object
4944 read_process_output_call (Lisp_Object fun_and_args)
4946 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4949 static Lisp_Object
4950 read_process_output_error_handler (Lisp_Object error_val)
4952 cmd_error_internal (error_val, "error in process filter: ");
4953 Vinhibit_quit = Qt;
4954 update_echo_area ();
4955 Fsleep_for (make_number (2), Qnil);
4956 return Qt;
4959 static void
4960 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
4961 ssize_t nbytes,
4962 struct coding_system *coding);
4964 /* Read pending output from the process channel,
4965 starting with our buffered-ahead character if we have one.
4966 Yield number of decoded characters read.
4968 This function reads at most 4096 characters.
4969 If you want to read all available subprocess output,
4970 you must call it repeatedly until it returns zero.
4972 The characters read are decoded according to PROC's coding-system
4973 for decoding. */
4975 static int
4976 read_process_output (Lisp_Object proc, register int channel)
4978 register ssize_t nbytes;
4979 char *chars;
4980 register struct Lisp_Process *p = XPROCESS (proc);
4981 struct coding_system *coding = proc_decode_coding_system[channel];
4982 int carryover = p->decoding_carryover;
4983 int readmax = 4096;
4984 ptrdiff_t count = SPECPDL_INDEX ();
4985 Lisp_Object odeactivate;
4987 chars = alloca (carryover + readmax);
4988 if (carryover)
4989 /* See the comment above. */
4990 memcpy (chars, SDATA (p->decoding_buf), carryover);
4992 #ifdef DATAGRAM_SOCKETS
4993 /* We have a working select, so proc_buffered_char is always -1. */
4994 if (DATAGRAM_CHAN_P (channel))
4996 socklen_t len = datagram_address[channel].len;
4997 nbytes = recvfrom (channel, chars + carryover, readmax,
4998 0, datagram_address[channel].sa, &len);
5000 else
5001 #endif
5003 bool buffered = proc_buffered_char[channel] >= 0;
5004 if (buffered)
5006 chars[carryover] = proc_buffered_char[channel];
5007 proc_buffered_char[channel] = -1;
5009 #ifdef HAVE_GNUTLS
5010 if (p->gnutls_p && p->gnutls_state)
5011 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5012 readmax - buffered);
5013 else
5014 #endif
5015 nbytes = emacs_read (channel, chars + carryover + buffered,
5016 readmax - buffered);
5017 #ifdef ADAPTIVE_READ_BUFFERING
5018 if (nbytes > 0 && p->adaptive_read_buffering)
5020 int delay = p->read_output_delay;
5021 if (nbytes < 256)
5023 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5025 if (delay == 0)
5026 process_output_delay_count++;
5027 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5030 else if (delay > 0 && nbytes == readmax - buffered)
5032 delay -= READ_OUTPUT_DELAY_INCREMENT;
5033 if (delay == 0)
5034 process_output_delay_count--;
5036 p->read_output_delay = delay;
5037 if (delay)
5039 p->read_output_skip = 1;
5040 process_output_skip = 1;
5043 #endif
5044 nbytes += buffered;
5045 nbytes += buffered && nbytes <= 0;
5048 p->decoding_carryover = 0;
5050 /* At this point, NBYTES holds number of bytes just received
5051 (including the one in proc_buffered_char[channel]). */
5052 if (nbytes <= 0)
5054 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5055 return nbytes;
5056 coding->mode |= CODING_MODE_LAST_BLOCK;
5059 /* Now set NBYTES how many bytes we must decode. */
5060 nbytes += carryover;
5062 odeactivate = Vdeactivate_mark;
5063 /* There's no good reason to let process filters change the current
5064 buffer, and many callers of accept-process-output, sit-for, and
5065 friends don't expect current-buffer to be changed from under them. */
5066 record_unwind_current_buffer ();
5068 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5070 /* Handling the process output should not deactivate the mark. */
5071 Vdeactivate_mark = odeactivate;
5073 unbind_to (count, Qnil);
5074 return nbytes;
5077 static void
5078 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5079 ssize_t nbytes,
5080 struct coding_system *coding)
5082 Lisp_Object outstream = p->filter;
5083 Lisp_Object text;
5084 bool outer_running_asynch_code = running_asynch_code;
5085 int waiting = waiting_for_user_input_p;
5087 /* No need to gcpro these, because all we do with them later
5088 is test them for EQness, and none of them should be a string. */
5089 #if 0
5090 Lisp_Object obuffer, okeymap;
5091 XSETBUFFER (obuffer, current_buffer);
5092 okeymap = BVAR (current_buffer, keymap);
5093 #endif
5095 /* We inhibit quit here instead of just catching it so that
5096 hitting ^G when a filter happens to be running won't screw
5097 it up. */
5098 specbind (Qinhibit_quit, Qt);
5099 specbind (Qlast_nonmenu_event, Qt);
5101 /* In case we get recursively called,
5102 and we already saved the match data nonrecursively,
5103 save the same match data in safely recursive fashion. */
5104 if (outer_running_asynch_code)
5106 Lisp_Object tem;
5107 /* Don't clobber the CURRENT match data, either! */
5108 tem = Fmatch_data (Qnil, Qnil, Qnil);
5109 restore_search_regs ();
5110 record_unwind_save_match_data ();
5111 Fset_match_data (tem, Qt);
5114 /* For speed, if a search happens within this code,
5115 save the match data in a special nonrecursive fashion. */
5116 running_asynch_code = 1;
5118 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5119 text = coding->dst_object;
5120 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5121 /* A new coding system might be found. */
5122 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5124 pset_decode_coding_system (p, Vlast_coding_system_used);
5126 /* Don't call setup_coding_system for
5127 proc_decode_coding_system[channel] here. It is done in
5128 detect_coding called via decode_coding above. */
5130 /* If a coding system for encoding is not yet decided, we set
5131 it as the same as coding-system for decoding.
5133 But, before doing that we must check if
5134 proc_encode_coding_system[p->outfd] surely points to a
5135 valid memory because p->outfd will be changed once EOF is
5136 sent to the process. */
5137 if (NILP (p->encode_coding_system)
5138 && proc_encode_coding_system[p->outfd])
5140 pset_encode_coding_system
5141 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5142 setup_coding_system (p->encode_coding_system,
5143 proc_encode_coding_system[p->outfd]);
5147 if (coding->carryover_bytes > 0)
5149 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5150 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5151 memcpy (SDATA (p->decoding_buf), coding->carryover,
5152 coding->carryover_bytes);
5153 p->decoding_carryover = coding->carryover_bytes;
5155 if (SBYTES (text) > 0)
5156 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5157 sometimes it's simply wrong to wrap (e.g. when called from
5158 accept-process-output). */
5159 internal_condition_case_1 (read_process_output_call,
5160 list3 (outstream, make_lisp_proc (p), text),
5161 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5162 read_process_output_error_handler);
5164 /* If we saved the match data nonrecursively, restore it now. */
5165 restore_search_regs ();
5166 running_asynch_code = outer_running_asynch_code;
5168 /* Restore waiting_for_user_input_p as it was
5169 when we were called, in case the filter clobbered it. */
5170 waiting_for_user_input_p = waiting;
5172 #if 0 /* Call record_asynch_buffer_change unconditionally,
5173 because we might have changed minor modes or other things
5174 that affect key bindings. */
5175 if (! EQ (Fcurrent_buffer (), obuffer)
5176 || ! EQ (current_buffer->keymap, okeymap))
5177 #endif
5178 /* But do it only if the caller is actually going to read events.
5179 Otherwise there's no need to make him wake up, and it could
5180 cause trouble (for example it would make sit_for return). */
5181 if (waiting_for_user_input_p == -1)
5182 record_asynch_buffer_change ();
5185 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5186 Sinternal_default_process_filter, 2, 2, 0,
5187 doc: /* Function used as default process filter. */)
5188 (Lisp_Object proc, Lisp_Object text)
5190 struct Lisp_Process *p;
5191 ptrdiff_t opoint;
5193 CHECK_PROCESS (proc);
5194 p = XPROCESS (proc);
5195 CHECK_STRING (text);
5197 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5199 Lisp_Object old_read_only;
5200 ptrdiff_t old_begv, old_zv;
5201 ptrdiff_t old_begv_byte, old_zv_byte;
5202 ptrdiff_t before, before_byte;
5203 ptrdiff_t opoint_byte;
5204 struct buffer *b;
5206 Fset_buffer (p->buffer);
5207 opoint = PT;
5208 opoint_byte = PT_BYTE;
5209 old_read_only = BVAR (current_buffer, read_only);
5210 old_begv = BEGV;
5211 old_zv = ZV;
5212 old_begv_byte = BEGV_BYTE;
5213 old_zv_byte = ZV_BYTE;
5215 bset_read_only (current_buffer, Qnil);
5217 /* Insert new output into buffer at the current end-of-output
5218 marker, thus preserving logical ordering of input and output. */
5219 if (XMARKER (p->mark)->buffer)
5220 set_point_from_marker (p->mark);
5221 else
5222 SET_PT_BOTH (ZV, ZV_BYTE);
5223 before = PT;
5224 before_byte = PT_BYTE;
5226 /* If the output marker is outside of the visible region, save
5227 the restriction and widen. */
5228 if (! (BEGV <= PT && PT <= ZV))
5229 Fwiden ();
5231 /* Adjust the multibyteness of TEXT to that of the buffer. */
5232 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5233 != ! STRING_MULTIBYTE (text))
5234 text = (STRING_MULTIBYTE (text)
5235 ? Fstring_as_unibyte (text)
5236 : Fstring_to_multibyte (text));
5237 /* Insert before markers in case we are inserting where
5238 the buffer's mark is, and the user's next command is Meta-y. */
5239 insert_from_string_before_markers (text, 0, 0,
5240 SCHARS (text), SBYTES (text), 0);
5242 /* Make sure the process marker's position is valid when the
5243 process buffer is changed in the signal_after_change above.
5244 W3 is known to do that. */
5245 if (BUFFERP (p->buffer)
5246 && (b = XBUFFER (p->buffer), b != current_buffer))
5247 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5248 else
5249 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5251 update_mode_lines = 23;
5253 /* Make sure opoint and the old restrictions
5254 float ahead of any new text just as point would. */
5255 if (opoint >= before)
5257 opoint += PT - before;
5258 opoint_byte += PT_BYTE - before_byte;
5260 if (old_begv > before)
5262 old_begv += PT - before;
5263 old_begv_byte += PT_BYTE - before_byte;
5265 if (old_zv >= before)
5267 old_zv += PT - before;
5268 old_zv_byte += PT_BYTE - before_byte;
5271 /* If the restriction isn't what it should be, set it. */
5272 if (old_begv != BEGV || old_zv != ZV)
5273 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5275 bset_read_only (current_buffer, old_read_only);
5276 SET_PT_BOTH (opoint, opoint_byte);
5278 return Qnil;
5281 /* Sending data to subprocess. */
5283 /* In send_process, when a write fails temporarily,
5284 wait_reading_process_output is called. It may execute user code,
5285 e.g. timers, that attempts to write new data to the same process.
5286 We must ensure that data is sent in the right order, and not
5287 interspersed half-completed with other writes (Bug#10815). This is
5288 handled by the write_queue element of struct process. It is a list
5289 with each entry having the form
5291 (string . (offset . length))
5293 where STRING is a lisp string, OFFSET is the offset into the
5294 string's byte sequence from which we should begin to send, and
5295 LENGTH is the number of bytes left to send. */
5297 /* Create a new entry in write_queue.
5298 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5299 BUF is a pointer to the string sequence of the input_obj or a C
5300 string in case of Qt or Qnil. */
5302 static void
5303 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5304 const char *buf, ptrdiff_t len, bool front)
5306 ptrdiff_t offset;
5307 Lisp_Object entry, obj;
5309 if (STRINGP (input_obj))
5311 offset = buf - SSDATA (input_obj);
5312 obj = input_obj;
5314 else
5316 offset = 0;
5317 obj = make_unibyte_string (buf, len);
5320 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5322 if (front)
5323 pset_write_queue (p, Fcons (entry, p->write_queue));
5324 else
5325 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5328 /* Remove the first element in the write_queue of process P, put its
5329 contents in OBJ, BUF and LEN, and return true. If the
5330 write_queue is empty, return false. */
5332 static bool
5333 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5334 const char **buf, ptrdiff_t *len)
5336 Lisp_Object entry, offset_length;
5337 ptrdiff_t offset;
5339 if (NILP (p->write_queue))
5340 return 0;
5342 entry = XCAR (p->write_queue);
5343 pset_write_queue (p, XCDR (p->write_queue));
5345 *obj = XCAR (entry);
5346 offset_length = XCDR (entry);
5348 *len = XINT (XCDR (offset_length));
5349 offset = XINT (XCAR (offset_length));
5350 *buf = SSDATA (*obj) + offset;
5352 return 1;
5355 /* Send some data to process PROC.
5356 BUF is the beginning of the data; LEN is the number of characters.
5357 OBJECT is the Lisp object that the data comes from. If OBJECT is
5358 nil or t, it means that the data comes from C string.
5360 If OBJECT is not nil, the data is encoded by PROC's coding-system
5361 for encoding before it is sent.
5363 This function can evaluate Lisp code and can garbage collect. */
5365 static void
5366 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5367 Lisp_Object object)
5369 struct Lisp_Process *p = XPROCESS (proc);
5370 ssize_t rv;
5371 struct coding_system *coding;
5373 if (p->raw_status_new)
5374 update_status (p);
5375 if (! EQ (p->status, Qrun))
5376 error ("Process %s not running", SDATA (p->name));
5377 if (p->outfd < 0)
5378 error ("Output file descriptor of %s is closed", SDATA (p->name));
5380 coding = proc_encode_coding_system[p->outfd];
5381 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5383 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5384 || (BUFFERP (object)
5385 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5386 || EQ (object, Qt))
5388 pset_encode_coding_system
5389 (p, complement_process_encoding_system (p->encode_coding_system));
5390 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5392 /* The coding system for encoding was changed to raw-text
5393 because we sent a unibyte text previously. Now we are
5394 sending a multibyte text, thus we must encode it by the
5395 original coding system specified for the current process.
5397 Another reason we come here is that the coding system
5398 was just complemented and a new one was returned by
5399 complement_process_encoding_system. */
5400 setup_coding_system (p->encode_coding_system, coding);
5401 Vlast_coding_system_used = p->encode_coding_system;
5403 coding->src_multibyte = 1;
5405 else
5407 coding->src_multibyte = 0;
5408 /* For sending a unibyte text, character code conversion should
5409 not take place but EOL conversion should. So, setup raw-text
5410 or one of the subsidiary if we have not yet done it. */
5411 if (CODING_REQUIRE_ENCODING (coding))
5413 if (CODING_REQUIRE_FLUSHING (coding))
5415 /* But, before changing the coding, we must flush out data. */
5416 coding->mode |= CODING_MODE_LAST_BLOCK;
5417 send_process (proc, "", 0, Qt);
5418 coding->mode &= CODING_MODE_LAST_BLOCK;
5420 setup_coding_system (raw_text_coding_system
5421 (Vlast_coding_system_used),
5422 coding);
5423 coding->src_multibyte = 0;
5426 coding->dst_multibyte = 0;
5428 if (CODING_REQUIRE_ENCODING (coding))
5430 coding->dst_object = Qt;
5431 if (BUFFERP (object))
5433 ptrdiff_t from_byte, from, to;
5434 ptrdiff_t save_pt, save_pt_byte;
5435 struct buffer *cur = current_buffer;
5437 set_buffer_internal (XBUFFER (object));
5438 save_pt = PT, save_pt_byte = PT_BYTE;
5440 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5441 from = BYTE_TO_CHAR (from_byte);
5442 to = BYTE_TO_CHAR (from_byte + len);
5443 TEMP_SET_PT_BOTH (from, from_byte);
5444 encode_coding_object (coding, object, from, from_byte,
5445 to, from_byte + len, Qt);
5446 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5447 set_buffer_internal (cur);
5449 else if (STRINGP (object))
5451 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5452 SBYTES (object), Qt);
5454 else
5456 coding->dst_object = make_unibyte_string (buf, len);
5457 coding->produced = len;
5460 len = coding->produced;
5461 object = coding->dst_object;
5462 buf = SSDATA (object);
5465 /* If there is already data in the write_queue, put the new data
5466 in the back of queue. Otherwise, ignore it. */
5467 if (!NILP (p->write_queue))
5468 write_queue_push (p, object, buf, len, 0);
5470 do /* while !NILP (p->write_queue) */
5472 ptrdiff_t cur_len = -1;
5473 const char *cur_buf;
5474 Lisp_Object cur_object;
5476 /* If write_queue is empty, ignore it. */
5477 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5479 cur_len = len;
5480 cur_buf = buf;
5481 cur_object = object;
5484 while (cur_len > 0)
5486 /* Send this batch, using one or more write calls. */
5487 ptrdiff_t written = 0;
5488 int outfd = p->outfd;
5489 #ifdef DATAGRAM_SOCKETS
5490 if (DATAGRAM_CHAN_P (outfd))
5492 rv = sendto (outfd, cur_buf, cur_len,
5493 0, datagram_address[outfd].sa,
5494 datagram_address[outfd].len);
5495 if (rv >= 0)
5496 written = rv;
5497 else if (errno == EMSGSIZE)
5498 report_file_error ("Sending datagram", proc);
5500 else
5501 #endif
5503 #ifdef HAVE_GNUTLS
5504 if (p->gnutls_p && p->gnutls_state)
5505 written = emacs_gnutls_write (p, cur_buf, cur_len);
5506 else
5507 #endif
5508 written = emacs_write_sig (outfd, cur_buf, cur_len);
5509 rv = (written ? 0 : -1);
5510 #ifdef ADAPTIVE_READ_BUFFERING
5511 if (p->read_output_delay > 0
5512 && p->adaptive_read_buffering == 1)
5514 p->read_output_delay = 0;
5515 process_output_delay_count--;
5516 p->read_output_skip = 0;
5518 #endif
5521 if (rv < 0)
5523 if (errno == EAGAIN
5524 #ifdef EWOULDBLOCK
5525 || errno == EWOULDBLOCK
5526 #endif
5528 /* Buffer is full. Wait, accepting input;
5529 that may allow the program
5530 to finish doing output and read more. */
5532 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5533 /* A gross hack to work around a bug in FreeBSD.
5534 In the following sequence, read(2) returns
5535 bogus data:
5537 write(2) 1022 bytes
5538 write(2) 954 bytes, get EAGAIN
5539 read(2) 1024 bytes in process_read_output
5540 read(2) 11 bytes in process_read_output
5542 That is, read(2) returns more bytes than have
5543 ever been written successfully. The 1033 bytes
5544 read are the 1022 bytes written successfully
5545 after processing (for example with CRs added if
5546 the terminal is set up that way which it is
5547 here). The same bytes will be seen again in a
5548 later read(2), without the CRs. */
5550 if (errno == EAGAIN)
5552 int flags = FWRITE;
5553 ioctl (p->outfd, TIOCFLUSH, &flags);
5555 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5557 /* Put what we should have written in wait_queue. */
5558 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5559 wait_reading_process_output (0, 20 * 1000 * 1000,
5560 0, 0, Qnil, NULL, 0);
5561 /* Reread queue, to see what is left. */
5562 break;
5564 else if (errno == EPIPE)
5566 p->raw_status_new = 0;
5567 pset_status (p, list2 (Qexit, make_number (256)));
5568 p->tick = ++process_tick;
5569 deactivate_process (proc);
5570 error ("process %s no longer connected to pipe; closed it",
5571 SDATA (p->name));
5573 else
5574 /* This is a real error. */
5575 report_file_error ("Writing to process", proc);
5577 cur_buf += written;
5578 cur_len -= written;
5581 while (!NILP (p->write_queue));
5584 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5585 3, 3, 0,
5586 doc: /* Send current contents of region as input to PROCESS.
5587 PROCESS may be a process, a buffer, the name of a process or buffer, or
5588 nil, indicating the current buffer's process.
5589 Called from program, takes three arguments, PROCESS, START and END.
5590 If the region is more than 500 characters long,
5591 it is sent in several bunches. This may happen even for shorter regions.
5592 Output from processes can arrive in between bunches. */)
5593 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5595 Lisp_Object proc = get_process (process);
5596 ptrdiff_t start_byte, end_byte;
5598 validate_region (&start, &end);
5600 start_byte = CHAR_TO_BYTE (XINT (start));
5601 end_byte = CHAR_TO_BYTE (XINT (end));
5603 if (XINT (start) < GPT && XINT (end) > GPT)
5604 move_gap_both (XINT (start), start_byte);
5606 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5607 end_byte - start_byte, Fcurrent_buffer ());
5609 return Qnil;
5612 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5613 2, 2, 0,
5614 doc: /* Send PROCESS the contents of STRING as input.
5615 PROCESS may be a process, a buffer, the name of a process or buffer, or
5616 nil, indicating the current buffer's process.
5617 If STRING is more than 500 characters long,
5618 it is sent in several bunches. This may happen even for shorter strings.
5619 Output from processes can arrive in between bunches. */)
5620 (Lisp_Object process, Lisp_Object string)
5622 Lisp_Object proc;
5623 CHECK_STRING (string);
5624 proc = get_process (process);
5625 send_process (proc, SSDATA (string),
5626 SBYTES (string), string);
5627 return Qnil;
5630 /* Return the foreground process group for the tty/pty that
5631 the process P uses. */
5632 static pid_t
5633 emacs_get_tty_pgrp (struct Lisp_Process *p)
5635 pid_t gid = -1;
5637 #ifdef TIOCGPGRP
5638 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5640 int fd;
5641 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5642 master side. Try the slave side. */
5643 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5645 if (fd != -1)
5647 ioctl (fd, TIOCGPGRP, &gid);
5648 emacs_close (fd);
5651 #endif /* defined (TIOCGPGRP ) */
5653 return gid;
5656 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5657 Sprocess_running_child_p, 0, 1, 0,
5658 doc: /* Return t if PROCESS has given the terminal to a child.
5659 If the operating system does not make it possible to find out,
5660 return t unconditionally. */)
5661 (Lisp_Object process)
5663 /* Initialize in case ioctl doesn't exist or gives an error,
5664 in a way that will cause returning t. */
5665 pid_t gid;
5666 Lisp_Object proc;
5667 struct Lisp_Process *p;
5669 proc = get_process (process);
5670 p = XPROCESS (proc);
5672 if (!EQ (p->type, Qreal))
5673 error ("Process %s is not a subprocess",
5674 SDATA (p->name));
5675 if (p->infd < 0)
5676 error ("Process %s is not active",
5677 SDATA (p->name));
5679 gid = emacs_get_tty_pgrp (p);
5681 if (gid == p->pid)
5682 return Qnil;
5683 return Qt;
5686 /* send a signal number SIGNO to PROCESS.
5687 If CURRENT_GROUP is t, that means send to the process group
5688 that currently owns the terminal being used to communicate with PROCESS.
5689 This is used for various commands in shell mode.
5690 If CURRENT_GROUP is lambda, that means send to the process group
5691 that currently owns the terminal, but only if it is NOT the shell itself.
5693 If NOMSG is false, insert signal-announcements into process's buffers
5694 right away.
5696 If we can, we try to signal PROCESS by sending control characters
5697 down the pty. This allows us to signal inferiors who have changed
5698 their uid, for which kill would return an EPERM error. */
5700 static void
5701 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5702 bool nomsg)
5704 Lisp_Object proc;
5705 struct Lisp_Process *p;
5706 pid_t gid;
5707 bool no_pgrp = 0;
5709 proc = get_process (process);
5710 p = XPROCESS (proc);
5712 if (!EQ (p->type, Qreal))
5713 error ("Process %s is not a subprocess",
5714 SDATA (p->name));
5715 if (p->infd < 0)
5716 error ("Process %s is not active",
5717 SDATA (p->name));
5719 if (!p->pty_flag)
5720 current_group = Qnil;
5722 /* If we are using pgrps, get a pgrp number and make it negative. */
5723 if (NILP (current_group))
5724 /* Send the signal to the shell's process group. */
5725 gid = p->pid;
5726 else
5728 #ifdef SIGNALS_VIA_CHARACTERS
5729 /* If possible, send signals to the entire pgrp
5730 by sending an input character to it. */
5732 struct termios t;
5733 cc_t *sig_char = NULL;
5735 tcgetattr (p->infd, &t);
5737 switch (signo)
5739 case SIGINT:
5740 sig_char = &t.c_cc[VINTR];
5741 break;
5743 case SIGQUIT:
5744 sig_char = &t.c_cc[VQUIT];
5745 break;
5747 case SIGTSTP:
5748 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5749 sig_char = &t.c_cc[VSWTCH];
5750 #else
5751 sig_char = &t.c_cc[VSUSP];
5752 #endif
5753 break;
5756 if (sig_char && *sig_char != CDISABLE)
5758 send_process (proc, (char *) sig_char, 1, Qnil);
5759 return;
5761 /* If we can't send the signal with a character,
5762 fall through and send it another way. */
5764 /* The code above may fall through if it can't
5765 handle the signal. */
5766 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5768 #ifdef TIOCGPGRP
5769 /* Get the current pgrp using the tty itself, if we have that.
5770 Otherwise, use the pty to get the pgrp.
5771 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5772 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5773 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5774 His patch indicates that if TIOCGPGRP returns an error, then
5775 we should just assume that p->pid is also the process group id. */
5777 gid = emacs_get_tty_pgrp (p);
5779 if (gid == -1)
5780 /* If we can't get the information, assume
5781 the shell owns the tty. */
5782 gid = p->pid;
5784 /* It is not clear whether anything really can set GID to -1.
5785 Perhaps on some system one of those ioctls can or could do so.
5786 Or perhaps this is vestigial. */
5787 if (gid == -1)
5788 no_pgrp = 1;
5789 #else /* ! defined (TIOCGPGRP ) */
5790 /* Can't select pgrps on this system, so we know that
5791 the child itself heads the pgrp. */
5792 gid = p->pid;
5793 #endif /* ! defined (TIOCGPGRP ) */
5795 /* If current_group is lambda, and the shell owns the terminal,
5796 don't send any signal. */
5797 if (EQ (current_group, Qlambda) && gid == p->pid)
5798 return;
5801 #ifdef SIGCONT
5802 if (signo == SIGCONT)
5804 p->raw_status_new = 0;
5805 pset_status (p, Qrun);
5806 p->tick = ++process_tick;
5807 if (!nomsg)
5809 status_notify (NULL);
5810 redisplay_preserve_echo_area (13);
5813 #endif
5815 /* If we don't have process groups, send the signal to the immediate
5816 subprocess. That isn't really right, but it's better than any
5817 obvious alternative. */
5818 if (no_pgrp)
5820 kill (p->pid, signo);
5821 return;
5824 /* gid may be a pid, or minus a pgrp's number */
5825 #ifdef TIOCSIGSEND
5826 if (!NILP (current_group))
5828 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
5829 kill (-gid, signo);
5831 else
5833 gid = - p->pid;
5834 kill (gid, signo);
5836 #else /* ! defined (TIOCSIGSEND) */
5837 kill (-gid, signo);
5838 #endif /* ! defined (TIOCSIGSEND) */
5841 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5842 doc: /* Interrupt process PROCESS.
5843 PROCESS may be a process, a buffer, or the name of a process or buffer.
5844 No arg or nil means current buffer's process.
5845 Second arg CURRENT-GROUP non-nil means send signal to
5846 the current process-group of the process's controlling terminal
5847 rather than to the process's own process group.
5848 If the process is a shell, this means interrupt current subjob
5849 rather than the shell.
5851 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5852 don't send the signal. */)
5853 (Lisp_Object process, Lisp_Object current_group)
5855 process_send_signal (process, SIGINT, current_group, 0);
5856 return process;
5859 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5860 doc: /* Kill process PROCESS. May be process or name of one.
5861 See function `interrupt-process' for more details on usage. */)
5862 (Lisp_Object process, Lisp_Object current_group)
5864 process_send_signal (process, SIGKILL, current_group, 0);
5865 return process;
5868 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5869 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5870 See function `interrupt-process' for more details on usage. */)
5871 (Lisp_Object process, Lisp_Object current_group)
5873 process_send_signal (process, SIGQUIT, current_group, 0);
5874 return process;
5877 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
5878 doc: /* Stop process PROCESS. May be process or name of one.
5879 See function `interrupt-process' for more details on usage.
5880 If PROCESS is a network or serial process, inhibit handling of incoming
5881 traffic. */)
5882 (Lisp_Object process, Lisp_Object current_group)
5884 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5886 struct Lisp_Process *p;
5888 p = XPROCESS (process);
5889 if (NILP (p->command)
5890 && p->infd >= 0)
5892 FD_CLR (p->infd, &input_wait_mask);
5893 FD_CLR (p->infd, &non_keyboard_wait_mask);
5895 pset_command (p, Qt);
5896 return process;
5898 #ifndef SIGTSTP
5899 error ("No SIGTSTP support");
5900 #else
5901 process_send_signal (process, SIGTSTP, current_group, 0);
5902 #endif
5903 return process;
5906 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
5907 doc: /* Continue process PROCESS. May be process or name of one.
5908 See function `interrupt-process' for more details on usage.
5909 If PROCESS is a network or serial process, resume handling of incoming
5910 traffic. */)
5911 (Lisp_Object process, Lisp_Object current_group)
5913 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5915 struct Lisp_Process *p;
5917 p = XPROCESS (process);
5918 if (EQ (p->command, Qt)
5919 && p->infd >= 0
5920 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
5922 FD_SET (p->infd, &input_wait_mask);
5923 FD_SET (p->infd, &non_keyboard_wait_mask);
5924 #ifdef WINDOWSNT
5925 if (fd_info[ p->infd ].flags & FILE_SERIAL)
5926 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
5927 #else /* not WINDOWSNT */
5928 tcflush (p->infd, TCIFLUSH);
5929 #endif /* not WINDOWSNT */
5931 pset_command (p, Qnil);
5932 return process;
5934 #ifdef SIGCONT
5935 process_send_signal (process, SIGCONT, current_group, 0);
5936 #else
5937 error ("No SIGCONT support");
5938 #endif
5939 return process;
5942 /* Return the integer value of the signal whose abbreviation is ABBR,
5943 or a negative number if there is no such signal. */
5944 static int
5945 abbr_to_signal (char const *name)
5947 int i, signo;
5948 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
5950 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
5951 name += 3;
5953 for (i = 0; i < sizeof sigbuf; i++)
5955 sigbuf[i] = c_toupper (name[i]);
5956 if (! sigbuf[i])
5957 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
5960 return -1;
5963 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
5964 2, 2, "sProcess (name or number): \nnSignal code: ",
5965 doc: /* Send PROCESS the signal with code SIGCODE.
5966 PROCESS may also be a number specifying the process id of the
5967 process to signal; in this case, the process need not be a child of
5968 this Emacs.
5969 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5970 (Lisp_Object process, Lisp_Object sigcode)
5972 pid_t pid;
5973 int signo;
5975 if (STRINGP (process))
5977 Lisp_Object tem = Fget_process (process);
5978 if (NILP (tem))
5980 Lisp_Object process_number =
5981 string_to_number (SSDATA (process), 10, 1);
5982 if (INTEGERP (process_number) || FLOATP (process_number))
5983 tem = process_number;
5985 process = tem;
5987 else if (!NUMBERP (process))
5988 process = get_process (process);
5990 if (NILP (process))
5991 return process;
5993 if (NUMBERP (process))
5994 CONS_TO_INTEGER (process, pid_t, pid);
5995 else
5997 CHECK_PROCESS (process);
5998 pid = XPROCESS (process)->pid;
5999 if (pid <= 0)
6000 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6003 if (INTEGERP (sigcode))
6005 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6006 signo = XINT (sigcode);
6008 else
6010 char *name;
6012 CHECK_SYMBOL (sigcode);
6013 name = SSDATA (SYMBOL_NAME (sigcode));
6015 signo = abbr_to_signal (name);
6016 if (signo < 0)
6017 error ("Undefined signal name %s", name);
6020 return make_number (kill (pid, signo));
6023 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6024 doc: /* Make PROCESS see end-of-file in its input.
6025 EOF comes after any text already sent to it.
6026 PROCESS may be a process, a buffer, the name of a process or buffer, or
6027 nil, indicating the current buffer's process.
6028 If PROCESS is a network connection, or is a process communicating
6029 through a pipe (as opposed to a pty), then you cannot send any more
6030 text to PROCESS after you call this function.
6031 If PROCESS is a serial process, wait until all output written to the
6032 process has been transmitted to the serial port. */)
6033 (Lisp_Object process)
6035 Lisp_Object proc;
6036 struct coding_system *coding = NULL;
6037 int outfd;
6039 if (DATAGRAM_CONN_P (process))
6040 return process;
6042 proc = get_process (process);
6043 outfd = XPROCESS (proc)->outfd;
6044 if (outfd >= 0)
6045 coding = proc_encode_coding_system[outfd];
6047 /* Make sure the process is really alive. */
6048 if (XPROCESS (proc)->raw_status_new)
6049 update_status (XPROCESS (proc));
6050 if (! EQ (XPROCESS (proc)->status, Qrun))
6051 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6053 if (coding && CODING_REQUIRE_FLUSHING (coding))
6055 coding->mode |= CODING_MODE_LAST_BLOCK;
6056 send_process (proc, "", 0, Qnil);
6059 if (XPROCESS (proc)->pty_flag)
6060 send_process (proc, "\004", 1, Qnil);
6061 else if (EQ (XPROCESS (proc)->type, Qserial))
6063 #ifndef WINDOWSNT
6064 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6065 report_file_error ("Failed tcdrain", Qnil);
6066 #endif /* not WINDOWSNT */
6067 /* Do nothing on Windows because writes are blocking. */
6069 else
6071 struct Lisp_Process *p = XPROCESS (proc);
6072 int old_outfd = p->outfd;
6073 int new_outfd;
6075 #ifdef HAVE_SHUTDOWN
6076 /* If this is a network connection, or socketpair is used
6077 for communication with the subprocess, call shutdown to cause EOF.
6078 (In some old system, shutdown to socketpair doesn't work.
6079 Then we just can't win.) */
6080 if (EQ (p->type, Qnetwork)
6081 || p->infd == old_outfd)
6082 shutdown (old_outfd, 1);
6083 #endif
6084 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6085 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6086 if (new_outfd < 0)
6087 report_file_error ("Opening null device", Qnil);
6088 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6089 p->outfd = new_outfd;
6091 if (!proc_encode_coding_system[new_outfd])
6092 proc_encode_coding_system[new_outfd]
6093 = xmalloc (sizeof (struct coding_system));
6094 if (old_outfd >= 0)
6096 *proc_encode_coding_system[new_outfd]
6097 = *proc_encode_coding_system[old_outfd];
6098 memset (proc_encode_coding_system[old_outfd], 0,
6099 sizeof (struct coding_system));
6101 else
6102 setup_coding_system (p->encode_coding_system,
6103 proc_encode_coding_system[new_outfd]);
6105 return process;
6108 /* The main Emacs thread records child processes in three places:
6110 - Vprocess_alist, for asynchronous subprocesses, which are child
6111 processes visible to Lisp.
6113 - deleted_pid_list, for child processes invisible to Lisp,
6114 typically because of delete-process. These are recorded so that
6115 the processes can be reaped when they exit, so that the operating
6116 system's process table is not cluttered by zombies.
6118 - the local variable PID in Fcall_process, call_process_cleanup and
6119 call_process_kill, for synchronous subprocesses.
6120 record_unwind_protect is used to make sure this process is not
6121 forgotten: if the user interrupts call-process and the child
6122 process refuses to exit immediately even with two C-g's,
6123 call_process_kill adds PID's contents to deleted_pid_list before
6124 returning.
6126 The main Emacs thread invokes waitpid only on child processes that
6127 it creates and that have not been reaped. This avoid races on
6128 platforms such as GTK, where other threads create their own
6129 subprocesses which the main thread should not reap. For example,
6130 if the main thread attempted to reap an already-reaped child, it
6131 might inadvertently reap a GTK-created process that happened to
6132 have the same process ID. */
6134 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6135 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6136 keep track of its own children. GNUstep is similar. */
6138 static void dummy_handler (int sig) {}
6139 static signal_handler_t volatile lib_child_handler;
6141 /* Handle a SIGCHLD signal by looking for known child processes of
6142 Emacs whose status have changed. For each one found, record its
6143 new status.
6145 All we do is change the status; we do not run sentinels or print
6146 notifications. That is saved for the next time keyboard input is
6147 done, in order to avoid timing errors.
6149 ** WARNING: this can be called during garbage collection.
6150 Therefore, it must not be fooled by the presence of mark bits in
6151 Lisp objects.
6153 ** USG WARNING: Although it is not obvious from the documentation
6154 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6155 signal() before executing at least one wait(), otherwise the
6156 handler will be called again, resulting in an infinite loop. The
6157 relevant portion of the documentation reads "SIGCLD signals will be
6158 queued and the signal-catching function will be continually
6159 reentered until the queue is empty". Invoking signal() causes the
6160 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6161 Inc.
6163 ** Malloc WARNING: This should never call malloc either directly or
6164 indirectly; if it does, that is a bug */
6166 static void
6167 handle_child_signal (int sig)
6169 Lisp_Object tail, proc;
6171 /* Find the process that signaled us, and record its status. */
6173 /* The process can have been deleted by Fdelete_process, or have
6174 been started asynchronously by Fcall_process. */
6175 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6177 bool all_pids_are_fixnums
6178 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6179 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6180 Lisp_Object head = XCAR (tail);
6181 Lisp_Object xpid;
6182 if (! CONSP (head))
6183 continue;
6184 xpid = XCAR (head);
6185 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6187 pid_t deleted_pid;
6188 if (INTEGERP (xpid))
6189 deleted_pid = XINT (xpid);
6190 else
6191 deleted_pid = XFLOAT_DATA (xpid);
6192 if (child_status_changed (deleted_pid, 0, 0))
6194 if (STRINGP (XCDR (head)))
6195 unlink (SSDATA (XCDR (head)));
6196 XSETCAR (tail, Qnil);
6201 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6202 FOR_EACH_PROCESS (tail, proc)
6204 struct Lisp_Process *p = XPROCESS (proc);
6205 int status;
6207 if (p->alive
6208 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6210 /* Change the status of the process that was found. */
6211 p->tick = ++process_tick;
6212 p->raw_status = status;
6213 p->raw_status_new = 1;
6215 /* If process has terminated, stop waiting for its output. */
6216 if (WIFSIGNALED (status) || WIFEXITED (status))
6218 bool clear_desc_flag = 0;
6219 p->alive = 0;
6220 if (p->infd >= 0)
6221 clear_desc_flag = 1;
6223 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6224 if (clear_desc_flag)
6226 FD_CLR (p->infd, &input_wait_mask);
6227 FD_CLR (p->infd, &non_keyboard_wait_mask);
6233 lib_child_handler (sig);
6234 #ifdef NS_IMPL_GNUSTEP
6235 /* NSTask in GNUStep sets its child handler each time it is called.
6236 So we must re-set ours. */
6237 catch_child_signal();
6238 #endif
6241 static void
6242 deliver_child_signal (int sig)
6244 deliver_process_signal (sig, handle_child_signal);
6248 static Lisp_Object
6249 exec_sentinel_error_handler (Lisp_Object error_val)
6251 cmd_error_internal (error_val, "error in process sentinel: ");
6252 Vinhibit_quit = Qt;
6253 update_echo_area ();
6254 Fsleep_for (make_number (2), Qnil);
6255 return Qt;
6258 static void
6259 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6261 Lisp_Object sentinel, odeactivate;
6262 struct Lisp_Process *p = XPROCESS (proc);
6263 ptrdiff_t count = SPECPDL_INDEX ();
6264 bool outer_running_asynch_code = running_asynch_code;
6265 int waiting = waiting_for_user_input_p;
6267 if (inhibit_sentinels)
6268 return;
6270 /* No need to gcpro these, because all we do with them later
6271 is test them for EQness, and none of them should be a string. */
6272 odeactivate = Vdeactivate_mark;
6273 #if 0
6274 Lisp_Object obuffer, okeymap;
6275 XSETBUFFER (obuffer, current_buffer);
6276 okeymap = BVAR (current_buffer, keymap);
6277 #endif
6279 /* There's no good reason to let sentinels change the current
6280 buffer, and many callers of accept-process-output, sit-for, and
6281 friends don't expect current-buffer to be changed from under them. */
6282 record_unwind_current_buffer ();
6284 sentinel = p->sentinel;
6286 /* Inhibit quit so that random quits don't screw up a running filter. */
6287 specbind (Qinhibit_quit, Qt);
6288 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6290 /* In case we get recursively called,
6291 and we already saved the match data nonrecursively,
6292 save the same match data in safely recursive fashion. */
6293 if (outer_running_asynch_code)
6295 Lisp_Object tem;
6296 tem = Fmatch_data (Qnil, Qnil, Qnil);
6297 restore_search_regs ();
6298 record_unwind_save_match_data ();
6299 Fset_match_data (tem, Qt);
6302 /* For speed, if a search happens within this code,
6303 save the match data in a special nonrecursive fashion. */
6304 running_asynch_code = 1;
6306 internal_condition_case_1 (read_process_output_call,
6307 list3 (sentinel, proc, reason),
6308 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6309 exec_sentinel_error_handler);
6311 /* If we saved the match data nonrecursively, restore it now. */
6312 restore_search_regs ();
6313 running_asynch_code = outer_running_asynch_code;
6315 Vdeactivate_mark = odeactivate;
6317 /* Restore waiting_for_user_input_p as it was
6318 when we were called, in case the filter clobbered it. */
6319 waiting_for_user_input_p = waiting;
6321 #if 0
6322 if (! EQ (Fcurrent_buffer (), obuffer)
6323 || ! EQ (current_buffer->keymap, okeymap))
6324 #endif
6325 /* But do it only if the caller is actually going to read events.
6326 Otherwise there's no need to make him wake up, and it could
6327 cause trouble (for example it would make sit_for return). */
6328 if (waiting_for_user_input_p == -1)
6329 record_asynch_buffer_change ();
6331 unbind_to (count, Qnil);
6334 /* Report all recent events of a change in process status
6335 (either run the sentinel or output a message).
6336 This is usually done while Emacs is waiting for keyboard input
6337 but can be done at other times. */
6339 static void
6340 status_notify (struct Lisp_Process *deleting_process)
6342 register Lisp_Object proc;
6343 Lisp_Object tail, msg;
6344 struct gcpro gcpro1, gcpro2;
6346 tail = Qnil;
6347 msg = Qnil;
6348 /* We need to gcpro tail; if read_process_output calls a filter
6349 which deletes a process and removes the cons to which tail points
6350 from Vprocess_alist, and then causes a GC, tail is an unprotected
6351 reference. */
6352 GCPRO2 (tail, msg);
6354 /* Set this now, so that if new processes are created by sentinels
6355 that we run, we get called again to handle their status changes. */
6356 update_tick = process_tick;
6358 FOR_EACH_PROCESS (tail, proc)
6360 Lisp_Object symbol;
6361 register struct Lisp_Process *p = XPROCESS (proc);
6363 if (p->tick != p->update_tick)
6365 p->update_tick = p->tick;
6367 /* If process is still active, read any output that remains. */
6368 while (! EQ (p->filter, Qt)
6369 && ! EQ (p->status, Qconnect)
6370 && ! EQ (p->status, Qlisten)
6371 /* Network or serial process not stopped: */
6372 && ! EQ (p->command, Qt)
6373 && p->infd >= 0
6374 && p != deleting_process
6375 && read_process_output (proc, p->infd) > 0);
6377 /* Get the text to use for the message. */
6378 if (p->raw_status_new)
6379 update_status (p);
6380 msg = status_message (p);
6382 /* If process is terminated, deactivate it or delete it. */
6383 symbol = p->status;
6384 if (CONSP (p->status))
6385 symbol = XCAR (p->status);
6387 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6388 || EQ (symbol, Qclosed))
6390 if (delete_exited_processes)
6391 remove_process (proc);
6392 else
6393 deactivate_process (proc);
6396 /* The actions above may have further incremented p->tick.
6397 So set p->update_tick again so that an error in the sentinel will
6398 not cause this code to be run again. */
6399 p->update_tick = p->tick;
6400 /* Now output the message suitably. */
6401 exec_sentinel (proc, msg);
6403 } /* end for */
6405 update_mode_lines = 24; /* In case buffers use %s in mode-line-format. */
6406 UNGCPRO;
6409 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6410 Sinternal_default_process_sentinel, 2, 2, 0,
6411 doc: /* Function used as default sentinel for processes. */)
6412 (Lisp_Object proc, Lisp_Object msg)
6414 Lisp_Object buffer, symbol;
6415 struct Lisp_Process *p;
6416 CHECK_PROCESS (proc);
6417 p = XPROCESS (proc);
6418 buffer = p->buffer;
6419 symbol = p->status;
6420 if (CONSP (symbol))
6421 symbol = XCAR (symbol);
6423 if (!EQ (symbol, Qrun) && !NILP (buffer))
6425 Lisp_Object tem;
6426 struct buffer *old = current_buffer;
6427 ptrdiff_t opoint, opoint_byte;
6428 ptrdiff_t before, before_byte;
6430 /* Avoid error if buffer is deleted
6431 (probably that's why the process is dead, too). */
6432 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6433 return Qnil;
6434 Fset_buffer (buffer);
6436 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6437 msg = (code_convert_string_norecord
6438 (msg, Vlocale_coding_system, 1));
6440 opoint = PT;
6441 opoint_byte = PT_BYTE;
6442 /* Insert new output into buffer
6443 at the current end-of-output marker,
6444 thus preserving logical ordering of input and output. */
6445 if (XMARKER (p->mark)->buffer)
6446 Fgoto_char (p->mark);
6447 else
6448 SET_PT_BOTH (ZV, ZV_BYTE);
6450 before = PT;
6451 before_byte = PT_BYTE;
6453 tem = BVAR (current_buffer, read_only);
6454 bset_read_only (current_buffer, Qnil);
6455 insert_string ("\nProcess ");
6456 { /* FIXME: temporary kludge. */
6457 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6458 insert_string (" ");
6459 Finsert (1, &msg);
6460 bset_read_only (current_buffer, tem);
6461 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6463 if (opoint >= before)
6464 SET_PT_BOTH (opoint + (PT - before),
6465 opoint_byte + (PT_BYTE - before_byte));
6466 else
6467 SET_PT_BOTH (opoint, opoint_byte);
6469 set_buffer_internal (old);
6471 return Qnil;
6475 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6476 Sset_process_coding_system, 1, 3, 0,
6477 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6478 DECODING will be used to decode subprocess output and ENCODING to
6479 encode subprocess input. */)
6480 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6482 register struct Lisp_Process *p;
6484 CHECK_PROCESS (process);
6485 p = XPROCESS (process);
6486 if (p->infd < 0)
6487 error ("Input file descriptor of %s closed", SDATA (p->name));
6488 if (p->outfd < 0)
6489 error ("Output file descriptor of %s closed", SDATA (p->name));
6490 Fcheck_coding_system (decoding);
6491 Fcheck_coding_system (encoding);
6492 encoding = coding_inherit_eol_type (encoding, Qnil);
6493 pset_decode_coding_system (p, decoding);
6494 pset_encode_coding_system (p, encoding);
6495 setup_process_coding_systems (process);
6497 return Qnil;
6500 DEFUN ("process-coding-system",
6501 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6502 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6503 (register Lisp_Object process)
6505 CHECK_PROCESS (process);
6506 return Fcons (XPROCESS (process)->decode_coding_system,
6507 XPROCESS (process)->encode_coding_system);
6510 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6511 Sset_process_filter_multibyte, 2, 2, 0,
6512 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6513 If FLAG is non-nil, the filter is given multibyte strings.
6514 If FLAG is nil, the filter is given unibyte strings. In this case,
6515 all character code conversion except for end-of-line conversion is
6516 suppressed. */)
6517 (Lisp_Object process, Lisp_Object flag)
6519 register struct Lisp_Process *p;
6521 CHECK_PROCESS (process);
6522 p = XPROCESS (process);
6523 if (NILP (flag))
6524 pset_decode_coding_system
6525 (p, raw_text_coding_system (p->decode_coding_system));
6526 setup_process_coding_systems (process);
6528 return Qnil;
6531 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6532 Sprocess_filter_multibyte_p, 1, 1, 0,
6533 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6534 (Lisp_Object process)
6536 register struct Lisp_Process *p;
6537 struct coding_system *coding;
6539 CHECK_PROCESS (process);
6540 p = XPROCESS (process);
6541 coding = proc_decode_coding_system[p->infd];
6542 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6548 # ifdef HAVE_GPM
6550 void
6551 add_gpm_wait_descriptor (int desc)
6553 add_keyboard_wait_descriptor (desc);
6556 void
6557 delete_gpm_wait_descriptor (int desc)
6559 delete_keyboard_wait_descriptor (desc);
6562 # endif
6564 # ifdef USABLE_SIGIO
6566 /* Return true if *MASK has a bit set
6567 that corresponds to one of the keyboard input descriptors. */
6569 static bool
6570 keyboard_bit_set (fd_set *mask)
6572 int fd;
6574 for (fd = 0; fd <= max_input_desc; fd++)
6575 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6576 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6577 return 1;
6579 return 0;
6581 # endif
6583 #else /* not subprocesses */
6585 /* Defined on msdos.c. */
6586 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6587 struct timespec *, void *);
6589 /* Implementation of wait_reading_process_output, assuming that there
6590 are no subprocesses. Used only by the MS-DOS build.
6592 Wait for timeout to elapse and/or keyboard input to be available.
6594 TIME_LIMIT is:
6595 timeout in seconds
6596 If negative, gobble data immediately available but don't wait for any.
6598 NSECS is:
6599 an additional duration to wait, measured in nanoseconds
6600 If TIME_LIMIT is zero, then:
6601 If NSECS == 0, there is no limit.
6602 If NSECS > 0, the timeout consists of NSECS only.
6603 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6605 READ_KBD is:
6606 0 to ignore keyboard input, or
6607 1 to return when input is available, or
6608 -1 means caller will actually read the input, so don't throw to
6609 the quit handler.
6611 see full version for other parameters. We know that wait_proc will
6612 always be NULL, since `subprocesses' isn't defined.
6614 DO_DISPLAY means redisplay should be done to show subprocess
6615 output that arrives.
6617 Return true if we received input from any process. */
6619 bool
6620 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6621 bool do_display,
6622 Lisp_Object wait_for_cell,
6623 struct Lisp_Process *wait_proc, int just_wait_proc)
6625 register int nfds;
6626 struct timespec end_time, timeout;
6628 if (time_limit < 0)
6630 time_limit = 0;
6631 nsecs = -1;
6633 else if (TYPE_MAXIMUM (time_t) < time_limit)
6634 time_limit = TYPE_MAXIMUM (time_t);
6636 /* What does time_limit really mean? */
6637 if (time_limit || nsecs > 0)
6639 timeout = make_timespec (time_limit, nsecs);
6640 end_time = timespec_add (current_timespec (), timeout);
6643 /* Turn off periodic alarms (in case they are in use)
6644 and then turn off any other atimers,
6645 because the select emulator uses alarms. */
6646 stop_polling ();
6647 turn_on_atimers (0);
6649 while (1)
6651 bool timeout_reduced_for_timers = 0;
6652 fd_set waitchannels;
6653 int xerrno;
6655 /* If calling from keyboard input, do not quit
6656 since we want to return C-g as an input character.
6657 Otherwise, do pending quit if requested. */
6658 if (read_kbd >= 0)
6659 QUIT;
6661 /* Exit now if the cell we're waiting for became non-nil. */
6662 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6663 break;
6665 /* Compute time from now till when time limit is up. */
6666 /* Exit if already run out. */
6667 if (nsecs < 0)
6669 /* A negative timeout means
6670 gobble output available now
6671 but don't wait at all. */
6673 timeout = make_timespec (0, 0);
6675 else if (time_limit || nsecs > 0)
6677 struct timespec now = current_timespec ();
6678 if (timespec_cmp (end_time, now) <= 0)
6679 break;
6680 timeout = timespec_sub (end_time, now);
6682 else
6684 timeout = make_timespec (100000, 0);
6687 /* If our caller will not immediately handle keyboard events,
6688 run timer events directly.
6689 (Callers that will immediately read keyboard events
6690 call timer_delay on their own.) */
6691 if (NILP (wait_for_cell))
6693 struct timespec timer_delay;
6697 unsigned old_timers_run = timers_run;
6698 timer_delay = timer_check ();
6699 if (timers_run != old_timers_run && do_display)
6700 /* We must retry, since a timer may have requeued itself
6701 and that could alter the time delay. */
6702 redisplay_preserve_echo_area (14);
6703 else
6704 break;
6706 while (!detect_input_pending ());
6708 /* If there is unread keyboard input, also return. */
6709 if (read_kbd != 0
6710 && requeued_events_pending_p ())
6711 break;
6713 if (timespec_valid_p (timer_delay) && nsecs >= 0)
6715 if (timespec_cmp (timer_delay, timeout) < 0)
6717 timeout = timer_delay;
6718 timeout_reduced_for_timers = 1;
6723 /* Cause C-g and alarm signals to take immediate action,
6724 and cause input available signals to zero out timeout. */
6725 if (read_kbd < 0)
6726 set_waiting_for_input (&timeout);
6728 /* If a frame has been newly mapped and needs updating,
6729 reprocess its display stuff. */
6730 if (frame_garbaged && do_display)
6732 clear_waiting_for_input ();
6733 redisplay_preserve_echo_area (15);
6734 if (read_kbd < 0)
6735 set_waiting_for_input (&timeout);
6738 /* Wait till there is something to do. */
6739 FD_ZERO (&waitchannels);
6740 if (read_kbd && detect_input_pending ())
6741 nfds = 0;
6742 else
6744 if (read_kbd || !NILP (wait_for_cell))
6745 FD_SET (0, &waitchannels);
6746 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
6749 xerrno = errno;
6751 /* Make C-g and alarm signals set flags again */
6752 clear_waiting_for_input ();
6754 /* If we woke up due to SIGWINCH, actually change size now. */
6755 do_pending_window_change (0);
6757 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
6758 /* We waited the full specified time, so return now. */
6759 break;
6761 if (nfds == -1)
6763 /* If the system call was interrupted, then go around the
6764 loop again. */
6765 if (xerrno == EINTR)
6766 FD_ZERO (&waitchannels);
6767 else
6768 report_file_errno ("Failed select", Qnil, xerrno);
6771 /* Check for keyboard input */
6773 if (read_kbd
6774 && detect_input_pending_run_timers (do_display))
6776 swallow_events (do_display);
6777 if (detect_input_pending_run_timers (do_display))
6778 break;
6781 /* If there is unread keyboard input, also return. */
6782 if (read_kbd
6783 && requeued_events_pending_p ())
6784 break;
6786 /* If wait_for_cell. check for keyboard input
6787 but don't run any timers.
6788 ??? (It seems wrong to me to check for keyboard
6789 input at all when wait_for_cell, but the code
6790 has been this way since July 1994.
6791 Try changing this after version 19.31.) */
6792 if (! NILP (wait_for_cell)
6793 && detect_input_pending ())
6795 swallow_events (do_display);
6796 if (detect_input_pending ())
6797 break;
6800 /* Exit now if the cell we're waiting for became non-nil. */
6801 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6802 break;
6805 start_polling ();
6807 return 0;
6810 #endif /* not subprocesses */
6812 /* The following functions are needed even if async subprocesses are
6813 not supported. Some of them are no-op stubs in that case. */
6815 /* Add DESC to the set of keyboard input descriptors. */
6817 void
6818 add_keyboard_wait_descriptor (int desc)
6820 #ifdef subprocesses /* actually means "not MSDOS" */
6821 FD_SET (desc, &input_wait_mask);
6822 FD_SET (desc, &non_process_wait_mask);
6823 if (desc > max_input_desc)
6824 max_input_desc = desc;
6825 #endif
6828 /* From now on, do not expect DESC to give keyboard input. */
6830 void
6831 delete_keyboard_wait_descriptor (int desc)
6833 #ifdef subprocesses
6834 FD_CLR (desc, &input_wait_mask);
6835 FD_CLR (desc, &non_process_wait_mask);
6836 delete_input_desc (desc);
6837 #endif
6840 /* Setup coding systems of PROCESS. */
6842 void
6843 setup_process_coding_systems (Lisp_Object process)
6845 #ifdef subprocesses
6846 struct Lisp_Process *p = XPROCESS (process);
6847 int inch = p->infd;
6848 int outch = p->outfd;
6849 Lisp_Object coding_system;
6851 if (inch < 0 || outch < 0)
6852 return;
6854 if (!proc_decode_coding_system[inch])
6855 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
6856 coding_system = p->decode_coding_system;
6857 if (EQ (p->filter, Qinternal_default_process_filter)
6858 && BUFFERP (p->buffer))
6860 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
6861 coding_system = raw_text_coding_system (coding_system);
6863 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
6865 if (!proc_encode_coding_system[outch])
6866 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
6867 setup_coding_system (p->encode_coding_system,
6868 proc_encode_coding_system[outch]);
6869 #endif
6872 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
6873 doc: /* Return the (or a) process associated with BUFFER.
6874 BUFFER may be a buffer or the name of one. */)
6875 (register Lisp_Object buffer)
6877 #ifdef subprocesses
6878 register Lisp_Object buf, tail, proc;
6880 if (NILP (buffer)) return Qnil;
6881 buf = Fget_buffer (buffer);
6882 if (NILP (buf)) return Qnil;
6884 FOR_EACH_PROCESS (tail, proc)
6885 if (EQ (XPROCESS (proc)->buffer, buf))
6886 return proc;
6887 #endif /* subprocesses */
6888 return Qnil;
6891 DEFUN ("process-inherit-coding-system-flag",
6892 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
6893 1, 1, 0,
6894 doc: /* Return the value of inherit-coding-system flag for PROCESS.
6895 If this flag is t, `buffer-file-coding-system' of the buffer
6896 associated with PROCESS will inherit the coding system used to decode
6897 the process output. */)
6898 (register Lisp_Object process)
6900 #ifdef subprocesses
6901 CHECK_PROCESS (process);
6902 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
6903 #else
6904 /* Ignore the argument and return the value of
6905 inherit-process-coding-system. */
6906 return inherit_process_coding_system ? Qt : Qnil;
6907 #endif
6910 /* Kill all processes associated with `buffer'.
6911 If `buffer' is nil, kill all processes */
6913 void
6914 kill_buffer_processes (Lisp_Object buffer)
6916 #ifdef subprocesses
6917 Lisp_Object tail, proc;
6919 FOR_EACH_PROCESS (tail, proc)
6920 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
6922 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6923 Fdelete_process (proc);
6924 else if (XPROCESS (proc)->infd >= 0)
6925 process_send_signal (proc, SIGHUP, Qnil, 1);
6927 #else /* subprocesses */
6928 /* Since we have no subprocesses, this does nothing. */
6929 #endif /* subprocesses */
6932 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
6933 Swaiting_for_user_input_p, 0, 0, 0,
6934 doc: /* Return non-nil if Emacs is waiting for input from the user.
6935 This is intended for use by asynchronous process output filters and sentinels. */)
6936 (void)
6938 #ifdef subprocesses
6939 return (waiting_for_user_input_p ? Qt : Qnil);
6940 #else
6941 return Qnil;
6942 #endif
6945 /* Stop reading input from keyboard sources. */
6947 void
6948 hold_keyboard_input (void)
6950 kbd_is_on_hold = 1;
6953 /* Resume reading input from keyboard sources. */
6955 void
6956 unhold_keyboard_input (void)
6958 kbd_is_on_hold = 0;
6961 /* Return true if keyboard input is on hold, zero otherwise. */
6963 bool
6964 kbd_on_hold_p (void)
6966 return kbd_is_on_hold;
6970 /* Enumeration of and access to system processes a-la ps(1). */
6972 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
6973 0, 0, 0,
6974 doc: /* Return a list of numerical process IDs of all running processes.
6975 If this functionality is unsupported, return nil.
6977 See `process-attributes' for getting attributes of a process given its ID. */)
6978 (void)
6980 return list_system_processes ();
6983 DEFUN ("process-attributes", Fprocess_attributes,
6984 Sprocess_attributes, 1, 1, 0,
6985 doc: /* Return attributes of the process given by its PID, a number.
6987 Value is an alist where each element is a cons cell of the form
6989 \(KEY . VALUE)
6991 If this functionality is unsupported, the value is nil.
6993 See `list-system-processes' for getting a list of all process IDs.
6995 The KEYs of the attributes that this function may return are listed
6996 below, together with the type of the associated VALUE (in parentheses).
6997 Not all platforms support all of these attributes; unsupported
6998 attributes will not appear in the returned alist.
6999 Unless explicitly indicated otherwise, numbers can have either
7000 integer or floating point values.
7002 euid -- Effective user User ID of the process (number)
7003 user -- User name corresponding to euid (string)
7004 egid -- Effective user Group ID of the process (number)
7005 group -- Group name corresponding to egid (string)
7006 comm -- Command name (executable name only) (string)
7007 state -- Process state code, such as "S", "R", or "T" (string)
7008 ppid -- Parent process ID (number)
7009 pgrp -- Process group ID (number)
7010 sess -- Session ID, i.e. process ID of session leader (number)
7011 ttname -- Controlling tty name (string)
7012 tpgid -- ID of foreground process group on the process's tty (number)
7013 minflt -- number of minor page faults (number)
7014 majflt -- number of major page faults (number)
7015 cminflt -- cumulative number of minor page faults (number)
7016 cmajflt -- cumulative number of major page faults (number)
7017 utime -- user time used by the process, in (current-time) format,
7018 which is a list of integers (HIGH LOW USEC PSEC)
7019 stime -- system time used by the process (current-time)
7020 time -- sum of utime and stime (current-time)
7021 cutime -- user time used by the process and its children (current-time)
7022 cstime -- system time used by the process and its children (current-time)
7023 ctime -- sum of cutime and cstime (current-time)
7024 pri -- priority of the process (number)
7025 nice -- nice value of the process (number)
7026 thcount -- process thread count (number)
7027 start -- time the process started (current-time)
7028 vsize -- virtual memory size of the process in KB's (number)
7029 rss -- resident set size of the process in KB's (number)
7030 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7031 pcpu -- percents of CPU time used by the process (floating-point number)
7032 pmem -- percents of total physical memory used by process's resident set
7033 (floating-point number)
7034 args -- command line which invoked the process (string). */)
7035 ( Lisp_Object pid)
7037 return system_process_attributes (pid);
7040 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7041 Invoke this after init_process_emacs, and after glib and/or GNUstep
7042 futz with the SIGCHLD handler, but before Emacs forks any children.
7043 This function's caller should block SIGCHLD. */
7045 #ifndef NS_IMPL_GNUSTEP
7046 static
7047 #endif
7048 void
7049 catch_child_signal (void)
7051 struct sigaction action, old_action;
7052 emacs_sigaction_init (&action, deliver_child_signal);
7053 block_child_signal ();
7054 sigaction (SIGCHLD, &action, &old_action);
7055 eassert (! (old_action.sa_flags & SA_SIGINFO));
7057 if (old_action.sa_handler != deliver_child_signal)
7058 lib_child_handler
7059 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7060 ? dummy_handler
7061 : old_action.sa_handler);
7062 unblock_child_signal ();
7066 /* This is not called "init_process" because that is the name of a
7067 Mach system call, so it would cause problems on Darwin systems. */
7068 void
7069 init_process_emacs (void)
7071 #ifdef subprocesses
7072 register int i;
7074 inhibit_sentinels = 0;
7076 #ifndef CANNOT_DUMP
7077 if (! noninteractive || initialized)
7078 #endif
7080 #if defined HAVE_GLIB && !defined WINDOWSNT
7081 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7082 this should always fail, but is enough to initialize glib's
7083 private SIGCHLD handler, allowing catch_child_signal to copy
7084 it into lib_child_handler. */
7085 g_source_unref (g_child_watch_source_new (getpid ()));
7086 #endif
7087 catch_child_signal ();
7090 FD_ZERO (&input_wait_mask);
7091 FD_ZERO (&non_keyboard_wait_mask);
7092 FD_ZERO (&non_process_wait_mask);
7093 FD_ZERO (&write_mask);
7094 max_process_desc = max_input_desc = -1;
7095 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7097 #ifdef NON_BLOCKING_CONNECT
7098 FD_ZERO (&connect_wait_mask);
7099 num_pending_connects = 0;
7100 #endif
7102 #ifdef ADAPTIVE_READ_BUFFERING
7103 process_output_delay_count = 0;
7104 process_output_skip = 0;
7105 #endif
7107 /* Don't do this, it caused infinite select loops. The display
7108 method should call add_keyboard_wait_descriptor on stdin if it
7109 needs that. */
7110 #if 0
7111 FD_SET (0, &input_wait_mask);
7112 #endif
7114 Vprocess_alist = Qnil;
7115 deleted_pid_list = Qnil;
7116 for (i = 0; i < FD_SETSIZE; i++)
7118 chan_process[i] = Qnil;
7119 proc_buffered_char[i] = -1;
7121 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7122 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7123 #ifdef DATAGRAM_SOCKETS
7124 memset (datagram_address, 0, sizeof datagram_address);
7125 #endif
7128 Lisp_Object subfeatures = Qnil;
7129 const struct socket_options *sopt;
7131 #define ADD_SUBFEATURE(key, val) \
7132 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7134 #ifdef NON_BLOCKING_CONNECT
7135 ADD_SUBFEATURE (QCnowait, Qt);
7136 #endif
7137 #ifdef DATAGRAM_SOCKETS
7138 ADD_SUBFEATURE (QCtype, Qdatagram);
7139 #endif
7140 #ifdef HAVE_SEQPACKET
7141 ADD_SUBFEATURE (QCtype, Qseqpacket);
7142 #endif
7143 #ifdef HAVE_LOCAL_SOCKETS
7144 ADD_SUBFEATURE (QCfamily, Qlocal);
7145 #endif
7146 ADD_SUBFEATURE (QCfamily, Qipv4);
7147 #ifdef AF_INET6
7148 ADD_SUBFEATURE (QCfamily, Qipv6);
7149 #endif
7150 #ifdef HAVE_GETSOCKNAME
7151 ADD_SUBFEATURE (QCservice, Qt);
7152 #endif
7153 ADD_SUBFEATURE (QCserver, Qt);
7155 for (sopt = socket_options; sopt->name; sopt++)
7156 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7158 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7161 #if defined (DARWIN_OS)
7162 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7163 processes. As such, we only change the default value. */
7164 if (initialized)
7166 char const *release = (STRINGP (Voperating_system_release)
7167 ? SSDATA (Voperating_system_release)
7168 : 0);
7169 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7170 Vprocess_connection_type = Qnil;
7173 #endif
7174 #endif /* subprocesses */
7175 kbd_is_on_hold = 0;
7178 void
7179 syms_of_process (void)
7181 #ifdef subprocesses
7183 DEFSYM (Qprocessp, "processp");
7184 DEFSYM (Qrun, "run");
7185 DEFSYM (Qstop, "stop");
7186 DEFSYM (Qsignal, "signal");
7188 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7189 here again.
7191 Qexit = intern_c_string ("exit");
7192 staticpro (&Qexit); */
7194 DEFSYM (Qopen, "open");
7195 DEFSYM (Qclosed, "closed");
7196 DEFSYM (Qconnect, "connect");
7197 DEFSYM (Qfailed, "failed");
7198 DEFSYM (Qlisten, "listen");
7199 DEFSYM (Qlocal, "local");
7200 DEFSYM (Qipv4, "ipv4");
7201 #ifdef AF_INET6
7202 DEFSYM (Qipv6, "ipv6");
7203 #endif
7204 DEFSYM (Qdatagram, "datagram");
7205 DEFSYM (Qseqpacket, "seqpacket");
7207 DEFSYM (QCport, ":port");
7208 DEFSYM (QCspeed, ":speed");
7209 DEFSYM (QCprocess, ":process");
7211 DEFSYM (QCbytesize, ":bytesize");
7212 DEFSYM (QCstopbits, ":stopbits");
7213 DEFSYM (QCparity, ":parity");
7214 DEFSYM (Qodd, "odd");
7215 DEFSYM (Qeven, "even");
7216 DEFSYM (QCflowcontrol, ":flowcontrol");
7217 DEFSYM (Qhw, "hw");
7218 DEFSYM (Qsw, "sw");
7219 DEFSYM (QCsummary, ":summary");
7221 DEFSYM (Qreal, "real");
7222 DEFSYM (Qnetwork, "network");
7223 DEFSYM (Qserial, "serial");
7224 DEFSYM (QCbuffer, ":buffer");
7225 DEFSYM (QChost, ":host");
7226 DEFSYM (QCservice, ":service");
7227 DEFSYM (QClocal, ":local");
7228 DEFSYM (QCremote, ":remote");
7229 DEFSYM (QCcoding, ":coding");
7230 DEFSYM (QCserver, ":server");
7231 DEFSYM (QCnowait, ":nowait");
7232 DEFSYM (QCsentinel, ":sentinel");
7233 DEFSYM (QClog, ":log");
7234 DEFSYM (QCnoquery, ":noquery");
7235 DEFSYM (QCstop, ":stop");
7236 DEFSYM (QCoptions, ":options");
7237 DEFSYM (QCplist, ":plist");
7239 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7241 staticpro (&Vprocess_alist);
7242 staticpro (&deleted_pid_list);
7244 #endif /* subprocesses */
7246 DEFSYM (QCname, ":name");
7247 DEFSYM (QCtype, ":type");
7249 DEFSYM (Qeuid, "euid");
7250 DEFSYM (Qegid, "egid");
7251 DEFSYM (Quser, "user");
7252 DEFSYM (Qgroup, "group");
7253 DEFSYM (Qcomm, "comm");
7254 DEFSYM (Qstate, "state");
7255 DEFSYM (Qppid, "ppid");
7256 DEFSYM (Qpgrp, "pgrp");
7257 DEFSYM (Qsess, "sess");
7258 DEFSYM (Qttname, "ttname");
7259 DEFSYM (Qtpgid, "tpgid");
7260 DEFSYM (Qminflt, "minflt");
7261 DEFSYM (Qmajflt, "majflt");
7262 DEFSYM (Qcminflt, "cminflt");
7263 DEFSYM (Qcmajflt, "cmajflt");
7264 DEFSYM (Qutime, "utime");
7265 DEFSYM (Qstime, "stime");
7266 DEFSYM (Qtime, "time");
7267 DEFSYM (Qcutime, "cutime");
7268 DEFSYM (Qcstime, "cstime");
7269 DEFSYM (Qctime, "ctime");
7270 DEFSYM (Qinternal_default_process_sentinel,
7271 "internal-default-process-sentinel");
7272 DEFSYM (Qinternal_default_process_filter,
7273 "internal-default-process-filter");
7274 DEFSYM (Qpri, "pri");
7275 DEFSYM (Qnice, "nice");
7276 DEFSYM (Qthcount, "thcount");
7277 DEFSYM (Qstart, "start");
7278 DEFSYM (Qvsize, "vsize");
7279 DEFSYM (Qrss, "rss");
7280 DEFSYM (Qetime, "etime");
7281 DEFSYM (Qpcpu, "pcpu");
7282 DEFSYM (Qpmem, "pmem");
7283 DEFSYM (Qargs, "args");
7285 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7286 doc: /* Non-nil means delete processes immediately when they exit.
7287 A value of nil means don't delete them until `list-processes' is run. */);
7289 delete_exited_processes = 1;
7291 #ifdef subprocesses
7292 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7293 doc: /* Control type of device used to communicate with subprocesses.
7294 Values are nil to use a pipe, or t or `pty' to use a pty.
7295 The value has no effect if the system has no ptys or if all ptys are busy:
7296 then a pipe is used in any case.
7297 The value takes effect when `start-process' is called. */);
7298 Vprocess_connection_type = Qt;
7300 #ifdef ADAPTIVE_READ_BUFFERING
7301 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7302 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7303 On some systems, when Emacs reads the output from a subprocess, the output data
7304 is read in very small blocks, potentially resulting in very poor performance.
7305 This behavior can be remedied to some extent by setting this variable to a
7306 non-nil value, as it will automatically delay reading from such processes, to
7307 allow them to produce more output before Emacs tries to read it.
7308 If the value is t, the delay is reset after each write to the process; any other
7309 non-nil value means that the delay is not reset on write.
7310 The variable takes effect when `start-process' is called. */);
7311 Vprocess_adaptive_read_buffering = Qt;
7312 #endif
7314 defsubr (&Sprocessp);
7315 defsubr (&Sget_process);
7316 defsubr (&Sdelete_process);
7317 defsubr (&Sprocess_status);
7318 defsubr (&Sprocess_exit_status);
7319 defsubr (&Sprocess_id);
7320 defsubr (&Sprocess_name);
7321 defsubr (&Sprocess_tty_name);
7322 defsubr (&Sprocess_command);
7323 defsubr (&Sset_process_buffer);
7324 defsubr (&Sprocess_buffer);
7325 defsubr (&Sprocess_mark);
7326 defsubr (&Sset_process_filter);
7327 defsubr (&Sprocess_filter);
7328 defsubr (&Sset_process_sentinel);
7329 defsubr (&Sprocess_sentinel);
7330 defsubr (&Sset_process_window_size);
7331 defsubr (&Sset_process_inherit_coding_system_flag);
7332 defsubr (&Sset_process_query_on_exit_flag);
7333 defsubr (&Sprocess_query_on_exit_flag);
7334 defsubr (&Sprocess_contact);
7335 defsubr (&Sprocess_plist);
7336 defsubr (&Sset_process_plist);
7337 defsubr (&Sprocess_list);
7338 defsubr (&Sstart_process);
7339 defsubr (&Sserial_process_configure);
7340 defsubr (&Smake_serial_process);
7341 defsubr (&Sset_network_process_option);
7342 defsubr (&Smake_network_process);
7343 defsubr (&Sformat_network_address);
7344 defsubr (&Snetwork_interface_list);
7345 defsubr (&Snetwork_interface_info);
7346 #ifdef DATAGRAM_SOCKETS
7347 defsubr (&Sprocess_datagram_address);
7348 defsubr (&Sset_process_datagram_address);
7349 #endif
7350 defsubr (&Saccept_process_output);
7351 defsubr (&Sprocess_send_region);
7352 defsubr (&Sprocess_send_string);
7353 defsubr (&Sinterrupt_process);
7354 defsubr (&Skill_process);
7355 defsubr (&Squit_process);
7356 defsubr (&Sstop_process);
7357 defsubr (&Scontinue_process);
7358 defsubr (&Sprocess_running_child_p);
7359 defsubr (&Sprocess_send_eof);
7360 defsubr (&Ssignal_process);
7361 defsubr (&Swaiting_for_user_input_p);
7362 defsubr (&Sprocess_type);
7363 defsubr (&Sinternal_default_process_sentinel);
7364 defsubr (&Sinternal_default_process_filter);
7365 defsubr (&Sset_process_coding_system);
7366 defsubr (&Sprocess_coding_system);
7367 defsubr (&Sset_process_filter_multibyte);
7368 defsubr (&Sprocess_filter_multibyte_p);
7370 #endif /* subprocesses */
7372 defsubr (&Sget_buffer_process);
7373 defsubr (&Sprocess_inherit_coding_system_flag);
7374 defsubr (&Slist_system_processes);
7375 defsubr (&Sprocess_attributes);