Warn against renaming git-bzr remote; nfc.
[emacs.git] / src / process.c
blobfdb0501f9ecdd897a98ef9645f25b18efad72177
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2014
4 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
27 #include <sys/file.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30 #include <fcntl.h>
32 #include "lisp.h"
34 /* Only MS-DOS does not define `subprocesses'. */
35 #ifdef subprocesses
37 #include <sys/socket.h>
38 #include <netdb.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
42 /* Are local (unix) sockets supported? */
43 #if defined (HAVE_SYS_UN_H)
44 #if !defined (AF_LOCAL) && defined (AF_UNIX)
45 #define AF_LOCAL AF_UNIX
46 #endif
47 #ifdef AF_LOCAL
48 #define HAVE_LOCAL_SOCKETS
49 #include <sys/un.h>
50 #endif
51 #endif
53 #include <sys/ioctl.h>
54 #if defined (HAVE_NET_IF_H)
55 #include <net/if.h>
56 #endif /* HAVE_NET_IF_H */
58 #if defined (HAVE_IFADDRS_H)
59 /* Must be after net/if.h */
60 #include <ifaddrs.h>
62 /* We only use structs from this header when we use getifaddrs. */
63 #if defined (HAVE_NET_IF_DL_H)
64 #include <net/if_dl.h>
65 #endif
67 #endif
69 #ifdef NEED_BSDTTY
70 #include <bsdtty.h>
71 #endif
73 #ifdef USG5_4
74 # include <sys/stream.h>
75 # include <sys/stropts.h>
76 #endif
78 #ifdef HAVE_RES_INIT
79 #include <arpa/nameser.h>
80 #include <resolv.h>
81 #endif
83 #ifdef HAVE_UTIL_H
84 #include <util.h>
85 #endif
87 #ifdef HAVE_PTY_H
88 #include <pty.h>
89 #endif
91 #include <c-ctype.h>
92 #include <sig2str.h>
93 #include <verify.h>
95 #endif /* subprocesses */
97 #include "systime.h"
98 #include "systty.h"
100 #include "window.h"
101 #include "character.h"
102 #include "buffer.h"
103 #include "coding.h"
104 #include "process.h"
105 #include "frame.h"
106 #include "termhooks.h"
107 #include "termopts.h"
108 #include "commands.h"
109 #include "keyboard.h"
110 #include "blockinput.h"
111 #include "dispextern.h"
112 #include "composite.h"
113 #include "atimer.h"
114 #include "sysselect.h"
115 #include "syssignal.h"
116 #include "syswait.h"
117 #ifdef HAVE_GNUTLS
118 #include "gnutls.h"
119 #endif
121 #ifdef HAVE_WINDOW_SYSTEM
122 #include TERM_HEADER
123 #endif /* HAVE_WINDOW_SYSTEM */
125 #ifdef HAVE_GLIB
126 #include "xgselect.h"
127 #ifndef WINDOWSNT
128 #include <glib.h>
129 #endif
130 #endif
132 #ifdef WINDOWSNT
133 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
134 struct timespec *, void *);
135 #endif
137 /* Work around GCC 4.7.0 bug with strict overflow checking; see
138 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
139 These lines can be removed once the GCC bug is fixed. */
140 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
141 # pragma GCC diagnostic ignored "-Wstrict-overflow"
142 #endif
144 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
145 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
146 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
147 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
148 Lisp_Object QCname, QCtype;
150 /* True if keyboard input is on hold, zero otherwise. */
152 static bool kbd_is_on_hold;
154 /* Nonzero means don't run process sentinels. This is used
155 when exiting. */
156 bool inhibit_sentinels;
158 #ifdef subprocesses
160 #ifndef SOCK_CLOEXEC
161 # define SOCK_CLOEXEC 0
162 #endif
164 #ifndef HAVE_ACCEPT4
166 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
168 static int
169 close_on_exec (int fd)
171 if (0 <= fd)
172 fcntl (fd, F_SETFD, FD_CLOEXEC);
173 return fd;
176 static int
177 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
179 return close_on_exec (accept (sockfd, addr, addrlen));
182 static int
183 process_socket (int domain, int type, int protocol)
185 return close_on_exec (socket (domain, type, protocol));
187 # undef socket
188 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
189 #endif
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) \
357 (PROCESSP (proc) && \
358 XPROCESS (proc)->infd >= 0 && \
359 datagram_address[XPROCESS (proc)->infd].sa != 0)
360 #else
361 #define DATAGRAM_CHAN_P(chan) (0)
362 #define DATAGRAM_CONN_P(proc) (0)
363 #endif
365 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
366 a `for' loop which iterates over processes from Vprocess_alist. */
368 #define FOR_EACH_PROCESS(list_var, proc_var) \
369 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
371 /* These setters are used only in this file, so they can be private. */
372 static void
373 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
375 p->buffer = val;
377 static void
378 pset_command (struct Lisp_Process *p, Lisp_Object val)
380 p->command = val;
382 static void
383 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
385 p->decode_coding_system = val;
387 static void
388 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
390 p->decoding_buf = val;
392 static void
393 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
395 p->encode_coding_system = val;
397 static void
398 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
400 p->encoding_buf = val;
402 static void
403 pset_filter (struct Lisp_Process *p, Lisp_Object val)
405 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
407 static void
408 pset_log (struct Lisp_Process *p, Lisp_Object val)
410 p->log = val;
412 static void
413 pset_mark (struct Lisp_Process *p, Lisp_Object val)
415 p->mark = val;
417 static void
418 pset_name (struct Lisp_Process *p, Lisp_Object val)
420 p->name = val;
422 static void
423 pset_plist (struct Lisp_Process *p, Lisp_Object val)
425 p->plist = val;
427 static void
428 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
430 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
432 static void
433 pset_status (struct Lisp_Process *p, Lisp_Object val)
435 p->status = val;
437 static void
438 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
440 p->tty_name = val;
442 static void
443 pset_type (struct Lisp_Process *p, Lisp_Object val)
445 p->type = val;
447 static void
448 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
450 p->write_queue = val;
455 static struct fd_callback_data
457 fd_callback func;
458 void *data;
459 #define FOR_READ 1
460 #define FOR_WRITE 2
461 int condition; /* mask of the defines above. */
462 } fd_callback_info[FD_SETSIZE];
465 /* Add a file descriptor FD to be monitored for when read is possible.
466 When read is possible, call FUNC with argument DATA. */
468 void
469 add_read_fd (int fd, fd_callback func, void *data)
471 eassert (fd < FD_SETSIZE);
472 add_keyboard_wait_descriptor (fd);
474 fd_callback_info[fd].func = func;
475 fd_callback_info[fd].data = data;
476 fd_callback_info[fd].condition |= FOR_READ;
479 /* Stop monitoring file descriptor FD for when read is possible. */
481 void
482 delete_read_fd (int fd)
484 eassert (fd < FD_SETSIZE);
485 delete_keyboard_wait_descriptor (fd);
487 fd_callback_info[fd].condition &= ~FOR_READ;
488 if (fd_callback_info[fd].condition == 0)
490 fd_callback_info[fd].func = 0;
491 fd_callback_info[fd].data = 0;
495 /* Add a file descriptor FD to be monitored for when write is possible.
496 When write is possible, call FUNC with argument DATA. */
498 void
499 add_write_fd (int fd, fd_callback func, void *data)
501 eassert (fd < FD_SETSIZE);
502 FD_SET (fd, &write_mask);
503 if (fd > max_input_desc)
504 max_input_desc = fd;
506 fd_callback_info[fd].func = func;
507 fd_callback_info[fd].data = data;
508 fd_callback_info[fd].condition |= FOR_WRITE;
511 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
513 static void
514 delete_input_desc (int fd)
516 if (fd == max_input_desc)
519 fd--;
520 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
521 || FD_ISSET (fd, &write_mask)));
523 max_input_desc = fd;
527 /* Stop monitoring file descriptor FD for when write is possible. */
529 void
530 delete_write_fd (int fd)
532 eassert (fd < FD_SETSIZE);
533 FD_CLR (fd, &write_mask);
534 fd_callback_info[fd].condition &= ~FOR_WRITE;
535 if (fd_callback_info[fd].condition == 0)
537 fd_callback_info[fd].func = 0;
538 fd_callback_info[fd].data = 0;
539 delete_input_desc (fd);
544 /* Compute the Lisp form of the process status, p->status, from
545 the numeric status that was returned by `wait'. */
547 static Lisp_Object status_convert (int);
549 static void
550 update_status (struct Lisp_Process *p)
552 eassert (p->raw_status_new);
553 pset_status (p, status_convert (p->raw_status));
554 p->raw_status_new = 0;
557 /* Convert a process status word in Unix format to
558 the list that we use internally. */
560 static Lisp_Object
561 status_convert (int w)
563 if (WIFSTOPPED (w))
564 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
565 else if (WIFEXITED (w))
566 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
567 WCOREDUMP (w) ? Qt : Qnil));
568 else if (WIFSIGNALED (w))
569 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
570 WCOREDUMP (w) ? Qt : Qnil));
571 else
572 return Qrun;
575 /* Given a status-list, extract the three pieces of information
576 and store them individually through the three pointers. */
578 static void
579 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
581 Lisp_Object tem;
583 if (SYMBOLP (l))
585 *symbol = l;
586 *code = 0;
587 *coredump = 0;
589 else
591 *symbol = XCAR (l);
592 tem = XCDR (l);
593 *code = XFASTINT (XCAR (tem));
594 tem = XCDR (tem);
595 *coredump = !NILP (tem);
599 /* Return a string describing a process status list. */
601 static Lisp_Object
602 status_message (struct Lisp_Process *p)
604 Lisp_Object status = p->status;
605 Lisp_Object symbol;
606 int code;
607 bool coredump;
608 Lisp_Object string, string2;
610 decode_status (status, &symbol, &code, &coredump);
612 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
614 char const *signame;
615 synchronize_system_messages_locale ();
616 signame = strsignal (code);
617 if (signame == 0)
618 string = build_string ("unknown");
619 else
621 int c1, c2;
623 string = build_unibyte_string (signame);
624 if (! NILP (Vlocale_coding_system))
625 string = (code_convert_string_norecord
626 (string, Vlocale_coding_system, 0));
627 c1 = STRING_CHAR (SDATA (string));
628 c2 = downcase (c1);
629 if (c1 != c2)
630 Faset (string, make_number (0), make_number (c2));
632 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
633 return concat2 (string, string2);
635 else if (EQ (symbol, Qexit))
637 if (NETCONN1_P (p))
638 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
639 if (code == 0)
640 return build_string ("finished\n");
641 string = Fnumber_to_string (make_number (code));
642 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
643 return concat3 (build_string ("exited abnormally with code "),
644 string, string2);
646 else if (EQ (symbol, Qfailed))
648 string = Fnumber_to_string (make_number (code));
649 string2 = build_string ("\n");
650 return concat3 (build_string ("failed with code "),
651 string, string2);
653 else
654 return Fcopy_sequence (Fsymbol_name (symbol));
657 enum { PTY_NAME_SIZE = 24 };
659 /* Open an available pty, returning a file descriptor.
660 Store into PTY_NAME the file name of the terminal corresponding to the pty.
661 Return -1 on failure. */
663 static int
664 allocate_pty (char pty_name[PTY_NAME_SIZE])
666 #ifdef HAVE_PTYS
667 int fd;
669 #ifdef PTY_ITERATION
670 PTY_ITERATION
671 #else
672 register int c, i;
673 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
674 for (i = 0; i < 16; i++)
675 #endif
677 #ifdef PTY_NAME_SPRINTF
678 PTY_NAME_SPRINTF
679 #else
680 sprintf (pty_name, "/dev/pty%c%x", c, i);
681 #endif /* no PTY_NAME_SPRINTF */
683 #ifdef PTY_OPEN
684 PTY_OPEN;
685 #else /* no PTY_OPEN */
686 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
687 #endif /* no PTY_OPEN */
689 if (fd >= 0)
691 #ifdef PTY_OPEN
692 /* Set FD's close-on-exec flag. This is needed even if
693 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
694 doesn't require support for that combination.
695 Multithreaded platforms where posix_openpt ignores
696 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
697 have a race condition between the PTY_OPEN and here. */
698 fcntl (fd, F_SETFD, FD_CLOEXEC);
699 #endif
700 /* check to make certain that both sides are available
701 this avoids a nasty yet stupid bug in rlogins */
702 #ifdef PTY_TTY_NAME_SPRINTF
703 PTY_TTY_NAME_SPRINTF
704 #else
705 sprintf (pty_name, "/dev/tty%c%x", c, i);
706 #endif /* no PTY_TTY_NAME_SPRINTF */
707 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
709 emacs_close (fd);
710 # ifndef __sgi
711 continue;
712 # else
713 return -1;
714 # endif /* __sgi */
716 setup_pty (fd);
717 return fd;
720 #endif /* HAVE_PTYS */
721 return -1;
724 static Lisp_Object
725 make_process (Lisp_Object name)
727 register Lisp_Object val, tem, name1;
728 register struct Lisp_Process *p;
729 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
730 printmax_t i;
732 p = allocate_process ();
733 /* Initialize Lisp data. Note that allocate_process initializes all
734 Lisp data to nil, so do it only for slots which should not be nil. */
735 pset_status (p, Qrun);
736 pset_mark (p, Fmake_marker ());
738 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
739 non-Lisp data, so do it only for slots which should not be zero. */
740 p->infd = -1;
741 p->outfd = -1;
742 for (i = 0; i < PROCESS_OPEN_FDS; i++)
743 p->open_fd[i] = -1;
745 #ifdef HAVE_GNUTLS
746 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
747 #endif
749 /* If name is already in use, modify it until it is unused. */
751 name1 = name;
752 for (i = 1; ; i++)
754 tem = Fget_process (name1);
755 if (NILP (tem)) break;
756 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
758 name = name1;
759 pset_name (p, name);
760 pset_sentinel (p, Qinternal_default_process_sentinel);
761 pset_filter (p, Qinternal_default_process_filter);
762 XSETPROCESS (val, p);
763 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
764 return val;
767 static void
768 remove_process (register Lisp_Object proc)
770 register Lisp_Object pair;
772 pair = Frassq (proc, Vprocess_alist);
773 Vprocess_alist = Fdelq (pair, Vprocess_alist);
775 deactivate_process (proc);
779 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
780 doc: /* Return t if OBJECT is a process. */)
781 (Lisp_Object object)
783 return PROCESSP (object) ? Qt : Qnil;
786 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
787 doc: /* Return the process named NAME, or nil if there is none. */)
788 (register Lisp_Object name)
790 if (PROCESSP (name))
791 return name;
792 CHECK_STRING (name);
793 return Fcdr (Fassoc (name, Vprocess_alist));
796 /* This is how commands for the user decode process arguments. It
797 accepts a process, a process name, a buffer, a buffer name, or nil.
798 Buffers denote the first process in the buffer, and nil denotes the
799 current buffer. */
801 static Lisp_Object
802 get_process (register Lisp_Object name)
804 register Lisp_Object proc, obj;
805 if (STRINGP (name))
807 obj = Fget_process (name);
808 if (NILP (obj))
809 obj = Fget_buffer (name);
810 if (NILP (obj))
811 error ("Process %s does not exist", SDATA (name));
813 else if (NILP (name))
814 obj = Fcurrent_buffer ();
815 else
816 obj = name;
818 /* Now obj should be either a buffer object or a process object. */
819 if (BUFFERP (obj))
821 if (NILP (BVAR (XBUFFER (obj), name)))
822 error ("Attempt to get process for a dead buffer");
823 proc = Fget_buffer_process (obj);
824 if (NILP (proc))
825 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
827 else
829 CHECK_PROCESS (obj);
830 proc = obj;
832 return proc;
836 /* Fdelete_process promises to immediately forget about the process, but in
837 reality, Emacs needs to remember those processes until they have been
838 treated by the SIGCHLD handler and waitpid has been invoked on them;
839 otherwise they might fill up the kernel's process table.
841 Some processes created by call-process are also put onto this list.
843 Members of this list are (process-ID . filename) pairs. The
844 process-ID is a number; the filename, if a string, is a file that
845 needs to be removed after the process exits. */
846 static Lisp_Object deleted_pid_list;
848 void
849 record_deleted_pid (pid_t pid, Lisp_Object filename)
851 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
852 /* GC treated elements set to nil. */
853 Fdelq (Qnil, deleted_pid_list));
857 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
858 doc: /* Delete PROCESS: kill it and forget about it immediately.
859 PROCESS may be a process, a buffer, the name of a process or buffer, or
860 nil, indicating the current buffer's process. */)
861 (register Lisp_Object process)
863 register struct Lisp_Process *p;
865 process = get_process (process);
866 p = XPROCESS (process);
868 p->raw_status_new = 0;
869 if (NETCONN1_P (p) || SERIALCONN1_P (p))
871 pset_status (p, list2 (Qexit, make_number (0)));
872 p->tick = ++process_tick;
873 status_notify (p);
874 redisplay_preserve_echo_area (13);
876 else
878 if (p->alive)
879 record_kill_process (p, Qnil);
881 if (p->infd >= 0)
883 /* Update P's status, since record_kill_process will make the
884 SIGCHLD handler update deleted_pid_list, not *P. */
885 Lisp_Object symbol;
886 if (p->raw_status_new)
887 update_status (p);
888 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
889 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
890 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
892 p->tick = ++process_tick;
893 status_notify (p);
894 redisplay_preserve_echo_area (13);
897 remove_process (process);
898 return Qnil;
901 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
902 doc: /* Return the status of PROCESS.
903 The returned value is one of the following symbols:
904 run -- for a process that is running.
905 stop -- for a process stopped but continuable.
906 exit -- for a process that has exited.
907 signal -- for a process that has got a fatal signal.
908 open -- for a network stream connection that is open.
909 listen -- for a network stream server that is listening.
910 closed -- for a network stream connection that is closed.
911 connect -- when waiting for a non-blocking connection to complete.
912 failed -- when a non-blocking connection has failed.
913 nil -- if arg is a process name and no such process exists.
914 PROCESS may be a process, a buffer, the name of a process, or
915 nil, indicating the current buffer's process. */)
916 (register Lisp_Object process)
918 register struct Lisp_Process *p;
919 register Lisp_Object status;
921 if (STRINGP (process))
922 process = Fget_process (process);
923 else
924 process = get_process (process);
926 if (NILP (process))
927 return process;
929 p = XPROCESS (process);
930 if (p->raw_status_new)
931 update_status (p);
932 status = p->status;
933 if (CONSP (status))
934 status = XCAR (status);
935 if (NETCONN1_P (p) || SERIALCONN1_P (p))
937 if (EQ (status, Qexit))
938 status = Qclosed;
939 else if (EQ (p->command, Qt))
940 status = Qstop;
941 else if (EQ (status, Qrun))
942 status = Qopen;
944 return status;
947 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
948 1, 1, 0,
949 doc: /* Return the exit status of PROCESS or the signal number that killed it.
950 If PROCESS has not yet exited or died, return 0. */)
951 (register Lisp_Object process)
953 CHECK_PROCESS (process);
954 if (XPROCESS (process)->raw_status_new)
955 update_status (XPROCESS (process));
956 if (CONSP (XPROCESS (process)->status))
957 return XCAR (XCDR (XPROCESS (process)->status));
958 return make_number (0);
961 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
962 doc: /* Return the process id of PROCESS.
963 This is the pid of the external process which PROCESS uses or talks to.
964 For a network connection, this value is nil. */)
965 (register Lisp_Object process)
967 pid_t pid;
969 CHECK_PROCESS (process);
970 pid = XPROCESS (process)->pid;
971 return (pid ? make_fixnum_or_float (pid) : Qnil);
974 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
975 doc: /* Return the name of PROCESS, as a string.
976 This is the name of the program invoked in PROCESS,
977 possibly modified to make it unique among process names. */)
978 (register Lisp_Object process)
980 CHECK_PROCESS (process);
981 return XPROCESS (process)->name;
984 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
985 doc: /* Return the command that was executed to start PROCESS.
986 This is a list of strings, the first string being the program executed
987 and the rest of the strings being the arguments given to it.
988 For a network or serial process, this is nil (process is running) or t
989 \(process is stopped). */)
990 (register Lisp_Object process)
992 CHECK_PROCESS (process);
993 return XPROCESS (process)->command;
996 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
997 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
998 This is the terminal that the process itself reads and writes on,
999 not the name of the pty that Emacs uses to talk with that terminal. */)
1000 (register Lisp_Object process)
1002 CHECK_PROCESS (process);
1003 return XPROCESS (process)->tty_name;
1006 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1007 2, 2, 0,
1008 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1009 Return BUFFER. */)
1010 (register Lisp_Object process, Lisp_Object buffer)
1012 struct Lisp_Process *p;
1014 CHECK_PROCESS (process);
1015 if (!NILP (buffer))
1016 CHECK_BUFFER (buffer);
1017 p = XPROCESS (process);
1018 pset_buffer (p, buffer);
1019 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1020 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1021 setup_process_coding_systems (process);
1022 return buffer;
1025 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1026 1, 1, 0,
1027 doc: /* Return the buffer PROCESS is associated with.
1028 The default process filter inserts output from PROCESS into this buffer. */)
1029 (register Lisp_Object process)
1031 CHECK_PROCESS (process);
1032 return XPROCESS (process)->buffer;
1035 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1036 1, 1, 0,
1037 doc: /* Return the marker for the end of the last output from PROCESS. */)
1038 (register Lisp_Object process)
1040 CHECK_PROCESS (process);
1041 return XPROCESS (process)->mark;
1044 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1045 2, 2, 0,
1046 doc: /* Give PROCESS the filter function FILTER; nil means default.
1047 A value of t means stop accepting output from the process.
1049 When a process has a non-default filter, its buffer is not used for output.
1050 Instead, each time it does output, the entire string of output is
1051 passed to the filter.
1053 The filter gets two arguments: the process and the string of output.
1054 The string argument is normally a multibyte string, except:
1055 - if the process's input coding system is no-conversion or raw-text,
1056 it is a unibyte string (the non-converted input), or else
1057 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1058 string (the result of converting the decoded input multibyte
1059 string to unibyte with `string-make-unibyte'). */)
1060 (register Lisp_Object process, Lisp_Object filter)
1062 struct Lisp_Process *p;
1064 CHECK_PROCESS (process);
1065 p = XPROCESS (process);
1067 /* Don't signal an error if the process's input file descriptor
1068 is closed. This could make debugging Lisp more difficult,
1069 for example when doing something like
1071 (setq process (start-process ...))
1072 (debug)
1073 (set-process-filter process ...) */
1075 if (NILP (filter))
1076 filter = Qinternal_default_process_filter;
1078 if (p->infd >= 0)
1080 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1082 FD_CLR (p->infd, &input_wait_mask);
1083 FD_CLR (p->infd, &non_keyboard_wait_mask);
1085 else if (EQ (p->filter, Qt)
1086 /* Network or serial process not stopped: */
1087 && !EQ (p->command, Qt))
1089 FD_SET (p->infd, &input_wait_mask);
1090 FD_SET (p->infd, &non_keyboard_wait_mask);
1094 pset_filter (p, filter);
1095 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1096 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1097 setup_process_coding_systems (process);
1098 return filter;
1101 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1102 1, 1, 0,
1103 doc: /* Return the filter function of PROCESS.
1104 See `set-process-filter' for more info on filter functions. */)
1105 (register Lisp_Object process)
1107 CHECK_PROCESS (process);
1108 return XPROCESS (process)->filter;
1111 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1112 2, 2, 0,
1113 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1114 The sentinel is called as a function when the process changes state.
1115 It gets two arguments: the process, and a string describing the change. */)
1116 (register Lisp_Object process, Lisp_Object sentinel)
1118 struct Lisp_Process *p;
1120 CHECK_PROCESS (process);
1121 p = XPROCESS (process);
1123 if (NILP (sentinel))
1124 sentinel = Qinternal_default_process_sentinel;
1126 pset_sentinel (p, sentinel);
1127 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1128 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1129 return sentinel;
1132 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1133 1, 1, 0,
1134 doc: /* Return the sentinel of PROCESS.
1135 See `set-process-sentinel' for more info on sentinels. */)
1136 (register Lisp_Object process)
1138 CHECK_PROCESS (process);
1139 return XPROCESS (process)->sentinel;
1142 DEFUN ("set-process-window-size", Fset_process_window_size,
1143 Sset_process_window_size, 3, 3, 0,
1144 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1145 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1147 CHECK_PROCESS (process);
1149 /* All known platforms store window sizes as 'unsigned short'. */
1150 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1151 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1153 if (XPROCESS (process)->infd < 0
1154 || (set_window_size (XPROCESS (process)->infd,
1155 XINT (height), XINT (width))
1156 < 0))
1157 return Qnil;
1158 else
1159 return Qt;
1162 DEFUN ("set-process-inherit-coding-system-flag",
1163 Fset_process_inherit_coding_system_flag,
1164 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1165 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1166 If the second argument FLAG is non-nil, then the variable
1167 `buffer-file-coding-system' of the buffer associated with PROCESS
1168 will be bound to the value of the coding system used to decode
1169 the process output.
1171 This is useful when the coding system specified for the process buffer
1172 leaves either the character code conversion or the end-of-line conversion
1173 unspecified, or if the coding system used to decode the process output
1174 is more appropriate for saving the process buffer.
1176 Binding the variable `inherit-process-coding-system' to non-nil before
1177 starting the process is an alternative way of setting the inherit flag
1178 for the process which will run.
1180 This function returns FLAG. */)
1181 (register Lisp_Object process, Lisp_Object flag)
1183 CHECK_PROCESS (process);
1184 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1185 return flag;
1188 DEFUN ("set-process-query-on-exit-flag",
1189 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1190 2, 2, 0,
1191 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1192 If the second argument FLAG is non-nil, Emacs will query the user before
1193 exiting or killing a buffer if PROCESS is running. This function
1194 returns FLAG. */)
1195 (register Lisp_Object process, Lisp_Object flag)
1197 CHECK_PROCESS (process);
1198 XPROCESS (process)->kill_without_query = NILP (flag);
1199 return flag;
1202 DEFUN ("process-query-on-exit-flag",
1203 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1204 1, 1, 0,
1205 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1206 (register Lisp_Object process)
1208 CHECK_PROCESS (process);
1209 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1212 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1213 1, 2, 0,
1214 doc: /* Return the contact info of PROCESS; t for a real child.
1215 For a network or serial connection, the value depends on the optional
1216 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1217 SERVICE) for a network connection or (PORT SPEED) for a serial
1218 connection. If KEY is t, the complete contact information for the
1219 connection is returned, else the specific value for the keyword KEY is
1220 returned. See `make-network-process' or `make-serial-process' for a
1221 list of keywords. */)
1222 (register Lisp_Object process, Lisp_Object key)
1224 Lisp_Object contact;
1226 CHECK_PROCESS (process);
1227 contact = XPROCESS (process)->childp;
1229 #ifdef DATAGRAM_SOCKETS
1230 if (DATAGRAM_CONN_P (process)
1231 && (EQ (key, Qt) || EQ (key, QCremote)))
1232 contact = Fplist_put (contact, QCremote,
1233 Fprocess_datagram_address (process));
1234 #endif
1236 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1237 return contact;
1238 if (NILP (key) && NETCONN_P (process))
1239 return list2 (Fplist_get (contact, QChost),
1240 Fplist_get (contact, QCservice));
1241 if (NILP (key) && SERIALCONN_P (process))
1242 return list2 (Fplist_get (contact, QCport),
1243 Fplist_get (contact, QCspeed));
1244 return Fplist_get (contact, key);
1247 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1248 1, 1, 0,
1249 doc: /* Return the plist of PROCESS. */)
1250 (register Lisp_Object process)
1252 CHECK_PROCESS (process);
1253 return XPROCESS (process)->plist;
1256 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1257 2, 2, 0,
1258 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1259 (register Lisp_Object process, Lisp_Object plist)
1261 CHECK_PROCESS (process);
1262 CHECK_LIST (plist);
1264 pset_plist (XPROCESS (process), plist);
1265 return plist;
1268 #if 0 /* Turned off because we don't currently record this info
1269 in the process. Perhaps add it. */
1270 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1271 doc: /* Return the connection type of PROCESS.
1272 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1273 a socket connection. */)
1274 (Lisp_Object process)
1276 return XPROCESS (process)->type;
1278 #endif
1280 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1281 doc: /* Return the connection type of PROCESS.
1282 The value is either the symbol `real', `network', or `serial'.
1283 PROCESS may be a process, a buffer, the name of a process or buffer, or
1284 nil, indicating the current buffer's process. */)
1285 (Lisp_Object process)
1287 Lisp_Object proc;
1288 proc = get_process (process);
1289 return XPROCESS (proc)->type;
1292 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1293 1, 2, 0,
1294 doc: /* Convert network ADDRESS from internal format to a string.
1295 A 4 or 5 element vector represents an IPv4 address (with port number).
1296 An 8 or 9 element vector represents an IPv6 address (with port number).
1297 If optional second argument OMIT-PORT is non-nil, don't include a port
1298 number in the string, even when present in ADDRESS.
1299 Returns nil if format of ADDRESS is invalid. */)
1300 (Lisp_Object address, Lisp_Object omit_port)
1302 if (NILP (address))
1303 return Qnil;
1305 if (STRINGP (address)) /* AF_LOCAL */
1306 return address;
1308 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1310 register struct Lisp_Vector *p = XVECTOR (address);
1311 ptrdiff_t size = p->header.size;
1312 Lisp_Object args[10];
1313 int nargs, i;
1315 if (size == 4 || (size == 5 && !NILP (omit_port)))
1317 args[0] = build_string ("%d.%d.%d.%d");
1318 nargs = 4;
1320 else if (size == 5)
1322 args[0] = build_string ("%d.%d.%d.%d:%d");
1323 nargs = 5;
1325 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1327 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1328 nargs = 8;
1330 else if (size == 9)
1332 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1333 nargs = 9;
1335 else
1336 return Qnil;
1338 for (i = 0; i < nargs; i++)
1340 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1341 return Qnil;
1343 if (nargs <= 5 /* IPv4 */
1344 && i < 4 /* host, not port */
1345 && XINT (p->contents[i]) > 255)
1346 return Qnil;
1348 args[i+1] = p->contents[i];
1351 return Fformat (nargs+1, args);
1354 if (CONSP (address))
1356 Lisp_Object args[2];
1357 args[0] = build_string ("<Family %d>");
1358 args[1] = Fcar (address);
1359 return Fformat (2, args);
1362 return Qnil;
1365 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1366 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1367 (void)
1369 return Fmapcar (Qcdr, Vprocess_alist);
1372 /* Starting asynchronous inferior processes. */
1374 static void start_process_unwind (Lisp_Object proc);
1376 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1377 doc: /* Start a program in a subprocess. Return the process object for it.
1378 NAME is name for process. It is modified if necessary to make it unique.
1379 BUFFER is the buffer (or buffer name) to associate with the process.
1381 Process output (both standard output and standard error streams) goes
1382 at end of BUFFER, unless you specify an output stream or filter
1383 function to handle the output. BUFFER may also be nil, meaning that
1384 this process is not associated with any buffer.
1386 PROGRAM is the program file name. It is searched for in `exec-path'
1387 (which see). If nil, just associate a pty with the buffer. Remaining
1388 arguments are strings to give program as arguments.
1390 If you want to separate standard output from standard error, invoke
1391 the command through a shell and redirect one of them using the shell
1392 syntax.
1394 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1395 (ptrdiff_t nargs, Lisp_Object *args)
1397 Lisp_Object buffer, name, program, proc, current_dir, tem;
1398 register unsigned char **new_argv;
1399 ptrdiff_t i;
1400 ptrdiff_t count = SPECPDL_INDEX ();
1402 buffer = args[1];
1403 if (!NILP (buffer))
1404 buffer = Fget_buffer_create (buffer);
1406 /* Make sure that the child will be able to chdir to the current
1407 buffer's current directory, or its unhandled equivalent. We
1408 can't just have the child check for an error when it does the
1409 chdir, since it's in a vfork.
1411 We have to GCPRO around this because Fexpand_file_name and
1412 Funhandled_file_name_directory might call a file name handling
1413 function. The argument list is protected by the caller, so all
1414 we really have to worry about is buffer. */
1416 struct gcpro gcpro1;
1417 GCPRO1 (buffer);
1418 current_dir = encode_current_directory ();
1419 UNGCPRO;
1422 name = args[0];
1423 CHECK_STRING (name);
1425 program = args[2];
1427 if (!NILP (program))
1428 CHECK_STRING (program);
1430 proc = make_process (name);
1431 /* If an error occurs and we can't start the process, we want to
1432 remove it from the process list. This means that each error
1433 check in create_process doesn't need to call remove_process
1434 itself; it's all taken care of here. */
1435 record_unwind_protect (start_process_unwind, proc);
1437 pset_childp (XPROCESS (proc), Qt);
1438 pset_plist (XPROCESS (proc), Qnil);
1439 pset_type (XPROCESS (proc), Qreal);
1440 pset_buffer (XPROCESS (proc), buffer);
1441 pset_sentinel (XPROCESS (proc), Qinternal_default_process_sentinel);
1442 pset_filter (XPROCESS (proc), Qinternal_default_process_filter);
1443 pset_command (XPROCESS (proc), Flist (nargs - 2, args + 2));
1445 #ifdef HAVE_GNUTLS
1446 /* AKA GNUTLS_INITSTAGE(proc). */
1447 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1448 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1449 #endif
1451 #ifdef ADAPTIVE_READ_BUFFERING
1452 XPROCESS (proc)->adaptive_read_buffering
1453 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1454 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1455 #endif
1457 /* Make the process marker point into the process buffer (if any). */
1458 if (BUFFERP (buffer))
1459 set_marker_both (XPROCESS (proc)->mark, buffer,
1460 BUF_ZV (XBUFFER (buffer)),
1461 BUF_ZV_BYTE (XBUFFER (buffer)));
1464 /* Decide coding systems for communicating with the process. Here
1465 we don't setup the structure coding_system nor pay attention to
1466 unibyte mode. They are done in create_process. */
1468 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1469 Lisp_Object coding_systems = Qt;
1470 Lisp_Object val, *args2;
1471 struct gcpro gcpro1, gcpro2;
1473 val = Vcoding_system_for_read;
1474 if (NILP (val))
1476 args2 = alloca ((nargs + 1) * sizeof *args2);
1477 args2[0] = Qstart_process;
1478 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1479 GCPRO2 (proc, current_dir);
1480 if (!NILP (program))
1481 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1482 UNGCPRO;
1483 if (CONSP (coding_systems))
1484 val = XCAR (coding_systems);
1485 else if (CONSP (Vdefault_process_coding_system))
1486 val = XCAR (Vdefault_process_coding_system);
1488 pset_decode_coding_system (XPROCESS (proc), val);
1490 val = Vcoding_system_for_write;
1491 if (NILP (val))
1493 if (EQ (coding_systems, Qt))
1495 args2 = alloca ((nargs + 1) * sizeof *args2);
1496 args2[0] = Qstart_process;
1497 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1498 GCPRO2 (proc, current_dir);
1499 if (!NILP (program))
1500 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1501 UNGCPRO;
1503 if (CONSP (coding_systems))
1504 val = XCDR (coding_systems);
1505 else if (CONSP (Vdefault_process_coding_system))
1506 val = XCDR (Vdefault_process_coding_system);
1508 pset_encode_coding_system (XPROCESS (proc), val);
1509 /* Note: At this moment, the above coding system may leave
1510 text-conversion or eol-conversion unspecified. They will be
1511 decided after we read output from the process and decode it by
1512 some coding system, or just before we actually send a text to
1513 the process. */
1517 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1518 XPROCESS (proc)->decoding_carryover = 0;
1519 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1521 XPROCESS (proc)->inherit_coding_system_flag
1522 = !(NILP (buffer) || !inherit_process_coding_system);
1524 if (!NILP (program))
1526 /* If program file name is not absolute, search our path for it.
1527 Put the name we will really use in TEM. */
1528 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1529 && !(SCHARS (program) > 1
1530 && IS_DEVICE_SEP (SREF (program, 1))))
1532 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1534 tem = Qnil;
1535 GCPRO4 (name, program, buffer, current_dir);
1536 openp (Vexec_path, program, Vexec_suffixes, &tem,
1537 make_number (X_OK), false);
1538 UNGCPRO;
1539 if (NILP (tem))
1540 report_file_error ("Searching for program", program);
1541 tem = Fexpand_file_name (tem, Qnil);
1543 else
1545 if (!NILP (Ffile_directory_p (program)))
1546 error ("Specified program for new process is a directory");
1547 tem = program;
1550 /* If program file name starts with /: for quoting a magic name,
1551 discard that. */
1552 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1553 && SREF (tem, 1) == ':')
1554 tem = Fsubstring (tem, make_number (2), Qnil);
1557 Lisp_Object arg_encoding = Qnil;
1558 struct gcpro gcpro1;
1559 GCPRO1 (tem);
1561 /* Encode the file name and put it in NEW_ARGV.
1562 That's where the child will use it to execute the program. */
1563 tem = list1 (ENCODE_FILE (tem));
1565 /* Here we encode arguments by the coding system used for sending
1566 data to the process. We don't support using different coding
1567 systems for encoding arguments and for encoding data sent to the
1568 process. */
1570 for (i = 3; i < nargs; i++)
1572 tem = Fcons (args[i], tem);
1573 CHECK_STRING (XCAR (tem));
1574 if (STRING_MULTIBYTE (XCAR (tem)))
1576 if (NILP (arg_encoding))
1577 arg_encoding = (complement_process_encoding_system
1578 (XPROCESS (proc)->encode_coding_system));
1579 XSETCAR (tem,
1580 code_convert_string_norecord
1581 (XCAR (tem), arg_encoding, 1));
1585 UNGCPRO;
1588 /* Now that everything is encoded we can collect the strings into
1589 NEW_ARGV. */
1590 new_argv = alloca ((nargs - 1) * sizeof *new_argv);
1591 new_argv[nargs - 2] = 0;
1593 for (i = nargs - 2; i-- != 0; )
1595 new_argv[i] = SDATA (XCAR (tem));
1596 tem = XCDR (tem);
1599 create_process (proc, (char **) new_argv, current_dir);
1601 else
1602 create_pty (proc);
1604 return unbind_to (count, proc);
1607 /* This function is the unwind_protect form for Fstart_process. If
1608 PROC doesn't have its pid set, then we know someone has signaled
1609 an error and the process wasn't started successfully, so we should
1610 remove it from the process list. */
1611 static void
1612 start_process_unwind (Lisp_Object proc)
1614 if (!PROCESSP (proc))
1615 emacs_abort ();
1617 /* Was PROC started successfully?
1618 -2 is used for a pty with no process, eg for gdb. */
1619 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1620 remove_process (proc);
1623 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1625 static void
1626 close_process_fd (int *fd_addr)
1628 int fd = *fd_addr;
1629 if (0 <= fd)
1631 *fd_addr = -1;
1632 emacs_close (fd);
1636 /* Indexes of file descriptors in open_fds. */
1637 enum
1639 /* The pipe from Emacs to its subprocess. */
1640 SUBPROCESS_STDIN,
1641 WRITE_TO_SUBPROCESS,
1643 /* The main pipe from the subprocess to Emacs. */
1644 READ_FROM_SUBPROCESS,
1645 SUBPROCESS_STDOUT,
1647 /* The pipe from the subprocess to Emacs that is closed when the
1648 subprocess execs. */
1649 READ_FROM_EXEC_MONITOR,
1650 EXEC_MONITOR_OUTPUT
1653 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1655 static void
1656 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1658 struct Lisp_Process *p = XPROCESS (process);
1659 int inchannel, outchannel;
1660 pid_t pid;
1661 int vfork_errno;
1662 int forkin, forkout;
1663 bool pty_flag = 0;
1664 char pty_name[PTY_NAME_SIZE];
1665 Lisp_Object lisp_pty_name = Qnil;
1666 sigset_t oldset;
1668 inchannel = outchannel = -1;
1670 if (!NILP (Vprocess_connection_type))
1671 outchannel = inchannel = allocate_pty (pty_name);
1673 if (inchannel >= 0)
1675 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1676 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1677 /* On most USG systems it does not work to open the pty's tty here,
1678 then close it and reopen it in the child. */
1679 /* Don't let this terminal become our controlling terminal
1680 (in case we don't have one). */
1681 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1682 if (forkin < 0)
1683 report_file_error ("Opening pty", Qnil);
1684 p->open_fd[SUBPROCESS_STDIN] = forkin;
1685 #else
1686 forkin = forkout = -1;
1687 #endif /* not USG, or USG_SUBTTY_WORKS */
1688 pty_flag = 1;
1689 lisp_pty_name = build_string (pty_name);
1691 else
1693 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1694 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1695 report_file_error ("Creating pipe", Qnil);
1696 forkin = p->open_fd[SUBPROCESS_STDIN];
1697 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1698 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1699 forkout = p->open_fd[SUBPROCESS_STDOUT];
1702 #ifndef WINDOWSNT
1703 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1704 report_file_error ("Creating pipe", Qnil);
1705 #endif
1707 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1708 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1710 /* Record this as an active process, with its channels. */
1711 chan_process[inchannel] = process;
1712 p->infd = inchannel;
1713 p->outfd = outchannel;
1715 /* Previously we recorded the tty descriptor used in the subprocess.
1716 It was only used for getting the foreground tty process, so now
1717 we just reopen the device (see emacs_get_tty_pgrp) as this is
1718 more portable (see USG_SUBTTY_WORKS above). */
1720 p->pty_flag = pty_flag;
1721 pset_status (p, Qrun);
1723 FD_SET (inchannel, &input_wait_mask);
1724 FD_SET (inchannel, &non_keyboard_wait_mask);
1725 if (inchannel > max_process_desc)
1726 max_process_desc = inchannel;
1728 /* This may signal an error. */
1729 setup_process_coding_systems (process);
1731 block_input ();
1732 block_child_signal (&oldset);
1734 #ifndef WINDOWSNT
1735 /* vfork, and prevent local vars from being clobbered by the vfork. */
1737 Lisp_Object volatile current_dir_volatile = current_dir;
1738 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1739 char **volatile new_argv_volatile = new_argv;
1740 int volatile forkin_volatile = forkin;
1741 int volatile forkout_volatile = forkout;
1742 struct Lisp_Process *p_volatile = p;
1744 pid = vfork ();
1746 current_dir = current_dir_volatile;
1747 lisp_pty_name = lisp_pty_name_volatile;
1748 new_argv = new_argv_volatile;
1749 forkin = forkin_volatile;
1750 forkout = forkout_volatile;
1751 p = p_volatile;
1753 pty_flag = p->pty_flag;
1756 if (pid == 0)
1757 #endif /* not WINDOWSNT */
1759 int xforkin = forkin;
1760 int xforkout = forkout;
1762 /* Make the pty be the controlling terminal of the process. */
1763 #ifdef HAVE_PTYS
1764 /* First, disconnect its current controlling terminal. */
1765 /* We tried doing setsid only if pty_flag, but it caused
1766 process_set_signal to fail on SGI when using a pipe. */
1767 setsid ();
1768 /* Make the pty's terminal the controlling terminal. */
1769 if (pty_flag && xforkin >= 0)
1771 #ifdef TIOCSCTTY
1772 /* We ignore the return value
1773 because faith@cs.unc.edu says that is necessary on Linux. */
1774 ioctl (xforkin, TIOCSCTTY, 0);
1775 #endif
1777 #if defined (LDISC1)
1778 if (pty_flag && xforkin >= 0)
1780 struct termios t;
1781 tcgetattr (xforkin, &t);
1782 t.c_lflag = LDISC1;
1783 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1784 emacs_perror ("create_process/tcsetattr LDISC1");
1786 #else
1787 #if defined (NTTYDISC) && defined (TIOCSETD)
1788 if (pty_flag && xforkin >= 0)
1790 /* Use new line discipline. */
1791 int ldisc = NTTYDISC;
1792 ioctl (xforkin, TIOCSETD, &ldisc);
1794 #endif
1795 #endif
1796 #ifdef TIOCNOTTY
1797 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1798 can do TIOCSPGRP only to the process's controlling tty. */
1799 if (pty_flag)
1801 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1802 I can't test it since I don't have 4.3. */
1803 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1804 if (j >= 0)
1806 ioctl (j, TIOCNOTTY, 0);
1807 emacs_close (j);
1810 #endif /* TIOCNOTTY */
1812 #if !defined (DONT_REOPEN_PTY)
1813 /*** There is a suggestion that this ought to be a
1814 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1815 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1816 that system does seem to need this code, even though
1817 both TIOCSCTTY is defined. */
1818 /* Now close the pty (if we had it open) and reopen it.
1819 This makes the pty the controlling terminal of the subprocess. */
1820 if (pty_flag)
1823 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1824 would work? */
1825 if (xforkin >= 0)
1826 emacs_close (xforkin);
1827 xforkout = xforkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1829 if (xforkin < 0)
1831 emacs_perror (SSDATA (lisp_pty_name));
1832 _exit (EXIT_CANCELED);
1836 #endif /* not DONT_REOPEN_PTY */
1838 #ifdef SETUP_SLAVE_PTY
1839 if (pty_flag)
1841 SETUP_SLAVE_PTY;
1843 #endif /* SETUP_SLAVE_PTY */
1844 #endif /* HAVE_PTYS */
1846 signal (SIGINT, SIG_DFL);
1847 signal (SIGQUIT, SIG_DFL);
1848 #ifdef SIGPROF
1849 signal (SIGPROF, SIG_DFL);
1850 #endif
1852 /* Emacs ignores SIGPIPE, but the child should not. */
1853 signal (SIGPIPE, SIG_DFL);
1855 /* Stop blocking SIGCHLD in the child. */
1856 unblock_child_signal (&oldset);
1858 if (pty_flag)
1859 child_setup_tty (xforkout);
1860 #ifdef WINDOWSNT
1861 pid = child_setup (xforkin, xforkout, xforkout, new_argv, 1, current_dir);
1862 #else /* not WINDOWSNT */
1863 child_setup (xforkin, xforkout, xforkout, new_argv, 1, current_dir);
1864 #endif /* not WINDOWSNT */
1867 /* Back in the parent process. */
1869 vfork_errno = errno;
1870 p->pid = pid;
1871 if (pid >= 0)
1872 p->alive = 1;
1874 /* Stop blocking in the parent. */
1875 unblock_child_signal (&oldset);
1876 unblock_input ();
1878 if (pid < 0)
1879 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1880 else
1882 /* vfork succeeded. */
1884 /* Close the pipe ends that the child uses, or the child's pty. */
1885 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
1886 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
1888 #ifdef WINDOWSNT
1889 register_child (pid, inchannel);
1890 #endif /* WINDOWSNT */
1892 pset_tty_name (p, lisp_pty_name);
1894 #ifndef WINDOWSNT
1895 /* Wait for child_setup to complete in case that vfork is
1896 actually defined as fork. The descriptor
1897 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1898 of a pipe is closed at the child side either by close-on-exec
1899 on successful execve or the _exit call in child_setup. */
1901 char dummy;
1903 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
1904 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
1905 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
1907 #endif
1911 static void
1912 create_pty (Lisp_Object process)
1914 struct Lisp_Process *p = XPROCESS (process);
1915 char pty_name[PTY_NAME_SIZE];
1916 int pty_fd = NILP (Vprocess_connection_type) ? -1 : allocate_pty (pty_name);
1918 if (pty_fd >= 0)
1920 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
1921 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1922 /* On most USG systems it does not work to open the pty's tty here,
1923 then close it and reopen it in the child. */
1924 /* Don't let this terminal become our controlling terminal
1925 (in case we don't have one). */
1926 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1927 if (forkout < 0)
1928 report_file_error ("Opening pty", Qnil);
1929 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
1930 #if defined (DONT_REOPEN_PTY)
1931 /* In the case that vfork is defined as fork, the parent process
1932 (Emacs) may send some data before the child process completes
1933 tty options setup. So we setup tty before forking. */
1934 child_setup_tty (forkout);
1935 #endif /* DONT_REOPEN_PTY */
1936 #endif /* not USG, or USG_SUBTTY_WORKS */
1938 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
1940 /* Record this as an active process, with its channels.
1941 As a result, child_setup will close Emacs's side of the pipes. */
1942 chan_process[pty_fd] = process;
1943 p->infd = pty_fd;
1944 p->outfd = pty_fd;
1946 /* Previously we recorded the tty descriptor used in the subprocess.
1947 It was only used for getting the foreground tty process, so now
1948 we just reopen the device (see emacs_get_tty_pgrp) as this is
1949 more portable (see USG_SUBTTY_WORKS above). */
1951 p->pty_flag = 1;
1952 pset_status (p, Qrun);
1953 setup_process_coding_systems (process);
1955 FD_SET (pty_fd, &input_wait_mask);
1956 FD_SET (pty_fd, &non_keyboard_wait_mask);
1957 if (pty_fd > max_process_desc)
1958 max_process_desc = pty_fd;
1960 pset_tty_name (p, build_string (pty_name));
1963 p->pid = -2;
1967 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1968 The address family of sa is not included in the result. */
1970 #ifndef WINDOWSNT
1971 static
1972 #endif
1973 Lisp_Object
1974 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
1976 Lisp_Object address;
1977 int i;
1978 unsigned char *cp;
1979 register struct Lisp_Vector *p;
1981 /* Workaround for a bug in getsockname on BSD: Names bound to
1982 sockets in the UNIX domain are inaccessible; getsockname returns
1983 a zero length name. */
1984 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
1985 return empty_unibyte_string;
1987 switch (sa->sa_family)
1989 case AF_INET:
1991 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
1992 len = sizeof (sin->sin_addr) + 1;
1993 address = Fmake_vector (make_number (len), Qnil);
1994 p = XVECTOR (address);
1995 p->contents[--len] = make_number (ntohs (sin->sin_port));
1996 cp = (unsigned char *) &sin->sin_addr;
1997 break;
1999 #ifdef AF_INET6
2000 case AF_INET6:
2002 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2003 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2004 len = sizeof (sin6->sin6_addr)/2 + 1;
2005 address = Fmake_vector (make_number (len), Qnil);
2006 p = XVECTOR (address);
2007 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2008 for (i = 0; i < len; i++)
2009 p->contents[i] = make_number (ntohs (ip6[i]));
2010 return address;
2012 #endif
2013 #ifdef HAVE_LOCAL_SOCKETS
2014 case AF_LOCAL:
2016 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2017 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2018 /* If the first byte is NUL, the name is a Linux abstract
2019 socket name, and the name can contain embedded NULs. If
2020 it's not, we have a NUL-terminated string. Be careful not
2021 to walk past the end of the object looking for the name
2022 terminator, however. */
2023 if (name_length > 0 && sockun->sun_path[0] != '\0')
2025 const char *terminator
2026 = memchr (sockun->sun_path, '\0', name_length);
2028 if (terminator)
2029 name_length = terminator - (const char *) sockun->sun_path;
2032 return make_unibyte_string (sockun->sun_path, name_length);
2034 #endif
2035 default:
2036 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2037 address = Fcons (make_number (sa->sa_family),
2038 Fmake_vector (make_number (len), Qnil));
2039 p = XVECTOR (XCDR (address));
2040 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2041 break;
2044 i = 0;
2045 while (i < len)
2046 p->contents[i++] = make_number (*cp++);
2048 return address;
2052 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2054 static int
2055 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2057 register struct Lisp_Vector *p;
2059 if (VECTORP (address))
2061 p = XVECTOR (address);
2062 if (p->header.size == 5)
2064 *familyp = AF_INET;
2065 return sizeof (struct sockaddr_in);
2067 #ifdef AF_INET6
2068 else if (p->header.size == 9)
2070 *familyp = AF_INET6;
2071 return sizeof (struct sockaddr_in6);
2073 #endif
2075 #ifdef HAVE_LOCAL_SOCKETS
2076 else if (STRINGP (address))
2078 *familyp = AF_LOCAL;
2079 return sizeof (struct sockaddr_un);
2081 #endif
2082 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2083 && VECTORP (XCDR (address)))
2085 struct sockaddr *sa;
2086 *familyp = XINT (XCAR (address));
2087 p = XVECTOR (XCDR (address));
2088 return p->header.size + sizeof (sa->sa_family);
2090 return 0;
2093 /* Convert an address object (vector or string) to an internal sockaddr.
2095 The address format has been basically validated by
2096 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2097 it could have come from user data. So if FAMILY is not valid,
2098 we return after zeroing *SA. */
2100 static void
2101 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2103 register struct Lisp_Vector *p;
2104 register unsigned char *cp = NULL;
2105 register int i;
2106 EMACS_INT hostport;
2108 memset (sa, 0, len);
2110 if (VECTORP (address))
2112 p = XVECTOR (address);
2113 if (family == AF_INET)
2115 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2116 len = sizeof (sin->sin_addr) + 1;
2117 hostport = XINT (p->contents[--len]);
2118 sin->sin_port = htons (hostport);
2119 cp = (unsigned char *)&sin->sin_addr;
2120 sa->sa_family = family;
2122 #ifdef AF_INET6
2123 else if (family == AF_INET6)
2125 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2126 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2127 len = sizeof (sin6->sin6_addr) + 1;
2128 hostport = XINT (p->contents[--len]);
2129 sin6->sin6_port = htons (hostport);
2130 for (i = 0; i < len; i++)
2131 if (INTEGERP (p->contents[i]))
2133 int j = XFASTINT (p->contents[i]) & 0xffff;
2134 ip6[i] = ntohs (j);
2136 sa->sa_family = family;
2137 return;
2139 #endif
2140 else
2141 return;
2143 else if (STRINGP (address))
2145 #ifdef HAVE_LOCAL_SOCKETS
2146 if (family == AF_LOCAL)
2148 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2149 cp = SDATA (address);
2150 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2151 sockun->sun_path[i] = *cp++;
2152 sa->sa_family = family;
2154 #endif
2155 return;
2157 else
2159 p = XVECTOR (XCDR (address));
2160 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2163 for (i = 0; i < len; i++)
2164 if (INTEGERP (p->contents[i]))
2165 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2168 #ifdef DATAGRAM_SOCKETS
2169 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2170 1, 1, 0,
2171 doc: /* Get the current datagram address associated with PROCESS. */)
2172 (Lisp_Object process)
2174 int channel;
2176 CHECK_PROCESS (process);
2178 if (!DATAGRAM_CONN_P (process))
2179 return Qnil;
2181 channel = XPROCESS (process)->infd;
2182 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2183 datagram_address[channel].len);
2186 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2187 2, 2, 0,
2188 doc: /* Set the datagram address for PROCESS to ADDRESS.
2189 Returns nil upon error setting address, ADDRESS otherwise. */)
2190 (Lisp_Object process, Lisp_Object address)
2192 int channel;
2193 int family, len;
2195 CHECK_PROCESS (process);
2197 if (!DATAGRAM_CONN_P (process))
2198 return Qnil;
2200 channel = XPROCESS (process)->infd;
2202 len = get_lisp_to_sockaddr_size (address, &family);
2203 if (len == 0 || datagram_address[channel].len != len)
2204 return Qnil;
2205 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2206 return address;
2208 #endif
2211 static const struct socket_options {
2212 /* The name of this option. Should be lowercase version of option
2213 name without SO_ prefix. */
2214 const char *name;
2215 /* Option level SOL_... */
2216 int optlevel;
2217 /* Option number SO_... */
2218 int optnum;
2219 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2220 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2221 } socket_options[] =
2223 #ifdef SO_BINDTODEVICE
2224 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2225 #endif
2226 #ifdef SO_BROADCAST
2227 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2228 #endif
2229 #ifdef SO_DONTROUTE
2230 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2231 #endif
2232 #ifdef SO_KEEPALIVE
2233 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2234 #endif
2235 #ifdef SO_LINGER
2236 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2237 #endif
2238 #ifdef SO_OOBINLINE
2239 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2240 #endif
2241 #ifdef SO_PRIORITY
2242 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2243 #endif
2244 #ifdef SO_REUSEADDR
2245 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2246 #endif
2247 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2250 /* Set option OPT to value VAL on socket S.
2252 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2253 Signals an error if setting a known option fails.
2256 static int
2257 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2259 char *name;
2260 const struct socket_options *sopt;
2261 int ret = 0;
2263 CHECK_SYMBOL (opt);
2265 name = SSDATA (SYMBOL_NAME (opt));
2266 for (sopt = socket_options; sopt->name; sopt++)
2267 if (strcmp (name, sopt->name) == 0)
2268 break;
2270 switch (sopt->opttype)
2272 case SOPT_BOOL:
2274 int optval;
2275 optval = NILP (val) ? 0 : 1;
2276 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2277 &optval, sizeof (optval));
2278 break;
2281 case SOPT_INT:
2283 int optval;
2284 if (TYPE_RANGED_INTEGERP (int, val))
2285 optval = XINT (val);
2286 else
2287 error ("Bad option value for %s", name);
2288 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2289 &optval, sizeof (optval));
2290 break;
2293 #ifdef SO_BINDTODEVICE
2294 case SOPT_IFNAME:
2296 char devname[IFNAMSIZ+1];
2298 /* This is broken, at least in the Linux 2.4 kernel.
2299 To unbind, the arg must be a zero integer, not the empty string.
2300 This should work on all systems. KFS. 2003-09-23. */
2301 memset (devname, 0, sizeof devname);
2302 if (STRINGP (val))
2304 char *arg = SSDATA (val);
2305 int len = min (strlen (arg), IFNAMSIZ);
2306 memcpy (devname, arg, len);
2308 else if (!NILP (val))
2309 error ("Bad option value for %s", name);
2310 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2311 devname, IFNAMSIZ);
2312 break;
2314 #endif
2316 #ifdef SO_LINGER
2317 case SOPT_LINGER:
2319 struct linger linger;
2321 linger.l_onoff = 1;
2322 linger.l_linger = 0;
2323 if (TYPE_RANGED_INTEGERP (int, val))
2324 linger.l_linger = XINT (val);
2325 else
2326 linger.l_onoff = NILP (val) ? 0 : 1;
2327 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2328 &linger, sizeof (linger));
2329 break;
2331 #endif
2333 default:
2334 return 0;
2337 if (ret < 0)
2339 int setsockopt_errno = errno;
2340 report_file_errno ("Cannot set network option", list2 (opt, val),
2341 setsockopt_errno);
2344 return (1 << sopt->optbit);
2348 DEFUN ("set-network-process-option",
2349 Fset_network_process_option, Sset_network_process_option,
2350 3, 4, 0,
2351 doc: /* For network process PROCESS set option OPTION to value VALUE.
2352 See `make-network-process' for a list of options and values.
2353 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2354 OPTION is not a supported option, return nil instead; otherwise return t. */)
2355 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2357 int s;
2358 struct Lisp_Process *p;
2360 CHECK_PROCESS (process);
2361 p = XPROCESS (process);
2362 if (!NETCONN1_P (p))
2363 error ("Process is not a network process");
2365 s = p->infd;
2366 if (s < 0)
2367 error ("Process is not running");
2369 if (set_socket_option (s, option, value))
2371 pset_childp (p, Fplist_put (p->childp, option, value));
2372 return Qt;
2375 if (NILP (no_error))
2376 error ("Unknown or unsupported option");
2378 return Qnil;
2382 DEFUN ("serial-process-configure",
2383 Fserial_process_configure,
2384 Sserial_process_configure,
2385 0, MANY, 0,
2386 doc: /* Configure speed, bytesize, etc. of a serial process.
2388 Arguments are specified as keyword/argument pairs. Attributes that
2389 are not given are re-initialized from the process's current
2390 configuration (available via the function `process-contact') or set to
2391 reasonable default values. The following arguments are defined:
2393 :process PROCESS
2394 :name NAME
2395 :buffer BUFFER
2396 :port PORT
2397 -- Any of these arguments can be given to identify the process that is
2398 to be configured. If none of these arguments is given, the current
2399 buffer's process is used.
2401 :speed SPEED -- SPEED is the speed of the serial port in bits per
2402 second, also called baud rate. Any value can be given for SPEED, but
2403 most serial ports work only at a few defined values between 1200 and
2404 115200, with 9600 being the most common value. If SPEED is nil, the
2405 serial port is not configured any further, i.e., all other arguments
2406 are ignored. This may be useful for special serial ports such as
2407 Bluetooth-to-serial converters which can only be configured through AT
2408 commands. A value of nil for SPEED can be used only when passed
2409 through `make-serial-process' or `serial-term'.
2411 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2412 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2414 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2415 `odd' (use odd parity), or the symbol `even' (use even parity). If
2416 PARITY is not given, no parity is used.
2418 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2419 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2420 is not given or nil, 1 stopbit is used.
2422 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2423 flowcontrol to be used, which is either nil (don't use flowcontrol),
2424 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2425 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2426 flowcontrol is used.
2428 `serial-process-configure' is called by `make-serial-process' for the
2429 initial configuration of the serial port.
2431 Examples:
2433 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2435 \(serial-process-configure
2436 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2438 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2440 usage: (serial-process-configure &rest ARGS) */)
2441 (ptrdiff_t nargs, Lisp_Object *args)
2443 struct Lisp_Process *p;
2444 Lisp_Object contact = Qnil;
2445 Lisp_Object proc = Qnil;
2446 struct gcpro gcpro1;
2448 contact = Flist (nargs, args);
2449 GCPRO1 (contact);
2451 proc = Fplist_get (contact, QCprocess);
2452 if (NILP (proc))
2453 proc = Fplist_get (contact, QCname);
2454 if (NILP (proc))
2455 proc = Fplist_get (contact, QCbuffer);
2456 if (NILP (proc))
2457 proc = Fplist_get (contact, QCport);
2458 proc = get_process (proc);
2459 p = XPROCESS (proc);
2460 if (!EQ (p->type, Qserial))
2461 error ("Not a serial process");
2463 if (NILP (Fplist_get (p->childp, QCspeed)))
2465 UNGCPRO;
2466 return Qnil;
2469 serial_configure (p, contact);
2471 UNGCPRO;
2472 return Qnil;
2475 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2476 0, MANY, 0,
2477 doc: /* Create and return a serial port process.
2479 In Emacs, serial port connections are represented by process objects,
2480 so input and output work as for subprocesses, and `delete-process'
2481 closes a serial port connection. However, a serial process has no
2482 process id, it cannot be signaled, and the status codes are different
2483 from normal processes.
2485 `make-serial-process' creates a process and a buffer, on which you
2486 probably want to use `process-send-string'. Try \\[serial-term] for
2487 an interactive terminal. See below for examples.
2489 Arguments are specified as keyword/argument pairs. The following
2490 arguments are defined:
2492 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2493 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2494 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2495 the backslashes in strings).
2497 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2498 which this function calls.
2500 :name NAME -- NAME is the name of the process. If NAME is not given,
2501 the value of PORT is used.
2503 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2504 with the process. Process output goes at the end of that buffer,
2505 unless you specify an output stream or filter function to handle the
2506 output. If BUFFER is not given, the value of NAME is used.
2508 :coding CODING -- If CODING is a symbol, it specifies the coding
2509 system used for both reading and writing for this process. If CODING
2510 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2511 ENCODING is used for writing.
2513 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2514 the process is running. If BOOL is not given, query before exiting.
2516 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2517 In the stopped state, a serial process does not accept incoming data,
2518 but you can send outgoing data. The stopped state is cleared by
2519 `continue-process' and set by `stop-process'.
2521 :filter FILTER -- Install FILTER as the process filter.
2523 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2525 :plist PLIST -- Install PLIST as the initial plist of the process.
2527 :bytesize
2528 :parity
2529 :stopbits
2530 :flowcontrol
2531 -- This function calls `serial-process-configure' to handle these
2532 arguments.
2534 The original argument list, possibly modified by later configuration,
2535 is available via the function `process-contact'.
2537 Examples:
2539 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2541 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2543 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2545 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2547 usage: (make-serial-process &rest ARGS) */)
2548 (ptrdiff_t nargs, Lisp_Object *args)
2550 int fd = -1;
2551 Lisp_Object proc, contact, port;
2552 struct Lisp_Process *p;
2553 struct gcpro gcpro1;
2554 Lisp_Object name, buffer;
2555 Lisp_Object tem, val;
2556 ptrdiff_t specpdl_count;
2558 if (nargs == 0)
2559 return Qnil;
2561 contact = Flist (nargs, args);
2562 GCPRO1 (contact);
2564 port = Fplist_get (contact, QCport);
2565 if (NILP (port))
2566 error ("No port specified");
2567 CHECK_STRING (port);
2569 if (NILP (Fplist_member (contact, QCspeed)))
2570 error (":speed not specified");
2571 if (!NILP (Fplist_get (contact, QCspeed)))
2572 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2574 name = Fplist_get (contact, QCname);
2575 if (NILP (name))
2576 name = port;
2577 CHECK_STRING (name);
2578 proc = make_process (name);
2579 specpdl_count = SPECPDL_INDEX ();
2580 record_unwind_protect (remove_process, proc);
2581 p = XPROCESS (proc);
2583 fd = serial_open (port);
2584 p->open_fd[SUBPROCESS_STDIN] = fd;
2585 p->infd = fd;
2586 p->outfd = fd;
2587 if (fd > max_process_desc)
2588 max_process_desc = fd;
2589 chan_process[fd] = proc;
2591 buffer = Fplist_get (contact, QCbuffer);
2592 if (NILP (buffer))
2593 buffer = name;
2594 buffer = Fget_buffer_create (buffer);
2595 pset_buffer (p, buffer);
2597 pset_childp (p, contact);
2598 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2599 pset_type (p, Qserial);
2600 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2601 pset_filter (p, Fplist_get (contact, QCfilter));
2602 pset_log (p, Qnil);
2603 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2604 p->kill_without_query = 1;
2605 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2606 pset_command (p, Qt);
2607 eassert (! p->pty_flag);
2609 if (!EQ (p->command, Qt))
2611 FD_SET (fd, &input_wait_mask);
2612 FD_SET (fd, &non_keyboard_wait_mask);
2615 if (BUFFERP (buffer))
2617 set_marker_both (p->mark, buffer,
2618 BUF_ZV (XBUFFER (buffer)),
2619 BUF_ZV_BYTE (XBUFFER (buffer)));
2622 tem = Fplist_member (contact, QCcoding);
2623 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2624 tem = Qnil;
2626 val = Qnil;
2627 if (!NILP (tem))
2629 val = XCAR (XCDR (tem));
2630 if (CONSP (val))
2631 val = XCAR (val);
2633 else if (!NILP (Vcoding_system_for_read))
2634 val = Vcoding_system_for_read;
2635 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2636 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2637 val = Qnil;
2638 pset_decode_coding_system (p, val);
2640 val = Qnil;
2641 if (!NILP (tem))
2643 val = XCAR (XCDR (tem));
2644 if (CONSP (val))
2645 val = XCDR (val);
2647 else if (!NILP (Vcoding_system_for_write))
2648 val = Vcoding_system_for_write;
2649 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2650 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2651 val = Qnil;
2652 pset_encode_coding_system (p, val);
2654 setup_process_coding_systems (proc);
2655 pset_decoding_buf (p, empty_unibyte_string);
2656 p->decoding_carryover = 0;
2657 pset_encoding_buf (p, empty_unibyte_string);
2658 p->inherit_coding_system_flag
2659 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2661 Fserial_process_configure (nargs, args);
2663 specpdl_ptr = specpdl + specpdl_count;
2665 UNGCPRO;
2666 return proc;
2669 /* Create a network stream/datagram client/server process. Treated
2670 exactly like a normal process when reading and writing. Primary
2671 differences are in status display and process deletion. A network
2672 connection has no PID; you cannot signal it. All you can do is
2673 stop/continue it and deactivate/close it via delete-process */
2675 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2676 0, MANY, 0,
2677 doc: /* Create and return a network server or client process.
2679 In Emacs, network connections are represented by process objects, so
2680 input and output work as for subprocesses and `delete-process' closes
2681 a network connection. However, a network process has no process id,
2682 it cannot be signaled, and the status codes are different from normal
2683 processes.
2685 Arguments are specified as keyword/argument pairs. The following
2686 arguments are defined:
2688 :name NAME -- NAME is name for process. It is modified if necessary
2689 to make it unique.
2691 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2692 with the process. Process output goes at end of that buffer, unless
2693 you specify an output stream or filter function to handle the output.
2694 BUFFER may be also nil, meaning that this process is not associated
2695 with any buffer.
2697 :host HOST -- HOST is name of the host to connect to, or its IP
2698 address. The symbol `local' specifies the local host. If specified
2699 for a server process, it must be a valid name or address for the local
2700 host, and only clients connecting to that address will be accepted.
2702 :service SERVICE -- SERVICE is name of the service desired, or an
2703 integer specifying a port number to connect to. If SERVICE is t,
2704 a random port number is selected for the server. (If Emacs was
2705 compiled with getaddrinfo, a port number can also be specified as a
2706 string, e.g. "80", as well as an integer. This is not portable.)
2708 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2709 stream type connection, `datagram' creates a datagram type connection,
2710 `seqpacket' creates a reliable datagram connection.
2712 :family FAMILY -- FAMILY is the address (and protocol) family for the
2713 service specified by HOST and SERVICE. The default (nil) is to use
2714 whatever address family (IPv4 or IPv6) that is defined for the host
2715 and port number specified by HOST and SERVICE. Other address families
2716 supported are:
2717 local -- for a local (i.e. UNIX) address specified by SERVICE.
2718 ipv4 -- use IPv4 address family only.
2719 ipv6 -- use IPv6 address family only.
2721 :local ADDRESS -- ADDRESS is the local address used for the connection.
2722 This parameter is ignored when opening a client process. When specified
2723 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2725 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2726 connection. This parameter is ignored when opening a stream server
2727 process. For a datagram server process, it specifies the initial
2728 setting of the remote datagram address. When specified for a client
2729 process, the FAMILY, HOST, and SERVICE args are ignored.
2731 The format of ADDRESS depends on the address family:
2732 - An IPv4 address is represented as an vector of integers [A B C D P]
2733 corresponding to numeric IP address A.B.C.D and port number P.
2734 - A local address is represented as a string with the address in the
2735 local address space.
2736 - An "unsupported family" address is represented by a cons (F . AV)
2737 where F is the family number and AV is a vector containing the socket
2738 address data with one element per address data byte. Do not rely on
2739 this format in portable code, as it may depend on implementation
2740 defined constants, data sizes, and data structure alignment.
2742 :coding CODING -- If CODING is a symbol, it specifies the coding
2743 system used for both reading and writing for this process. If CODING
2744 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2745 ENCODING is used for writing.
2747 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2748 return without waiting for the connection to complete; instead, the
2749 sentinel function will be called with second arg matching "open" (if
2750 successful) or "failed" when the connect completes. Default is to use
2751 a blocking connect (i.e. wait) for stream type connections.
2753 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2754 running when Emacs is exited.
2756 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2757 In the stopped state, a server process does not accept new
2758 connections, and a client process does not handle incoming traffic.
2759 The stopped state is cleared by `continue-process' and set by
2760 `stop-process'.
2762 :filter FILTER -- Install FILTER as the process filter.
2764 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2765 process filter are multibyte, otherwise they are unibyte.
2766 If this keyword is not specified, the strings are multibyte if
2767 the default value of `enable-multibyte-characters' is non-nil.
2769 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2771 :log LOG -- Install LOG as the server process log function. This
2772 function is called when the server accepts a network connection from a
2773 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2774 is the server process, CLIENT is the new process for the connection,
2775 and MESSAGE is a string.
2777 :plist PLIST -- Install PLIST as the new process's initial plist.
2779 :server QLEN -- if QLEN is non-nil, create a server process for the
2780 specified FAMILY, SERVICE, and connection type (stream or datagram).
2781 If QLEN is an integer, it is used as the max. length of the server's
2782 pending connection queue (also known as the backlog); the default
2783 queue length is 5. Default is to create a client process.
2785 The following network options can be specified for this connection:
2787 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2788 :dontroute BOOL -- Only send to directly connected hosts.
2789 :keepalive BOOL -- Send keep-alive messages on network stream.
2790 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2791 :oobinline BOOL -- Place out-of-band data in receive data stream.
2792 :priority INT -- Set protocol defined priority for sent packets.
2793 :reuseaddr BOOL -- Allow reusing a recently used local address
2794 (this is allowed by default for a server process).
2795 :bindtodevice NAME -- bind to interface NAME. Using this may require
2796 special privileges on some systems.
2798 Consult the relevant system programmer's manual pages for more
2799 information on using these options.
2802 A server process will listen for and accept connections from clients.
2803 When a client connection is accepted, a new network process is created
2804 for the connection with the following parameters:
2806 - The client's process name is constructed by concatenating the server
2807 process's NAME and a client identification string.
2808 - If the FILTER argument is non-nil, the client process will not get a
2809 separate process buffer; otherwise, the client's process buffer is a newly
2810 created buffer named after the server process's BUFFER name or process
2811 NAME concatenated with the client identification string.
2812 - The connection type and the process filter and sentinel parameters are
2813 inherited from the server process's TYPE, FILTER and SENTINEL.
2814 - The client process's contact info is set according to the client's
2815 addressing information (typically an IP address and a port number).
2816 - The client process's plist is initialized from the server's plist.
2818 Notice that the FILTER and SENTINEL args are never used directly by
2819 the server process. Also, the BUFFER argument is not used directly by
2820 the server process, but via the optional :log function, accepted (and
2821 failed) connections may be logged in the server process's buffer.
2823 The original argument list, modified with the actual connection
2824 information, is available via the `process-contact' function.
2826 usage: (make-network-process &rest ARGS) */)
2827 (ptrdiff_t nargs, Lisp_Object *args)
2829 Lisp_Object proc;
2830 Lisp_Object contact;
2831 struct Lisp_Process *p;
2832 #ifdef HAVE_GETADDRINFO
2833 struct addrinfo ai, *res, *lres;
2834 struct addrinfo hints;
2835 const char *portstring;
2836 char portbuf[128];
2837 #else /* HAVE_GETADDRINFO */
2838 struct _emacs_addrinfo
2840 int ai_family;
2841 int ai_socktype;
2842 int ai_protocol;
2843 int ai_addrlen;
2844 struct sockaddr *ai_addr;
2845 struct _emacs_addrinfo *ai_next;
2846 } ai, *res, *lres;
2847 #endif /* HAVE_GETADDRINFO */
2848 struct sockaddr_in address_in;
2849 #ifdef HAVE_LOCAL_SOCKETS
2850 struct sockaddr_un address_un;
2851 #endif
2852 int port;
2853 int ret = 0;
2854 int xerrno = 0;
2855 int s = -1, outch, inch;
2856 struct gcpro gcpro1;
2857 ptrdiff_t count = SPECPDL_INDEX ();
2858 ptrdiff_t count1;
2859 Lisp_Object QCaddress; /* one of QClocal or QCremote */
2860 Lisp_Object tem;
2861 Lisp_Object name, buffer, host, service, address;
2862 Lisp_Object filter, sentinel;
2863 bool is_non_blocking_client = 0;
2864 bool is_server = 0;
2865 int backlog = 5;
2866 int socktype;
2867 int family = -1;
2869 if (nargs == 0)
2870 return Qnil;
2872 /* Save arguments for process-contact and clone-process. */
2873 contact = Flist (nargs, args);
2874 GCPRO1 (contact);
2876 #ifdef WINDOWSNT
2877 /* Ensure socket support is loaded if available. */
2878 init_winsock (TRUE);
2879 #endif
2881 /* :type TYPE (nil: stream, datagram */
2882 tem = Fplist_get (contact, QCtype);
2883 if (NILP (tem))
2884 socktype = SOCK_STREAM;
2885 #ifdef DATAGRAM_SOCKETS
2886 else if (EQ (tem, Qdatagram))
2887 socktype = SOCK_DGRAM;
2888 #endif
2889 #ifdef HAVE_SEQPACKET
2890 else if (EQ (tem, Qseqpacket))
2891 socktype = SOCK_SEQPACKET;
2892 #endif
2893 else
2894 error ("Unsupported connection type");
2896 /* :server BOOL */
2897 tem = Fplist_get (contact, QCserver);
2898 if (!NILP (tem))
2900 /* Don't support network sockets when non-blocking mode is
2901 not available, since a blocked Emacs is not useful. */
2902 is_server = 1;
2903 if (TYPE_RANGED_INTEGERP (int, tem))
2904 backlog = XINT (tem);
2907 /* Make QCaddress an alias for :local (server) or :remote (client). */
2908 QCaddress = is_server ? QClocal : QCremote;
2910 /* :nowait BOOL */
2911 if (!is_server && socktype != SOCK_DGRAM
2912 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2914 #ifndef NON_BLOCKING_CONNECT
2915 error ("Non-blocking connect not supported");
2916 #else
2917 is_non_blocking_client = 1;
2918 #endif
2921 name = Fplist_get (contact, QCname);
2922 buffer = Fplist_get (contact, QCbuffer);
2923 filter = Fplist_get (contact, QCfilter);
2924 sentinel = Fplist_get (contact, QCsentinel);
2926 CHECK_STRING (name);
2928 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2929 ai.ai_socktype = socktype;
2930 ai.ai_protocol = 0;
2931 ai.ai_next = NULL;
2932 res = &ai;
2934 /* :local ADDRESS or :remote ADDRESS */
2935 address = Fplist_get (contact, QCaddress);
2936 if (!NILP (address))
2938 host = service = Qnil;
2940 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2941 error ("Malformed :address");
2942 ai.ai_family = family;
2943 ai.ai_addr = alloca (ai.ai_addrlen);
2944 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
2945 goto open_socket;
2948 /* :family FAMILY -- nil (for Inet), local, or integer. */
2949 tem = Fplist_get (contact, QCfamily);
2950 if (NILP (tem))
2952 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
2953 family = AF_UNSPEC;
2954 #else
2955 family = AF_INET;
2956 #endif
2958 #ifdef HAVE_LOCAL_SOCKETS
2959 else if (EQ (tem, Qlocal))
2960 family = AF_LOCAL;
2961 #endif
2962 #ifdef AF_INET6
2963 else if (EQ (tem, Qipv6))
2964 family = AF_INET6;
2965 #endif
2966 else if (EQ (tem, Qipv4))
2967 family = AF_INET;
2968 else if (TYPE_RANGED_INTEGERP (int, tem))
2969 family = XINT (tem);
2970 else
2971 error ("Unknown address family");
2973 ai.ai_family = family;
2975 /* :service SERVICE -- string, integer (port number), or t (random port). */
2976 service = Fplist_get (contact, QCservice);
2978 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2979 host = Fplist_get (contact, QChost);
2980 if (!NILP (host))
2982 if (EQ (host, Qlocal))
2983 /* Depending on setup, "localhost" may map to different IPv4 and/or
2984 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
2985 host = build_string ("127.0.0.1");
2986 CHECK_STRING (host);
2989 #ifdef HAVE_LOCAL_SOCKETS
2990 if (family == AF_LOCAL)
2992 if (!NILP (host))
2994 message (":family local ignores the :host \"%s\" property",
2995 SDATA (host));
2996 contact = Fplist_put (contact, QChost, Qnil);
2997 host = Qnil;
2999 CHECK_STRING (service);
3000 memset (&address_un, 0, sizeof address_un);
3001 address_un.sun_family = AF_LOCAL;
3002 if (sizeof address_un.sun_path <= SBYTES (service))
3003 error ("Service name too long");
3004 strcpy (address_un.sun_path, SSDATA (service));
3005 ai.ai_addr = (struct sockaddr *) &address_un;
3006 ai.ai_addrlen = sizeof address_un;
3007 goto open_socket;
3009 #endif
3011 /* Slow down polling to every ten seconds.
3012 Some kernels have a bug which causes retrying connect to fail
3013 after a connect. Polling can interfere with gethostbyname too. */
3014 #ifdef POLL_FOR_INPUT
3015 if (socktype != SOCK_DGRAM)
3017 record_unwind_protect_void (run_all_atimers);
3018 bind_polling_period (10);
3020 #endif
3022 #ifdef HAVE_GETADDRINFO
3023 /* If we have a host, use getaddrinfo to resolve both host and service.
3024 Otherwise, use getservbyname to lookup the service. */
3025 if (!NILP (host))
3028 /* SERVICE can either be a string or int.
3029 Convert to a C string for later use by getaddrinfo. */
3030 if (EQ (service, Qt))
3031 portstring = "0";
3032 else if (INTEGERP (service))
3034 sprintf (portbuf, "%"pI"d", XINT (service));
3035 portstring = portbuf;
3037 else
3039 CHECK_STRING (service);
3040 portstring = SSDATA (service);
3043 immediate_quit = 1;
3044 QUIT;
3045 memset (&hints, 0, sizeof (hints));
3046 hints.ai_flags = 0;
3047 hints.ai_family = family;
3048 hints.ai_socktype = socktype;
3049 hints.ai_protocol = 0;
3051 #ifdef HAVE_RES_INIT
3052 res_init ();
3053 #endif
3055 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3056 if (ret)
3057 #ifdef HAVE_GAI_STRERROR
3058 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3059 #else
3060 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3061 #endif
3062 immediate_quit = 0;
3064 goto open_socket;
3066 #endif /* HAVE_GETADDRINFO */
3068 /* We end up here if getaddrinfo is not defined, or in case no hostname
3069 has been specified (e.g. for a local server process). */
3071 if (EQ (service, Qt))
3072 port = 0;
3073 else if (INTEGERP (service))
3074 port = htons ((unsigned short) XINT (service));
3075 else
3077 struct servent *svc_info;
3078 CHECK_STRING (service);
3079 svc_info = getservbyname (SSDATA (service),
3080 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3081 if (svc_info == 0)
3082 error ("Unknown service: %s", SDATA (service));
3083 port = svc_info->s_port;
3086 memset (&address_in, 0, sizeof address_in);
3087 address_in.sin_family = family;
3088 address_in.sin_addr.s_addr = INADDR_ANY;
3089 address_in.sin_port = port;
3091 #ifndef HAVE_GETADDRINFO
3092 if (!NILP (host))
3094 struct hostent *host_info_ptr;
3096 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3097 as it may `hang' Emacs for a very long time. */
3098 immediate_quit = 1;
3099 QUIT;
3101 #ifdef HAVE_RES_INIT
3102 res_init ();
3103 #endif
3105 host_info_ptr = gethostbyname (SDATA (host));
3106 immediate_quit = 0;
3108 if (host_info_ptr)
3110 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3111 host_info_ptr->h_length);
3112 family = host_info_ptr->h_addrtype;
3113 address_in.sin_family = family;
3115 else
3116 /* Attempt to interpret host as numeric inet address */
3118 unsigned long numeric_addr;
3119 numeric_addr = inet_addr (SSDATA (host));
3120 if (numeric_addr == -1)
3121 error ("Unknown host \"%s\"", SDATA (host));
3123 memcpy (&address_in.sin_addr, &numeric_addr,
3124 sizeof (address_in.sin_addr));
3128 #endif /* not HAVE_GETADDRINFO */
3130 ai.ai_family = family;
3131 ai.ai_addr = (struct sockaddr *) &address_in;
3132 ai.ai_addrlen = sizeof address_in;
3134 open_socket:
3136 /* Do this in case we never enter the for-loop below. */
3137 count1 = SPECPDL_INDEX ();
3138 s = -1;
3140 for (lres = res; lres; lres = lres->ai_next)
3142 ptrdiff_t optn;
3143 int optbits;
3145 #ifdef WINDOWSNT
3146 retry_connect:
3147 #endif
3149 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3150 lres->ai_protocol);
3151 if (s < 0)
3153 xerrno = errno;
3154 continue;
3157 #ifdef DATAGRAM_SOCKETS
3158 if (!is_server && socktype == SOCK_DGRAM)
3159 break;
3160 #endif /* DATAGRAM_SOCKETS */
3162 #ifdef NON_BLOCKING_CONNECT
3163 if (is_non_blocking_client)
3165 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3166 if (ret < 0)
3168 xerrno = errno;
3169 emacs_close (s);
3170 s = -1;
3171 continue;
3174 #endif
3176 /* Make us close S if quit. */
3177 record_unwind_protect_int (close_file_unwind, s);
3179 /* Parse network options in the arg list.
3180 We simply ignore anything which isn't a known option (including other keywords).
3181 An error is signaled if setting a known option fails. */
3182 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3183 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3185 if (is_server)
3187 /* Configure as a server socket. */
3189 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3190 explicit :reuseaddr key to override this. */
3191 #ifdef HAVE_LOCAL_SOCKETS
3192 if (family != AF_LOCAL)
3193 #endif
3194 if (!(optbits & (1 << OPIX_REUSEADDR)))
3196 int optval = 1;
3197 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3198 report_file_error ("Cannot set reuse option on server socket", Qnil);
3201 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3202 report_file_error ("Cannot bind server socket", Qnil);
3204 #ifdef HAVE_GETSOCKNAME
3205 if (EQ (service, Qt))
3207 struct sockaddr_in sa1;
3208 socklen_t len1 = sizeof (sa1);
3209 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3211 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3212 service = make_number (ntohs (sa1.sin_port));
3213 contact = Fplist_put (contact, QCservice, service);
3216 #endif
3218 if (socktype != SOCK_DGRAM && listen (s, backlog))
3219 report_file_error ("Cannot listen on server socket", Qnil);
3221 break;
3224 immediate_quit = 1;
3225 QUIT;
3227 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3228 xerrno = errno;
3230 if (ret == 0 || xerrno == EISCONN)
3232 /* The unwind-protect will be discarded afterwards.
3233 Likewise for immediate_quit. */
3234 break;
3237 #ifdef NON_BLOCKING_CONNECT
3238 #ifdef EINPROGRESS
3239 if (is_non_blocking_client && xerrno == EINPROGRESS)
3240 break;
3241 #else
3242 #ifdef EWOULDBLOCK
3243 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3244 break;
3245 #endif
3246 #endif
3247 #endif
3249 #ifndef WINDOWSNT
3250 if (xerrno == EINTR)
3252 /* Unlike most other syscalls connect() cannot be called
3253 again. (That would return EALREADY.) The proper way to
3254 wait for completion is pselect(). */
3255 int sc;
3256 socklen_t len;
3257 fd_set fdset;
3258 retry_select:
3259 FD_ZERO (&fdset);
3260 FD_SET (s, &fdset);
3261 QUIT;
3262 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3263 if (sc == -1)
3265 if (errno == EINTR)
3266 goto retry_select;
3267 else
3268 report_file_error ("Failed select", Qnil);
3270 eassert (sc > 0);
3272 len = sizeof xerrno;
3273 eassert (FD_ISSET (s, &fdset));
3274 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3275 report_file_error ("Failed getsockopt", Qnil);
3276 if (xerrno)
3277 report_file_errno ("Failed connect", Qnil, xerrno);
3278 break;
3280 #endif /* !WINDOWSNT */
3282 immediate_quit = 0;
3284 /* Discard the unwind protect closing S. */
3285 specpdl_ptr = specpdl + count1;
3286 emacs_close (s);
3287 s = -1;
3289 #ifdef WINDOWSNT
3290 if (xerrno == EINTR)
3291 goto retry_connect;
3292 #endif
3295 if (s >= 0)
3297 #ifdef DATAGRAM_SOCKETS
3298 if (socktype == SOCK_DGRAM)
3300 if (datagram_address[s].sa)
3301 emacs_abort ();
3302 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3303 datagram_address[s].len = lres->ai_addrlen;
3304 if (is_server)
3306 Lisp_Object remote;
3307 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3308 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3310 int rfamily, rlen;
3311 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3312 if (rlen != 0 && rfamily == lres->ai_family
3313 && rlen == lres->ai_addrlen)
3314 conv_lisp_to_sockaddr (rfamily, remote,
3315 datagram_address[s].sa, rlen);
3318 else
3319 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3321 #endif
3322 contact = Fplist_put (contact, QCaddress,
3323 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3324 #ifdef HAVE_GETSOCKNAME
3325 if (!is_server)
3327 struct sockaddr_in sa1;
3328 socklen_t len1 = sizeof (sa1);
3329 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3330 contact = Fplist_put (contact, QClocal,
3331 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3333 #endif
3336 immediate_quit = 0;
3338 #ifdef HAVE_GETADDRINFO
3339 if (res != &ai)
3341 block_input ();
3342 freeaddrinfo (res);
3343 unblock_input ();
3345 #endif
3347 if (s < 0)
3349 /* If non-blocking got this far - and failed - assume non-blocking is
3350 not supported after all. This is probably a wrong assumption, but
3351 the normal blocking calls to open-network-stream handles this error
3352 better. */
3353 if (is_non_blocking_client)
3354 return Qnil;
3356 report_file_errno ((is_server
3357 ? "make server process failed"
3358 : "make client process failed"),
3359 contact, xerrno);
3362 inch = s;
3363 outch = s;
3365 if (!NILP (buffer))
3366 buffer = Fget_buffer_create (buffer);
3367 proc = make_process (name);
3369 chan_process[inch] = proc;
3371 fcntl (inch, F_SETFL, O_NONBLOCK);
3373 p = XPROCESS (proc);
3375 pset_childp (p, contact);
3376 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3377 pset_type (p, Qnetwork);
3379 pset_buffer (p, buffer);
3380 pset_sentinel (p, sentinel);
3381 pset_filter (p, filter);
3382 pset_log (p, Fplist_get (contact, QClog));
3383 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3384 p->kill_without_query = 1;
3385 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3386 pset_command (p, Qt);
3387 p->pid = 0;
3389 p->open_fd[SUBPROCESS_STDIN] = inch;
3390 p->infd = inch;
3391 p->outfd = outch;
3393 /* Discard the unwind protect for closing S, if any. */
3394 specpdl_ptr = specpdl + count1;
3396 /* Unwind bind_polling_period and request_sigio. */
3397 unbind_to (count, Qnil);
3399 if (is_server && socktype != SOCK_DGRAM)
3400 pset_status (p, Qlisten);
3402 /* Make the process marker point into the process buffer (if any). */
3403 if (BUFFERP (buffer))
3404 set_marker_both (p->mark, buffer,
3405 BUF_ZV (XBUFFER (buffer)),
3406 BUF_ZV_BYTE (XBUFFER (buffer)));
3408 #ifdef NON_BLOCKING_CONNECT
3409 if (is_non_blocking_client)
3411 /* We may get here if connect did succeed immediately. However,
3412 in that case, we still need to signal this like a non-blocking
3413 connection. */
3414 pset_status (p, Qconnect);
3415 if (!FD_ISSET (inch, &connect_wait_mask))
3417 FD_SET (inch, &connect_wait_mask);
3418 FD_SET (inch, &write_mask);
3419 num_pending_connects++;
3422 else
3423 #endif
3424 /* A server may have a client filter setting of Qt, but it must
3425 still listen for incoming connects unless it is stopped. */
3426 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3427 || (EQ (p->status, Qlisten) && NILP (p->command)))
3429 FD_SET (inch, &input_wait_mask);
3430 FD_SET (inch, &non_keyboard_wait_mask);
3433 if (inch > max_process_desc)
3434 max_process_desc = inch;
3436 tem = Fplist_member (contact, QCcoding);
3437 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3438 tem = Qnil; /* No error message (too late!). */
3441 /* Setup coding systems for communicating with the network stream. */
3442 struct gcpro gcpro1;
3443 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3444 Lisp_Object coding_systems = Qt;
3445 Lisp_Object fargs[5], val;
3447 if (!NILP (tem))
3449 val = XCAR (XCDR (tem));
3450 if (CONSP (val))
3451 val = XCAR (val);
3453 else if (!NILP (Vcoding_system_for_read))
3454 val = Vcoding_system_for_read;
3455 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3456 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3457 /* We dare not decode end-of-line format by setting VAL to
3458 Qraw_text, because the existing Emacs Lisp libraries
3459 assume that they receive bare code including a sequence of
3460 CR LF. */
3461 val = Qnil;
3462 else
3464 if (NILP (host) || NILP (service))
3465 coding_systems = Qnil;
3466 else
3468 fargs[0] = Qopen_network_stream, fargs[1] = name,
3469 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3470 GCPRO1 (proc);
3471 coding_systems = Ffind_operation_coding_system (5, fargs);
3472 UNGCPRO;
3474 if (CONSP (coding_systems))
3475 val = XCAR (coding_systems);
3476 else if (CONSP (Vdefault_process_coding_system))
3477 val = XCAR (Vdefault_process_coding_system);
3478 else
3479 val = Qnil;
3481 pset_decode_coding_system (p, val);
3483 if (!NILP (tem))
3485 val = XCAR (XCDR (tem));
3486 if (CONSP (val))
3487 val = XCDR (val);
3489 else if (!NILP (Vcoding_system_for_write))
3490 val = Vcoding_system_for_write;
3491 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3492 val = Qnil;
3493 else
3495 if (EQ (coding_systems, Qt))
3497 if (NILP (host) || NILP (service))
3498 coding_systems = Qnil;
3499 else
3501 fargs[0] = Qopen_network_stream, fargs[1] = name,
3502 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3503 GCPRO1 (proc);
3504 coding_systems = Ffind_operation_coding_system (5, fargs);
3505 UNGCPRO;
3508 if (CONSP (coding_systems))
3509 val = XCDR (coding_systems);
3510 else if (CONSP (Vdefault_process_coding_system))
3511 val = XCDR (Vdefault_process_coding_system);
3512 else
3513 val = Qnil;
3515 pset_encode_coding_system (p, val);
3517 setup_process_coding_systems (proc);
3519 pset_decoding_buf (p, empty_unibyte_string);
3520 p->decoding_carryover = 0;
3521 pset_encoding_buf (p, empty_unibyte_string);
3523 p->inherit_coding_system_flag
3524 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3526 UNGCPRO;
3527 return proc;
3531 #ifdef HAVE_NET_IF_H
3533 #ifdef SIOCGIFCONF
3534 static Lisp_Object
3535 network_interface_list (void)
3537 struct ifconf ifconf;
3538 struct ifreq *ifreq;
3539 void *buf = NULL;
3540 ptrdiff_t buf_size = 512;
3541 int s;
3542 Lisp_Object res;
3543 ptrdiff_t count;
3545 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3546 if (s < 0)
3547 return Qnil;
3548 count = SPECPDL_INDEX ();
3549 record_unwind_protect_int (close_file_unwind, s);
3553 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3554 ifconf.ifc_buf = buf;
3555 ifconf.ifc_len = buf_size;
3556 if (ioctl (s, SIOCGIFCONF, &ifconf))
3558 emacs_close (s);
3559 xfree (buf);
3560 return Qnil;
3563 while (ifconf.ifc_len == buf_size);
3565 res = unbind_to (count, Qnil);
3566 ifreq = ifconf.ifc_req;
3567 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3569 struct ifreq *ifq = ifreq;
3570 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3571 #define SIZEOF_IFREQ(sif) \
3572 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3573 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3575 int len = SIZEOF_IFREQ (ifq);
3576 #else
3577 int len = sizeof (*ifreq);
3578 #endif
3579 char namebuf[sizeof (ifq->ifr_name) + 1];
3580 ifreq = (struct ifreq *) ((char *) ifreq + len);
3582 if (ifq->ifr_addr.sa_family != AF_INET)
3583 continue;
3585 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3586 namebuf[sizeof (ifq->ifr_name)] = 0;
3587 res = Fcons (Fcons (build_string (namebuf),
3588 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3589 sizeof (struct sockaddr))),
3590 res);
3593 xfree (buf);
3594 return res;
3596 #endif /* SIOCGIFCONF */
3598 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3600 struct ifflag_def {
3601 int flag_bit;
3602 const char *flag_sym;
3605 static const struct ifflag_def ifflag_table[] = {
3606 #ifdef IFF_UP
3607 { IFF_UP, "up" },
3608 #endif
3609 #ifdef IFF_BROADCAST
3610 { IFF_BROADCAST, "broadcast" },
3611 #endif
3612 #ifdef IFF_DEBUG
3613 { IFF_DEBUG, "debug" },
3614 #endif
3615 #ifdef IFF_LOOPBACK
3616 { IFF_LOOPBACK, "loopback" },
3617 #endif
3618 #ifdef IFF_POINTOPOINT
3619 { IFF_POINTOPOINT, "pointopoint" },
3620 #endif
3621 #ifdef IFF_RUNNING
3622 { IFF_RUNNING, "running" },
3623 #endif
3624 #ifdef IFF_NOARP
3625 { IFF_NOARP, "noarp" },
3626 #endif
3627 #ifdef IFF_PROMISC
3628 { IFF_PROMISC, "promisc" },
3629 #endif
3630 #ifdef IFF_NOTRAILERS
3631 #ifdef NS_IMPL_COCOA
3632 /* Really means smart, notrailers is obsolete */
3633 { IFF_NOTRAILERS, "smart" },
3634 #else
3635 { IFF_NOTRAILERS, "notrailers" },
3636 #endif
3637 #endif
3638 #ifdef IFF_ALLMULTI
3639 { IFF_ALLMULTI, "allmulti" },
3640 #endif
3641 #ifdef IFF_MASTER
3642 { IFF_MASTER, "master" },
3643 #endif
3644 #ifdef IFF_SLAVE
3645 { IFF_SLAVE, "slave" },
3646 #endif
3647 #ifdef IFF_MULTICAST
3648 { IFF_MULTICAST, "multicast" },
3649 #endif
3650 #ifdef IFF_PORTSEL
3651 { IFF_PORTSEL, "portsel" },
3652 #endif
3653 #ifdef IFF_AUTOMEDIA
3654 { IFF_AUTOMEDIA, "automedia" },
3655 #endif
3656 #ifdef IFF_DYNAMIC
3657 { IFF_DYNAMIC, "dynamic" },
3658 #endif
3659 #ifdef IFF_OACTIVE
3660 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3661 #endif
3662 #ifdef IFF_SIMPLEX
3663 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3664 #endif
3665 #ifdef IFF_LINK0
3666 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3667 #endif
3668 #ifdef IFF_LINK1
3669 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3670 #endif
3671 #ifdef IFF_LINK2
3672 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3673 #endif
3674 { 0, 0 }
3677 static Lisp_Object
3678 network_interface_info (Lisp_Object ifname)
3680 struct ifreq rq;
3681 Lisp_Object res = Qnil;
3682 Lisp_Object elt;
3683 int s;
3684 bool any = 0;
3685 ptrdiff_t count;
3686 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3687 && defined HAVE_GETIFADDRS && defined LLADDR)
3688 struct ifaddrs *ifap;
3689 #endif
3691 CHECK_STRING (ifname);
3693 if (sizeof rq.ifr_name <= SBYTES (ifname))
3694 error ("interface name too long");
3695 strcpy (rq.ifr_name, SSDATA (ifname));
3697 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3698 if (s < 0)
3699 return Qnil;
3700 count = SPECPDL_INDEX ();
3701 record_unwind_protect_int (close_file_unwind, s);
3703 elt = Qnil;
3704 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3705 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3707 int flags = rq.ifr_flags;
3708 const struct ifflag_def *fp;
3709 int fnum;
3711 /* If flags is smaller than int (i.e. short) it may have the high bit set
3712 due to IFF_MULTICAST. In that case, sign extending it into
3713 an int is wrong. */
3714 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3715 flags = (unsigned short) rq.ifr_flags;
3717 any = 1;
3718 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3720 if (flags & fp->flag_bit)
3722 elt = Fcons (intern (fp->flag_sym), elt);
3723 flags -= fp->flag_bit;
3726 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3728 if (flags & 1)
3730 elt = Fcons (make_number (fnum), elt);
3734 #endif
3735 res = Fcons (elt, res);
3737 elt = Qnil;
3738 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3739 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3741 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3742 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3743 int n;
3745 any = 1;
3746 for (n = 0; n < 6; n++)
3747 p->contents[n] = make_number (((unsigned char *)
3748 &rq.ifr_hwaddr.sa_data[0])
3749 [n]);
3750 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3752 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3753 if (getifaddrs (&ifap) != -1)
3755 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3756 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3757 struct ifaddrs *it;
3759 for (it = ifap; it != NULL; it = it->ifa_next)
3761 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3762 unsigned char linkaddr[6];
3763 int n;
3765 if (it->ifa_addr->sa_family != AF_LINK
3766 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3767 || sdl->sdl_alen != 6)
3768 continue;
3770 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3771 for (n = 0; n < 6; n++)
3772 p->contents[n] = make_number (linkaddr[n]);
3774 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
3775 break;
3778 #ifdef HAVE_FREEIFADDRS
3779 freeifaddrs (ifap);
3780 #endif
3782 #endif /* HAVE_GETIFADDRS && LLADDR */
3784 res = Fcons (elt, res);
3786 elt = Qnil;
3787 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3788 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3790 any = 1;
3791 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3792 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3793 #else
3794 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3795 #endif
3797 #endif
3798 res = Fcons (elt, res);
3800 elt = Qnil;
3801 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3802 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3804 any = 1;
3805 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3807 #endif
3808 res = Fcons (elt, res);
3810 elt = Qnil;
3811 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3812 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3814 any = 1;
3815 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3817 #endif
3818 res = Fcons (elt, res);
3820 return unbind_to (count, any ? res : Qnil);
3822 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
3823 #endif /* defined (HAVE_NET_IF_H) */
3825 DEFUN ("network-interface-list", Fnetwork_interface_list,
3826 Snetwork_interface_list, 0, 0, 0,
3827 doc: /* Return an alist of all network interfaces and their network address.
3828 Each element is a cons, the car of which is a string containing the
3829 interface name, and the cdr is the network address in internal
3830 format; see the description of ADDRESS in `make-network-process'.
3832 If the information is not available, return nil. */)
3833 (void)
3835 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
3836 return network_interface_list ();
3837 #else
3838 return Qnil;
3839 #endif
3842 DEFUN ("network-interface-info", Fnetwork_interface_info,
3843 Snetwork_interface_info, 1, 1, 0,
3844 doc: /* Return information about network interface named IFNAME.
3845 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3846 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3847 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3848 FLAGS is the current flags of the interface.
3850 Data that is unavailable is returned as nil. */)
3851 (Lisp_Object ifname)
3853 #if ((defined HAVE_NET_IF_H \
3854 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
3855 || defined SIOCGIFFLAGS)) \
3856 || defined WINDOWSNT)
3857 return network_interface_info (ifname);
3858 #else
3859 return Qnil;
3860 #endif
3864 /* Turn off input and output for process PROC. */
3866 static void
3867 deactivate_process (Lisp_Object proc)
3869 int inchannel;
3870 struct Lisp_Process *p = XPROCESS (proc);
3871 int i;
3873 #ifdef HAVE_GNUTLS
3874 /* Delete GnuTLS structures in PROC, if any. */
3875 emacs_gnutls_deinit (proc);
3876 #endif /* HAVE_GNUTLS */
3878 #ifdef ADAPTIVE_READ_BUFFERING
3879 if (p->read_output_delay > 0)
3881 if (--process_output_delay_count < 0)
3882 process_output_delay_count = 0;
3883 p->read_output_delay = 0;
3884 p->read_output_skip = 0;
3886 #endif
3888 /* Beware SIGCHLD hereabouts. */
3890 for (i = 0; i < PROCESS_OPEN_FDS; i++)
3891 close_process_fd (&p->open_fd[i]);
3893 inchannel = p->infd;
3894 if (inchannel >= 0)
3896 p->infd = -1;
3897 p->outfd = -1;
3898 #ifdef DATAGRAM_SOCKETS
3899 if (DATAGRAM_CHAN_P (inchannel))
3901 xfree (datagram_address[inchannel].sa);
3902 datagram_address[inchannel].sa = 0;
3903 datagram_address[inchannel].len = 0;
3905 #endif
3906 chan_process[inchannel] = Qnil;
3907 FD_CLR (inchannel, &input_wait_mask);
3908 FD_CLR (inchannel, &non_keyboard_wait_mask);
3909 #ifdef NON_BLOCKING_CONNECT
3910 if (FD_ISSET (inchannel, &connect_wait_mask))
3912 FD_CLR (inchannel, &connect_wait_mask);
3913 FD_CLR (inchannel, &write_mask);
3914 if (--num_pending_connects < 0)
3915 emacs_abort ();
3917 #endif
3918 if (inchannel == max_process_desc)
3920 /* We just closed the highest-numbered process input descriptor,
3921 so recompute the highest-numbered one now. */
3922 int i = inchannel;
3924 i--;
3925 while (0 <= i && NILP (chan_process[i]));
3927 max_process_desc = i;
3933 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3934 0, 4, 0,
3935 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3936 It is given to their filter functions.
3937 Non-nil arg PROCESS means do not return until some output has been received
3938 from PROCESS.
3940 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
3941 and milliseconds to wait; return after that much time whether or not
3942 there is any subprocess output. If SECONDS is a floating point number,
3943 it specifies a fractional number of seconds to wait.
3944 The MILLISEC argument is obsolete and should be avoided.
3946 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
3947 from PROCESS, suspending reading output from other processes.
3948 If JUST-THIS-ONE is an integer, don't run any timers either.
3949 Return non-nil if we received any output before the timeout expired. */)
3950 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
3952 intmax_t secs;
3953 int nsecs;
3955 if (! NILP (process))
3956 CHECK_PROCESS (process);
3957 else
3958 just_this_one = Qnil;
3960 if (!NILP (millisec))
3961 { /* Obsolete calling convention using integers rather than floats. */
3962 CHECK_NUMBER (millisec);
3963 if (NILP (seconds))
3964 seconds = make_float (XINT (millisec) / 1000.0);
3965 else
3967 CHECK_NUMBER (seconds);
3968 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
3972 secs = 0;
3973 nsecs = -1;
3975 if (!NILP (seconds))
3977 if (INTEGERP (seconds))
3979 if (XINT (seconds) > 0)
3981 secs = XINT (seconds);
3982 nsecs = 0;
3985 else if (FLOATP (seconds))
3987 if (XFLOAT_DATA (seconds) > 0)
3989 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
3990 secs = min (t.tv_sec, WAIT_READING_MAX);
3991 nsecs = t.tv_nsec;
3994 else
3995 wrong_type_argument (Qnumberp, seconds);
3997 else if (! NILP (process))
3998 nsecs = 0;
4000 return
4001 (wait_reading_process_output (secs, nsecs, 0, 0,
4002 Qnil,
4003 !NILP (process) ? XPROCESS (process) : NULL,
4004 NILP (just_this_one) ? 0 :
4005 !INTEGERP (just_this_one) ? 1 : -1)
4006 ? Qt : Qnil);
4009 /* Accept a connection for server process SERVER on CHANNEL. */
4011 static EMACS_INT connect_counter = 0;
4013 static void
4014 server_accept_connection (Lisp_Object server, int channel)
4016 Lisp_Object proc, caller, name, buffer;
4017 Lisp_Object contact, host, service;
4018 struct Lisp_Process *ps= XPROCESS (server);
4019 struct Lisp_Process *p;
4020 int s;
4021 union u_sockaddr {
4022 struct sockaddr sa;
4023 struct sockaddr_in in;
4024 #ifdef AF_INET6
4025 struct sockaddr_in6 in6;
4026 #endif
4027 #ifdef HAVE_LOCAL_SOCKETS
4028 struct sockaddr_un un;
4029 #endif
4030 } saddr;
4031 socklen_t len = sizeof saddr;
4032 ptrdiff_t count;
4034 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4036 if (s < 0)
4038 int code = errno;
4040 if (code == EAGAIN)
4041 return;
4042 #ifdef EWOULDBLOCK
4043 if (code == EWOULDBLOCK)
4044 return;
4045 #endif
4047 if (!NILP (ps->log))
4048 call3 (ps->log, server, Qnil,
4049 concat3 (build_string ("accept failed with code"),
4050 Fnumber_to_string (make_number (code)),
4051 build_string ("\n")));
4052 return;
4055 count = SPECPDL_INDEX ();
4056 record_unwind_protect_int (close_file_unwind, s);
4058 connect_counter++;
4060 /* Setup a new process to handle the connection. */
4062 /* Generate a unique identification of the caller, and build contact
4063 information for this process. */
4064 host = Qt;
4065 service = Qnil;
4066 switch (saddr.sa.sa_family)
4068 case AF_INET:
4070 Lisp_Object args[5];
4071 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4072 args[0] = build_string ("%d.%d.%d.%d");
4073 args[1] = make_number (*ip++);
4074 args[2] = make_number (*ip++);
4075 args[3] = make_number (*ip++);
4076 args[4] = make_number (*ip++);
4077 host = Fformat (5, 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;
4087 #ifdef AF_INET6
4088 case AF_INET6:
4090 Lisp_Object args[9];
4091 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4092 int i;
4093 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4094 for (i = 0; i < 8; i++)
4095 args[i+1] = make_number (ntohs (ip6[i]));
4096 host = Fformat (9, args);
4097 service = make_number (ntohs (saddr.in.sin_port));
4099 args[0] = build_string (" <[%s]:%d>");
4100 args[1] = host;
4101 args[2] = service;
4102 caller = Fformat (3, args);
4104 break;
4105 #endif
4107 #ifdef HAVE_LOCAL_SOCKETS
4108 case AF_LOCAL:
4109 #endif
4110 default:
4111 caller = Fnumber_to_string (make_number (connect_counter));
4112 caller = concat3 (build_string (" <"), caller, build_string (">"));
4113 break;
4116 /* Create a new buffer name for this process if it doesn't have a
4117 filter. The new buffer name is based on the buffer name or
4118 process name of the server process concatenated with the caller
4119 identification. */
4121 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4122 || EQ (ps->filter, Qt)))
4123 buffer = Qnil;
4124 else
4126 buffer = ps->buffer;
4127 if (!NILP (buffer))
4128 buffer = Fbuffer_name (buffer);
4129 else
4130 buffer = ps->name;
4131 if (!NILP (buffer))
4133 buffer = concat2 (buffer, caller);
4134 buffer = Fget_buffer_create (buffer);
4138 /* Generate a unique name for the new server process. Combine the
4139 server process name with the caller identification. */
4141 name = concat2 (ps->name, caller);
4142 proc = make_process (name);
4144 chan_process[s] = proc;
4146 fcntl (s, F_SETFL, O_NONBLOCK);
4148 p = XPROCESS (proc);
4150 /* Build new contact information for this setup. */
4151 contact = Fcopy_sequence (ps->childp);
4152 contact = Fplist_put (contact, QCserver, Qnil);
4153 contact = Fplist_put (contact, QChost, host);
4154 if (!NILP (service))
4155 contact = Fplist_put (contact, QCservice, service);
4156 contact = Fplist_put (contact, QCremote,
4157 conv_sockaddr_to_lisp (&saddr.sa, len));
4158 #ifdef HAVE_GETSOCKNAME
4159 len = sizeof saddr;
4160 if (getsockname (s, &saddr.sa, &len) == 0)
4161 contact = Fplist_put (contact, QClocal,
4162 conv_sockaddr_to_lisp (&saddr.sa, len));
4163 #endif
4165 pset_childp (p, contact);
4166 pset_plist (p, Fcopy_sequence (ps->plist));
4167 pset_type (p, Qnetwork);
4169 pset_buffer (p, buffer);
4170 pset_sentinel (p, ps->sentinel);
4171 pset_filter (p, ps->filter);
4172 pset_command (p, Qnil);
4173 p->pid = 0;
4175 /* Discard the unwind protect for closing S. */
4176 specpdl_ptr = specpdl + count;
4178 p->open_fd[SUBPROCESS_STDIN] = s;
4179 p->infd = s;
4180 p->outfd = s;
4181 pset_status (p, Qrun);
4183 /* Client processes for accepted connections are not stopped initially. */
4184 if (!EQ (p->filter, Qt))
4186 FD_SET (s, &input_wait_mask);
4187 FD_SET (s, &non_keyboard_wait_mask);
4190 if (s > max_process_desc)
4191 max_process_desc = s;
4193 /* Setup coding system for new process based on server process.
4194 This seems to be the proper thing to do, as the coding system
4195 of the new process should reflect the settings at the time the
4196 server socket was opened; not the current settings. */
4198 pset_decode_coding_system (p, ps->decode_coding_system);
4199 pset_encode_coding_system (p, ps->encode_coding_system);
4200 setup_process_coding_systems (proc);
4202 pset_decoding_buf (p, empty_unibyte_string);
4203 p->decoding_carryover = 0;
4204 pset_encoding_buf (p, empty_unibyte_string);
4206 p->inherit_coding_system_flag
4207 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4209 if (!NILP (ps->log))
4210 call3 (ps->log, server, proc,
4211 concat3 (build_string ("accept from "),
4212 (STRINGP (host) ? host : build_string ("-")),
4213 build_string ("\n")));
4215 exec_sentinel (proc,
4216 concat3 (build_string ("open from "),
4217 (STRINGP (host) ? host : build_string ("-")),
4218 build_string ("\n")));
4221 /* This variable is different from waiting_for_input in keyboard.c.
4222 It is used to communicate to a lisp process-filter/sentinel (via the
4223 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4224 for user-input when that process-filter was called.
4225 waiting_for_input cannot be used as that is by definition 0 when
4226 lisp code is being evalled.
4227 This is also used in record_asynch_buffer_change.
4228 For that purpose, this must be 0
4229 when not inside wait_reading_process_output. */
4230 static int waiting_for_user_input_p;
4232 static void
4233 wait_reading_process_output_unwind (int data)
4235 waiting_for_user_input_p = data;
4238 /* This is here so breakpoints can be put on it. */
4239 static void
4240 wait_reading_process_output_1 (void)
4244 /* Read and dispose of subprocess output while waiting for timeout to
4245 elapse and/or keyboard input to be available.
4247 TIME_LIMIT is:
4248 timeout in seconds
4249 If negative, gobble data immediately available but don't wait for any.
4251 NSECS is:
4252 an additional duration to wait, measured in nanoseconds
4253 If TIME_LIMIT is zero, then:
4254 If NSECS == 0, there is no limit.
4255 If NSECS > 0, the timeout consists of NSECS only.
4256 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4258 READ_KBD is:
4259 0 to ignore keyboard input, or
4260 1 to return when input is available, or
4261 -1 meaning caller will actually read the input, so don't throw to
4262 the quit handler, or
4264 DO_DISPLAY means redisplay should be done to show subprocess
4265 output that arrives.
4267 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4268 (and gobble terminal input into the buffer if any arrives).
4270 If WAIT_PROC is specified, wait until something arrives from that
4271 process. The return value is true if we read some input from
4272 that process.
4274 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4275 (suspending output from other processes). A negative value
4276 means don't run any timers either.
4278 If WAIT_PROC is specified, then the function returns true if we
4279 received input from that process before the timeout elapsed.
4280 Otherwise, return true if we received input from any process. */
4282 bool
4283 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4284 bool do_display,
4285 Lisp_Object wait_for_cell,
4286 struct Lisp_Process *wait_proc, int just_wait_proc)
4288 int channel, nfds;
4289 fd_set Available;
4290 fd_set Writeok;
4291 bool check_write;
4292 int check_delay;
4293 bool no_avail;
4294 int xerrno;
4295 Lisp_Object proc;
4296 struct timespec timeout, end_time;
4297 int wait_channel = -1;
4298 bool got_some_input = 0;
4299 ptrdiff_t count = SPECPDL_INDEX ();
4301 FD_ZERO (&Available);
4302 FD_ZERO (&Writeok);
4304 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4305 && !(CONSP (wait_proc->status)
4306 && EQ (XCAR (wait_proc->status), Qexit)))
4307 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4309 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4310 if (wait_proc != NULL)
4311 wait_channel = wait_proc->infd;
4313 record_unwind_protect_int (wait_reading_process_output_unwind,
4314 waiting_for_user_input_p);
4315 waiting_for_user_input_p = read_kbd;
4317 if (time_limit < 0)
4319 time_limit = 0;
4320 nsecs = -1;
4322 else if (TYPE_MAXIMUM (time_t) < time_limit)
4323 time_limit = TYPE_MAXIMUM (time_t);
4325 /* Since we may need to wait several times,
4326 compute the absolute time to return at. */
4327 if (time_limit || nsecs > 0)
4329 timeout = make_timespec (time_limit, nsecs);
4330 end_time = timespec_add (current_timespec (), timeout);
4333 while (1)
4335 bool timeout_reduced_for_timers = 0;
4337 /* If calling from keyboard input, do not quit
4338 since we want to return C-g as an input character.
4339 Otherwise, do pending quit if requested. */
4340 if (read_kbd >= 0)
4341 QUIT;
4342 else if (pending_signals)
4343 process_pending_signals ();
4345 /* Exit now if the cell we're waiting for became non-nil. */
4346 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4347 break;
4349 /* Compute time from now till when time limit is up. */
4350 /* Exit if already run out. */
4351 if (nsecs < 0)
4353 /* A negative timeout means
4354 gobble output available now
4355 but don't wait at all. */
4357 timeout = make_timespec (0, 0);
4359 else if (time_limit || nsecs > 0)
4361 struct timespec now = current_timespec ();
4362 if (timespec_cmp (end_time, now) <= 0)
4363 break;
4364 timeout = timespec_sub (end_time, now);
4366 else
4368 timeout = make_timespec (100000, 0);
4371 /* Normally we run timers here.
4372 But not if wait_for_cell; in those cases,
4373 the wait is supposed to be short,
4374 and those callers cannot handle running arbitrary Lisp code here. */
4375 if (NILP (wait_for_cell)
4376 && just_wait_proc >= 0)
4378 struct timespec timer_delay;
4382 unsigned old_timers_run = timers_run;
4383 struct buffer *old_buffer = current_buffer;
4384 Lisp_Object old_window = selected_window;
4386 timer_delay = timer_check ();
4388 /* If a timer has run, this might have changed buffers
4389 an alike. Make read_key_sequence aware of that. */
4390 if (timers_run != old_timers_run
4391 && (old_buffer != current_buffer
4392 || !EQ (old_window, selected_window))
4393 && waiting_for_user_input_p == -1)
4394 record_asynch_buffer_change ();
4396 if (timers_run != old_timers_run && do_display)
4397 /* We must retry, since a timer may have requeued itself
4398 and that could alter the time_delay. */
4399 redisplay_preserve_echo_area (9);
4400 else
4401 break;
4403 while (!detect_input_pending ());
4405 /* If there is unread keyboard input, also return. */
4406 if (read_kbd != 0
4407 && requeued_events_pending_p ())
4408 break;
4410 /* A negative timeout means do not wait at all. */
4411 if (nsecs >= 0)
4413 if (timespec_valid_p (timer_delay))
4415 if (timespec_cmp (timer_delay, timeout) < 0)
4417 timeout = timer_delay;
4418 timeout_reduced_for_timers = 1;
4421 else
4423 /* This is so a breakpoint can be put here. */
4424 wait_reading_process_output_1 ();
4429 /* Cause C-g and alarm signals to take immediate action,
4430 and cause input available signals to zero out timeout.
4432 It is important that we do this before checking for process
4433 activity. If we get a SIGCHLD after the explicit checks for
4434 process activity, timeout is the only way we will know. */
4435 if (read_kbd < 0)
4436 set_waiting_for_input (&timeout);
4438 /* If status of something has changed, and no input is
4439 available, notify the user of the change right away. After
4440 this explicit check, we'll let the SIGCHLD handler zap
4441 timeout to get our attention. */
4442 if (update_tick != process_tick)
4444 fd_set Atemp;
4445 fd_set Ctemp;
4447 if (kbd_on_hold_p ())
4448 FD_ZERO (&Atemp);
4449 else
4450 Atemp = input_wait_mask;
4451 Ctemp = write_mask;
4453 timeout = make_timespec (0, 0);
4454 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4455 &Atemp,
4456 #ifdef NON_BLOCKING_CONNECT
4457 (num_pending_connects > 0 ? &Ctemp : NULL),
4458 #else
4459 NULL,
4460 #endif
4461 NULL, &timeout, NULL)
4462 <= 0))
4464 /* It's okay for us to do this and then continue with
4465 the loop, since timeout has already been zeroed out. */
4466 clear_waiting_for_input ();
4467 status_notify (NULL);
4468 if (do_display) redisplay_preserve_echo_area (13);
4472 /* Don't wait for output from a non-running process. Just
4473 read whatever data has already been received. */
4474 if (wait_proc && wait_proc->raw_status_new)
4475 update_status (wait_proc);
4476 if (wait_proc
4477 && ! EQ (wait_proc->status, Qrun)
4478 && ! EQ (wait_proc->status, Qconnect))
4480 bool read_some_bytes = 0;
4482 clear_waiting_for_input ();
4483 XSETPROCESS (proc, wait_proc);
4485 /* Read data from the process, until we exhaust it. */
4486 while (wait_proc->infd >= 0)
4488 int nread = read_process_output (proc, wait_proc->infd);
4490 if (nread == 0)
4491 break;
4493 if (nread > 0)
4494 got_some_input = read_some_bytes = 1;
4495 else if (nread == -1 && (errno == EIO || errno == EAGAIN))
4496 break;
4497 #ifdef EWOULDBLOCK
4498 else if (nread == -1 && EWOULDBLOCK == errno)
4499 break;
4500 #endif
4502 if (read_some_bytes && do_display)
4503 redisplay_preserve_echo_area (10);
4505 break;
4508 /* Wait till there is something to do */
4510 if (wait_proc && just_wait_proc)
4512 if (wait_proc->infd < 0) /* Terminated */
4513 break;
4514 FD_SET (wait_proc->infd, &Available);
4515 check_delay = 0;
4516 check_write = 0;
4518 else if (!NILP (wait_for_cell))
4520 Available = non_process_wait_mask;
4521 check_delay = 0;
4522 check_write = 0;
4524 else
4526 if (! read_kbd)
4527 Available = non_keyboard_wait_mask;
4528 else
4529 Available = input_wait_mask;
4530 Writeok = write_mask;
4531 #ifdef SELECT_CANT_DO_WRITE_MASK
4532 check_write = 0;
4533 #else
4534 check_write = 1;
4535 #endif
4536 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4539 /* If frame size has changed or the window is newly mapped,
4540 redisplay now, before we start to wait. There is a race
4541 condition here; if a SIGIO arrives between now and the select
4542 and indicates that a frame is trashed, the select may block
4543 displaying a trashed screen. */
4544 if (frame_garbaged && do_display)
4546 clear_waiting_for_input ();
4547 redisplay_preserve_echo_area (11);
4548 if (read_kbd < 0)
4549 set_waiting_for_input (&timeout);
4552 /* Skip the `select' call if input is available and we're
4553 waiting for keyboard input or a cell change (which can be
4554 triggered by processing X events). In the latter case, set
4555 nfds to 1 to avoid breaking the loop. */
4556 no_avail = 0;
4557 if ((read_kbd || !NILP (wait_for_cell))
4558 && detect_input_pending ())
4560 nfds = read_kbd ? 0 : 1;
4561 no_avail = 1;
4564 if (!no_avail)
4567 #ifdef ADAPTIVE_READ_BUFFERING
4568 /* Set the timeout for adaptive read buffering if any
4569 process has non-zero read_output_skip and non-zero
4570 read_output_delay, and we are not reading output for a
4571 specific wait_channel. It is not executed if
4572 Vprocess_adaptive_read_buffering is nil. */
4573 if (process_output_skip && check_delay > 0)
4575 int nsecs = timeout.tv_nsec;
4576 if (timeout.tv_sec > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4577 nsecs = READ_OUTPUT_DELAY_MAX;
4578 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4580 proc = chan_process[channel];
4581 if (NILP (proc))
4582 continue;
4583 /* Find minimum non-zero read_output_delay among the
4584 processes with non-zero read_output_skip. */
4585 if (XPROCESS (proc)->read_output_delay > 0)
4587 check_delay--;
4588 if (!XPROCESS (proc)->read_output_skip)
4589 continue;
4590 FD_CLR (channel, &Available);
4591 XPROCESS (proc)->read_output_skip = 0;
4592 if (XPROCESS (proc)->read_output_delay < nsecs)
4593 nsecs = XPROCESS (proc)->read_output_delay;
4596 timeout = make_timespec (0, nsecs);
4597 process_output_skip = 0;
4599 #endif
4601 #if defined (HAVE_NS)
4602 nfds = ns_select
4603 #elif defined (HAVE_GLIB)
4604 nfds = xg_select
4605 #else
4606 nfds = pselect
4607 #endif
4608 (max (max_process_desc, max_input_desc) + 1,
4609 &Available,
4610 (check_write ? &Writeok : 0),
4611 NULL, &timeout, NULL);
4613 #ifdef HAVE_GNUTLS
4614 /* GnuTLS buffers data internally. In lowat mode it leaves
4615 some data in the TCP buffers so that select works, but
4616 with custom pull/push functions we need to check if some
4617 data is available in the buffers manually. */
4618 if (nfds == 0)
4620 if (! wait_proc)
4622 /* We're not waiting on a specific process, so loop
4623 through all the channels and check for data.
4624 This is a workaround needed for some versions of
4625 the gnutls library -- 2.12.14 has been confirmed
4626 to need it. See
4627 http://comments.gmane.org/gmane.emacs.devel/145074 */
4628 for (channel = 0; channel < FD_SETSIZE; ++channel)
4629 if (! NILP (chan_process[channel]))
4631 struct Lisp_Process *p =
4632 XPROCESS (chan_process[channel]);
4633 if (p && p->gnutls_p && p->gnutls_state && p->infd
4634 && ((emacs_gnutls_record_check_pending
4635 (p->gnutls_state))
4636 > 0))
4638 nfds++;
4639 FD_SET (p->infd, &Available);
4643 else
4645 /* Check this specific channel. */
4646 if (wait_proc->gnutls_p /* Check for valid process. */
4647 && wait_proc->gnutls_state
4648 /* Do we have pending data? */
4649 && ((emacs_gnutls_record_check_pending
4650 (wait_proc->gnutls_state))
4651 > 0))
4653 nfds = 1;
4654 /* Set to Available. */
4655 FD_SET (wait_proc->infd, &Available);
4659 #endif
4662 xerrno = errno;
4664 /* Make C-g and alarm signals set flags again */
4665 clear_waiting_for_input ();
4667 /* If we woke up due to SIGWINCH, actually change size now. */
4668 do_pending_window_change (0);
4670 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4671 /* We waited the full specified time, so return now. */
4672 break;
4673 if (nfds < 0)
4675 if (xerrno == EINTR)
4676 no_avail = 1;
4677 else if (xerrno == EBADF)
4678 emacs_abort ();
4679 else
4680 report_file_errno ("Failed select", Qnil, xerrno);
4683 if (no_avail)
4685 FD_ZERO (&Available);
4686 check_write = 0;
4689 /* Check for keyboard input */
4690 /* If there is any, return immediately
4691 to give it higher priority than subprocesses */
4693 if (read_kbd != 0)
4695 unsigned old_timers_run = timers_run;
4696 struct buffer *old_buffer = current_buffer;
4697 Lisp_Object old_window = selected_window;
4698 bool leave = 0;
4700 if (detect_input_pending_run_timers (do_display))
4702 swallow_events (do_display);
4703 if (detect_input_pending_run_timers (do_display))
4704 leave = 1;
4707 /* If a timer has run, this might have changed buffers
4708 an alike. Make read_key_sequence aware of that. */
4709 if (timers_run != old_timers_run
4710 && waiting_for_user_input_p == -1
4711 && (old_buffer != current_buffer
4712 || !EQ (old_window, selected_window)))
4713 record_asynch_buffer_change ();
4715 if (leave)
4716 break;
4719 /* If there is unread keyboard input, also return. */
4720 if (read_kbd != 0
4721 && requeued_events_pending_p ())
4722 break;
4724 /* If we are not checking for keyboard input now,
4725 do process events (but don't run any timers).
4726 This is so that X events will be processed.
4727 Otherwise they may have to wait until polling takes place.
4728 That would causes delays in pasting selections, for example.
4730 (We used to do this only if wait_for_cell.) */
4731 if (read_kbd == 0 && detect_input_pending ())
4733 swallow_events (do_display);
4734 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4735 if (detect_input_pending ())
4736 break;
4737 #endif
4740 /* Exit now if the cell we're waiting for became non-nil. */
4741 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4742 break;
4744 #ifdef USABLE_SIGIO
4745 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4746 go read it. This can happen with X on BSD after logging out.
4747 In that case, there really is no input and no SIGIO,
4748 but select says there is input. */
4750 if (read_kbd && interrupt_input
4751 && keyboard_bit_set (&Available) && ! noninteractive)
4752 handle_input_available_signal (SIGIO);
4753 #endif
4755 if (! wait_proc)
4756 got_some_input |= nfds > 0;
4758 /* If checking input just got us a size-change event from X,
4759 obey it now if we should. */
4760 if (read_kbd || ! NILP (wait_for_cell))
4761 do_pending_window_change (0);
4763 /* Check for data from a process. */
4764 if (no_avail || nfds == 0)
4765 continue;
4767 for (channel = 0; channel <= max_input_desc; ++channel)
4769 struct fd_callback_data *d = &fd_callback_info[channel];
4770 if (d->func
4771 && ((d->condition & FOR_READ
4772 && FD_ISSET (channel, &Available))
4773 || (d->condition & FOR_WRITE
4774 && FD_ISSET (channel, &write_mask))))
4775 d->func (channel, d->data);
4778 for (channel = 0; channel <= max_process_desc; channel++)
4780 if (FD_ISSET (channel, &Available)
4781 && FD_ISSET (channel, &non_keyboard_wait_mask)
4782 && !FD_ISSET (channel, &non_process_wait_mask))
4784 int nread;
4786 /* If waiting for this channel, arrange to return as
4787 soon as no more input to be processed. No more
4788 waiting. */
4789 if (wait_channel == channel)
4791 wait_channel = -1;
4792 nsecs = -1;
4793 got_some_input = 1;
4795 proc = chan_process[channel];
4796 if (NILP (proc))
4797 continue;
4799 /* If this is a server stream socket, accept connection. */
4800 if (EQ (XPROCESS (proc)->status, Qlisten))
4802 server_accept_connection (proc, channel);
4803 continue;
4806 /* Read data from the process, starting with our
4807 buffered-ahead character if we have one. */
4809 nread = read_process_output (proc, channel);
4810 if (nread > 0)
4812 /* Since read_process_output can run a filter,
4813 which can call accept-process-output,
4814 don't try to read from any other processes
4815 before doing the select again. */
4816 FD_ZERO (&Available);
4818 if (do_display)
4819 redisplay_preserve_echo_area (12);
4821 #ifdef EWOULDBLOCK
4822 else if (nread == -1 && errno == EWOULDBLOCK)
4824 #endif
4825 else if (nread == -1 && errno == EAGAIN)
4827 #ifdef WINDOWSNT
4828 /* FIXME: Is this special case still needed? */
4829 /* Note that we cannot distinguish between no input
4830 available now and a closed pipe.
4831 With luck, a closed pipe will be accompanied by
4832 subprocess termination and SIGCHLD. */
4833 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4835 #endif
4836 #ifdef HAVE_PTYS
4837 /* On some OSs with ptys, when the process on one end of
4838 a pty exits, the other end gets an error reading with
4839 errno = EIO instead of getting an EOF (0 bytes read).
4840 Therefore, if we get an error reading and errno =
4841 EIO, just continue, because the child process has
4842 exited and should clean itself up soon (e.g. when we
4843 get a SIGCHLD). */
4844 else if (nread == -1 && errno == EIO)
4846 struct Lisp_Process *p = XPROCESS (proc);
4848 /* Clear the descriptor now, so we only raise the
4849 signal once. */
4850 FD_CLR (channel, &input_wait_mask);
4851 FD_CLR (channel, &non_keyboard_wait_mask);
4853 if (p->pid == -2)
4855 /* If the EIO occurs on a pty, the SIGCHLD handler's
4856 waitpid call will not find the process object to
4857 delete. Do it here. */
4858 p->tick = ++process_tick;
4859 pset_status (p, Qfailed);
4862 #endif /* HAVE_PTYS */
4863 /* If we can detect process termination, don't consider the
4864 process gone just because its pipe is closed. */
4865 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4867 else
4869 /* Preserve status of processes already terminated. */
4870 XPROCESS (proc)->tick = ++process_tick;
4871 deactivate_process (proc);
4872 if (XPROCESS (proc)->raw_status_new)
4873 update_status (XPROCESS (proc));
4874 if (EQ (XPROCESS (proc)->status, Qrun))
4875 pset_status (XPROCESS (proc),
4876 list2 (Qexit, make_number (256)));
4879 #ifdef NON_BLOCKING_CONNECT
4880 if (FD_ISSET (channel, &Writeok)
4881 && FD_ISSET (channel, &connect_wait_mask))
4883 struct Lisp_Process *p;
4885 FD_CLR (channel, &connect_wait_mask);
4886 FD_CLR (channel, &write_mask);
4887 if (--num_pending_connects < 0)
4888 emacs_abort ();
4890 proc = chan_process[channel];
4891 if (NILP (proc))
4892 continue;
4894 p = XPROCESS (proc);
4896 #ifdef GNU_LINUX
4897 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4898 So only use it on systems where it is known to work. */
4900 socklen_t xlen = sizeof (xerrno);
4901 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4902 xerrno = errno;
4904 #else
4906 struct sockaddr pname;
4907 socklen_t pnamelen = sizeof (pname);
4909 /* If connection failed, getpeername will fail. */
4910 xerrno = 0;
4911 if (getpeername (channel, &pname, &pnamelen) < 0)
4913 /* Obtain connect failure code through error slippage. */
4914 char dummy;
4915 xerrno = errno;
4916 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
4917 xerrno = errno;
4920 #endif
4921 if (xerrno)
4923 p->tick = ++process_tick;
4924 pset_status (p, list2 (Qfailed, make_number (xerrno)));
4925 deactivate_process (proc);
4927 else
4929 pset_status (p, Qrun);
4930 /* Execute the sentinel here. If we had relied on
4931 status_notify to do it later, it will read input
4932 from the process before calling the sentinel. */
4933 exec_sentinel (proc, build_string ("open\n"));
4934 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
4936 FD_SET (p->infd, &input_wait_mask);
4937 FD_SET (p->infd, &non_keyboard_wait_mask);
4941 #endif /* NON_BLOCKING_CONNECT */
4942 } /* End for each file descriptor. */
4943 } /* End while exit conditions not met. */
4945 unbind_to (count, Qnil);
4947 /* If calling from keyboard input, do not quit
4948 since we want to return C-g as an input character.
4949 Otherwise, do pending quit if requested. */
4950 if (read_kbd >= 0)
4952 /* Prevent input_pending from remaining set if we quit. */
4953 clear_input_pending ();
4954 QUIT;
4957 return got_some_input;
4960 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4962 static Lisp_Object
4963 read_process_output_call (Lisp_Object fun_and_args)
4965 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4968 static Lisp_Object
4969 read_process_output_error_handler (Lisp_Object error_val)
4971 cmd_error_internal (error_val, "error in process filter: ");
4972 Vinhibit_quit = Qt;
4973 update_echo_area ();
4974 Fsleep_for (make_number (2), Qnil);
4975 return Qt;
4978 static void
4979 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
4980 ssize_t nbytes,
4981 struct coding_system *coding);
4983 /* Read pending output from the process channel,
4984 starting with our buffered-ahead character if we have one.
4985 Yield number of decoded characters read.
4987 This function reads at most 4096 characters.
4988 If you want to read all available subprocess output,
4989 you must call it repeatedly until it returns zero.
4991 The characters read are decoded according to PROC's coding-system
4992 for decoding. */
4994 static int
4995 read_process_output (Lisp_Object proc, register int channel)
4997 register ssize_t nbytes;
4998 char *chars;
4999 register struct Lisp_Process *p = XPROCESS (proc);
5000 struct coding_system *coding = proc_decode_coding_system[channel];
5001 int carryover = p->decoding_carryover;
5002 int readmax = 4096;
5003 ptrdiff_t count = SPECPDL_INDEX ();
5004 Lisp_Object odeactivate;
5006 chars = alloca (carryover + readmax);
5007 if (carryover)
5008 /* See the comment above. */
5009 memcpy (chars, SDATA (p->decoding_buf), carryover);
5011 #ifdef DATAGRAM_SOCKETS
5012 /* We have a working select, so proc_buffered_char is always -1. */
5013 if (DATAGRAM_CHAN_P (channel))
5015 socklen_t len = datagram_address[channel].len;
5016 nbytes = recvfrom (channel, chars + carryover, readmax,
5017 0, datagram_address[channel].sa, &len);
5019 else
5020 #endif
5022 bool buffered = proc_buffered_char[channel] >= 0;
5023 if (buffered)
5025 chars[carryover] = proc_buffered_char[channel];
5026 proc_buffered_char[channel] = -1;
5028 #ifdef HAVE_GNUTLS
5029 if (p->gnutls_p && p->gnutls_state)
5030 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5031 readmax - buffered);
5032 else
5033 #endif
5034 nbytes = emacs_read (channel, chars + carryover + buffered,
5035 readmax - buffered);
5036 #ifdef ADAPTIVE_READ_BUFFERING
5037 if (nbytes > 0 && p->adaptive_read_buffering)
5039 int delay = p->read_output_delay;
5040 if (nbytes < 256)
5042 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5044 if (delay == 0)
5045 process_output_delay_count++;
5046 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5049 else if (delay > 0 && nbytes == readmax - buffered)
5051 delay -= READ_OUTPUT_DELAY_INCREMENT;
5052 if (delay == 0)
5053 process_output_delay_count--;
5055 p->read_output_delay = delay;
5056 if (delay)
5058 p->read_output_skip = 1;
5059 process_output_skip = 1;
5062 #endif
5063 nbytes += buffered;
5064 nbytes += buffered && nbytes <= 0;
5067 p->decoding_carryover = 0;
5069 /* At this point, NBYTES holds number of bytes just received
5070 (including the one in proc_buffered_char[channel]). */
5071 if (nbytes <= 0)
5073 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5074 return nbytes;
5075 coding->mode |= CODING_MODE_LAST_BLOCK;
5078 /* Now set NBYTES how many bytes we must decode. */
5079 nbytes += carryover;
5081 odeactivate = Vdeactivate_mark;
5082 /* There's no good reason to let process filters change the current
5083 buffer, and many callers of accept-process-output, sit-for, and
5084 friends don't expect current-buffer to be changed from under them. */
5085 record_unwind_current_buffer ();
5087 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5089 /* Handling the process output should not deactivate the mark. */
5090 Vdeactivate_mark = odeactivate;
5092 unbind_to (count, Qnil);
5093 return nbytes;
5096 static void
5097 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5098 ssize_t nbytes,
5099 struct coding_system *coding)
5101 Lisp_Object outstream = p->filter;
5102 Lisp_Object text;
5103 bool outer_running_asynch_code = running_asynch_code;
5104 int waiting = waiting_for_user_input_p;
5106 /* No need to gcpro these, because all we do with them later
5107 is test them for EQness, and none of them should be a string. */
5108 #if 0
5109 Lisp_Object obuffer, okeymap;
5110 XSETBUFFER (obuffer, current_buffer);
5111 okeymap = BVAR (current_buffer, keymap);
5112 #endif
5114 /* We inhibit quit here instead of just catching it so that
5115 hitting ^G when a filter happens to be running won't screw
5116 it up. */
5117 specbind (Qinhibit_quit, Qt);
5118 specbind (Qlast_nonmenu_event, Qt);
5120 /* In case we get recursively called,
5121 and we already saved the match data nonrecursively,
5122 save the same match data in safely recursive fashion. */
5123 if (outer_running_asynch_code)
5125 Lisp_Object tem;
5126 /* Don't clobber the CURRENT match data, either! */
5127 tem = Fmatch_data (Qnil, Qnil, Qnil);
5128 restore_search_regs ();
5129 record_unwind_save_match_data ();
5130 Fset_match_data (tem, Qt);
5133 /* For speed, if a search happens within this code,
5134 save the match data in a special nonrecursive fashion. */
5135 running_asynch_code = 1;
5137 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5138 text = coding->dst_object;
5139 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5140 /* A new coding system might be found. */
5141 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5143 pset_decode_coding_system (p, Vlast_coding_system_used);
5145 /* Don't call setup_coding_system for
5146 proc_decode_coding_system[channel] here. It is done in
5147 detect_coding called via decode_coding above. */
5149 /* If a coding system for encoding is not yet decided, we set
5150 it as the same as coding-system for decoding.
5152 But, before doing that we must check if
5153 proc_encode_coding_system[p->outfd] surely points to a
5154 valid memory because p->outfd will be changed once EOF is
5155 sent to the process. */
5156 if (NILP (p->encode_coding_system)
5157 && proc_encode_coding_system[p->outfd])
5159 pset_encode_coding_system
5160 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5161 setup_coding_system (p->encode_coding_system,
5162 proc_encode_coding_system[p->outfd]);
5166 if (coding->carryover_bytes > 0)
5168 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5169 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5170 memcpy (SDATA (p->decoding_buf), coding->carryover,
5171 coding->carryover_bytes);
5172 p->decoding_carryover = coding->carryover_bytes;
5174 if (SBYTES (text) > 0)
5175 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5176 sometimes it's simply wrong to wrap (e.g. when called from
5177 accept-process-output). */
5178 internal_condition_case_1 (read_process_output_call,
5179 list3 (outstream, make_lisp_proc (p), text),
5180 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5181 read_process_output_error_handler);
5183 /* If we saved the match data nonrecursively, restore it now. */
5184 restore_search_regs ();
5185 running_asynch_code = outer_running_asynch_code;
5187 /* Restore waiting_for_user_input_p as it was
5188 when we were called, in case the filter clobbered it. */
5189 waiting_for_user_input_p = waiting;
5191 #if 0 /* Call record_asynch_buffer_change unconditionally,
5192 because we might have changed minor modes or other things
5193 that affect key bindings. */
5194 if (! EQ (Fcurrent_buffer (), obuffer)
5195 || ! EQ (current_buffer->keymap, okeymap))
5196 #endif
5197 /* But do it only if the caller is actually going to read events.
5198 Otherwise there's no need to make him wake up, and it could
5199 cause trouble (for example it would make sit_for return). */
5200 if (waiting_for_user_input_p == -1)
5201 record_asynch_buffer_change ();
5204 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5205 Sinternal_default_process_filter, 2, 2, 0,
5206 doc: /* Function used as default process filter.
5207 This inserts the process's output into its buffer, if there is one.
5208 Otherwise it discards the output. */)
5209 (Lisp_Object proc, Lisp_Object text)
5211 struct Lisp_Process *p;
5212 ptrdiff_t opoint;
5214 CHECK_PROCESS (proc);
5215 p = XPROCESS (proc);
5216 CHECK_STRING (text);
5218 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5220 Lisp_Object old_read_only;
5221 ptrdiff_t old_begv, old_zv;
5222 ptrdiff_t old_begv_byte, old_zv_byte;
5223 ptrdiff_t before, before_byte;
5224 ptrdiff_t opoint_byte;
5225 struct buffer *b;
5227 Fset_buffer (p->buffer);
5228 opoint = PT;
5229 opoint_byte = PT_BYTE;
5230 old_read_only = BVAR (current_buffer, read_only);
5231 old_begv = BEGV;
5232 old_zv = ZV;
5233 old_begv_byte = BEGV_BYTE;
5234 old_zv_byte = ZV_BYTE;
5236 bset_read_only (current_buffer, Qnil);
5238 /* Insert new output into buffer at the current end-of-output
5239 marker, thus preserving logical ordering of input and output. */
5240 if (XMARKER (p->mark)->buffer)
5241 set_point_from_marker (p->mark);
5242 else
5243 SET_PT_BOTH (ZV, ZV_BYTE);
5244 before = PT;
5245 before_byte = PT_BYTE;
5247 /* If the output marker is outside of the visible region, save
5248 the restriction and widen. */
5249 if (! (BEGV <= PT && PT <= ZV))
5250 Fwiden ();
5252 /* Adjust the multibyteness of TEXT to that of the buffer. */
5253 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5254 != ! STRING_MULTIBYTE (text))
5255 text = (STRING_MULTIBYTE (text)
5256 ? Fstring_as_unibyte (text)
5257 : Fstring_to_multibyte (text));
5258 /* Insert before markers in case we are inserting where
5259 the buffer's mark is, and the user's next command is Meta-y. */
5260 insert_from_string_before_markers (text, 0, 0,
5261 SCHARS (text), SBYTES (text), 0);
5263 /* Make sure the process marker's position is valid when the
5264 process buffer is changed in the signal_after_change above.
5265 W3 is known to do that. */
5266 if (BUFFERP (p->buffer)
5267 && (b = XBUFFER (p->buffer), b != current_buffer))
5268 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5269 else
5270 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5272 update_mode_lines = 23;
5274 /* Make sure opoint and the old restrictions
5275 float ahead of any new text just as point would. */
5276 if (opoint >= before)
5278 opoint += PT - before;
5279 opoint_byte += PT_BYTE - before_byte;
5281 if (old_begv > before)
5283 old_begv += PT - before;
5284 old_begv_byte += PT_BYTE - before_byte;
5286 if (old_zv >= before)
5288 old_zv += PT - before;
5289 old_zv_byte += PT_BYTE - before_byte;
5292 /* If the restriction isn't what it should be, set it. */
5293 if (old_begv != BEGV || old_zv != ZV)
5294 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5296 bset_read_only (current_buffer, old_read_only);
5297 SET_PT_BOTH (opoint, opoint_byte);
5299 return Qnil;
5302 /* Sending data to subprocess. */
5304 /* In send_process, when a write fails temporarily,
5305 wait_reading_process_output is called. It may execute user code,
5306 e.g. timers, that attempts to write new data to the same process.
5307 We must ensure that data is sent in the right order, and not
5308 interspersed half-completed with other writes (Bug#10815). This is
5309 handled by the write_queue element of struct process. It is a list
5310 with each entry having the form
5312 (string . (offset . length))
5314 where STRING is a lisp string, OFFSET is the offset into the
5315 string's byte sequence from which we should begin to send, and
5316 LENGTH is the number of bytes left to send. */
5318 /* Create a new entry in write_queue.
5319 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5320 BUF is a pointer to the string sequence of the input_obj or a C
5321 string in case of Qt or Qnil. */
5323 static void
5324 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5325 const char *buf, ptrdiff_t len, bool front)
5327 ptrdiff_t offset;
5328 Lisp_Object entry, obj;
5330 if (STRINGP (input_obj))
5332 offset = buf - SSDATA (input_obj);
5333 obj = input_obj;
5335 else
5337 offset = 0;
5338 obj = make_unibyte_string (buf, len);
5341 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5343 if (front)
5344 pset_write_queue (p, Fcons (entry, p->write_queue));
5345 else
5346 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5349 /* Remove the first element in the write_queue of process P, put its
5350 contents in OBJ, BUF and LEN, and return true. If the
5351 write_queue is empty, return false. */
5353 static bool
5354 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5355 const char **buf, ptrdiff_t *len)
5357 Lisp_Object entry, offset_length;
5358 ptrdiff_t offset;
5360 if (NILP (p->write_queue))
5361 return 0;
5363 entry = XCAR (p->write_queue);
5364 pset_write_queue (p, XCDR (p->write_queue));
5366 *obj = XCAR (entry);
5367 offset_length = XCDR (entry);
5369 *len = XINT (XCDR (offset_length));
5370 offset = XINT (XCAR (offset_length));
5371 *buf = SSDATA (*obj) + offset;
5373 return 1;
5376 /* Send some data to process PROC.
5377 BUF is the beginning of the data; LEN is the number of characters.
5378 OBJECT is the Lisp object that the data comes from. If OBJECT is
5379 nil or t, it means that the data comes from C string.
5381 If OBJECT is not nil, the data is encoded by PROC's coding-system
5382 for encoding before it is sent.
5384 This function can evaluate Lisp code and can garbage collect. */
5386 static void
5387 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5388 Lisp_Object object)
5390 struct Lisp_Process *p = XPROCESS (proc);
5391 ssize_t rv;
5392 struct coding_system *coding;
5394 if (p->raw_status_new)
5395 update_status (p);
5396 if (! EQ (p->status, Qrun))
5397 error ("Process %s not running", SDATA (p->name));
5398 if (p->outfd < 0)
5399 error ("Output file descriptor of %s is closed", SDATA (p->name));
5401 coding = proc_encode_coding_system[p->outfd];
5402 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5404 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5405 || (BUFFERP (object)
5406 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5407 || EQ (object, Qt))
5409 pset_encode_coding_system
5410 (p, complement_process_encoding_system (p->encode_coding_system));
5411 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5413 /* The coding system for encoding was changed to raw-text
5414 because we sent a unibyte text previously. Now we are
5415 sending a multibyte text, thus we must encode it by the
5416 original coding system specified for the current process.
5418 Another reason we come here is that the coding system
5419 was just complemented and a new one was returned by
5420 complement_process_encoding_system. */
5421 setup_coding_system (p->encode_coding_system, coding);
5422 Vlast_coding_system_used = p->encode_coding_system;
5424 coding->src_multibyte = 1;
5426 else
5428 coding->src_multibyte = 0;
5429 /* For sending a unibyte text, character code conversion should
5430 not take place but EOL conversion should. So, setup raw-text
5431 or one of the subsidiary if we have not yet done it. */
5432 if (CODING_REQUIRE_ENCODING (coding))
5434 if (CODING_REQUIRE_FLUSHING (coding))
5436 /* But, before changing the coding, we must flush out data. */
5437 coding->mode |= CODING_MODE_LAST_BLOCK;
5438 send_process (proc, "", 0, Qt);
5439 coding->mode &= CODING_MODE_LAST_BLOCK;
5441 setup_coding_system (raw_text_coding_system
5442 (Vlast_coding_system_used),
5443 coding);
5444 coding->src_multibyte = 0;
5447 coding->dst_multibyte = 0;
5449 if (CODING_REQUIRE_ENCODING (coding))
5451 coding->dst_object = Qt;
5452 if (BUFFERP (object))
5454 ptrdiff_t from_byte, from, to;
5455 ptrdiff_t save_pt, save_pt_byte;
5456 struct buffer *cur = current_buffer;
5458 set_buffer_internal (XBUFFER (object));
5459 save_pt = PT, save_pt_byte = PT_BYTE;
5461 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5462 from = BYTE_TO_CHAR (from_byte);
5463 to = BYTE_TO_CHAR (from_byte + len);
5464 TEMP_SET_PT_BOTH (from, from_byte);
5465 encode_coding_object (coding, object, from, from_byte,
5466 to, from_byte + len, Qt);
5467 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5468 set_buffer_internal (cur);
5470 else if (STRINGP (object))
5472 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5473 SBYTES (object), Qt);
5475 else
5477 coding->dst_object = make_unibyte_string (buf, len);
5478 coding->produced = len;
5481 len = coding->produced;
5482 object = coding->dst_object;
5483 buf = SSDATA (object);
5486 /* If there is already data in the write_queue, put the new data
5487 in the back of queue. Otherwise, ignore it. */
5488 if (!NILP (p->write_queue))
5489 write_queue_push (p, object, buf, len, 0);
5491 do /* while !NILP (p->write_queue) */
5493 ptrdiff_t cur_len = -1;
5494 const char *cur_buf;
5495 Lisp_Object cur_object;
5497 /* If write_queue is empty, ignore it. */
5498 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5500 cur_len = len;
5501 cur_buf = buf;
5502 cur_object = object;
5505 while (cur_len > 0)
5507 /* Send this batch, using one or more write calls. */
5508 ptrdiff_t written = 0;
5509 int outfd = p->outfd;
5510 #ifdef DATAGRAM_SOCKETS
5511 if (DATAGRAM_CHAN_P (outfd))
5513 rv = sendto (outfd, cur_buf, cur_len,
5514 0, datagram_address[outfd].sa,
5515 datagram_address[outfd].len);
5516 if (rv >= 0)
5517 written = rv;
5518 else if (errno == EMSGSIZE)
5519 report_file_error ("Sending datagram", proc);
5521 else
5522 #endif
5524 #ifdef HAVE_GNUTLS
5525 if (p->gnutls_p && p->gnutls_state)
5526 written = emacs_gnutls_write (p, cur_buf, cur_len);
5527 else
5528 #endif
5529 written = emacs_write_sig (outfd, cur_buf, cur_len);
5530 rv = (written ? 0 : -1);
5531 #ifdef ADAPTIVE_READ_BUFFERING
5532 if (p->read_output_delay > 0
5533 && p->adaptive_read_buffering == 1)
5535 p->read_output_delay = 0;
5536 process_output_delay_count--;
5537 p->read_output_skip = 0;
5539 #endif
5542 if (rv < 0)
5544 if (errno == EAGAIN
5545 #ifdef EWOULDBLOCK
5546 || errno == EWOULDBLOCK
5547 #endif
5549 /* Buffer is full. Wait, accepting input;
5550 that may allow the program
5551 to finish doing output and read more. */
5553 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5554 /* A gross hack to work around a bug in FreeBSD.
5555 In the following sequence, read(2) returns
5556 bogus data:
5558 write(2) 1022 bytes
5559 write(2) 954 bytes, get EAGAIN
5560 read(2) 1024 bytes in process_read_output
5561 read(2) 11 bytes in process_read_output
5563 That is, read(2) returns more bytes than have
5564 ever been written successfully. The 1033 bytes
5565 read are the 1022 bytes written successfully
5566 after processing (for example with CRs added if
5567 the terminal is set up that way which it is
5568 here). The same bytes will be seen again in a
5569 later read(2), without the CRs. */
5571 if (errno == EAGAIN)
5573 int flags = FWRITE;
5574 ioctl (p->outfd, TIOCFLUSH, &flags);
5576 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5578 /* Put what we should have written in wait_queue. */
5579 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5580 wait_reading_process_output (0, 20 * 1000 * 1000,
5581 0, 0, Qnil, NULL, 0);
5582 /* Reread queue, to see what is left. */
5583 break;
5585 else if (errno == EPIPE)
5587 p->raw_status_new = 0;
5588 pset_status (p, list2 (Qexit, make_number (256)));
5589 p->tick = ++process_tick;
5590 deactivate_process (proc);
5591 error ("process %s no longer connected to pipe; closed it",
5592 SDATA (p->name));
5594 else
5595 /* This is a real error. */
5596 report_file_error ("Writing to process", proc);
5598 cur_buf += written;
5599 cur_len -= written;
5602 while (!NILP (p->write_queue));
5605 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5606 3, 3, 0,
5607 doc: /* Send current contents of region as input to PROCESS.
5608 PROCESS may be a process, a buffer, the name of a process or buffer, or
5609 nil, indicating the current buffer's process.
5610 Called from program, takes three arguments, PROCESS, START and END.
5611 If the region is more than 500 characters long,
5612 it is sent in several bunches. This may happen even for shorter regions.
5613 Output from processes can arrive in between bunches. */)
5614 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5616 Lisp_Object proc = get_process (process);
5617 ptrdiff_t start_byte, end_byte;
5619 validate_region (&start, &end);
5621 start_byte = CHAR_TO_BYTE (XINT (start));
5622 end_byte = CHAR_TO_BYTE (XINT (end));
5624 if (XINT (start) < GPT && XINT (end) > GPT)
5625 move_gap_both (XINT (start), start_byte);
5627 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5628 end_byte - start_byte, Fcurrent_buffer ());
5630 return Qnil;
5633 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5634 2, 2, 0,
5635 doc: /* Send PROCESS the contents of STRING as input.
5636 PROCESS may be a process, a buffer, the name of a process or buffer, or
5637 nil, indicating the current buffer's process.
5638 If STRING is more than 500 characters long,
5639 it is sent in several bunches. This may happen even for shorter strings.
5640 Output from processes can arrive in between bunches. */)
5641 (Lisp_Object process, Lisp_Object string)
5643 Lisp_Object proc;
5644 CHECK_STRING (string);
5645 proc = get_process (process);
5646 send_process (proc, SSDATA (string),
5647 SBYTES (string), string);
5648 return Qnil;
5651 /* Return the foreground process group for the tty/pty that
5652 the process P uses. */
5653 static pid_t
5654 emacs_get_tty_pgrp (struct Lisp_Process *p)
5656 pid_t gid = -1;
5658 #ifdef TIOCGPGRP
5659 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5661 int fd;
5662 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5663 master side. Try the slave side. */
5664 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5666 if (fd != -1)
5668 ioctl (fd, TIOCGPGRP, &gid);
5669 emacs_close (fd);
5672 #endif /* defined (TIOCGPGRP ) */
5674 return gid;
5677 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5678 Sprocess_running_child_p, 0, 1, 0,
5679 doc: /* Return t if PROCESS has given the terminal to a child.
5680 If the operating system does not make it possible to find out,
5681 return t unconditionally. */)
5682 (Lisp_Object process)
5684 /* Initialize in case ioctl doesn't exist or gives an error,
5685 in a way that will cause returning t. */
5686 pid_t gid;
5687 Lisp_Object proc;
5688 struct Lisp_Process *p;
5690 proc = get_process (process);
5691 p = XPROCESS (proc);
5693 if (!EQ (p->type, Qreal))
5694 error ("Process %s is not a subprocess",
5695 SDATA (p->name));
5696 if (p->infd < 0)
5697 error ("Process %s is not active",
5698 SDATA (p->name));
5700 gid = emacs_get_tty_pgrp (p);
5702 if (gid == p->pid)
5703 return Qnil;
5704 return Qt;
5707 /* send a signal number SIGNO to PROCESS.
5708 If CURRENT_GROUP is t, that means send to the process group
5709 that currently owns the terminal being used to communicate with PROCESS.
5710 This is used for various commands in shell mode.
5711 If CURRENT_GROUP is lambda, that means send to the process group
5712 that currently owns the terminal, but only if it is NOT the shell itself.
5714 If NOMSG is false, insert signal-announcements into process's buffers
5715 right away.
5717 If we can, we try to signal PROCESS by sending control characters
5718 down the pty. This allows us to signal inferiors who have changed
5719 their uid, for which kill would return an EPERM error. */
5721 static void
5722 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5723 bool nomsg)
5725 Lisp_Object proc;
5726 struct Lisp_Process *p;
5727 pid_t gid;
5728 bool no_pgrp = 0;
5730 proc = get_process (process);
5731 p = XPROCESS (proc);
5733 if (!EQ (p->type, Qreal))
5734 error ("Process %s is not a subprocess",
5735 SDATA (p->name));
5736 if (p->infd < 0)
5737 error ("Process %s is not active",
5738 SDATA (p->name));
5740 if (!p->pty_flag)
5741 current_group = Qnil;
5743 /* If we are using pgrps, get a pgrp number and make it negative. */
5744 if (NILP (current_group))
5745 /* Send the signal to the shell's process group. */
5746 gid = p->pid;
5747 else
5749 #ifdef SIGNALS_VIA_CHARACTERS
5750 /* If possible, send signals to the entire pgrp
5751 by sending an input character to it. */
5753 struct termios t;
5754 cc_t *sig_char = NULL;
5756 tcgetattr (p->infd, &t);
5758 switch (signo)
5760 case SIGINT:
5761 sig_char = &t.c_cc[VINTR];
5762 break;
5764 case SIGQUIT:
5765 sig_char = &t.c_cc[VQUIT];
5766 break;
5768 case SIGTSTP:
5769 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5770 sig_char = &t.c_cc[VSWTCH];
5771 #else
5772 sig_char = &t.c_cc[VSUSP];
5773 #endif
5774 break;
5777 if (sig_char && *sig_char != CDISABLE)
5779 send_process (proc, (char *) sig_char, 1, Qnil);
5780 return;
5782 /* If we can't send the signal with a character,
5783 fall through and send it another way. */
5785 /* The code above may fall through if it can't
5786 handle the signal. */
5787 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5789 #ifdef TIOCGPGRP
5790 /* Get the current pgrp using the tty itself, if we have that.
5791 Otherwise, use the pty to get the pgrp.
5792 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5793 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5794 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5795 His patch indicates that if TIOCGPGRP returns an error, then
5796 we should just assume that p->pid is also the process group id. */
5798 gid = emacs_get_tty_pgrp (p);
5800 if (gid == -1)
5801 /* If we can't get the information, assume
5802 the shell owns the tty. */
5803 gid = p->pid;
5805 /* It is not clear whether anything really can set GID to -1.
5806 Perhaps on some system one of those ioctls can or could do so.
5807 Or perhaps this is vestigial. */
5808 if (gid == -1)
5809 no_pgrp = 1;
5810 #else /* ! defined (TIOCGPGRP ) */
5811 /* Can't select pgrps on this system, so we know that
5812 the child itself heads the pgrp. */
5813 gid = p->pid;
5814 #endif /* ! defined (TIOCGPGRP ) */
5816 /* If current_group is lambda, and the shell owns the terminal,
5817 don't send any signal. */
5818 if (EQ (current_group, Qlambda) && gid == p->pid)
5819 return;
5822 #ifdef SIGCONT
5823 if (signo == SIGCONT)
5825 p->raw_status_new = 0;
5826 pset_status (p, Qrun);
5827 p->tick = ++process_tick;
5828 if (!nomsg)
5830 status_notify (NULL);
5831 redisplay_preserve_echo_area (13);
5834 #endif
5836 /* If we don't have process groups, send the signal to the immediate
5837 subprocess. That isn't really right, but it's better than any
5838 obvious alternative. */
5839 if (no_pgrp)
5841 kill (p->pid, signo);
5842 return;
5845 /* gid may be a pid, or minus a pgrp's number */
5846 #ifdef TIOCSIGSEND
5847 if (!NILP (current_group))
5849 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
5850 kill (-gid, signo);
5852 else
5854 gid = - p->pid;
5855 kill (gid, signo);
5857 #else /* ! defined (TIOCSIGSEND) */
5858 kill (-gid, signo);
5859 #endif /* ! defined (TIOCSIGSEND) */
5862 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5863 doc: /* Interrupt process PROCESS.
5864 PROCESS may be a process, a buffer, or the name of a process or buffer.
5865 No arg or nil means current buffer's process.
5866 Second arg CURRENT-GROUP non-nil means send signal to
5867 the current process-group of the process's controlling terminal
5868 rather than to the process's own process group.
5869 If the process is a shell, this means interrupt current subjob
5870 rather than the shell.
5872 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5873 don't send the signal. */)
5874 (Lisp_Object process, Lisp_Object current_group)
5876 process_send_signal (process, SIGINT, current_group, 0);
5877 return process;
5880 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5881 doc: /* Kill process PROCESS. May be process or name of one.
5882 See function `interrupt-process' for more details on usage. */)
5883 (Lisp_Object process, Lisp_Object current_group)
5885 process_send_signal (process, SIGKILL, current_group, 0);
5886 return process;
5889 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5890 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5891 See function `interrupt-process' for more details on usage. */)
5892 (Lisp_Object process, Lisp_Object current_group)
5894 process_send_signal (process, SIGQUIT, current_group, 0);
5895 return process;
5898 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
5899 doc: /* Stop process PROCESS. May be process or name of one.
5900 See function `interrupt-process' for more details on usage.
5901 If PROCESS is a network or serial process, inhibit handling of incoming
5902 traffic. */)
5903 (Lisp_Object process, Lisp_Object current_group)
5905 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5907 struct Lisp_Process *p;
5909 p = XPROCESS (process);
5910 if (NILP (p->command)
5911 && p->infd >= 0)
5913 FD_CLR (p->infd, &input_wait_mask);
5914 FD_CLR (p->infd, &non_keyboard_wait_mask);
5916 pset_command (p, Qt);
5917 return process;
5919 #ifndef SIGTSTP
5920 error ("No SIGTSTP support");
5921 #else
5922 process_send_signal (process, SIGTSTP, current_group, 0);
5923 #endif
5924 return process;
5927 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
5928 doc: /* Continue process PROCESS. May be process or name of one.
5929 See function `interrupt-process' for more details on usage.
5930 If PROCESS is a network or serial process, resume handling of incoming
5931 traffic. */)
5932 (Lisp_Object process, Lisp_Object current_group)
5934 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5936 struct Lisp_Process *p;
5938 p = XPROCESS (process);
5939 if (EQ (p->command, Qt)
5940 && p->infd >= 0
5941 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
5943 FD_SET (p->infd, &input_wait_mask);
5944 FD_SET (p->infd, &non_keyboard_wait_mask);
5945 #ifdef WINDOWSNT
5946 if (fd_info[ p->infd ].flags & FILE_SERIAL)
5947 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
5948 #else /* not WINDOWSNT */
5949 tcflush (p->infd, TCIFLUSH);
5950 #endif /* not WINDOWSNT */
5952 pset_command (p, Qnil);
5953 return process;
5955 #ifdef SIGCONT
5956 process_send_signal (process, SIGCONT, current_group, 0);
5957 #else
5958 error ("No SIGCONT support");
5959 #endif
5960 return process;
5963 /* Return the integer value of the signal whose abbreviation is ABBR,
5964 or a negative number if there is no such signal. */
5965 static int
5966 abbr_to_signal (char const *name)
5968 int i, signo;
5969 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
5971 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
5972 name += 3;
5974 for (i = 0; i < sizeof sigbuf; i++)
5976 sigbuf[i] = c_toupper (name[i]);
5977 if (! sigbuf[i])
5978 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
5981 return -1;
5984 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
5985 2, 2, "sProcess (name or number): \nnSignal code: ",
5986 doc: /* Send PROCESS the signal with code SIGCODE.
5987 PROCESS may also be a number specifying the process id of the
5988 process to signal; in this case, the process need not be a child of
5989 this Emacs.
5990 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5991 (Lisp_Object process, Lisp_Object sigcode)
5993 pid_t pid;
5994 int signo;
5996 if (STRINGP (process))
5998 Lisp_Object tem = Fget_process (process);
5999 if (NILP (tem))
6001 Lisp_Object process_number =
6002 string_to_number (SSDATA (process), 10, 1);
6003 if (INTEGERP (process_number) || FLOATP (process_number))
6004 tem = process_number;
6006 process = tem;
6008 else if (!NUMBERP (process))
6009 process = get_process (process);
6011 if (NILP (process))
6012 return process;
6014 if (NUMBERP (process))
6015 CONS_TO_INTEGER (process, pid_t, pid);
6016 else
6018 CHECK_PROCESS (process);
6019 pid = XPROCESS (process)->pid;
6020 if (pid <= 0)
6021 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6024 if (INTEGERP (sigcode))
6026 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6027 signo = XINT (sigcode);
6029 else
6031 char *name;
6033 CHECK_SYMBOL (sigcode);
6034 name = SSDATA (SYMBOL_NAME (sigcode));
6036 signo = abbr_to_signal (name);
6037 if (signo < 0)
6038 error ("Undefined signal name %s", name);
6041 return make_number (kill (pid, signo));
6044 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6045 doc: /* Make PROCESS see end-of-file in its input.
6046 EOF comes after any text already sent to it.
6047 PROCESS may be a process, a buffer, the name of a process or buffer, or
6048 nil, indicating the current buffer's process.
6049 If PROCESS is a network connection, or is a process communicating
6050 through a pipe (as opposed to a pty), then you cannot send any more
6051 text to PROCESS after you call this function.
6052 If PROCESS is a serial process, wait until all output written to the
6053 process has been transmitted to the serial port. */)
6054 (Lisp_Object process)
6056 Lisp_Object proc;
6057 struct coding_system *coding = NULL;
6058 int outfd;
6060 if (DATAGRAM_CONN_P (process))
6061 return process;
6063 proc = get_process (process);
6064 outfd = XPROCESS (proc)->outfd;
6065 if (outfd >= 0)
6066 coding = proc_encode_coding_system[outfd];
6068 /* Make sure the process is really alive. */
6069 if (XPROCESS (proc)->raw_status_new)
6070 update_status (XPROCESS (proc));
6071 if (! EQ (XPROCESS (proc)->status, Qrun))
6072 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6074 if (coding && CODING_REQUIRE_FLUSHING (coding))
6076 coding->mode |= CODING_MODE_LAST_BLOCK;
6077 send_process (proc, "", 0, Qnil);
6080 if (XPROCESS (proc)->pty_flag)
6081 send_process (proc, "\004", 1, Qnil);
6082 else if (EQ (XPROCESS (proc)->type, Qserial))
6084 #ifndef WINDOWSNT
6085 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6086 report_file_error ("Failed tcdrain", Qnil);
6087 #endif /* not WINDOWSNT */
6088 /* Do nothing on Windows because writes are blocking. */
6090 else
6092 struct Lisp_Process *p = XPROCESS (proc);
6093 int old_outfd = p->outfd;
6094 int new_outfd;
6096 #ifdef HAVE_SHUTDOWN
6097 /* If this is a network connection, or socketpair is used
6098 for communication with the subprocess, call shutdown to cause EOF.
6099 (In some old system, shutdown to socketpair doesn't work.
6100 Then we just can't win.) */
6101 if (EQ (p->type, Qnetwork)
6102 || p->infd == old_outfd)
6103 shutdown (old_outfd, 1);
6104 #endif
6105 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6106 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6107 if (new_outfd < 0)
6108 report_file_error ("Opening null device", Qnil);
6109 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6110 p->outfd = new_outfd;
6112 if (!proc_encode_coding_system[new_outfd])
6113 proc_encode_coding_system[new_outfd]
6114 = xmalloc (sizeof (struct coding_system));
6115 if (old_outfd >= 0)
6117 *proc_encode_coding_system[new_outfd]
6118 = *proc_encode_coding_system[old_outfd];
6119 memset (proc_encode_coding_system[old_outfd], 0,
6120 sizeof (struct coding_system));
6122 else
6123 setup_coding_system (p->encode_coding_system,
6124 proc_encode_coding_system[new_outfd]);
6126 return process;
6129 /* The main Emacs thread records child processes in three places:
6131 - Vprocess_alist, for asynchronous subprocesses, which are child
6132 processes visible to Lisp.
6134 - deleted_pid_list, for child processes invisible to Lisp,
6135 typically because of delete-process. These are recorded so that
6136 the processes can be reaped when they exit, so that the operating
6137 system's process table is not cluttered by zombies.
6139 - the local variable PID in Fcall_process, call_process_cleanup and
6140 call_process_kill, for synchronous subprocesses.
6141 record_unwind_protect is used to make sure this process is not
6142 forgotten: if the user interrupts call-process and the child
6143 process refuses to exit immediately even with two C-g's,
6144 call_process_kill adds PID's contents to deleted_pid_list before
6145 returning.
6147 The main Emacs thread invokes waitpid only on child processes that
6148 it creates and that have not been reaped. This avoid races on
6149 platforms such as GTK, where other threads create their own
6150 subprocesses which the main thread should not reap. For example,
6151 if the main thread attempted to reap an already-reaped child, it
6152 might inadvertently reap a GTK-created process that happened to
6153 have the same process ID. */
6155 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6156 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6157 keep track of its own children. GNUstep is similar. */
6159 static void dummy_handler (int sig) {}
6160 static signal_handler_t volatile lib_child_handler;
6162 /* Handle a SIGCHLD signal by looking for known child processes of
6163 Emacs whose status have changed. For each one found, record its
6164 new status.
6166 All we do is change the status; we do not run sentinels or print
6167 notifications. That is saved for the next time keyboard input is
6168 done, in order to avoid timing errors.
6170 ** WARNING: this can be called during garbage collection.
6171 Therefore, it must not be fooled by the presence of mark bits in
6172 Lisp objects.
6174 ** USG WARNING: Although it is not obvious from the documentation
6175 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6176 signal() before executing at least one wait(), otherwise the
6177 handler will be called again, resulting in an infinite loop. The
6178 relevant portion of the documentation reads "SIGCLD signals will be
6179 queued and the signal-catching function will be continually
6180 reentered until the queue is empty". Invoking signal() causes the
6181 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6182 Inc.
6184 ** Malloc WARNING: This should never call malloc either directly or
6185 indirectly; if it does, that is a bug */
6187 static void
6188 handle_child_signal (int sig)
6190 Lisp_Object tail, proc;
6192 /* Find the process that signaled us, and record its status. */
6194 /* The process can have been deleted by Fdelete_process, or have
6195 been started asynchronously by Fcall_process. */
6196 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6198 bool all_pids_are_fixnums
6199 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6200 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6201 Lisp_Object head = XCAR (tail);
6202 Lisp_Object xpid;
6203 if (! CONSP (head))
6204 continue;
6205 xpid = XCAR (head);
6206 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6208 pid_t deleted_pid;
6209 if (INTEGERP (xpid))
6210 deleted_pid = XINT (xpid);
6211 else
6212 deleted_pid = XFLOAT_DATA (xpid);
6213 if (child_status_changed (deleted_pid, 0, 0))
6215 if (STRINGP (XCDR (head)))
6216 unlink (SSDATA (XCDR (head)));
6217 XSETCAR (tail, Qnil);
6222 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6223 FOR_EACH_PROCESS (tail, proc)
6225 struct Lisp_Process *p = XPROCESS (proc);
6226 int status;
6228 if (p->alive
6229 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6231 /* Change the status of the process that was found. */
6232 p->tick = ++process_tick;
6233 p->raw_status = status;
6234 p->raw_status_new = 1;
6236 /* If process has terminated, stop waiting for its output. */
6237 if (WIFSIGNALED (status) || WIFEXITED (status))
6239 bool clear_desc_flag = 0;
6240 p->alive = 0;
6241 if (p->infd >= 0)
6242 clear_desc_flag = 1;
6244 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6245 if (clear_desc_flag)
6247 FD_CLR (p->infd, &input_wait_mask);
6248 FD_CLR (p->infd, &non_keyboard_wait_mask);
6254 lib_child_handler (sig);
6255 #ifdef NS_IMPL_GNUSTEP
6256 /* NSTask in GNUstep sets its child handler each time it is called.
6257 So we must re-set ours. */
6258 catch_child_signal();
6259 #endif
6262 static void
6263 deliver_child_signal (int sig)
6265 deliver_process_signal (sig, handle_child_signal);
6269 static Lisp_Object
6270 exec_sentinel_error_handler (Lisp_Object error_val)
6272 cmd_error_internal (error_val, "error in process sentinel: ");
6273 Vinhibit_quit = Qt;
6274 update_echo_area ();
6275 Fsleep_for (make_number (2), Qnil);
6276 return Qt;
6279 static void
6280 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6282 Lisp_Object sentinel, odeactivate;
6283 struct Lisp_Process *p = XPROCESS (proc);
6284 ptrdiff_t count = SPECPDL_INDEX ();
6285 bool outer_running_asynch_code = running_asynch_code;
6286 int waiting = waiting_for_user_input_p;
6288 if (inhibit_sentinels)
6289 return;
6291 /* No need to gcpro these, because all we do with them later
6292 is test them for EQness, and none of them should be a string. */
6293 odeactivate = Vdeactivate_mark;
6294 #if 0
6295 Lisp_Object obuffer, okeymap;
6296 XSETBUFFER (obuffer, current_buffer);
6297 okeymap = BVAR (current_buffer, keymap);
6298 #endif
6300 /* There's no good reason to let sentinels change the current
6301 buffer, and many callers of accept-process-output, sit-for, and
6302 friends don't expect current-buffer to be changed from under them. */
6303 record_unwind_current_buffer ();
6305 sentinel = p->sentinel;
6307 /* Inhibit quit so that random quits don't screw up a running filter. */
6308 specbind (Qinhibit_quit, Qt);
6309 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6311 /* In case we get recursively called,
6312 and we already saved the match data nonrecursively,
6313 save the same match data in safely recursive fashion. */
6314 if (outer_running_asynch_code)
6316 Lisp_Object tem;
6317 tem = Fmatch_data (Qnil, Qnil, Qnil);
6318 restore_search_regs ();
6319 record_unwind_save_match_data ();
6320 Fset_match_data (tem, Qt);
6323 /* For speed, if a search happens within this code,
6324 save the match data in a special nonrecursive fashion. */
6325 running_asynch_code = 1;
6327 internal_condition_case_1 (read_process_output_call,
6328 list3 (sentinel, proc, reason),
6329 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6330 exec_sentinel_error_handler);
6332 /* If we saved the match data nonrecursively, restore it now. */
6333 restore_search_regs ();
6334 running_asynch_code = outer_running_asynch_code;
6336 Vdeactivate_mark = odeactivate;
6338 /* Restore waiting_for_user_input_p as it was
6339 when we were called, in case the filter clobbered it. */
6340 waiting_for_user_input_p = waiting;
6342 #if 0
6343 if (! EQ (Fcurrent_buffer (), obuffer)
6344 || ! EQ (current_buffer->keymap, okeymap))
6345 #endif
6346 /* But do it only if the caller is actually going to read events.
6347 Otherwise there's no need to make him wake up, and it could
6348 cause trouble (for example it would make sit_for return). */
6349 if (waiting_for_user_input_p == -1)
6350 record_asynch_buffer_change ();
6352 unbind_to (count, Qnil);
6355 /* Report all recent events of a change in process status
6356 (either run the sentinel or output a message).
6357 This is usually done while Emacs is waiting for keyboard input
6358 but can be done at other times. */
6360 static void
6361 status_notify (struct Lisp_Process *deleting_process)
6363 register Lisp_Object proc;
6364 Lisp_Object tail, msg;
6365 struct gcpro gcpro1, gcpro2;
6367 tail = Qnil;
6368 msg = Qnil;
6369 /* We need to gcpro tail; if read_process_output calls a filter
6370 which deletes a process and removes the cons to which tail points
6371 from Vprocess_alist, and then causes a GC, tail is an unprotected
6372 reference. */
6373 GCPRO2 (tail, msg);
6375 /* Set this now, so that if new processes are created by sentinels
6376 that we run, we get called again to handle their status changes. */
6377 update_tick = process_tick;
6379 FOR_EACH_PROCESS (tail, proc)
6381 Lisp_Object symbol;
6382 register struct Lisp_Process *p = XPROCESS (proc);
6384 if (p->tick != p->update_tick)
6386 p->update_tick = p->tick;
6388 /* If process is still active, read any output that remains. */
6389 while (! EQ (p->filter, Qt)
6390 && ! EQ (p->status, Qconnect)
6391 && ! EQ (p->status, Qlisten)
6392 /* Network or serial process not stopped: */
6393 && ! EQ (p->command, Qt)
6394 && p->infd >= 0
6395 && p != deleting_process
6396 && read_process_output (proc, p->infd) > 0);
6398 /* Get the text to use for the message. */
6399 if (p->raw_status_new)
6400 update_status (p);
6401 msg = status_message (p);
6403 /* If process is terminated, deactivate it or delete it. */
6404 symbol = p->status;
6405 if (CONSP (p->status))
6406 symbol = XCAR (p->status);
6408 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6409 || EQ (symbol, Qclosed))
6411 if (delete_exited_processes)
6412 remove_process (proc);
6413 else
6414 deactivate_process (proc);
6417 /* The actions above may have further incremented p->tick.
6418 So set p->update_tick again so that an error in the sentinel will
6419 not cause this code to be run again. */
6420 p->update_tick = p->tick;
6421 /* Now output the message suitably. */
6422 exec_sentinel (proc, msg);
6424 } /* end for */
6426 update_mode_lines = 24; /* In case buffers use %s in mode-line-format. */
6427 UNGCPRO;
6430 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6431 Sinternal_default_process_sentinel, 2, 2, 0,
6432 doc: /* Function used as default sentinel for processes.
6433 This inserts a status message into the process's buffer, if there is one. */)
6434 (Lisp_Object proc, Lisp_Object msg)
6436 Lisp_Object buffer, symbol;
6437 struct Lisp_Process *p;
6438 CHECK_PROCESS (proc);
6439 p = XPROCESS (proc);
6440 buffer = p->buffer;
6441 symbol = p->status;
6442 if (CONSP (symbol))
6443 symbol = XCAR (symbol);
6445 if (!EQ (symbol, Qrun) && !NILP (buffer))
6447 Lisp_Object tem;
6448 struct buffer *old = current_buffer;
6449 ptrdiff_t opoint, opoint_byte;
6450 ptrdiff_t before, before_byte;
6452 /* Avoid error if buffer is deleted
6453 (probably that's why the process is dead, too). */
6454 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6455 return Qnil;
6456 Fset_buffer (buffer);
6458 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6459 msg = (code_convert_string_norecord
6460 (msg, Vlocale_coding_system, 1));
6462 opoint = PT;
6463 opoint_byte = PT_BYTE;
6464 /* Insert new output into buffer
6465 at the current end-of-output marker,
6466 thus preserving logical ordering of input and output. */
6467 if (XMARKER (p->mark)->buffer)
6468 Fgoto_char (p->mark);
6469 else
6470 SET_PT_BOTH (ZV, ZV_BYTE);
6472 before = PT;
6473 before_byte = PT_BYTE;
6475 tem = BVAR (current_buffer, read_only);
6476 bset_read_only (current_buffer, Qnil);
6477 insert_string ("\nProcess ");
6478 { /* FIXME: temporary kludge. */
6479 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6480 insert_string (" ");
6481 Finsert (1, &msg);
6482 bset_read_only (current_buffer, tem);
6483 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6485 if (opoint >= before)
6486 SET_PT_BOTH (opoint + (PT - before),
6487 opoint_byte + (PT_BYTE - before_byte));
6488 else
6489 SET_PT_BOTH (opoint, opoint_byte);
6491 set_buffer_internal (old);
6493 return Qnil;
6497 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6498 Sset_process_coding_system, 1, 3, 0,
6499 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6500 DECODING will be used to decode subprocess output and ENCODING to
6501 encode subprocess input. */)
6502 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6504 register struct Lisp_Process *p;
6506 CHECK_PROCESS (process);
6507 p = XPROCESS (process);
6508 if (p->infd < 0)
6509 error ("Input file descriptor of %s closed", SDATA (p->name));
6510 if (p->outfd < 0)
6511 error ("Output file descriptor of %s closed", SDATA (p->name));
6512 Fcheck_coding_system (decoding);
6513 Fcheck_coding_system (encoding);
6514 encoding = coding_inherit_eol_type (encoding, Qnil);
6515 pset_decode_coding_system (p, decoding);
6516 pset_encode_coding_system (p, encoding);
6517 setup_process_coding_systems (process);
6519 return Qnil;
6522 DEFUN ("process-coding-system",
6523 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6524 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6525 (register Lisp_Object process)
6527 CHECK_PROCESS (process);
6528 return Fcons (XPROCESS (process)->decode_coding_system,
6529 XPROCESS (process)->encode_coding_system);
6532 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6533 Sset_process_filter_multibyte, 2, 2, 0,
6534 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6535 If FLAG is non-nil, the filter is given multibyte strings.
6536 If FLAG is nil, the filter is given unibyte strings. In this case,
6537 all character code conversion except for end-of-line conversion is
6538 suppressed. */)
6539 (Lisp_Object process, Lisp_Object flag)
6541 register struct Lisp_Process *p;
6543 CHECK_PROCESS (process);
6544 p = XPROCESS (process);
6545 if (NILP (flag))
6546 pset_decode_coding_system
6547 (p, raw_text_coding_system (p->decode_coding_system));
6548 setup_process_coding_systems (process);
6550 return Qnil;
6553 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6554 Sprocess_filter_multibyte_p, 1, 1, 0,
6555 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6556 (Lisp_Object process)
6558 register struct Lisp_Process *p;
6559 struct coding_system *coding;
6561 CHECK_PROCESS (process);
6562 p = XPROCESS (process);
6563 coding = proc_decode_coding_system[p->infd];
6564 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6570 # ifdef HAVE_GPM
6572 void
6573 add_gpm_wait_descriptor (int desc)
6575 add_keyboard_wait_descriptor (desc);
6578 void
6579 delete_gpm_wait_descriptor (int desc)
6581 delete_keyboard_wait_descriptor (desc);
6584 # endif
6586 # ifdef USABLE_SIGIO
6588 /* Return true if *MASK has a bit set
6589 that corresponds to one of the keyboard input descriptors. */
6591 static bool
6592 keyboard_bit_set (fd_set *mask)
6594 int fd;
6596 for (fd = 0; fd <= max_input_desc; fd++)
6597 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6598 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6599 return 1;
6601 return 0;
6603 # endif
6605 #else /* not subprocesses */
6607 /* Defined on msdos.c. */
6608 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6609 struct timespec *, void *);
6611 /* Implementation of wait_reading_process_output, assuming that there
6612 are no subprocesses. Used only by the MS-DOS build.
6614 Wait for timeout to elapse and/or keyboard input to be available.
6616 TIME_LIMIT is:
6617 timeout in seconds
6618 If negative, gobble data immediately available but don't wait for any.
6620 NSECS is:
6621 an additional duration to wait, measured in nanoseconds
6622 If TIME_LIMIT is zero, then:
6623 If NSECS == 0, there is no limit.
6624 If NSECS > 0, the timeout consists of NSECS only.
6625 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6627 READ_KBD is:
6628 0 to ignore keyboard input, or
6629 1 to return when input is available, or
6630 -1 means caller will actually read the input, so don't throw to
6631 the quit handler.
6633 see full version for other parameters. We know that wait_proc will
6634 always be NULL, since `subprocesses' isn't defined.
6636 DO_DISPLAY means redisplay should be done to show subprocess
6637 output that arrives.
6639 Return true if we received input from any process. */
6641 bool
6642 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6643 bool do_display,
6644 Lisp_Object wait_for_cell,
6645 struct Lisp_Process *wait_proc, int just_wait_proc)
6647 register int nfds;
6648 struct timespec end_time, timeout;
6650 if (time_limit < 0)
6652 time_limit = 0;
6653 nsecs = -1;
6655 else if (TYPE_MAXIMUM (time_t) < time_limit)
6656 time_limit = TYPE_MAXIMUM (time_t);
6658 /* What does time_limit really mean? */
6659 if (time_limit || nsecs > 0)
6661 timeout = make_timespec (time_limit, nsecs);
6662 end_time = timespec_add (current_timespec (), timeout);
6665 /* Turn off periodic alarms (in case they are in use)
6666 and then turn off any other atimers,
6667 because the select emulator uses alarms. */
6668 stop_polling ();
6669 turn_on_atimers (0);
6671 while (1)
6673 bool timeout_reduced_for_timers = 0;
6674 fd_set waitchannels;
6675 int xerrno;
6677 /* If calling from keyboard input, do not quit
6678 since we want to return C-g as an input character.
6679 Otherwise, do pending quit if requested. */
6680 if (read_kbd >= 0)
6681 QUIT;
6683 /* Exit now if the cell we're waiting for became non-nil. */
6684 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6685 break;
6687 /* Compute time from now till when time limit is up. */
6688 /* Exit if already run out. */
6689 if (nsecs < 0)
6691 /* A negative timeout means
6692 gobble output available now
6693 but don't wait at all. */
6695 timeout = make_timespec (0, 0);
6697 else if (time_limit || nsecs > 0)
6699 struct timespec now = current_timespec ();
6700 if (timespec_cmp (end_time, now) <= 0)
6701 break;
6702 timeout = timespec_sub (end_time, now);
6704 else
6706 timeout = make_timespec (100000, 0);
6709 /* If our caller will not immediately handle keyboard events,
6710 run timer events directly.
6711 (Callers that will immediately read keyboard events
6712 call timer_delay on their own.) */
6713 if (NILP (wait_for_cell))
6715 struct timespec timer_delay;
6719 unsigned old_timers_run = timers_run;
6720 timer_delay = timer_check ();
6721 if (timers_run != old_timers_run && do_display)
6722 /* We must retry, since a timer may have requeued itself
6723 and that could alter the time delay. */
6724 redisplay_preserve_echo_area (14);
6725 else
6726 break;
6728 while (!detect_input_pending ());
6730 /* If there is unread keyboard input, also return. */
6731 if (read_kbd != 0
6732 && requeued_events_pending_p ())
6733 break;
6735 if (timespec_valid_p (timer_delay) && nsecs >= 0)
6737 if (timespec_cmp (timer_delay, timeout) < 0)
6739 timeout = timer_delay;
6740 timeout_reduced_for_timers = 1;
6745 /* Cause C-g and alarm signals to take immediate action,
6746 and cause input available signals to zero out timeout. */
6747 if (read_kbd < 0)
6748 set_waiting_for_input (&timeout);
6750 /* If a frame has been newly mapped and needs updating,
6751 reprocess its display stuff. */
6752 if (frame_garbaged && do_display)
6754 clear_waiting_for_input ();
6755 redisplay_preserve_echo_area (15);
6756 if (read_kbd < 0)
6757 set_waiting_for_input (&timeout);
6760 /* Wait till there is something to do. */
6761 FD_ZERO (&waitchannels);
6762 if (read_kbd && detect_input_pending ())
6763 nfds = 0;
6764 else
6766 if (read_kbd || !NILP (wait_for_cell))
6767 FD_SET (0, &waitchannels);
6768 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
6771 xerrno = errno;
6773 /* Make C-g and alarm signals set flags again */
6774 clear_waiting_for_input ();
6776 /* If we woke up due to SIGWINCH, actually change size now. */
6777 do_pending_window_change (0);
6779 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
6780 /* We waited the full specified time, so return now. */
6781 break;
6783 if (nfds == -1)
6785 /* If the system call was interrupted, then go around the
6786 loop again. */
6787 if (xerrno == EINTR)
6788 FD_ZERO (&waitchannels);
6789 else
6790 report_file_errno ("Failed select", Qnil, xerrno);
6793 /* Check for keyboard input */
6795 if (read_kbd
6796 && detect_input_pending_run_timers (do_display))
6798 swallow_events (do_display);
6799 if (detect_input_pending_run_timers (do_display))
6800 break;
6803 /* If there is unread keyboard input, also return. */
6804 if (read_kbd
6805 && requeued_events_pending_p ())
6806 break;
6808 /* If wait_for_cell. check for keyboard input
6809 but don't run any timers.
6810 ??? (It seems wrong to me to check for keyboard
6811 input at all when wait_for_cell, but the code
6812 has been this way since July 1994.
6813 Try changing this after version 19.31.) */
6814 if (! NILP (wait_for_cell)
6815 && detect_input_pending ())
6817 swallow_events (do_display);
6818 if (detect_input_pending ())
6819 break;
6822 /* Exit now if the cell we're waiting for became non-nil. */
6823 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6824 break;
6827 start_polling ();
6829 return 0;
6832 #endif /* not subprocesses */
6834 /* The following functions are needed even if async subprocesses are
6835 not supported. Some of them are no-op stubs in that case. */
6837 /* Add DESC to the set of keyboard input descriptors. */
6839 void
6840 add_keyboard_wait_descriptor (int desc)
6842 #ifdef subprocesses /* actually means "not MSDOS" */
6843 FD_SET (desc, &input_wait_mask);
6844 FD_SET (desc, &non_process_wait_mask);
6845 if (desc > max_input_desc)
6846 max_input_desc = desc;
6847 #endif
6850 /* From now on, do not expect DESC to give keyboard input. */
6852 void
6853 delete_keyboard_wait_descriptor (int desc)
6855 #ifdef subprocesses
6856 FD_CLR (desc, &input_wait_mask);
6857 FD_CLR (desc, &non_process_wait_mask);
6858 delete_input_desc (desc);
6859 #endif
6862 /* Setup coding systems of PROCESS. */
6864 void
6865 setup_process_coding_systems (Lisp_Object process)
6867 #ifdef subprocesses
6868 struct Lisp_Process *p = XPROCESS (process);
6869 int inch = p->infd;
6870 int outch = p->outfd;
6871 Lisp_Object coding_system;
6873 if (inch < 0 || outch < 0)
6874 return;
6876 if (!proc_decode_coding_system[inch])
6877 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
6878 coding_system = p->decode_coding_system;
6879 if (EQ (p->filter, Qinternal_default_process_filter)
6880 && BUFFERP (p->buffer))
6882 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
6883 coding_system = raw_text_coding_system (coding_system);
6885 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
6887 if (!proc_encode_coding_system[outch])
6888 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
6889 setup_coding_system (p->encode_coding_system,
6890 proc_encode_coding_system[outch]);
6891 #endif
6894 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
6895 doc: /* Return the (or a) process associated with BUFFER.
6896 BUFFER may be a buffer or the name of one. */)
6897 (register Lisp_Object buffer)
6899 #ifdef subprocesses
6900 register Lisp_Object buf, tail, proc;
6902 if (NILP (buffer)) return Qnil;
6903 buf = Fget_buffer (buffer);
6904 if (NILP (buf)) return Qnil;
6906 FOR_EACH_PROCESS (tail, proc)
6907 if (EQ (XPROCESS (proc)->buffer, buf))
6908 return proc;
6909 #endif /* subprocesses */
6910 return Qnil;
6913 DEFUN ("process-inherit-coding-system-flag",
6914 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
6915 1, 1, 0,
6916 doc: /* Return the value of inherit-coding-system flag for PROCESS.
6917 If this flag is t, `buffer-file-coding-system' of the buffer
6918 associated with PROCESS will inherit the coding system used to decode
6919 the process output. */)
6920 (register Lisp_Object process)
6922 #ifdef subprocesses
6923 CHECK_PROCESS (process);
6924 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
6925 #else
6926 /* Ignore the argument and return the value of
6927 inherit-process-coding-system. */
6928 return inherit_process_coding_system ? Qt : Qnil;
6929 #endif
6932 /* Kill all processes associated with `buffer'.
6933 If `buffer' is nil, kill all processes */
6935 void
6936 kill_buffer_processes (Lisp_Object buffer)
6938 #ifdef subprocesses
6939 Lisp_Object tail, proc;
6941 FOR_EACH_PROCESS (tail, proc)
6942 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
6944 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6945 Fdelete_process (proc);
6946 else if (XPROCESS (proc)->infd >= 0)
6947 process_send_signal (proc, SIGHUP, Qnil, 1);
6949 #else /* subprocesses */
6950 /* Since we have no subprocesses, this does nothing. */
6951 #endif /* subprocesses */
6954 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
6955 Swaiting_for_user_input_p, 0, 0, 0,
6956 doc: /* Return non-nil if Emacs is waiting for input from the user.
6957 This is intended for use by asynchronous process output filters and sentinels. */)
6958 (void)
6960 #ifdef subprocesses
6961 return (waiting_for_user_input_p ? Qt : Qnil);
6962 #else
6963 return Qnil;
6964 #endif
6967 /* Stop reading input from keyboard sources. */
6969 void
6970 hold_keyboard_input (void)
6972 kbd_is_on_hold = 1;
6975 /* Resume reading input from keyboard sources. */
6977 void
6978 unhold_keyboard_input (void)
6980 kbd_is_on_hold = 0;
6983 /* Return true if keyboard input is on hold, zero otherwise. */
6985 bool
6986 kbd_on_hold_p (void)
6988 return kbd_is_on_hold;
6992 /* Enumeration of and access to system processes a-la ps(1). */
6994 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
6995 0, 0, 0,
6996 doc: /* Return a list of numerical process IDs of all running processes.
6997 If this functionality is unsupported, return nil.
6999 See `process-attributes' for getting attributes of a process given its ID. */)
7000 (void)
7002 return list_system_processes ();
7005 DEFUN ("process-attributes", Fprocess_attributes,
7006 Sprocess_attributes, 1, 1, 0,
7007 doc: /* Return attributes of the process given by its PID, a number.
7009 Value is an alist where each element is a cons cell of the form
7011 \(KEY . VALUE)
7013 If this functionality is unsupported, the value is nil.
7015 See `list-system-processes' for getting a list of all process IDs.
7017 The KEYs of the attributes that this function may return are listed
7018 below, together with the type of the associated VALUE (in parentheses).
7019 Not all platforms support all of these attributes; unsupported
7020 attributes will not appear in the returned alist.
7021 Unless explicitly indicated otherwise, numbers can have either
7022 integer or floating point values.
7024 euid -- Effective user User ID of the process (number)
7025 user -- User name corresponding to euid (string)
7026 egid -- Effective user Group ID of the process (number)
7027 group -- Group name corresponding to egid (string)
7028 comm -- Command name (executable name only) (string)
7029 state -- Process state code, such as "S", "R", or "T" (string)
7030 ppid -- Parent process ID (number)
7031 pgrp -- Process group ID (number)
7032 sess -- Session ID, i.e. process ID of session leader (number)
7033 ttname -- Controlling tty name (string)
7034 tpgid -- ID of foreground process group on the process's tty (number)
7035 minflt -- number of minor page faults (number)
7036 majflt -- number of major page faults (number)
7037 cminflt -- cumulative number of minor page faults (number)
7038 cmajflt -- cumulative number of major page faults (number)
7039 utime -- user time used by the process, in (current-time) format,
7040 which is a list of integers (HIGH LOW USEC PSEC)
7041 stime -- system time used by the process (current-time)
7042 time -- sum of utime and stime (current-time)
7043 cutime -- user time used by the process and its children (current-time)
7044 cstime -- system time used by the process and its children (current-time)
7045 ctime -- sum of cutime and cstime (current-time)
7046 pri -- priority of the process (number)
7047 nice -- nice value of the process (number)
7048 thcount -- process thread count (number)
7049 start -- time the process started (current-time)
7050 vsize -- virtual memory size of the process in KB's (number)
7051 rss -- resident set size of the process in KB's (number)
7052 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7053 pcpu -- percents of CPU time used by the process (floating-point number)
7054 pmem -- percents of total physical memory used by process's resident set
7055 (floating-point number)
7056 args -- command line which invoked the process (string). */)
7057 ( Lisp_Object pid)
7059 return system_process_attributes (pid);
7062 #ifdef subprocesses
7063 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7064 Invoke this after init_process_emacs, and after glib and/or GNUstep
7065 futz with the SIGCHLD handler, but before Emacs forks any children.
7066 This function's caller should block SIGCHLD. */
7068 #ifndef NS_IMPL_GNUSTEP
7069 static
7070 #endif
7071 void
7072 catch_child_signal (void)
7074 struct sigaction action, old_action;
7075 sigset_t oldset;
7076 emacs_sigaction_init (&action, deliver_child_signal);
7077 block_child_signal (&oldset);
7078 sigaction (SIGCHLD, &action, &old_action);
7079 eassert (! (old_action.sa_flags & SA_SIGINFO));
7081 if (old_action.sa_handler != deliver_child_signal)
7082 lib_child_handler
7083 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7084 ? dummy_handler
7085 : old_action.sa_handler);
7086 unblock_child_signal (&oldset);
7088 #endif /* subprocesses */
7091 /* This is not called "init_process" because that is the name of a
7092 Mach system call, so it would cause problems on Darwin systems. */
7093 void
7094 init_process_emacs (void)
7096 #ifdef subprocesses
7097 register int i;
7099 inhibit_sentinels = 0;
7101 #ifndef CANNOT_DUMP
7102 if (! noninteractive || initialized)
7103 #endif
7105 #if defined HAVE_GLIB && !defined WINDOWSNT
7106 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7107 this should always fail, but is enough to initialize glib's
7108 private SIGCHLD handler, allowing catch_child_signal to copy
7109 it into lib_child_handler. */
7110 g_source_unref (g_child_watch_source_new (getpid ()));
7111 #endif
7112 catch_child_signal ();
7115 FD_ZERO (&input_wait_mask);
7116 FD_ZERO (&non_keyboard_wait_mask);
7117 FD_ZERO (&non_process_wait_mask);
7118 FD_ZERO (&write_mask);
7119 max_process_desc = max_input_desc = -1;
7120 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7122 #ifdef NON_BLOCKING_CONNECT
7123 FD_ZERO (&connect_wait_mask);
7124 num_pending_connects = 0;
7125 #endif
7127 #ifdef ADAPTIVE_READ_BUFFERING
7128 process_output_delay_count = 0;
7129 process_output_skip = 0;
7130 #endif
7132 /* Don't do this, it caused infinite select loops. The display
7133 method should call add_keyboard_wait_descriptor on stdin if it
7134 needs that. */
7135 #if 0
7136 FD_SET (0, &input_wait_mask);
7137 #endif
7139 Vprocess_alist = Qnil;
7140 deleted_pid_list = Qnil;
7141 for (i = 0; i < FD_SETSIZE; i++)
7143 chan_process[i] = Qnil;
7144 proc_buffered_char[i] = -1;
7146 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7147 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7148 #ifdef DATAGRAM_SOCKETS
7149 memset (datagram_address, 0, sizeof datagram_address);
7150 #endif
7153 Lisp_Object subfeatures = Qnil;
7154 const struct socket_options *sopt;
7156 #define ADD_SUBFEATURE(key, val) \
7157 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7159 #ifdef NON_BLOCKING_CONNECT
7160 ADD_SUBFEATURE (QCnowait, Qt);
7161 #endif
7162 #ifdef DATAGRAM_SOCKETS
7163 ADD_SUBFEATURE (QCtype, Qdatagram);
7164 #endif
7165 #ifdef HAVE_SEQPACKET
7166 ADD_SUBFEATURE (QCtype, Qseqpacket);
7167 #endif
7168 #ifdef HAVE_LOCAL_SOCKETS
7169 ADD_SUBFEATURE (QCfamily, Qlocal);
7170 #endif
7171 ADD_SUBFEATURE (QCfamily, Qipv4);
7172 #ifdef AF_INET6
7173 ADD_SUBFEATURE (QCfamily, Qipv6);
7174 #endif
7175 #ifdef HAVE_GETSOCKNAME
7176 ADD_SUBFEATURE (QCservice, Qt);
7177 #endif
7178 ADD_SUBFEATURE (QCserver, Qt);
7180 for (sopt = socket_options; sopt->name; sopt++)
7181 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7183 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7186 #if defined (DARWIN_OS)
7187 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7188 processes. As such, we only change the default value. */
7189 if (initialized)
7191 char const *release = (STRINGP (Voperating_system_release)
7192 ? SSDATA (Voperating_system_release)
7193 : 0);
7194 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7195 Vprocess_connection_type = Qnil;
7198 #endif
7199 #endif /* subprocesses */
7200 kbd_is_on_hold = 0;
7203 void
7204 syms_of_process (void)
7206 #ifdef subprocesses
7208 DEFSYM (Qprocessp, "processp");
7209 DEFSYM (Qrun, "run");
7210 DEFSYM (Qstop, "stop");
7211 DEFSYM (Qsignal, "signal");
7213 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7214 here again.
7216 Qexit = intern_c_string ("exit");
7217 staticpro (&Qexit); */
7219 DEFSYM (Qopen, "open");
7220 DEFSYM (Qclosed, "closed");
7221 DEFSYM (Qconnect, "connect");
7222 DEFSYM (Qfailed, "failed");
7223 DEFSYM (Qlisten, "listen");
7224 DEFSYM (Qlocal, "local");
7225 DEFSYM (Qipv4, "ipv4");
7226 #ifdef AF_INET6
7227 DEFSYM (Qipv6, "ipv6");
7228 #endif
7229 DEFSYM (Qdatagram, "datagram");
7230 DEFSYM (Qseqpacket, "seqpacket");
7232 DEFSYM (QCport, ":port");
7233 DEFSYM (QCspeed, ":speed");
7234 DEFSYM (QCprocess, ":process");
7236 DEFSYM (QCbytesize, ":bytesize");
7237 DEFSYM (QCstopbits, ":stopbits");
7238 DEFSYM (QCparity, ":parity");
7239 DEFSYM (Qodd, "odd");
7240 DEFSYM (Qeven, "even");
7241 DEFSYM (QCflowcontrol, ":flowcontrol");
7242 DEFSYM (Qhw, "hw");
7243 DEFSYM (Qsw, "sw");
7244 DEFSYM (QCsummary, ":summary");
7246 DEFSYM (Qreal, "real");
7247 DEFSYM (Qnetwork, "network");
7248 DEFSYM (Qserial, "serial");
7249 DEFSYM (QCbuffer, ":buffer");
7250 DEFSYM (QChost, ":host");
7251 DEFSYM (QCservice, ":service");
7252 DEFSYM (QClocal, ":local");
7253 DEFSYM (QCremote, ":remote");
7254 DEFSYM (QCcoding, ":coding");
7255 DEFSYM (QCserver, ":server");
7256 DEFSYM (QCnowait, ":nowait");
7257 DEFSYM (QCsentinel, ":sentinel");
7258 DEFSYM (QClog, ":log");
7259 DEFSYM (QCnoquery, ":noquery");
7260 DEFSYM (QCstop, ":stop");
7261 DEFSYM (QCoptions, ":options");
7262 DEFSYM (QCplist, ":plist");
7264 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7266 staticpro (&Vprocess_alist);
7267 staticpro (&deleted_pid_list);
7269 #endif /* subprocesses */
7271 DEFSYM (QCname, ":name");
7272 DEFSYM (QCtype, ":type");
7274 DEFSYM (Qeuid, "euid");
7275 DEFSYM (Qegid, "egid");
7276 DEFSYM (Quser, "user");
7277 DEFSYM (Qgroup, "group");
7278 DEFSYM (Qcomm, "comm");
7279 DEFSYM (Qstate, "state");
7280 DEFSYM (Qppid, "ppid");
7281 DEFSYM (Qpgrp, "pgrp");
7282 DEFSYM (Qsess, "sess");
7283 DEFSYM (Qttname, "ttname");
7284 DEFSYM (Qtpgid, "tpgid");
7285 DEFSYM (Qminflt, "minflt");
7286 DEFSYM (Qmajflt, "majflt");
7287 DEFSYM (Qcminflt, "cminflt");
7288 DEFSYM (Qcmajflt, "cmajflt");
7289 DEFSYM (Qutime, "utime");
7290 DEFSYM (Qstime, "stime");
7291 DEFSYM (Qtime, "time");
7292 DEFSYM (Qcutime, "cutime");
7293 DEFSYM (Qcstime, "cstime");
7294 DEFSYM (Qctime, "ctime");
7295 #ifdef subprocesses
7296 DEFSYM (Qinternal_default_process_sentinel,
7297 "internal-default-process-sentinel");
7298 DEFSYM (Qinternal_default_process_filter,
7299 "internal-default-process-filter");
7300 #endif
7301 DEFSYM (Qpri, "pri");
7302 DEFSYM (Qnice, "nice");
7303 DEFSYM (Qthcount, "thcount");
7304 DEFSYM (Qstart, "start");
7305 DEFSYM (Qvsize, "vsize");
7306 DEFSYM (Qrss, "rss");
7307 DEFSYM (Qetime, "etime");
7308 DEFSYM (Qpcpu, "pcpu");
7309 DEFSYM (Qpmem, "pmem");
7310 DEFSYM (Qargs, "args");
7312 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7313 doc: /* Non-nil means delete processes immediately when they exit.
7314 A value of nil means don't delete them until `list-processes' is run. */);
7316 delete_exited_processes = 1;
7318 #ifdef subprocesses
7319 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7320 doc: /* Control type of device used to communicate with subprocesses.
7321 Values are nil to use a pipe, or t or `pty' to use a pty.
7322 The value has no effect if the system has no ptys or if all ptys are busy:
7323 then a pipe is used in any case.
7324 The value takes effect when `start-process' is called. */);
7325 Vprocess_connection_type = Qt;
7327 #ifdef ADAPTIVE_READ_BUFFERING
7328 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7329 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7330 On some systems, when Emacs reads the output from a subprocess, the output data
7331 is read in very small blocks, potentially resulting in very poor performance.
7332 This behavior can be remedied to some extent by setting this variable to a
7333 non-nil value, as it will automatically delay reading from such processes, to
7334 allow them to produce more output before Emacs tries to read it.
7335 If the value is t, the delay is reset after each write to the process; any other
7336 non-nil value means that the delay is not reset on write.
7337 The variable takes effect when `start-process' is called. */);
7338 Vprocess_adaptive_read_buffering = Qt;
7339 #endif
7341 defsubr (&Sprocessp);
7342 defsubr (&Sget_process);
7343 defsubr (&Sdelete_process);
7344 defsubr (&Sprocess_status);
7345 defsubr (&Sprocess_exit_status);
7346 defsubr (&Sprocess_id);
7347 defsubr (&Sprocess_name);
7348 defsubr (&Sprocess_tty_name);
7349 defsubr (&Sprocess_command);
7350 defsubr (&Sset_process_buffer);
7351 defsubr (&Sprocess_buffer);
7352 defsubr (&Sprocess_mark);
7353 defsubr (&Sset_process_filter);
7354 defsubr (&Sprocess_filter);
7355 defsubr (&Sset_process_sentinel);
7356 defsubr (&Sprocess_sentinel);
7357 defsubr (&Sset_process_window_size);
7358 defsubr (&Sset_process_inherit_coding_system_flag);
7359 defsubr (&Sset_process_query_on_exit_flag);
7360 defsubr (&Sprocess_query_on_exit_flag);
7361 defsubr (&Sprocess_contact);
7362 defsubr (&Sprocess_plist);
7363 defsubr (&Sset_process_plist);
7364 defsubr (&Sprocess_list);
7365 defsubr (&Sstart_process);
7366 defsubr (&Sserial_process_configure);
7367 defsubr (&Smake_serial_process);
7368 defsubr (&Sset_network_process_option);
7369 defsubr (&Smake_network_process);
7370 defsubr (&Sformat_network_address);
7371 defsubr (&Snetwork_interface_list);
7372 defsubr (&Snetwork_interface_info);
7373 #ifdef DATAGRAM_SOCKETS
7374 defsubr (&Sprocess_datagram_address);
7375 defsubr (&Sset_process_datagram_address);
7376 #endif
7377 defsubr (&Saccept_process_output);
7378 defsubr (&Sprocess_send_region);
7379 defsubr (&Sprocess_send_string);
7380 defsubr (&Sinterrupt_process);
7381 defsubr (&Skill_process);
7382 defsubr (&Squit_process);
7383 defsubr (&Sstop_process);
7384 defsubr (&Scontinue_process);
7385 defsubr (&Sprocess_running_child_p);
7386 defsubr (&Sprocess_send_eof);
7387 defsubr (&Ssignal_process);
7388 defsubr (&Swaiting_for_user_input_p);
7389 defsubr (&Sprocess_type);
7390 defsubr (&Sinternal_default_process_sentinel);
7391 defsubr (&Sinternal_default_process_filter);
7392 defsubr (&Sset_process_coding_system);
7393 defsubr (&Sprocess_coding_system);
7394 defsubr (&Sset_process_filter_multibyte);
7395 defsubr (&Sprocess_filter_multibyte_p);
7397 #endif /* subprocesses */
7399 defsubr (&Sget_buffer_process);
7400 defsubr (&Sprocess_inherit_coding_system_flag);
7401 defsubr (&Slist_system_processes);
7402 defsubr (&Sprocess_attributes);