* lisp/progmodes/python.el (inferior-python-mode): Use add-hook.
[emacs.git] / src / process.c
blob178fba8887e547c397f5e674e271b5deac67103d
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 # undef accept4
177 # define accept4(sockfd, addr, addrlen, flags) \
178 process_accept4 (sockfd, addr, addrlen, flags)
179 static int
180 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
182 return close_on_exec (accept (sockfd, addr, addrlen));
185 static int
186 process_socket (int domain, int type, int protocol)
188 return close_on_exec (socket (domain, type, protocol));
190 # undef socket
191 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
192 #endif
194 Lisp_Object Qprocessp;
195 static Lisp_Object Qrun, Qstop, Qsignal;
196 static Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
197 Lisp_Object Qlocal;
198 static Lisp_Object Qipv4, Qdatagram, Qseqpacket;
199 static Lisp_Object Qreal, Qnetwork, Qserial;
200 #ifdef AF_INET6
201 static Lisp_Object Qipv6;
202 #endif
203 static Lisp_Object QCport, QCprocess;
204 Lisp_Object QCspeed;
205 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
206 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
207 static Lisp_Object QCbuffer, QChost, QCservice;
208 static Lisp_Object QClocal, QCremote, QCcoding;
209 static Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
210 static Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
211 static Lisp_Object Qlast_nonmenu_event;
212 static Lisp_Object Qinternal_default_process_sentinel;
213 static Lisp_Object Qinternal_default_process_filter;
215 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
216 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
217 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
218 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
220 /* Number of events of change of status of a process. */
221 static EMACS_INT process_tick;
222 /* Number of events for which the user or sentinel has been notified. */
223 static EMACS_INT update_tick;
225 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
227 /* Only W32 has this, it really means that select can't take write mask. */
228 #ifdef BROKEN_NON_BLOCKING_CONNECT
229 #undef NON_BLOCKING_CONNECT
230 #define SELECT_CANT_DO_WRITE_MASK
231 #else
232 #ifndef NON_BLOCKING_CONNECT
233 #ifdef HAVE_SELECT
234 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
235 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
236 #define NON_BLOCKING_CONNECT
237 #endif /* EWOULDBLOCK || EINPROGRESS */
238 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
239 #endif /* HAVE_SELECT */
240 #endif /* NON_BLOCKING_CONNECT */
241 #endif /* BROKEN_NON_BLOCKING_CONNECT */
243 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
244 this system. We need to read full packets, so we need a
245 "non-destructive" select. So we require either native select,
246 or emulation of select using FIONREAD. */
248 #ifndef BROKEN_DATAGRAM_SOCKETS
249 # if defined HAVE_SELECT || defined USABLE_FIONREAD
250 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
251 # define DATAGRAM_SOCKETS
252 # endif
253 # endif
254 #endif
256 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
257 # define HAVE_SEQPACKET
258 #endif
260 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
261 #define ADAPTIVE_READ_BUFFERING
262 #endif
264 #ifdef ADAPTIVE_READ_BUFFERING
265 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
266 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
267 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
269 /* Number of processes which have a non-zero read_output_delay,
270 and therefore might be delayed for adaptive read buffering. */
272 static int process_output_delay_count;
274 /* True if any process has non-nil read_output_skip. */
276 static bool process_output_skip;
278 #else
279 #define process_output_delay_count 0
280 #endif
282 static void create_process (Lisp_Object, char **, Lisp_Object);
283 #ifdef USABLE_SIGIO
284 static bool keyboard_bit_set (fd_set *);
285 #endif
286 static void deactivate_process (Lisp_Object);
287 static void status_notify (struct Lisp_Process *);
288 static int read_process_output (Lisp_Object, int);
289 static void handle_child_signal (int);
290 static void create_pty (Lisp_Object);
292 /* If we support a window system, turn on the code to poll periodically
293 to detect C-g. It isn't actually used when doing interrupt input. */
294 #ifdef HAVE_WINDOW_SYSTEM
295 #define POLL_FOR_INPUT
296 #endif
298 static Lisp_Object get_process (register Lisp_Object name);
299 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
301 /* Mask of bits indicating the descriptors that we wait for input on. */
303 static fd_set input_wait_mask;
305 /* Mask that excludes keyboard input descriptor(s). */
307 static fd_set non_keyboard_wait_mask;
309 /* Mask that excludes process input descriptor(s). */
311 static fd_set non_process_wait_mask;
313 /* Mask for selecting for write. */
315 static fd_set write_mask;
317 #ifdef NON_BLOCKING_CONNECT
318 /* Mask of bits indicating the descriptors that we wait for connect to
319 complete on. Once they complete, they are removed from this mask
320 and added to the input_wait_mask and non_keyboard_wait_mask. */
322 static fd_set connect_wait_mask;
324 /* Number of bits set in connect_wait_mask. */
325 static int num_pending_connects;
326 #endif /* NON_BLOCKING_CONNECT */
328 /* The largest descriptor currently in use for a process object; -1 if none. */
329 static int max_process_desc;
331 /* The largest descriptor currently in use for input; -1 if none. */
332 static int max_input_desc;
334 /* Indexed by descriptor, gives the process (if any) for that descriptor */
335 static Lisp_Object chan_process[FD_SETSIZE];
337 /* Alist of elements (NAME . PROCESS) */
338 static Lisp_Object Vprocess_alist;
340 /* Buffered-ahead input char from process, indexed by channel.
341 -1 means empty (no char is buffered).
342 Used on sys V where the only way to tell if there is any
343 output from the process is to read at least one char.
344 Always -1 on systems that support FIONREAD. */
346 static int proc_buffered_char[FD_SETSIZE];
348 /* Table of `struct coding-system' for each process. */
349 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
350 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
352 #ifdef DATAGRAM_SOCKETS
353 /* Table of `partner address' for datagram sockets. */
354 static struct sockaddr_and_len {
355 struct sockaddr *sa;
356 int len;
357 } datagram_address[FD_SETSIZE];
358 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
359 #define DATAGRAM_CONN_P(proc) \
360 (PROCESSP (proc) && \
361 XPROCESS (proc)->infd >= 0 && \
362 datagram_address[XPROCESS (proc)->infd].sa != 0)
363 #else
364 #define DATAGRAM_CHAN_P(chan) (0)
365 #define DATAGRAM_CONN_P(proc) (0)
366 #endif
368 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
369 a `for' loop which iterates over processes from Vprocess_alist. */
371 #define FOR_EACH_PROCESS(list_var, proc_var) \
372 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
374 /* These setters are used only in this file, so they can be private. */
375 static void
376 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
378 p->buffer = val;
380 static void
381 pset_command (struct Lisp_Process *p, Lisp_Object val)
383 p->command = val;
385 static void
386 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
388 p->decode_coding_system = val;
390 static void
391 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
393 p->decoding_buf = val;
395 static void
396 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
398 p->encode_coding_system = val;
400 static void
401 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
403 p->encoding_buf = val;
405 static void
406 pset_filter (struct Lisp_Process *p, Lisp_Object val)
408 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
410 static void
411 pset_log (struct Lisp_Process *p, Lisp_Object val)
413 p->log = val;
415 static void
416 pset_mark (struct Lisp_Process *p, Lisp_Object val)
418 p->mark = val;
420 static void
421 pset_name (struct Lisp_Process *p, Lisp_Object val)
423 p->name = val;
425 static void
426 pset_plist (struct Lisp_Process *p, Lisp_Object val)
428 p->plist = val;
430 static void
431 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
433 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
435 static void
436 pset_status (struct Lisp_Process *p, Lisp_Object val)
438 p->status = val;
440 static void
441 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
443 p->tty_name = val;
445 static void
446 pset_type (struct Lisp_Process *p, Lisp_Object val)
448 p->type = val;
450 static void
451 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
453 p->write_queue = val;
458 static struct fd_callback_data
460 fd_callback func;
461 void *data;
462 #define FOR_READ 1
463 #define FOR_WRITE 2
464 int condition; /* mask of the defines above. */
465 } fd_callback_info[FD_SETSIZE];
468 /* Add a file descriptor FD to be monitored for when read is possible.
469 When read is possible, call FUNC with argument DATA. */
471 void
472 add_read_fd (int fd, fd_callback func, void *data)
474 eassert (fd < FD_SETSIZE);
475 add_keyboard_wait_descriptor (fd);
477 fd_callback_info[fd].func = func;
478 fd_callback_info[fd].data = data;
479 fd_callback_info[fd].condition |= FOR_READ;
482 /* Stop monitoring file descriptor FD for when read is possible. */
484 void
485 delete_read_fd (int fd)
487 eassert (fd < FD_SETSIZE);
488 delete_keyboard_wait_descriptor (fd);
490 fd_callback_info[fd].condition &= ~FOR_READ;
491 if (fd_callback_info[fd].condition == 0)
493 fd_callback_info[fd].func = 0;
494 fd_callback_info[fd].data = 0;
498 /* Add a file descriptor FD to be monitored for when write is possible.
499 When write is possible, call FUNC with argument DATA. */
501 void
502 add_write_fd (int fd, fd_callback func, void *data)
504 eassert (fd < FD_SETSIZE);
505 FD_SET (fd, &write_mask);
506 if (fd > max_input_desc)
507 max_input_desc = fd;
509 fd_callback_info[fd].func = func;
510 fd_callback_info[fd].data = data;
511 fd_callback_info[fd].condition |= FOR_WRITE;
514 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
516 static void
517 delete_input_desc (int fd)
519 if (fd == max_input_desc)
522 fd--;
523 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
524 || FD_ISSET (fd, &write_mask)));
526 max_input_desc = fd;
530 /* Stop monitoring file descriptor FD for when write is possible. */
532 void
533 delete_write_fd (int fd)
535 eassert (fd < FD_SETSIZE);
536 FD_CLR (fd, &write_mask);
537 fd_callback_info[fd].condition &= ~FOR_WRITE;
538 if (fd_callback_info[fd].condition == 0)
540 fd_callback_info[fd].func = 0;
541 fd_callback_info[fd].data = 0;
542 delete_input_desc (fd);
547 /* Compute the Lisp form of the process status, p->status, from
548 the numeric status that was returned by `wait'. */
550 static Lisp_Object status_convert (int);
552 static void
553 update_status (struct Lisp_Process *p)
555 eassert (p->raw_status_new);
556 pset_status (p, status_convert (p->raw_status));
557 p->raw_status_new = 0;
560 /* Convert a process status word in Unix format to
561 the list that we use internally. */
563 static Lisp_Object
564 status_convert (int w)
566 if (WIFSTOPPED (w))
567 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
568 else if (WIFEXITED (w))
569 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
570 WCOREDUMP (w) ? Qt : Qnil));
571 else if (WIFSIGNALED (w))
572 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
573 WCOREDUMP (w) ? Qt : Qnil));
574 else
575 return Qrun;
578 /* Given a status-list, extract the three pieces of information
579 and store them individually through the three pointers. */
581 static void
582 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
584 Lisp_Object tem;
586 if (SYMBOLP (l))
588 *symbol = l;
589 *code = 0;
590 *coredump = 0;
592 else
594 *symbol = XCAR (l);
595 tem = XCDR (l);
596 *code = XFASTINT (XCAR (tem));
597 tem = XCDR (tem);
598 *coredump = !NILP (tem);
602 /* Return a string describing a process status list. */
604 static Lisp_Object
605 status_message (struct Lisp_Process *p)
607 Lisp_Object status = p->status;
608 Lisp_Object symbol;
609 int code;
610 bool coredump;
611 Lisp_Object string, string2;
613 decode_status (status, &symbol, &code, &coredump);
615 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
617 char const *signame;
618 synchronize_system_messages_locale ();
619 signame = strsignal (code);
620 if (signame == 0)
621 string = build_string ("unknown");
622 else
624 int c1, c2;
626 string = build_unibyte_string (signame);
627 if (! NILP (Vlocale_coding_system))
628 string = (code_convert_string_norecord
629 (string, Vlocale_coding_system, 0));
630 c1 = STRING_CHAR (SDATA (string));
631 c2 = downcase (c1);
632 if (c1 != c2)
633 Faset (string, make_number (0), make_number (c2));
635 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
636 return concat2 (string, string2);
638 else if (EQ (symbol, Qexit))
640 if (NETCONN1_P (p))
641 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
642 if (code == 0)
643 return build_string ("finished\n");
644 string = Fnumber_to_string (make_number (code));
645 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
646 return concat3 (build_string ("exited abnormally with code "),
647 string, string2);
649 else if (EQ (symbol, Qfailed))
651 string = Fnumber_to_string (make_number (code));
652 string2 = build_string ("\n");
653 return concat3 (build_string ("failed with code "),
654 string, string2);
656 else
657 return Fcopy_sequence (Fsymbol_name (symbol));
660 enum { PTY_NAME_SIZE = 24 };
662 /* Open an available pty, returning a file descriptor.
663 Store into PTY_NAME the file name of the terminal corresponding to the pty.
664 Return -1 on failure. */
666 static int
667 allocate_pty (char pty_name[PTY_NAME_SIZE])
669 #ifdef HAVE_PTYS
670 int fd;
672 #ifdef PTY_ITERATION
673 PTY_ITERATION
674 #else
675 register int c, i;
676 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
677 for (i = 0; i < 16; i++)
678 #endif
680 #ifdef PTY_NAME_SPRINTF
681 PTY_NAME_SPRINTF
682 #else
683 sprintf (pty_name, "/dev/pty%c%x", c, i);
684 #endif /* no PTY_NAME_SPRINTF */
686 #ifdef PTY_OPEN
687 PTY_OPEN;
688 #else /* no PTY_OPEN */
689 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
690 #endif /* no PTY_OPEN */
692 if (fd >= 0)
694 #ifdef PTY_OPEN
695 /* Set FD's close-on-exec flag. This is needed even if
696 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
697 doesn't require support for that combination.
698 Multithreaded platforms where posix_openpt ignores
699 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
700 have a race condition between the PTY_OPEN and here. */
701 fcntl (fd, F_SETFD, FD_CLOEXEC);
702 #endif
703 /* check to make certain that both sides are available
704 this avoids a nasty yet stupid bug in rlogins */
705 #ifdef PTY_TTY_NAME_SPRINTF
706 PTY_TTY_NAME_SPRINTF
707 #else
708 sprintf (pty_name, "/dev/tty%c%x", c, i);
709 #endif /* no PTY_TTY_NAME_SPRINTF */
710 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
712 emacs_close (fd);
713 # ifndef __sgi
714 continue;
715 # else
716 return -1;
717 # endif /* __sgi */
719 setup_pty (fd);
720 return fd;
723 #endif /* HAVE_PTYS */
724 return -1;
727 static Lisp_Object
728 make_process (Lisp_Object name)
730 register Lisp_Object val, tem, name1;
731 register struct Lisp_Process *p;
732 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
733 printmax_t i;
735 p = allocate_process ();
736 /* Initialize Lisp data. Note that allocate_process initializes all
737 Lisp data to nil, so do it only for slots which should not be nil. */
738 pset_status (p, Qrun);
739 pset_mark (p, Fmake_marker ());
741 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
742 non-Lisp data, so do it only for slots which should not be zero. */
743 p->infd = -1;
744 p->outfd = -1;
745 for (i = 0; i < PROCESS_OPEN_FDS; i++)
746 p->open_fd[i] = -1;
748 #ifdef HAVE_GNUTLS
749 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
750 #endif
752 /* If name is already in use, modify it until it is unused. */
754 name1 = name;
755 for (i = 1; ; i++)
757 tem = Fget_process (name1);
758 if (NILP (tem)) break;
759 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
761 name = name1;
762 pset_name (p, name);
763 pset_sentinel (p, Qinternal_default_process_sentinel);
764 pset_filter (p, Qinternal_default_process_filter);
765 XSETPROCESS (val, p);
766 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
767 return val;
770 static void
771 remove_process (register Lisp_Object proc)
773 register Lisp_Object pair;
775 pair = Frassq (proc, Vprocess_alist);
776 Vprocess_alist = Fdelq (pair, Vprocess_alist);
778 deactivate_process (proc);
782 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
783 doc: /* Return t if OBJECT is a process. */)
784 (Lisp_Object object)
786 return PROCESSP (object) ? Qt : Qnil;
789 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
790 doc: /* Return the process named NAME, or nil if there is none. */)
791 (register Lisp_Object name)
793 if (PROCESSP (name))
794 return name;
795 CHECK_STRING (name);
796 return Fcdr (Fassoc (name, Vprocess_alist));
799 /* This is how commands for the user decode process arguments. It
800 accepts a process, a process name, a buffer, a buffer name, or nil.
801 Buffers denote the first process in the buffer, and nil denotes the
802 current buffer. */
804 static Lisp_Object
805 get_process (register Lisp_Object name)
807 register Lisp_Object proc, obj;
808 if (STRINGP (name))
810 obj = Fget_process (name);
811 if (NILP (obj))
812 obj = Fget_buffer (name);
813 if (NILP (obj))
814 error ("Process %s does not exist", SDATA (name));
816 else if (NILP (name))
817 obj = Fcurrent_buffer ();
818 else
819 obj = name;
821 /* Now obj should be either a buffer object or a process object. */
822 if (BUFFERP (obj))
824 if (NILP (BVAR (XBUFFER (obj), name)))
825 error ("Attempt to get process for a dead buffer");
826 proc = Fget_buffer_process (obj);
827 if (NILP (proc))
828 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
830 else
832 CHECK_PROCESS (obj);
833 proc = obj;
835 return proc;
839 /* Fdelete_process promises to immediately forget about the process, but in
840 reality, Emacs needs to remember those processes until they have been
841 treated by the SIGCHLD handler and waitpid has been invoked on them;
842 otherwise they might fill up the kernel's process table.
844 Some processes created by call-process are also put onto this list.
846 Members of this list are (process-ID . filename) pairs. The
847 process-ID is a number; the filename, if a string, is a file that
848 needs to be removed after the process exits. */
849 static Lisp_Object deleted_pid_list;
851 void
852 record_deleted_pid (pid_t pid, Lisp_Object filename)
854 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
855 /* GC treated elements set to nil. */
856 Fdelq (Qnil, deleted_pid_list));
860 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
861 doc: /* Delete PROCESS: kill it and forget about it immediately.
862 PROCESS may be a process, a buffer, the name of a process or buffer, or
863 nil, indicating the current buffer's process. */)
864 (register Lisp_Object process)
866 register struct Lisp_Process *p;
868 process = get_process (process);
869 p = XPROCESS (process);
871 p->raw_status_new = 0;
872 if (NETCONN1_P (p) || SERIALCONN1_P (p))
874 pset_status (p, list2 (Qexit, make_number (0)));
875 p->tick = ++process_tick;
876 status_notify (p);
877 redisplay_preserve_echo_area (13);
879 else
881 if (p->alive)
882 record_kill_process (p, Qnil);
884 if (p->infd >= 0)
886 /* Update P's status, since record_kill_process will make the
887 SIGCHLD handler update deleted_pid_list, not *P. */
888 Lisp_Object symbol;
889 if (p->raw_status_new)
890 update_status (p);
891 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
892 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
893 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
895 p->tick = ++process_tick;
896 status_notify (p);
897 redisplay_preserve_echo_area (13);
900 remove_process (process);
901 return Qnil;
904 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
905 doc: /* Return the status of PROCESS.
906 The returned value is one of the following symbols:
907 run -- for a process that is running.
908 stop -- for a process stopped but continuable.
909 exit -- for a process that has exited.
910 signal -- for a process that has got a fatal signal.
911 open -- for a network stream connection that is open.
912 listen -- for a network stream server that is listening.
913 closed -- for a network stream connection that is closed.
914 connect -- when waiting for a non-blocking connection to complete.
915 failed -- when a non-blocking connection has failed.
916 nil -- if arg is a process name and no such process exists.
917 PROCESS may be a process, a buffer, the name of a process, or
918 nil, indicating the current buffer's process. */)
919 (register Lisp_Object process)
921 register struct Lisp_Process *p;
922 register Lisp_Object status;
924 if (STRINGP (process))
925 process = Fget_process (process);
926 else
927 process = get_process (process);
929 if (NILP (process))
930 return process;
932 p = XPROCESS (process);
933 if (p->raw_status_new)
934 update_status (p);
935 status = p->status;
936 if (CONSP (status))
937 status = XCAR (status);
938 if (NETCONN1_P (p) || SERIALCONN1_P (p))
940 if (EQ (status, Qexit))
941 status = Qclosed;
942 else if (EQ (p->command, Qt))
943 status = Qstop;
944 else if (EQ (status, Qrun))
945 status = Qopen;
947 return status;
950 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
951 1, 1, 0,
952 doc: /* Return the exit status of PROCESS or the signal number that killed it.
953 If PROCESS has not yet exited or died, return 0. */)
954 (register Lisp_Object process)
956 CHECK_PROCESS (process);
957 if (XPROCESS (process)->raw_status_new)
958 update_status (XPROCESS (process));
959 if (CONSP (XPROCESS (process)->status))
960 return XCAR (XCDR (XPROCESS (process)->status));
961 return make_number (0);
964 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
965 doc: /* Return the process id of PROCESS.
966 This is the pid of the external process which PROCESS uses or talks to.
967 For a network connection, this value is nil. */)
968 (register Lisp_Object process)
970 pid_t pid;
972 CHECK_PROCESS (process);
973 pid = XPROCESS (process)->pid;
974 return (pid ? make_fixnum_or_float (pid) : Qnil);
977 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
978 doc: /* Return the name of PROCESS, as a string.
979 This is the name of the program invoked in PROCESS,
980 possibly modified to make it unique among process names. */)
981 (register Lisp_Object process)
983 CHECK_PROCESS (process);
984 return XPROCESS (process)->name;
987 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
988 doc: /* Return the command that was executed to start PROCESS.
989 This is a list of strings, the first string being the program executed
990 and the rest of the strings being the arguments given to it.
991 For a network or serial process, this is nil (process is running) or t
992 \(process is stopped). */)
993 (register Lisp_Object process)
995 CHECK_PROCESS (process);
996 return XPROCESS (process)->command;
999 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
1000 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
1001 This is the terminal that the process itself reads and writes on,
1002 not the name of the pty that Emacs uses to talk with that terminal. */)
1003 (register Lisp_Object process)
1005 CHECK_PROCESS (process);
1006 return XPROCESS (process)->tty_name;
1009 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1010 2, 2, 0,
1011 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1012 Return BUFFER. */)
1013 (register Lisp_Object process, Lisp_Object buffer)
1015 struct Lisp_Process *p;
1017 CHECK_PROCESS (process);
1018 if (!NILP (buffer))
1019 CHECK_BUFFER (buffer);
1020 p = XPROCESS (process);
1021 pset_buffer (p, buffer);
1022 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1023 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1024 setup_process_coding_systems (process);
1025 return buffer;
1028 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1029 1, 1, 0,
1030 doc: /* Return the buffer PROCESS is associated with.
1031 The default process filter inserts output from PROCESS into this buffer. */)
1032 (register Lisp_Object process)
1034 CHECK_PROCESS (process);
1035 return XPROCESS (process)->buffer;
1038 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1039 1, 1, 0,
1040 doc: /* Return the marker for the end of the last output from PROCESS. */)
1041 (register Lisp_Object process)
1043 CHECK_PROCESS (process);
1044 return XPROCESS (process)->mark;
1047 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1048 2, 2, 0,
1049 doc: /* Give PROCESS the filter function FILTER; nil means default.
1050 A value of t means stop accepting output from the process.
1052 When a process has a non-default filter, its buffer is not used for output.
1053 Instead, each time it does output, the entire string of output is
1054 passed to the filter.
1056 The filter gets two arguments: the process and the string of output.
1057 The string argument is normally a multibyte string, except:
1058 - if the process's input coding system is no-conversion or raw-text,
1059 it is a unibyte string (the non-converted input), or else
1060 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1061 string (the result of converting the decoded input multibyte
1062 string to unibyte with `string-make-unibyte'). */)
1063 (register Lisp_Object process, Lisp_Object filter)
1065 struct Lisp_Process *p;
1067 CHECK_PROCESS (process);
1068 p = XPROCESS (process);
1070 /* Don't signal an error if the process's input file descriptor
1071 is closed. This could make debugging Lisp more difficult,
1072 for example when doing something like
1074 (setq process (start-process ...))
1075 (debug)
1076 (set-process-filter process ...) */
1078 if (NILP (filter))
1079 filter = Qinternal_default_process_filter;
1081 if (p->infd >= 0)
1083 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1085 FD_CLR (p->infd, &input_wait_mask);
1086 FD_CLR (p->infd, &non_keyboard_wait_mask);
1088 else if (EQ (p->filter, Qt)
1089 /* Network or serial process not stopped: */
1090 && !EQ (p->command, Qt))
1092 FD_SET (p->infd, &input_wait_mask);
1093 FD_SET (p->infd, &non_keyboard_wait_mask);
1097 pset_filter (p, filter);
1098 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1099 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1100 setup_process_coding_systems (process);
1101 return filter;
1104 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1105 1, 1, 0,
1106 doc: /* Return the filter function of PROCESS.
1107 See `set-process-filter' for more info on filter functions. */)
1108 (register Lisp_Object process)
1110 CHECK_PROCESS (process);
1111 return XPROCESS (process)->filter;
1114 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1115 2, 2, 0,
1116 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1117 The sentinel is called as a function when the process changes state.
1118 It gets two arguments: the process, and a string describing the change. */)
1119 (register Lisp_Object process, Lisp_Object sentinel)
1121 struct Lisp_Process *p;
1123 CHECK_PROCESS (process);
1124 p = XPROCESS (process);
1126 if (NILP (sentinel))
1127 sentinel = Qinternal_default_process_sentinel;
1129 pset_sentinel (p, sentinel);
1130 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1131 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1132 return sentinel;
1135 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1136 1, 1, 0,
1137 doc: /* Return the sentinel of PROCESS.
1138 See `set-process-sentinel' for more info on sentinels. */)
1139 (register Lisp_Object process)
1141 CHECK_PROCESS (process);
1142 return XPROCESS (process)->sentinel;
1145 DEFUN ("set-process-window-size", Fset_process_window_size,
1146 Sset_process_window_size, 3, 3, 0,
1147 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1148 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1150 CHECK_PROCESS (process);
1152 /* All known platforms store window sizes as 'unsigned short'. */
1153 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1154 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1156 if (XPROCESS (process)->infd < 0
1157 || (set_window_size (XPROCESS (process)->infd,
1158 XINT (height), XINT (width))
1159 < 0))
1160 return Qnil;
1161 else
1162 return Qt;
1165 DEFUN ("set-process-inherit-coding-system-flag",
1166 Fset_process_inherit_coding_system_flag,
1167 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1168 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1169 If the second argument FLAG is non-nil, then the variable
1170 `buffer-file-coding-system' of the buffer associated with PROCESS
1171 will be bound to the value of the coding system used to decode
1172 the process output.
1174 This is useful when the coding system specified for the process buffer
1175 leaves either the character code conversion or the end-of-line conversion
1176 unspecified, or if the coding system used to decode the process output
1177 is more appropriate for saving the process buffer.
1179 Binding the variable `inherit-process-coding-system' to non-nil before
1180 starting the process is an alternative way of setting the inherit flag
1181 for the process which will run.
1183 This function returns FLAG. */)
1184 (register Lisp_Object process, Lisp_Object flag)
1186 CHECK_PROCESS (process);
1187 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1188 return flag;
1191 DEFUN ("set-process-query-on-exit-flag",
1192 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1193 2, 2, 0,
1194 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1195 If the second argument FLAG is non-nil, Emacs will query the user before
1196 exiting or killing a buffer if PROCESS is running. This function
1197 returns FLAG. */)
1198 (register Lisp_Object process, Lisp_Object flag)
1200 CHECK_PROCESS (process);
1201 XPROCESS (process)->kill_without_query = NILP (flag);
1202 return flag;
1205 DEFUN ("process-query-on-exit-flag",
1206 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1207 1, 1, 0,
1208 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1209 (register Lisp_Object process)
1211 CHECK_PROCESS (process);
1212 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1215 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1216 1, 2, 0,
1217 doc: /* Return the contact info of PROCESS; t for a real child.
1218 For a network or serial connection, the value depends on the optional
1219 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1220 SERVICE) for a network connection or (PORT SPEED) for a serial
1221 connection. If KEY is t, the complete contact information for the
1222 connection is returned, else the specific value for the keyword KEY is
1223 returned. See `make-network-process' or `make-serial-process' for a
1224 list of keywords. */)
1225 (register Lisp_Object process, Lisp_Object key)
1227 Lisp_Object contact;
1229 CHECK_PROCESS (process);
1230 contact = XPROCESS (process)->childp;
1232 #ifdef DATAGRAM_SOCKETS
1233 if (DATAGRAM_CONN_P (process)
1234 && (EQ (key, Qt) || EQ (key, QCremote)))
1235 contact = Fplist_put (contact, QCremote,
1236 Fprocess_datagram_address (process));
1237 #endif
1239 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1240 return contact;
1241 if (NILP (key) && NETCONN_P (process))
1242 return list2 (Fplist_get (contact, QChost),
1243 Fplist_get (contact, QCservice));
1244 if (NILP (key) && SERIALCONN_P (process))
1245 return list2 (Fplist_get (contact, QCport),
1246 Fplist_get (contact, QCspeed));
1247 return Fplist_get (contact, key);
1250 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1251 1, 1, 0,
1252 doc: /* Return the plist of PROCESS. */)
1253 (register Lisp_Object process)
1255 CHECK_PROCESS (process);
1256 return XPROCESS (process)->plist;
1259 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1260 2, 2, 0,
1261 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1262 (register Lisp_Object process, Lisp_Object plist)
1264 CHECK_PROCESS (process);
1265 CHECK_LIST (plist);
1267 pset_plist (XPROCESS (process), plist);
1268 return plist;
1271 #if 0 /* Turned off because we don't currently record this info
1272 in the process. Perhaps add it. */
1273 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1274 doc: /* Return the connection type of PROCESS.
1275 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1276 a socket connection. */)
1277 (Lisp_Object process)
1279 return XPROCESS (process)->type;
1281 #endif
1283 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1284 doc: /* Return the connection type of PROCESS.
1285 The value is either the symbol `real', `network', or `serial'.
1286 PROCESS may be a process, a buffer, the name of a process or buffer, or
1287 nil, indicating the current buffer's process. */)
1288 (Lisp_Object process)
1290 Lisp_Object proc;
1291 proc = get_process (process);
1292 return XPROCESS (proc)->type;
1295 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1296 1, 2, 0,
1297 doc: /* Convert network ADDRESS from internal format to a string.
1298 A 4 or 5 element vector represents an IPv4 address (with port number).
1299 An 8 or 9 element vector represents an IPv6 address (with port number).
1300 If optional second argument OMIT-PORT is non-nil, don't include a port
1301 number in the string, even when present in ADDRESS.
1302 Returns nil if format of ADDRESS is invalid. */)
1303 (Lisp_Object address, Lisp_Object omit_port)
1305 if (NILP (address))
1306 return Qnil;
1308 if (STRINGP (address)) /* AF_LOCAL */
1309 return address;
1311 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1313 register struct Lisp_Vector *p = XVECTOR (address);
1314 ptrdiff_t size = p->header.size;
1315 Lisp_Object args[10];
1316 int nargs, i;
1318 if (size == 4 || (size == 5 && !NILP (omit_port)))
1320 args[0] = build_string ("%d.%d.%d.%d");
1321 nargs = 4;
1323 else if (size == 5)
1325 args[0] = build_string ("%d.%d.%d.%d:%d");
1326 nargs = 5;
1328 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1330 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1331 nargs = 8;
1333 else if (size == 9)
1335 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1336 nargs = 9;
1338 else
1339 return Qnil;
1341 for (i = 0; i < nargs; i++)
1343 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1344 return Qnil;
1346 if (nargs <= 5 /* IPv4 */
1347 && i < 4 /* host, not port */
1348 && XINT (p->contents[i]) > 255)
1349 return Qnil;
1351 args[i+1] = p->contents[i];
1354 return Fformat (nargs+1, args);
1357 if (CONSP (address))
1359 Lisp_Object args[2];
1360 args[0] = build_string ("<Family %d>");
1361 args[1] = Fcar (address);
1362 return Fformat (2, args);
1365 return Qnil;
1368 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1369 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1370 (void)
1372 return Fmapcar (Qcdr, Vprocess_alist);
1375 /* Starting asynchronous inferior processes. */
1377 static void start_process_unwind (Lisp_Object proc);
1379 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1380 doc: /* Start a program in a subprocess. Return the process object for it.
1381 NAME is name for process. It is modified if necessary to make it unique.
1382 BUFFER is the buffer (or buffer name) to associate with the process.
1384 Process output (both standard output and standard error streams) goes
1385 at end of BUFFER, unless you specify an output stream or filter
1386 function to handle the output. BUFFER may also be nil, meaning that
1387 this process is not associated with any buffer.
1389 PROGRAM is the program file name. It is searched for in `exec-path'
1390 (which see). If nil, just associate a pty with the buffer. Remaining
1391 arguments are strings to give program as arguments.
1393 If you want to separate standard output from standard error, invoke
1394 the command through a shell and redirect one of them using the shell
1395 syntax.
1397 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1398 (ptrdiff_t nargs, Lisp_Object *args)
1400 Lisp_Object buffer, name, program, proc, current_dir, tem;
1401 register unsigned char **new_argv;
1402 ptrdiff_t i;
1403 ptrdiff_t count = SPECPDL_INDEX ();
1405 buffer = args[1];
1406 if (!NILP (buffer))
1407 buffer = Fget_buffer_create (buffer);
1409 /* Make sure that the child will be able to chdir to the current
1410 buffer's current directory, or its unhandled equivalent. We
1411 can't just have the child check for an error when it does the
1412 chdir, since it's in a vfork.
1414 We have to GCPRO around this because Fexpand_file_name and
1415 Funhandled_file_name_directory might call a file name handling
1416 function. The argument list is protected by the caller, so all
1417 we really have to worry about is buffer. */
1419 struct gcpro gcpro1;
1420 GCPRO1 (buffer);
1421 current_dir = encode_current_directory ();
1422 UNGCPRO;
1425 name = args[0];
1426 CHECK_STRING (name);
1428 program = args[2];
1430 if (!NILP (program))
1431 CHECK_STRING (program);
1433 proc = make_process (name);
1434 /* If an error occurs and we can't start the process, we want to
1435 remove it from the process list. This means that each error
1436 check in create_process doesn't need to call remove_process
1437 itself; it's all taken care of here. */
1438 record_unwind_protect (start_process_unwind, proc);
1440 pset_childp (XPROCESS (proc), Qt);
1441 pset_plist (XPROCESS (proc), Qnil);
1442 pset_type (XPROCESS (proc), Qreal);
1443 pset_buffer (XPROCESS (proc), buffer);
1444 pset_sentinel (XPROCESS (proc), Qinternal_default_process_sentinel);
1445 pset_filter (XPROCESS (proc), Qinternal_default_process_filter);
1446 pset_command (XPROCESS (proc), Flist (nargs - 2, args + 2));
1448 #ifdef HAVE_GNUTLS
1449 /* AKA GNUTLS_INITSTAGE(proc). */
1450 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1451 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1452 #endif
1454 #ifdef ADAPTIVE_READ_BUFFERING
1455 XPROCESS (proc)->adaptive_read_buffering
1456 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1457 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1458 #endif
1460 /* Make the process marker point into the process buffer (if any). */
1461 if (BUFFERP (buffer))
1462 set_marker_both (XPROCESS (proc)->mark, buffer,
1463 BUF_ZV (XBUFFER (buffer)),
1464 BUF_ZV_BYTE (XBUFFER (buffer)));
1467 /* Decide coding systems for communicating with the process. Here
1468 we don't setup the structure coding_system nor pay attention to
1469 unibyte mode. They are done in create_process. */
1471 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1472 Lisp_Object coding_systems = Qt;
1473 Lisp_Object val, *args2;
1474 struct gcpro gcpro1, gcpro2;
1476 val = Vcoding_system_for_read;
1477 if (NILP (val))
1479 args2 = alloca ((nargs + 1) * sizeof *args2);
1480 args2[0] = Qstart_process;
1481 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1482 GCPRO2 (proc, current_dir);
1483 if (!NILP (program))
1484 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1485 UNGCPRO;
1486 if (CONSP (coding_systems))
1487 val = XCAR (coding_systems);
1488 else if (CONSP (Vdefault_process_coding_system))
1489 val = XCAR (Vdefault_process_coding_system);
1491 pset_decode_coding_system (XPROCESS (proc), val);
1493 val = Vcoding_system_for_write;
1494 if (NILP (val))
1496 if (EQ (coding_systems, Qt))
1498 args2 = alloca ((nargs + 1) * sizeof *args2);
1499 args2[0] = Qstart_process;
1500 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1501 GCPRO2 (proc, current_dir);
1502 if (!NILP (program))
1503 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1504 UNGCPRO;
1506 if (CONSP (coding_systems))
1507 val = XCDR (coding_systems);
1508 else if (CONSP (Vdefault_process_coding_system))
1509 val = XCDR (Vdefault_process_coding_system);
1511 pset_encode_coding_system (XPROCESS (proc), val);
1512 /* Note: At this moment, the above coding system may leave
1513 text-conversion or eol-conversion unspecified. They will be
1514 decided after we read output from the process and decode it by
1515 some coding system, or just before we actually send a text to
1516 the process. */
1520 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1521 XPROCESS (proc)->decoding_carryover = 0;
1522 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1524 XPROCESS (proc)->inherit_coding_system_flag
1525 = !(NILP (buffer) || !inherit_process_coding_system);
1527 if (!NILP (program))
1529 /* If program file name is not absolute, search our path for it.
1530 Put the name we will really use in TEM. */
1531 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1532 && !(SCHARS (program) > 1
1533 && IS_DEVICE_SEP (SREF (program, 1))))
1535 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1537 tem = Qnil;
1538 GCPRO4 (name, program, buffer, current_dir);
1539 openp (Vexec_path, program, Vexec_suffixes, &tem,
1540 make_number (X_OK), false);
1541 UNGCPRO;
1542 if (NILP (tem))
1543 report_file_error ("Searching for program", program);
1544 tem = Fexpand_file_name (tem, Qnil);
1546 else
1548 if (!NILP (Ffile_directory_p (program)))
1549 error ("Specified program for new process is a directory");
1550 tem = program;
1553 /* If program file name starts with /: for quoting a magic name,
1554 discard that. */
1555 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1556 && SREF (tem, 1) == ':')
1557 tem = Fsubstring (tem, make_number (2), Qnil);
1560 Lisp_Object arg_encoding = Qnil;
1561 struct gcpro gcpro1;
1562 GCPRO1 (tem);
1564 /* Encode the file name and put it in NEW_ARGV.
1565 That's where the child will use it to execute the program. */
1566 tem = list1 (ENCODE_FILE (tem));
1568 /* Here we encode arguments by the coding system used for sending
1569 data to the process. We don't support using different coding
1570 systems for encoding arguments and for encoding data sent to the
1571 process. */
1573 for (i = 3; i < nargs; i++)
1575 tem = Fcons (args[i], tem);
1576 CHECK_STRING (XCAR (tem));
1577 if (STRING_MULTIBYTE (XCAR (tem)))
1579 if (NILP (arg_encoding))
1580 arg_encoding = (complement_process_encoding_system
1581 (XPROCESS (proc)->encode_coding_system));
1582 XSETCAR (tem,
1583 code_convert_string_norecord
1584 (XCAR (tem), arg_encoding, 1));
1588 UNGCPRO;
1591 /* Now that everything is encoded we can collect the strings into
1592 NEW_ARGV. */
1593 new_argv = alloca ((nargs - 1) * sizeof *new_argv);
1594 new_argv[nargs - 2] = 0;
1596 for (i = nargs - 2; i-- != 0; )
1598 new_argv[i] = SDATA (XCAR (tem));
1599 tem = XCDR (tem);
1602 create_process (proc, (char **) new_argv, current_dir);
1604 else
1605 create_pty (proc);
1607 return unbind_to (count, proc);
1610 /* This function is the unwind_protect form for Fstart_process. If
1611 PROC doesn't have its pid set, then we know someone has signaled
1612 an error and the process wasn't started successfully, so we should
1613 remove it from the process list. */
1614 static void
1615 start_process_unwind (Lisp_Object proc)
1617 if (!PROCESSP (proc))
1618 emacs_abort ();
1620 /* Was PROC started successfully?
1621 -2 is used for a pty with no process, eg for gdb. */
1622 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1623 remove_process (proc);
1626 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1628 static void
1629 close_process_fd (int *fd_addr)
1631 int fd = *fd_addr;
1632 if (0 <= fd)
1634 *fd_addr = -1;
1635 emacs_close (fd);
1639 /* Indexes of file descriptors in open_fds. */
1640 enum
1642 /* The pipe from Emacs to its subprocess. */
1643 SUBPROCESS_STDIN,
1644 WRITE_TO_SUBPROCESS,
1646 /* The main pipe from the subprocess to Emacs. */
1647 READ_FROM_SUBPROCESS,
1648 SUBPROCESS_STDOUT,
1650 /* The pipe from the subprocess to Emacs that is closed when the
1651 subprocess execs. */
1652 READ_FROM_EXEC_MONITOR,
1653 EXEC_MONITOR_OUTPUT
1656 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1658 static void
1659 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1661 struct Lisp_Process *p = XPROCESS (process);
1662 int inchannel, outchannel;
1663 pid_t pid;
1664 int vfork_errno;
1665 int forkin, forkout;
1666 bool pty_flag = 0;
1667 char pty_name[PTY_NAME_SIZE];
1668 Lisp_Object lisp_pty_name = Qnil;
1670 inchannel = outchannel = -1;
1672 if (!NILP (Vprocess_connection_type))
1673 outchannel = inchannel = allocate_pty (pty_name);
1675 if (inchannel >= 0)
1677 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1678 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1679 /* On most USG systems it does not work to open the pty's tty here,
1680 then close it and reopen it in the child. */
1681 /* Don't let this terminal become our controlling terminal
1682 (in case we don't have one). */
1683 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1684 if (forkin < 0)
1685 report_file_error ("Opening pty", Qnil);
1686 p->open_fd[SUBPROCESS_STDIN] = forkin;
1687 #else
1688 forkin = forkout = -1;
1689 #endif /* not USG, or USG_SUBTTY_WORKS */
1690 pty_flag = 1;
1691 lisp_pty_name = build_string (pty_name);
1693 else
1695 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1696 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1697 report_file_error ("Creating pipe", Qnil);
1698 forkin = p->open_fd[SUBPROCESS_STDIN];
1699 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1700 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1701 forkout = p->open_fd[SUBPROCESS_STDOUT];
1704 #ifndef WINDOWSNT
1705 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1706 report_file_error ("Creating pipe", Qnil);
1707 #endif
1709 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1710 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1712 /* Record this as an active process, with its channels. */
1713 chan_process[inchannel] = process;
1714 p->infd = inchannel;
1715 p->outfd = outchannel;
1717 /* Previously we recorded the tty descriptor used in the subprocess.
1718 It was only used for getting the foreground tty process, so now
1719 we just reopen the device (see emacs_get_tty_pgrp) as this is
1720 more portable (see USG_SUBTTY_WORKS above). */
1722 p->pty_flag = pty_flag;
1723 pset_status (p, Qrun);
1725 FD_SET (inchannel, &input_wait_mask);
1726 FD_SET (inchannel, &non_keyboard_wait_mask);
1727 if (inchannel > max_process_desc)
1728 max_process_desc = inchannel;
1730 /* This may signal an error. */
1731 setup_process_coding_systems (process);
1733 block_input ();
1734 block_child_signal ();
1736 #ifndef WINDOWSNT
1737 /* vfork, and prevent local vars from being clobbered by the vfork. */
1739 Lisp_Object volatile current_dir_volatile = current_dir;
1740 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1741 char **volatile new_argv_volatile = new_argv;
1742 int volatile forkin_volatile = forkin;
1743 int volatile forkout_volatile = forkout;
1744 struct Lisp_Process *p_volatile = p;
1746 pid = vfork ();
1748 current_dir = current_dir_volatile;
1749 lisp_pty_name = lisp_pty_name_volatile;
1750 new_argv = new_argv_volatile;
1751 forkin = forkin_volatile;
1752 forkout = forkout_volatile;
1753 p = p_volatile;
1755 pty_flag = p->pty_flag;
1758 if (pid == 0)
1759 #endif /* not WINDOWSNT */
1761 int xforkin = forkin;
1762 int xforkout = forkout;
1764 /* Make the pty be the controlling terminal of the process. */
1765 #ifdef HAVE_PTYS
1766 /* First, disconnect its current controlling terminal. */
1767 /* We tried doing setsid only if pty_flag, but it caused
1768 process_set_signal to fail on SGI when using a pipe. */
1769 setsid ();
1770 /* Make the pty's terminal the controlling terminal. */
1771 if (pty_flag && xforkin >= 0)
1773 #ifdef TIOCSCTTY
1774 /* We ignore the return value
1775 because faith@cs.unc.edu says that is necessary on Linux. */
1776 ioctl (xforkin, TIOCSCTTY, 0);
1777 #endif
1779 #if defined (LDISC1)
1780 if (pty_flag && xforkin >= 0)
1782 struct termios t;
1783 tcgetattr (xforkin, &t);
1784 t.c_lflag = LDISC1;
1785 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1786 emacs_perror ("create_process/tcsetattr LDISC1");
1788 #else
1789 #if defined (NTTYDISC) && defined (TIOCSETD)
1790 if (pty_flag && xforkin >= 0)
1792 /* Use new line discipline. */
1793 int ldisc = NTTYDISC;
1794 ioctl (xforkin, TIOCSETD, &ldisc);
1796 #endif
1797 #endif
1798 #ifdef TIOCNOTTY
1799 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1800 can do TIOCSPGRP only to the process's controlling tty. */
1801 if (pty_flag)
1803 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1804 I can't test it since I don't have 4.3. */
1805 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1806 if (j >= 0)
1808 ioctl (j, TIOCNOTTY, 0);
1809 emacs_close (j);
1812 #endif /* TIOCNOTTY */
1814 #if !defined (DONT_REOPEN_PTY)
1815 /*** There is a suggestion that this ought to be a
1816 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1817 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1818 that system does seem to need this code, even though
1819 both TIOCSCTTY is defined. */
1820 /* Now close the pty (if we had it open) and reopen it.
1821 This makes the pty the controlling terminal of the subprocess. */
1822 if (pty_flag)
1825 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1826 would work? */
1827 if (xforkin >= 0)
1828 emacs_close (xforkin);
1829 xforkout = xforkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1831 if (xforkin < 0)
1833 emacs_perror (SSDATA (lisp_pty_name));
1834 _exit (EXIT_CANCELED);
1838 #endif /* not DONT_REOPEN_PTY */
1840 #ifdef SETUP_SLAVE_PTY
1841 if (pty_flag)
1843 SETUP_SLAVE_PTY;
1845 #endif /* SETUP_SLAVE_PTY */
1846 #endif /* HAVE_PTYS */
1848 signal (SIGINT, SIG_DFL);
1849 signal (SIGQUIT, SIG_DFL);
1850 #ifdef SIGPROF
1851 signal (SIGPROF, SIG_DFL);
1852 #endif
1854 /* Emacs ignores SIGPIPE, but the child should not. */
1855 signal (SIGPIPE, SIG_DFL);
1857 /* Stop blocking SIGCHLD in the child. */
1858 unblock_child_signal ();
1860 if (pty_flag)
1861 child_setup_tty (xforkout);
1862 #ifdef WINDOWSNT
1863 pid = child_setup (xforkin, xforkout, xforkout, new_argv, 1, current_dir);
1864 #else /* not WINDOWSNT */
1865 child_setup (xforkin, xforkout, xforkout, new_argv, 1, current_dir);
1866 #endif /* not WINDOWSNT */
1869 /* Back in the parent process. */
1871 vfork_errno = errno;
1872 p->pid = pid;
1873 if (pid >= 0)
1874 p->alive = 1;
1876 /* Stop blocking in the parent. */
1877 unblock_child_signal ();
1878 unblock_input ();
1880 if (pid < 0)
1881 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1882 else
1884 /* vfork succeeded. */
1886 /* Close the pipe ends that the child uses, or the child's pty. */
1887 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
1888 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
1890 #ifdef WINDOWSNT
1891 register_child (pid, inchannel);
1892 #endif /* WINDOWSNT */
1894 pset_tty_name (p, lisp_pty_name);
1896 #ifndef WINDOWSNT
1897 /* Wait for child_setup to complete in case that vfork is
1898 actually defined as fork. The descriptor
1899 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1900 of a pipe is closed at the child side either by close-on-exec
1901 on successful execve or the _exit call in child_setup. */
1903 char dummy;
1905 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
1906 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
1907 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
1909 #endif
1913 static void
1914 create_pty (Lisp_Object process)
1916 struct Lisp_Process *p = XPROCESS (process);
1917 char pty_name[PTY_NAME_SIZE];
1918 int pty_fd = NILP (Vprocess_connection_type) ? -1 : allocate_pty (pty_name);
1920 if (pty_fd >= 0)
1922 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
1923 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1924 /* On most USG systems it does not work to open the pty's tty here,
1925 then close it and reopen it in the child. */
1926 /* Don't let this terminal become our controlling terminal
1927 (in case we don't have one). */
1928 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1929 if (forkout < 0)
1930 report_file_error ("Opening pty", Qnil);
1931 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
1932 #if defined (DONT_REOPEN_PTY)
1933 /* In the case that vfork is defined as fork, the parent process
1934 (Emacs) may send some data before the child process completes
1935 tty options setup. So we setup tty before forking. */
1936 child_setup_tty (forkout);
1937 #endif /* DONT_REOPEN_PTY */
1938 #endif /* not USG, or USG_SUBTTY_WORKS */
1940 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
1942 /* Record this as an active process, with its channels.
1943 As a result, child_setup will close Emacs's side of the pipes. */
1944 chan_process[pty_fd] = process;
1945 p->infd = pty_fd;
1946 p->outfd = pty_fd;
1948 /* Previously we recorded the tty descriptor used in the subprocess.
1949 It was only used for getting the foreground tty process, so now
1950 we just reopen the device (see emacs_get_tty_pgrp) as this is
1951 more portable (see USG_SUBTTY_WORKS above). */
1953 p->pty_flag = 1;
1954 pset_status (p, Qrun);
1955 setup_process_coding_systems (process);
1957 FD_SET (pty_fd, &input_wait_mask);
1958 FD_SET (pty_fd, &non_keyboard_wait_mask);
1959 if (pty_fd > max_process_desc)
1960 max_process_desc = pty_fd;
1962 pset_tty_name (p, build_string (pty_name));
1965 p->pid = -2;
1969 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1970 The address family of sa is not included in the result. */
1972 #ifndef WINDOWSNT
1973 static
1974 #endif
1975 Lisp_Object
1976 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
1978 Lisp_Object address;
1979 int i;
1980 unsigned char *cp;
1981 register struct Lisp_Vector *p;
1983 /* Workaround for a bug in getsockname on BSD: Names bound to
1984 sockets in the UNIX domain are inaccessible; getsockname returns
1985 a zero length name. */
1986 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
1987 return empty_unibyte_string;
1989 switch (sa->sa_family)
1991 case AF_INET:
1993 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
1994 len = sizeof (sin->sin_addr) + 1;
1995 address = Fmake_vector (make_number (len), Qnil);
1996 p = XVECTOR (address);
1997 p->contents[--len] = make_number (ntohs (sin->sin_port));
1998 cp = (unsigned char *) &sin->sin_addr;
1999 break;
2001 #ifdef AF_INET6
2002 case AF_INET6:
2004 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2005 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2006 len = sizeof (sin6->sin6_addr)/2 + 1;
2007 address = Fmake_vector (make_number (len), Qnil);
2008 p = XVECTOR (address);
2009 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2010 for (i = 0; i < len; i++)
2011 p->contents[i] = make_number (ntohs (ip6[i]));
2012 return address;
2014 #endif
2015 #ifdef HAVE_LOCAL_SOCKETS
2016 case AF_LOCAL:
2018 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2019 ptrdiff_t name_length = len - offsetof (struct sockaddr_un, sun_path);
2020 /* If the first byte is NUL, the name is a Linux abstract
2021 socket name, and the name can contain embedded NULs. If
2022 it's not, we have a NUL-terminated string. Be careful not
2023 to walk past the end of the object looking for the name
2024 terminator, however. */
2025 if (name_length > 0 && sockun->sun_path[0] != '\0')
2027 const char* terminator =
2028 memchr (sockun->sun_path, '\0', name_length);
2030 if (terminator)
2031 name_length = terminator - (const char*) sockun->sun_path;
2034 return make_unibyte_string (sockun->sun_path, name_length);
2036 #endif
2037 default:
2038 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2039 address = Fcons (make_number (sa->sa_family),
2040 Fmake_vector (make_number (len), Qnil));
2041 p = XVECTOR (XCDR (address));
2042 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2043 break;
2046 i = 0;
2047 while (i < len)
2048 p->contents[i++] = make_number (*cp++);
2050 return address;
2054 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2056 static int
2057 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2059 register struct Lisp_Vector *p;
2061 if (VECTORP (address))
2063 p = XVECTOR (address);
2064 if (p->header.size == 5)
2066 *familyp = AF_INET;
2067 return sizeof (struct sockaddr_in);
2069 #ifdef AF_INET6
2070 else if (p->header.size == 9)
2072 *familyp = AF_INET6;
2073 return sizeof (struct sockaddr_in6);
2075 #endif
2077 #ifdef HAVE_LOCAL_SOCKETS
2078 else if (STRINGP (address))
2080 *familyp = AF_LOCAL;
2081 return sizeof (struct sockaddr_un);
2083 #endif
2084 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2085 && VECTORP (XCDR (address)))
2087 struct sockaddr *sa;
2088 *familyp = XINT (XCAR (address));
2089 p = XVECTOR (XCDR (address));
2090 return p->header.size + sizeof (sa->sa_family);
2092 return 0;
2095 /* Convert an address object (vector or string) to an internal sockaddr.
2097 The address format has been basically validated by
2098 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2099 it could have come from user data. So if FAMILY is not valid,
2100 we return after zeroing *SA. */
2102 static void
2103 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2105 register struct Lisp_Vector *p;
2106 register unsigned char *cp = NULL;
2107 register int i;
2108 EMACS_INT hostport;
2110 memset (sa, 0, len);
2112 if (VECTORP (address))
2114 p = XVECTOR (address);
2115 if (family == AF_INET)
2117 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2118 len = sizeof (sin->sin_addr) + 1;
2119 hostport = XINT (p->contents[--len]);
2120 sin->sin_port = htons (hostport);
2121 cp = (unsigned char *)&sin->sin_addr;
2122 sa->sa_family = family;
2124 #ifdef AF_INET6
2125 else if (family == AF_INET6)
2127 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2128 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2129 len = sizeof (sin6->sin6_addr) + 1;
2130 hostport = XINT (p->contents[--len]);
2131 sin6->sin6_port = htons (hostport);
2132 for (i = 0; i < len; i++)
2133 if (INTEGERP (p->contents[i]))
2135 int j = XFASTINT (p->contents[i]) & 0xffff;
2136 ip6[i] = ntohs (j);
2138 sa->sa_family = family;
2139 return;
2141 #endif
2142 else
2143 return;
2145 else if (STRINGP (address))
2147 #ifdef HAVE_LOCAL_SOCKETS
2148 if (family == AF_LOCAL)
2150 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2151 cp = SDATA (address);
2152 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2153 sockun->sun_path[i] = *cp++;
2154 sa->sa_family = family;
2156 #endif
2157 return;
2159 else
2161 p = XVECTOR (XCDR (address));
2162 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2165 for (i = 0; i < len; i++)
2166 if (INTEGERP (p->contents[i]))
2167 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2170 #ifdef DATAGRAM_SOCKETS
2171 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2172 1, 1, 0,
2173 doc: /* Get the current datagram address associated with PROCESS. */)
2174 (Lisp_Object process)
2176 int channel;
2178 CHECK_PROCESS (process);
2180 if (!DATAGRAM_CONN_P (process))
2181 return Qnil;
2183 channel = XPROCESS (process)->infd;
2184 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2185 datagram_address[channel].len);
2188 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2189 2, 2, 0,
2190 doc: /* Set the datagram address for PROCESS to ADDRESS.
2191 Returns nil upon error setting address, ADDRESS otherwise. */)
2192 (Lisp_Object process, Lisp_Object address)
2194 int channel;
2195 int family, len;
2197 CHECK_PROCESS (process);
2199 if (!DATAGRAM_CONN_P (process))
2200 return Qnil;
2202 channel = XPROCESS (process)->infd;
2204 len = get_lisp_to_sockaddr_size (address, &family);
2205 if (len == 0 || datagram_address[channel].len != len)
2206 return Qnil;
2207 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2208 return address;
2210 #endif
2213 static const struct socket_options {
2214 /* The name of this option. Should be lowercase version of option
2215 name without SO_ prefix. */
2216 const char *name;
2217 /* Option level SOL_... */
2218 int optlevel;
2219 /* Option number SO_... */
2220 int optnum;
2221 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2222 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2223 } socket_options[] =
2225 #ifdef SO_BINDTODEVICE
2226 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2227 #endif
2228 #ifdef SO_BROADCAST
2229 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2230 #endif
2231 #ifdef SO_DONTROUTE
2232 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2233 #endif
2234 #ifdef SO_KEEPALIVE
2235 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2236 #endif
2237 #ifdef SO_LINGER
2238 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2239 #endif
2240 #ifdef SO_OOBINLINE
2241 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2242 #endif
2243 #ifdef SO_PRIORITY
2244 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2245 #endif
2246 #ifdef SO_REUSEADDR
2247 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2248 #endif
2249 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2252 /* Set option OPT to value VAL on socket S.
2254 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2255 Signals an error if setting a known option fails.
2258 static int
2259 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2261 char *name;
2262 const struct socket_options *sopt;
2263 int ret = 0;
2265 CHECK_SYMBOL (opt);
2267 name = SSDATA (SYMBOL_NAME (opt));
2268 for (sopt = socket_options; sopt->name; sopt++)
2269 if (strcmp (name, sopt->name) == 0)
2270 break;
2272 switch (sopt->opttype)
2274 case SOPT_BOOL:
2276 int optval;
2277 optval = NILP (val) ? 0 : 1;
2278 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2279 &optval, sizeof (optval));
2280 break;
2283 case SOPT_INT:
2285 int optval;
2286 if (TYPE_RANGED_INTEGERP (int, val))
2287 optval = XINT (val);
2288 else
2289 error ("Bad option value for %s", name);
2290 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2291 &optval, sizeof (optval));
2292 break;
2295 #ifdef SO_BINDTODEVICE
2296 case SOPT_IFNAME:
2298 char devname[IFNAMSIZ+1];
2300 /* This is broken, at least in the Linux 2.4 kernel.
2301 To unbind, the arg must be a zero integer, not the empty string.
2302 This should work on all systems. KFS. 2003-09-23. */
2303 memset (devname, 0, sizeof devname);
2304 if (STRINGP (val))
2306 char *arg = SSDATA (val);
2307 int len = min (strlen (arg), IFNAMSIZ);
2308 memcpy (devname, arg, len);
2310 else if (!NILP (val))
2311 error ("Bad option value for %s", name);
2312 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2313 devname, IFNAMSIZ);
2314 break;
2316 #endif
2318 #ifdef SO_LINGER
2319 case SOPT_LINGER:
2321 struct linger linger;
2323 linger.l_onoff = 1;
2324 linger.l_linger = 0;
2325 if (TYPE_RANGED_INTEGERP (int, val))
2326 linger.l_linger = XINT (val);
2327 else
2328 linger.l_onoff = NILP (val) ? 0 : 1;
2329 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2330 &linger, sizeof (linger));
2331 break;
2333 #endif
2335 default:
2336 return 0;
2339 if (ret < 0)
2341 int setsockopt_errno = errno;
2342 report_file_errno ("Cannot set network option", list2 (opt, val),
2343 setsockopt_errno);
2346 return (1 << sopt->optbit);
2350 DEFUN ("set-network-process-option",
2351 Fset_network_process_option, Sset_network_process_option,
2352 3, 4, 0,
2353 doc: /* For network process PROCESS set option OPTION to value VALUE.
2354 See `make-network-process' for a list of options and values.
2355 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2356 OPTION is not a supported option, return nil instead; otherwise return t. */)
2357 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2359 int s;
2360 struct Lisp_Process *p;
2362 CHECK_PROCESS (process);
2363 p = XPROCESS (process);
2364 if (!NETCONN1_P (p))
2365 error ("Process is not a network process");
2367 s = p->infd;
2368 if (s < 0)
2369 error ("Process is not running");
2371 if (set_socket_option (s, option, value))
2373 pset_childp (p, Fplist_put (p->childp, option, value));
2374 return Qt;
2377 if (NILP (no_error))
2378 error ("Unknown or unsupported option");
2380 return Qnil;
2384 DEFUN ("serial-process-configure",
2385 Fserial_process_configure,
2386 Sserial_process_configure,
2387 0, MANY, 0,
2388 doc: /* Configure speed, bytesize, etc. of a serial process.
2390 Arguments are specified as keyword/argument pairs. Attributes that
2391 are not given are re-initialized from the process's current
2392 configuration (available via the function `process-contact') or set to
2393 reasonable default values. The following arguments are defined:
2395 :process PROCESS
2396 :name NAME
2397 :buffer BUFFER
2398 :port PORT
2399 -- Any of these arguments can be given to identify the process that is
2400 to be configured. If none of these arguments is given, the current
2401 buffer's process is used.
2403 :speed SPEED -- SPEED is the speed of the serial port in bits per
2404 second, also called baud rate. Any value can be given for SPEED, but
2405 most serial ports work only at a few defined values between 1200 and
2406 115200, with 9600 being the most common value. If SPEED is nil, the
2407 serial port is not configured any further, i.e., all other arguments
2408 are ignored. This may be useful for special serial ports such as
2409 Bluetooth-to-serial converters which can only be configured through AT
2410 commands. A value of nil for SPEED can be used only when passed
2411 through `make-serial-process' or `serial-term'.
2413 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2414 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2416 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2417 `odd' (use odd parity), or the symbol `even' (use even parity). If
2418 PARITY is not given, no parity is used.
2420 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2421 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2422 is not given or nil, 1 stopbit is used.
2424 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2425 flowcontrol to be used, which is either nil (don't use flowcontrol),
2426 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2427 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2428 flowcontrol is used.
2430 `serial-process-configure' is called by `make-serial-process' for the
2431 initial configuration of the serial port.
2433 Examples:
2435 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2437 \(serial-process-configure
2438 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2440 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2442 usage: (serial-process-configure &rest ARGS) */)
2443 (ptrdiff_t nargs, Lisp_Object *args)
2445 struct Lisp_Process *p;
2446 Lisp_Object contact = Qnil;
2447 Lisp_Object proc = Qnil;
2448 struct gcpro gcpro1;
2450 contact = Flist (nargs, args);
2451 GCPRO1 (contact);
2453 proc = Fplist_get (contact, QCprocess);
2454 if (NILP (proc))
2455 proc = Fplist_get (contact, QCname);
2456 if (NILP (proc))
2457 proc = Fplist_get (contact, QCbuffer);
2458 if (NILP (proc))
2459 proc = Fplist_get (contact, QCport);
2460 proc = get_process (proc);
2461 p = XPROCESS (proc);
2462 if (!EQ (p->type, Qserial))
2463 error ("Not a serial process");
2465 if (NILP (Fplist_get (p->childp, QCspeed)))
2467 UNGCPRO;
2468 return Qnil;
2471 serial_configure (p, contact);
2473 UNGCPRO;
2474 return Qnil;
2477 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2478 0, MANY, 0,
2479 doc: /* Create and return a serial port process.
2481 In Emacs, serial port connections are represented by process objects,
2482 so input and output work as for subprocesses, and `delete-process'
2483 closes a serial port connection. However, a serial process has no
2484 process id, it cannot be signaled, and the status codes are different
2485 from normal processes.
2487 `make-serial-process' creates a process and a buffer, on which you
2488 probably want to use `process-send-string'. Try \\[serial-term] for
2489 an interactive terminal. See below for examples.
2491 Arguments are specified as keyword/argument pairs. The following
2492 arguments are defined:
2494 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2495 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2496 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2497 the backslashes in strings).
2499 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2500 which this function calls.
2502 :name NAME -- NAME is the name of the process. If NAME is not given,
2503 the value of PORT is used.
2505 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2506 with the process. Process output goes at the end of that buffer,
2507 unless you specify an output stream or filter function to handle the
2508 output. If BUFFER is not given, the value of NAME is used.
2510 :coding CODING -- If CODING is a symbol, it specifies the coding
2511 system used for both reading and writing for this process. If CODING
2512 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2513 ENCODING is used for writing.
2515 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2516 the process is running. If BOOL is not given, query before exiting.
2518 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2519 In the stopped state, a serial process does not accept incoming data,
2520 but you can send outgoing data. The stopped state is cleared by
2521 `continue-process' and set by `stop-process'.
2523 :filter FILTER -- Install FILTER as the process filter.
2525 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2527 :plist PLIST -- Install PLIST as the initial plist of the process.
2529 :bytesize
2530 :parity
2531 :stopbits
2532 :flowcontrol
2533 -- This function calls `serial-process-configure' to handle these
2534 arguments.
2536 The original argument list, possibly modified by later configuration,
2537 is available via the function `process-contact'.
2539 Examples:
2541 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2543 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2545 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2547 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2549 usage: (make-serial-process &rest ARGS) */)
2550 (ptrdiff_t nargs, Lisp_Object *args)
2552 int fd = -1;
2553 Lisp_Object proc, contact, port;
2554 struct Lisp_Process *p;
2555 struct gcpro gcpro1;
2556 Lisp_Object name, buffer;
2557 Lisp_Object tem, val;
2558 ptrdiff_t specpdl_count;
2560 if (nargs == 0)
2561 return Qnil;
2563 contact = Flist (nargs, args);
2564 GCPRO1 (contact);
2566 port = Fplist_get (contact, QCport);
2567 if (NILP (port))
2568 error ("No port specified");
2569 CHECK_STRING (port);
2571 if (NILP (Fplist_member (contact, QCspeed)))
2572 error (":speed not specified");
2573 if (!NILP (Fplist_get (contact, QCspeed)))
2574 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2576 name = Fplist_get (contact, QCname);
2577 if (NILP (name))
2578 name = port;
2579 CHECK_STRING (name);
2580 proc = make_process (name);
2581 specpdl_count = SPECPDL_INDEX ();
2582 record_unwind_protect (remove_process, proc);
2583 p = XPROCESS (proc);
2585 fd = serial_open (port);
2586 p->open_fd[SUBPROCESS_STDIN] = fd;
2587 p->infd = fd;
2588 p->outfd = fd;
2589 if (fd > max_process_desc)
2590 max_process_desc = fd;
2591 chan_process[fd] = proc;
2593 buffer = Fplist_get (contact, QCbuffer);
2594 if (NILP (buffer))
2595 buffer = name;
2596 buffer = Fget_buffer_create (buffer);
2597 pset_buffer (p, buffer);
2599 pset_childp (p, contact);
2600 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2601 pset_type (p, Qserial);
2602 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2603 pset_filter (p, Fplist_get (contact, QCfilter));
2604 pset_log (p, Qnil);
2605 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2606 p->kill_without_query = 1;
2607 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2608 pset_command (p, Qt);
2609 eassert (! p->pty_flag);
2611 if (!EQ (p->command, Qt))
2613 FD_SET (fd, &input_wait_mask);
2614 FD_SET (fd, &non_keyboard_wait_mask);
2617 if (BUFFERP (buffer))
2619 set_marker_both (p->mark, buffer,
2620 BUF_ZV (XBUFFER (buffer)),
2621 BUF_ZV_BYTE (XBUFFER (buffer)));
2624 tem = Fplist_member (contact, QCcoding);
2625 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2626 tem = Qnil;
2628 val = Qnil;
2629 if (!NILP (tem))
2631 val = XCAR (XCDR (tem));
2632 if (CONSP (val))
2633 val = XCAR (val);
2635 else if (!NILP (Vcoding_system_for_read))
2636 val = Vcoding_system_for_read;
2637 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2638 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2639 val = Qnil;
2640 pset_decode_coding_system (p, val);
2642 val = Qnil;
2643 if (!NILP (tem))
2645 val = XCAR (XCDR (tem));
2646 if (CONSP (val))
2647 val = XCDR (val);
2649 else if (!NILP (Vcoding_system_for_write))
2650 val = Vcoding_system_for_write;
2651 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2652 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2653 val = Qnil;
2654 pset_encode_coding_system (p, val);
2656 setup_process_coding_systems (proc);
2657 pset_decoding_buf (p, empty_unibyte_string);
2658 p->decoding_carryover = 0;
2659 pset_encoding_buf (p, empty_unibyte_string);
2660 p->inherit_coding_system_flag
2661 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2663 Fserial_process_configure (nargs, args);
2665 specpdl_ptr = specpdl + specpdl_count;
2667 UNGCPRO;
2668 return proc;
2671 /* Create a network stream/datagram client/server process. Treated
2672 exactly like a normal process when reading and writing. Primary
2673 differences are in status display and process deletion. A network
2674 connection has no PID; you cannot signal it. All you can do is
2675 stop/continue it and deactivate/close it via delete-process */
2677 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2678 0, MANY, 0,
2679 doc: /* Create and return a network server or client process.
2681 In Emacs, network connections are represented by process objects, so
2682 input and output work as for subprocesses and `delete-process' closes
2683 a network connection. However, a network process has no process id,
2684 it cannot be signaled, and the status codes are different from normal
2685 processes.
2687 Arguments are specified as keyword/argument pairs. The following
2688 arguments are defined:
2690 :name NAME -- NAME is name for process. It is modified if necessary
2691 to make it unique.
2693 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2694 with the process. Process output goes at end of that buffer, unless
2695 you specify an output stream or filter function to handle the output.
2696 BUFFER may be also nil, meaning that this process is not associated
2697 with any buffer.
2699 :host HOST -- HOST is name of the host to connect to, or its IP
2700 address. The symbol `local' specifies the local host. If specified
2701 for a server process, it must be a valid name or address for the local
2702 host, and only clients connecting to that address will be accepted.
2704 :service SERVICE -- SERVICE is name of the service desired, or an
2705 integer specifying a port number to connect to. If SERVICE is t,
2706 a random port number is selected for the server. (If Emacs was
2707 compiled with getaddrinfo, a port number can also be specified as a
2708 string, e.g. "80", as well as an integer. This is not portable.)
2710 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2711 stream type connection, `datagram' creates a datagram type connection,
2712 `seqpacket' creates a reliable datagram connection.
2714 :family FAMILY -- FAMILY is the address (and protocol) family for the
2715 service specified by HOST and SERVICE. The default (nil) is to use
2716 whatever address family (IPv4 or IPv6) that is defined for the host
2717 and port number specified by HOST and SERVICE. Other address families
2718 supported are:
2719 local -- for a local (i.e. UNIX) address specified by SERVICE.
2720 ipv4 -- use IPv4 address family only.
2721 ipv6 -- use IPv6 address family only.
2723 :local ADDRESS -- ADDRESS is the local address used for the connection.
2724 This parameter is ignored when opening a client process. When specified
2725 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2727 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2728 connection. This parameter is ignored when opening a stream server
2729 process. For a datagram server process, it specifies the initial
2730 setting of the remote datagram address. When specified for a client
2731 process, the FAMILY, HOST, and SERVICE args are ignored.
2733 The format of ADDRESS depends on the address family:
2734 - An IPv4 address is represented as an vector of integers [A B C D P]
2735 corresponding to numeric IP address A.B.C.D and port number P.
2736 - A local address is represented as a string with the address in the
2737 local address space.
2738 - An "unsupported family" address is represented by a cons (F . AV)
2739 where F is the family number and AV is a vector containing the socket
2740 address data with one element per address data byte. Do not rely on
2741 this format in portable code, as it may depend on implementation
2742 defined constants, data sizes, and data structure alignment.
2744 :coding CODING -- If CODING is a symbol, it specifies the coding
2745 system used for both reading and writing for this process. If CODING
2746 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2747 ENCODING is used for writing.
2749 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2750 return without waiting for the connection to complete; instead, the
2751 sentinel function will be called with second arg matching "open" (if
2752 successful) or "failed" when the connect completes. Default is to use
2753 a blocking connect (i.e. wait) for stream type connections.
2755 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2756 running when Emacs is exited.
2758 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2759 In the stopped state, a server process does not accept new
2760 connections, and a client process does not handle incoming traffic.
2761 The stopped state is cleared by `continue-process' and set by
2762 `stop-process'.
2764 :filter FILTER -- Install FILTER as the process filter.
2766 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2767 process filter are multibyte, otherwise they are unibyte.
2768 If this keyword is not specified, the strings are multibyte if
2769 the default value of `enable-multibyte-characters' is non-nil.
2771 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2773 :log LOG -- Install LOG as the server process log function. This
2774 function is called when the server accepts a network connection from a
2775 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2776 is the server process, CLIENT is the new process for the connection,
2777 and MESSAGE is a string.
2779 :plist PLIST -- Install PLIST as the new process's initial plist.
2781 :server QLEN -- if QLEN is non-nil, create a server process for the
2782 specified FAMILY, SERVICE, and connection type (stream or datagram).
2783 If QLEN is an integer, it is used as the max. length of the server's
2784 pending connection queue (also known as the backlog); the default
2785 queue length is 5. Default is to create a client process.
2787 The following network options can be specified for this connection:
2789 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2790 :dontroute BOOL -- Only send to directly connected hosts.
2791 :keepalive BOOL -- Send keep-alive messages on network stream.
2792 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2793 :oobinline BOOL -- Place out-of-band data in receive data stream.
2794 :priority INT -- Set protocol defined priority for sent packets.
2795 :reuseaddr BOOL -- Allow reusing a recently used local address
2796 (this is allowed by default for a server process).
2797 :bindtodevice NAME -- bind to interface NAME. Using this may require
2798 special privileges on some systems.
2800 Consult the relevant system programmer's manual pages for more
2801 information on using these options.
2804 A server process will listen for and accept connections from clients.
2805 When a client connection is accepted, a new network process is created
2806 for the connection with the following parameters:
2808 - The client's process name is constructed by concatenating the server
2809 process's NAME and a client identification string.
2810 - If the FILTER argument is non-nil, the client process will not get a
2811 separate process buffer; otherwise, the client's process buffer is a newly
2812 created buffer named after the server process's BUFFER name or process
2813 NAME concatenated with the client identification string.
2814 - The connection type and the process filter and sentinel parameters are
2815 inherited from the server process's TYPE, FILTER and SENTINEL.
2816 - The client process's contact info is set according to the client's
2817 addressing information (typically an IP address and a port number).
2818 - The client process's plist is initialized from the server's plist.
2820 Notice that the FILTER and SENTINEL args are never used directly by
2821 the server process. Also, the BUFFER argument is not used directly by
2822 the server process, but via the optional :log function, accepted (and
2823 failed) connections may be logged in the server process's buffer.
2825 The original argument list, modified with the actual connection
2826 information, is available via the `process-contact' function.
2828 usage: (make-network-process &rest ARGS) */)
2829 (ptrdiff_t nargs, Lisp_Object *args)
2831 Lisp_Object proc;
2832 Lisp_Object contact;
2833 struct Lisp_Process *p;
2834 #ifdef HAVE_GETADDRINFO
2835 struct addrinfo ai, *res, *lres;
2836 struct addrinfo hints;
2837 const char *portstring;
2838 char portbuf[128];
2839 #else /* HAVE_GETADDRINFO */
2840 struct _emacs_addrinfo
2842 int ai_family;
2843 int ai_socktype;
2844 int ai_protocol;
2845 int ai_addrlen;
2846 struct sockaddr *ai_addr;
2847 struct _emacs_addrinfo *ai_next;
2848 } ai, *res, *lres;
2849 #endif /* HAVE_GETADDRINFO */
2850 struct sockaddr_in address_in;
2851 #ifdef HAVE_LOCAL_SOCKETS
2852 struct sockaddr_un address_un;
2853 #endif
2854 int port;
2855 int ret = 0;
2856 int xerrno = 0;
2857 int s = -1, outch, inch;
2858 struct gcpro gcpro1;
2859 ptrdiff_t count = SPECPDL_INDEX ();
2860 ptrdiff_t count1;
2861 Lisp_Object QCaddress; /* one of QClocal or QCremote */
2862 Lisp_Object tem;
2863 Lisp_Object name, buffer, host, service, address;
2864 Lisp_Object filter, sentinel;
2865 bool is_non_blocking_client = 0;
2866 bool is_server = 0;
2867 int backlog = 5;
2868 int socktype;
2869 int family = -1;
2871 if (nargs == 0)
2872 return Qnil;
2874 /* Save arguments for process-contact and clone-process. */
2875 contact = Flist (nargs, args);
2876 GCPRO1 (contact);
2878 #ifdef WINDOWSNT
2879 /* Ensure socket support is loaded if available. */
2880 init_winsock (TRUE);
2881 #endif
2883 /* :type TYPE (nil: stream, datagram */
2884 tem = Fplist_get (contact, QCtype);
2885 if (NILP (tem))
2886 socktype = SOCK_STREAM;
2887 #ifdef DATAGRAM_SOCKETS
2888 else if (EQ (tem, Qdatagram))
2889 socktype = SOCK_DGRAM;
2890 #endif
2891 #ifdef HAVE_SEQPACKET
2892 else if (EQ (tem, Qseqpacket))
2893 socktype = SOCK_SEQPACKET;
2894 #endif
2895 else
2896 error ("Unsupported connection type");
2898 /* :server BOOL */
2899 tem = Fplist_get (contact, QCserver);
2900 if (!NILP (tem))
2902 /* Don't support network sockets when non-blocking mode is
2903 not available, since a blocked Emacs is not useful. */
2904 is_server = 1;
2905 if (TYPE_RANGED_INTEGERP (int, tem))
2906 backlog = XINT (tem);
2909 /* Make QCaddress an alias for :local (server) or :remote (client). */
2910 QCaddress = is_server ? QClocal : QCremote;
2912 /* :nowait BOOL */
2913 if (!is_server && socktype != SOCK_DGRAM
2914 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2916 #ifndef NON_BLOCKING_CONNECT
2917 error ("Non-blocking connect not supported");
2918 #else
2919 is_non_blocking_client = 1;
2920 #endif
2923 name = Fplist_get (contact, QCname);
2924 buffer = Fplist_get (contact, QCbuffer);
2925 filter = Fplist_get (contact, QCfilter);
2926 sentinel = Fplist_get (contact, QCsentinel);
2928 CHECK_STRING (name);
2930 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2931 ai.ai_socktype = socktype;
2932 ai.ai_protocol = 0;
2933 ai.ai_next = NULL;
2934 res = &ai;
2936 /* :local ADDRESS or :remote ADDRESS */
2937 address = Fplist_get (contact, QCaddress);
2938 if (!NILP (address))
2940 host = service = Qnil;
2942 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2943 error ("Malformed :address");
2944 ai.ai_family = family;
2945 ai.ai_addr = alloca (ai.ai_addrlen);
2946 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
2947 goto open_socket;
2950 /* :family FAMILY -- nil (for Inet), local, or integer. */
2951 tem = Fplist_get (contact, QCfamily);
2952 if (NILP (tem))
2954 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
2955 family = AF_UNSPEC;
2956 #else
2957 family = AF_INET;
2958 #endif
2960 #ifdef HAVE_LOCAL_SOCKETS
2961 else if (EQ (tem, Qlocal))
2962 family = AF_LOCAL;
2963 #endif
2964 #ifdef AF_INET6
2965 else if (EQ (tem, Qipv6))
2966 family = AF_INET6;
2967 #endif
2968 else if (EQ (tem, Qipv4))
2969 family = AF_INET;
2970 else if (TYPE_RANGED_INTEGERP (int, tem))
2971 family = XINT (tem);
2972 else
2973 error ("Unknown address family");
2975 ai.ai_family = family;
2977 /* :service SERVICE -- string, integer (port number), or t (random port). */
2978 service = Fplist_get (contact, QCservice);
2980 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2981 host = Fplist_get (contact, QChost);
2982 if (!NILP (host))
2984 if (EQ (host, Qlocal))
2985 /* Depending on setup, "localhost" may map to different IPv4 and/or
2986 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
2987 host = build_string ("127.0.0.1");
2988 CHECK_STRING (host);
2991 #ifdef HAVE_LOCAL_SOCKETS
2992 if (family == AF_LOCAL)
2994 if (!NILP (host))
2996 message (":family local ignores the :host \"%s\" property",
2997 SDATA (host));
2998 contact = Fplist_put (contact, QChost, Qnil);
2999 host = Qnil;
3001 CHECK_STRING (service);
3002 memset (&address_un, 0, sizeof address_un);
3003 address_un.sun_family = AF_LOCAL;
3004 if (sizeof address_un.sun_path <= SBYTES (service))
3005 error ("Service name too long");
3006 strcpy (address_un.sun_path, SSDATA (service));
3007 ai.ai_addr = (struct sockaddr *) &address_un;
3008 ai.ai_addrlen = sizeof address_un;
3009 goto open_socket;
3011 #endif
3013 /* Slow down polling to every ten seconds.
3014 Some kernels have a bug which causes retrying connect to fail
3015 after a connect. Polling can interfere with gethostbyname too. */
3016 #ifdef POLL_FOR_INPUT
3017 if (socktype != SOCK_DGRAM)
3019 record_unwind_protect_void (run_all_atimers);
3020 bind_polling_period (10);
3022 #endif
3024 #ifdef HAVE_GETADDRINFO
3025 /* If we have a host, use getaddrinfo to resolve both host and service.
3026 Otherwise, use getservbyname to lookup the service. */
3027 if (!NILP (host))
3030 /* SERVICE can either be a string or int.
3031 Convert to a C string for later use by getaddrinfo. */
3032 if (EQ (service, Qt))
3033 portstring = "0";
3034 else if (INTEGERP (service))
3036 sprintf (portbuf, "%"pI"d", XINT (service));
3037 portstring = portbuf;
3039 else
3041 CHECK_STRING (service);
3042 portstring = SSDATA (service);
3045 immediate_quit = 1;
3046 QUIT;
3047 memset (&hints, 0, sizeof (hints));
3048 hints.ai_flags = 0;
3049 hints.ai_family = family;
3050 hints.ai_socktype = socktype;
3051 hints.ai_protocol = 0;
3053 #ifdef HAVE_RES_INIT
3054 res_init ();
3055 #endif
3057 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3058 if (ret)
3059 #ifdef HAVE_GAI_STRERROR
3060 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3061 #else
3062 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3063 #endif
3064 immediate_quit = 0;
3066 goto open_socket;
3068 #endif /* HAVE_GETADDRINFO */
3070 /* We end up here if getaddrinfo is not defined, or in case no hostname
3071 has been specified (e.g. for a local server process). */
3073 if (EQ (service, Qt))
3074 port = 0;
3075 else if (INTEGERP (service))
3076 port = htons ((unsigned short) XINT (service));
3077 else
3079 struct servent *svc_info;
3080 CHECK_STRING (service);
3081 svc_info = getservbyname (SSDATA (service),
3082 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3083 if (svc_info == 0)
3084 error ("Unknown service: %s", SDATA (service));
3085 port = svc_info->s_port;
3088 memset (&address_in, 0, sizeof address_in);
3089 address_in.sin_family = family;
3090 address_in.sin_addr.s_addr = INADDR_ANY;
3091 address_in.sin_port = port;
3093 #ifndef HAVE_GETADDRINFO
3094 if (!NILP (host))
3096 struct hostent *host_info_ptr;
3098 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3099 as it may `hang' Emacs for a very long time. */
3100 immediate_quit = 1;
3101 QUIT;
3103 #ifdef HAVE_RES_INIT
3104 res_init ();
3105 #endif
3107 host_info_ptr = gethostbyname (SDATA (host));
3108 immediate_quit = 0;
3110 if (host_info_ptr)
3112 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3113 host_info_ptr->h_length);
3114 family = host_info_ptr->h_addrtype;
3115 address_in.sin_family = family;
3117 else
3118 /* Attempt to interpret host as numeric inet address */
3120 unsigned long numeric_addr;
3121 numeric_addr = inet_addr (SSDATA (host));
3122 if (numeric_addr == -1)
3123 error ("Unknown host \"%s\"", SDATA (host));
3125 memcpy (&address_in.sin_addr, &numeric_addr,
3126 sizeof (address_in.sin_addr));
3130 #endif /* not HAVE_GETADDRINFO */
3132 ai.ai_family = family;
3133 ai.ai_addr = (struct sockaddr *) &address_in;
3134 ai.ai_addrlen = sizeof address_in;
3136 open_socket:
3138 /* Do this in case we never enter the for-loop below. */
3139 count1 = SPECPDL_INDEX ();
3140 s = -1;
3142 for (lres = res; lres; lres = lres->ai_next)
3144 ptrdiff_t optn;
3145 int optbits;
3147 #ifdef WINDOWSNT
3148 retry_connect:
3149 #endif
3151 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3152 lres->ai_protocol);
3153 if (s < 0)
3155 xerrno = errno;
3156 continue;
3159 #ifdef DATAGRAM_SOCKETS
3160 if (!is_server && socktype == SOCK_DGRAM)
3161 break;
3162 #endif /* DATAGRAM_SOCKETS */
3164 #ifdef NON_BLOCKING_CONNECT
3165 if (is_non_blocking_client)
3167 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3168 if (ret < 0)
3170 xerrno = errno;
3171 emacs_close (s);
3172 s = -1;
3173 continue;
3176 #endif
3178 /* Make us close S if quit. */
3179 record_unwind_protect_int (close_file_unwind, s);
3181 /* Parse network options in the arg list.
3182 We simply ignore anything which isn't a known option (including other keywords).
3183 An error is signaled if setting a known option fails. */
3184 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3185 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3187 if (is_server)
3189 /* Configure as a server socket. */
3191 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3192 explicit :reuseaddr key to override this. */
3193 #ifdef HAVE_LOCAL_SOCKETS
3194 if (family != AF_LOCAL)
3195 #endif
3196 if (!(optbits & (1 << OPIX_REUSEADDR)))
3198 int optval = 1;
3199 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3200 report_file_error ("Cannot set reuse option on server socket", Qnil);
3203 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3204 report_file_error ("Cannot bind server socket", Qnil);
3206 #ifdef HAVE_GETSOCKNAME
3207 if (EQ (service, Qt))
3209 struct sockaddr_in sa1;
3210 socklen_t len1 = sizeof (sa1);
3211 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3213 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3214 service = make_number (ntohs (sa1.sin_port));
3215 contact = Fplist_put (contact, QCservice, service);
3218 #endif
3220 if (socktype != SOCK_DGRAM && listen (s, backlog))
3221 report_file_error ("Cannot listen on server socket", Qnil);
3223 break;
3226 immediate_quit = 1;
3227 QUIT;
3229 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3230 xerrno = errno;
3232 if (ret == 0 || xerrno == EISCONN)
3234 /* The unwind-protect will be discarded afterwards.
3235 Likewise for immediate_quit. */
3236 break;
3239 #ifdef NON_BLOCKING_CONNECT
3240 #ifdef EINPROGRESS
3241 if (is_non_blocking_client && xerrno == EINPROGRESS)
3242 break;
3243 #else
3244 #ifdef EWOULDBLOCK
3245 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3246 break;
3247 #endif
3248 #endif
3249 #endif
3251 #ifndef WINDOWSNT
3252 if (xerrno == EINTR)
3254 /* Unlike most other syscalls connect() cannot be called
3255 again. (That would return EALREADY.) The proper way to
3256 wait for completion is pselect(). */
3257 int sc;
3258 socklen_t len;
3259 fd_set fdset;
3260 retry_select:
3261 FD_ZERO (&fdset);
3262 FD_SET (s, &fdset);
3263 QUIT;
3264 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3265 if (sc == -1)
3267 if (errno == EINTR)
3268 goto retry_select;
3269 else
3270 report_file_error ("Failed select", Qnil);
3272 eassert (sc > 0);
3274 len = sizeof xerrno;
3275 eassert (FD_ISSET (s, &fdset));
3276 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3277 report_file_error ("Failed getsockopt", Qnil);
3278 if (xerrno)
3279 report_file_errno ("Failed connect", Qnil, xerrno);
3280 break;
3282 #endif /* !WINDOWSNT */
3284 immediate_quit = 0;
3286 /* Discard the unwind protect closing S. */
3287 specpdl_ptr = specpdl + count1;
3288 emacs_close (s);
3289 s = -1;
3291 #ifdef WINDOWSNT
3292 if (xerrno == EINTR)
3293 goto retry_connect;
3294 #endif
3297 if (s >= 0)
3299 #ifdef DATAGRAM_SOCKETS
3300 if (socktype == SOCK_DGRAM)
3302 if (datagram_address[s].sa)
3303 emacs_abort ();
3304 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3305 datagram_address[s].len = lres->ai_addrlen;
3306 if (is_server)
3308 Lisp_Object remote;
3309 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3310 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3312 int rfamily, rlen;
3313 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3314 if (rlen != 0 && rfamily == lres->ai_family
3315 && rlen == lres->ai_addrlen)
3316 conv_lisp_to_sockaddr (rfamily, remote,
3317 datagram_address[s].sa, rlen);
3320 else
3321 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3323 #endif
3324 contact = Fplist_put (contact, QCaddress,
3325 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3326 #ifdef HAVE_GETSOCKNAME
3327 if (!is_server)
3329 struct sockaddr_in sa1;
3330 socklen_t len1 = sizeof (sa1);
3331 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3332 contact = Fplist_put (contact, QClocal,
3333 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3335 #endif
3338 immediate_quit = 0;
3340 #ifdef HAVE_GETADDRINFO
3341 if (res != &ai)
3343 block_input ();
3344 freeaddrinfo (res);
3345 unblock_input ();
3347 #endif
3349 if (s < 0)
3351 /* If non-blocking got this far - and failed - assume non-blocking is
3352 not supported after all. This is probably a wrong assumption, but
3353 the normal blocking calls to open-network-stream handles this error
3354 better. */
3355 if (is_non_blocking_client)
3356 return Qnil;
3358 report_file_errno ((is_server
3359 ? "make server process failed"
3360 : "make client process failed"),
3361 contact, xerrno);
3364 inch = s;
3365 outch = s;
3367 if (!NILP (buffer))
3368 buffer = Fget_buffer_create (buffer);
3369 proc = make_process (name);
3371 chan_process[inch] = proc;
3373 fcntl (inch, F_SETFL, O_NONBLOCK);
3375 p = XPROCESS (proc);
3377 pset_childp (p, contact);
3378 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3379 pset_type (p, Qnetwork);
3381 pset_buffer (p, buffer);
3382 pset_sentinel (p, sentinel);
3383 pset_filter (p, filter);
3384 pset_log (p, Fplist_get (contact, QClog));
3385 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3386 p->kill_without_query = 1;
3387 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3388 pset_command (p, Qt);
3389 p->pid = 0;
3391 p->open_fd[SUBPROCESS_STDIN] = inch;
3392 p->infd = inch;
3393 p->outfd = outch;
3395 /* Discard the unwind protect for closing S, if any. */
3396 specpdl_ptr = specpdl + count1;
3398 /* Unwind bind_polling_period and request_sigio. */
3399 unbind_to (count, Qnil);
3401 if (is_server && socktype != SOCK_DGRAM)
3402 pset_status (p, Qlisten);
3404 /* Make the process marker point into the process buffer (if any). */
3405 if (BUFFERP (buffer))
3406 set_marker_both (p->mark, buffer,
3407 BUF_ZV (XBUFFER (buffer)),
3408 BUF_ZV_BYTE (XBUFFER (buffer)));
3410 #ifdef NON_BLOCKING_CONNECT
3411 if (is_non_blocking_client)
3413 /* We may get here if connect did succeed immediately. However,
3414 in that case, we still need to signal this like a non-blocking
3415 connection. */
3416 pset_status (p, Qconnect);
3417 if (!FD_ISSET (inch, &connect_wait_mask))
3419 FD_SET (inch, &connect_wait_mask);
3420 FD_SET (inch, &write_mask);
3421 num_pending_connects++;
3424 else
3425 #endif
3426 /* A server may have a client filter setting of Qt, but it must
3427 still listen for incoming connects unless it is stopped. */
3428 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3429 || (EQ (p->status, Qlisten) && NILP (p->command)))
3431 FD_SET (inch, &input_wait_mask);
3432 FD_SET (inch, &non_keyboard_wait_mask);
3435 if (inch > max_process_desc)
3436 max_process_desc = inch;
3438 tem = Fplist_member (contact, QCcoding);
3439 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3440 tem = Qnil; /* No error message (too late!). */
3443 /* Setup coding systems for communicating with the network stream. */
3444 struct gcpro gcpro1;
3445 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3446 Lisp_Object coding_systems = Qt;
3447 Lisp_Object fargs[5], val;
3449 if (!NILP (tem))
3451 val = XCAR (XCDR (tem));
3452 if (CONSP (val))
3453 val = XCAR (val);
3455 else if (!NILP (Vcoding_system_for_read))
3456 val = Vcoding_system_for_read;
3457 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3458 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3459 /* We dare not decode end-of-line format by setting VAL to
3460 Qraw_text, because the existing Emacs Lisp libraries
3461 assume that they receive bare code including a sequence of
3462 CR LF. */
3463 val = Qnil;
3464 else
3466 if (NILP (host) || NILP (service))
3467 coding_systems = Qnil;
3468 else
3470 fargs[0] = Qopen_network_stream, fargs[1] = name,
3471 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3472 GCPRO1 (proc);
3473 coding_systems = Ffind_operation_coding_system (5, fargs);
3474 UNGCPRO;
3476 if (CONSP (coding_systems))
3477 val = XCAR (coding_systems);
3478 else if (CONSP (Vdefault_process_coding_system))
3479 val = XCAR (Vdefault_process_coding_system);
3480 else
3481 val = Qnil;
3483 pset_decode_coding_system (p, val);
3485 if (!NILP (tem))
3487 val = XCAR (XCDR (tem));
3488 if (CONSP (val))
3489 val = XCDR (val);
3491 else if (!NILP (Vcoding_system_for_write))
3492 val = Vcoding_system_for_write;
3493 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3494 val = Qnil;
3495 else
3497 if (EQ (coding_systems, Qt))
3499 if (NILP (host) || NILP (service))
3500 coding_systems = Qnil;
3501 else
3503 fargs[0] = Qopen_network_stream, fargs[1] = name,
3504 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3505 GCPRO1 (proc);
3506 coding_systems = Ffind_operation_coding_system (5, fargs);
3507 UNGCPRO;
3510 if (CONSP (coding_systems))
3511 val = XCDR (coding_systems);
3512 else if (CONSP (Vdefault_process_coding_system))
3513 val = XCDR (Vdefault_process_coding_system);
3514 else
3515 val = Qnil;
3517 pset_encode_coding_system (p, val);
3519 setup_process_coding_systems (proc);
3521 pset_decoding_buf (p, empty_unibyte_string);
3522 p->decoding_carryover = 0;
3523 pset_encoding_buf (p, empty_unibyte_string);
3525 p->inherit_coding_system_flag
3526 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3528 UNGCPRO;
3529 return proc;
3533 #ifdef HAVE_NET_IF_H
3535 #ifdef SIOCGIFCONF
3536 static Lisp_Object
3537 network_interface_list (void)
3539 struct ifconf ifconf;
3540 struct ifreq *ifreq;
3541 void *buf = NULL;
3542 ptrdiff_t buf_size = 512;
3543 int s;
3544 Lisp_Object res;
3545 ptrdiff_t count;
3547 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3548 if (s < 0)
3549 return Qnil;
3550 count = SPECPDL_INDEX ();
3551 record_unwind_protect_int (close_file_unwind, s);
3555 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3556 ifconf.ifc_buf = buf;
3557 ifconf.ifc_len = buf_size;
3558 if (ioctl (s, SIOCGIFCONF, &ifconf))
3560 emacs_close (s);
3561 xfree (buf);
3562 return Qnil;
3565 while (ifconf.ifc_len == buf_size);
3567 res = unbind_to (count, Qnil);
3568 ifreq = ifconf.ifc_req;
3569 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3571 struct ifreq *ifq = ifreq;
3572 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3573 #define SIZEOF_IFREQ(sif) \
3574 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3575 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3577 int len = SIZEOF_IFREQ (ifq);
3578 #else
3579 int len = sizeof (*ifreq);
3580 #endif
3581 char namebuf[sizeof (ifq->ifr_name) + 1];
3582 ifreq = (struct ifreq *) ((char *) ifreq + len);
3584 if (ifq->ifr_addr.sa_family != AF_INET)
3585 continue;
3587 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3588 namebuf[sizeof (ifq->ifr_name)] = 0;
3589 res = Fcons (Fcons (build_string (namebuf),
3590 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3591 sizeof (struct sockaddr))),
3592 res);
3595 xfree (buf);
3596 return res;
3598 #endif /* SIOCGIFCONF */
3600 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3602 struct ifflag_def {
3603 int flag_bit;
3604 const char *flag_sym;
3607 static const struct ifflag_def ifflag_table[] = {
3608 #ifdef IFF_UP
3609 { IFF_UP, "up" },
3610 #endif
3611 #ifdef IFF_BROADCAST
3612 { IFF_BROADCAST, "broadcast" },
3613 #endif
3614 #ifdef IFF_DEBUG
3615 { IFF_DEBUG, "debug" },
3616 #endif
3617 #ifdef IFF_LOOPBACK
3618 { IFF_LOOPBACK, "loopback" },
3619 #endif
3620 #ifdef IFF_POINTOPOINT
3621 { IFF_POINTOPOINT, "pointopoint" },
3622 #endif
3623 #ifdef IFF_RUNNING
3624 { IFF_RUNNING, "running" },
3625 #endif
3626 #ifdef IFF_NOARP
3627 { IFF_NOARP, "noarp" },
3628 #endif
3629 #ifdef IFF_PROMISC
3630 { IFF_PROMISC, "promisc" },
3631 #endif
3632 #ifdef IFF_NOTRAILERS
3633 #ifdef NS_IMPL_COCOA
3634 /* Really means smart, notrailers is obsolete */
3635 { IFF_NOTRAILERS, "smart" },
3636 #else
3637 { IFF_NOTRAILERS, "notrailers" },
3638 #endif
3639 #endif
3640 #ifdef IFF_ALLMULTI
3641 { IFF_ALLMULTI, "allmulti" },
3642 #endif
3643 #ifdef IFF_MASTER
3644 { IFF_MASTER, "master" },
3645 #endif
3646 #ifdef IFF_SLAVE
3647 { IFF_SLAVE, "slave" },
3648 #endif
3649 #ifdef IFF_MULTICAST
3650 { IFF_MULTICAST, "multicast" },
3651 #endif
3652 #ifdef IFF_PORTSEL
3653 { IFF_PORTSEL, "portsel" },
3654 #endif
3655 #ifdef IFF_AUTOMEDIA
3656 { IFF_AUTOMEDIA, "automedia" },
3657 #endif
3658 #ifdef IFF_DYNAMIC
3659 { IFF_DYNAMIC, "dynamic" },
3660 #endif
3661 #ifdef IFF_OACTIVE
3662 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3663 #endif
3664 #ifdef IFF_SIMPLEX
3665 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3666 #endif
3667 #ifdef IFF_LINK0
3668 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3669 #endif
3670 #ifdef IFF_LINK1
3671 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3672 #endif
3673 #ifdef IFF_LINK2
3674 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3675 #endif
3676 { 0, 0 }
3679 static Lisp_Object
3680 network_interface_info (Lisp_Object ifname)
3682 struct ifreq rq;
3683 Lisp_Object res = Qnil;
3684 Lisp_Object elt;
3685 int s;
3686 bool any = 0;
3687 ptrdiff_t count;
3688 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3689 && defined HAVE_GETIFADDRS && defined LLADDR)
3690 struct ifaddrs *ifap;
3691 #endif
3693 CHECK_STRING (ifname);
3695 if (sizeof rq.ifr_name <= SBYTES (ifname))
3696 error ("interface name too long");
3697 strcpy (rq.ifr_name, SSDATA (ifname));
3699 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3700 if (s < 0)
3701 return Qnil;
3702 count = SPECPDL_INDEX ();
3703 record_unwind_protect_int (close_file_unwind, s);
3705 elt = Qnil;
3706 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3707 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3709 int flags = rq.ifr_flags;
3710 const struct ifflag_def *fp;
3711 int fnum;
3713 /* If flags is smaller than int (i.e. short) it may have the high bit set
3714 due to IFF_MULTICAST. In that case, sign extending it into
3715 an int is wrong. */
3716 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3717 flags = (unsigned short) rq.ifr_flags;
3719 any = 1;
3720 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3722 if (flags & fp->flag_bit)
3724 elt = Fcons (intern (fp->flag_sym), elt);
3725 flags -= fp->flag_bit;
3728 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3730 if (flags & 1)
3732 elt = Fcons (make_number (fnum), elt);
3736 #endif
3737 res = Fcons (elt, res);
3739 elt = Qnil;
3740 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3741 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3743 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3744 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3745 int n;
3747 any = 1;
3748 for (n = 0; n < 6; n++)
3749 p->contents[n] = make_number (((unsigned char *)
3750 &rq.ifr_hwaddr.sa_data[0])
3751 [n]);
3752 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3754 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3755 if (getifaddrs (&ifap) != -1)
3757 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3758 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3759 struct ifaddrs *it;
3761 for (it = ifap; it != NULL; it = it->ifa_next)
3763 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3764 unsigned char linkaddr[6];
3765 int n;
3767 if (it->ifa_addr->sa_family != AF_LINK
3768 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3769 || sdl->sdl_alen != 6)
3770 continue;
3772 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3773 for (n = 0; n < 6; n++)
3774 p->contents[n] = make_number (linkaddr[n]);
3776 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
3777 break;
3780 #ifdef HAVE_FREEIFADDRS
3781 freeifaddrs (ifap);
3782 #endif
3784 #endif /* HAVE_GETIFADDRS && LLADDR */
3786 res = Fcons (elt, res);
3788 elt = Qnil;
3789 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3790 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3792 any = 1;
3793 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3794 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3795 #else
3796 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3797 #endif
3799 #endif
3800 res = Fcons (elt, res);
3802 elt = Qnil;
3803 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3804 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3806 any = 1;
3807 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3809 #endif
3810 res = Fcons (elt, res);
3812 elt = Qnil;
3813 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3814 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3816 any = 1;
3817 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3819 #endif
3820 res = Fcons (elt, res);
3822 return unbind_to (count, any ? res : Qnil);
3824 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
3825 #endif /* defined (HAVE_NET_IF_H) */
3827 DEFUN ("network-interface-list", Fnetwork_interface_list,
3828 Snetwork_interface_list, 0, 0, 0,
3829 doc: /* Return an alist of all network interfaces and their network address.
3830 Each element is a cons, the car of which is a string containing the
3831 interface name, and the cdr is the network address in internal
3832 format; see the description of ADDRESS in `make-network-process'.
3834 If the information is not available, return nil. */)
3835 (void)
3837 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
3838 return network_interface_list ();
3839 #else
3840 return Qnil;
3841 #endif
3844 DEFUN ("network-interface-info", Fnetwork_interface_info,
3845 Snetwork_interface_info, 1, 1, 0,
3846 doc: /* Return information about network interface named IFNAME.
3847 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3848 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3849 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3850 FLAGS is the current flags of the interface.
3852 Data that is unavailable is returned as nil. */)
3853 (Lisp_Object ifname)
3855 #if ((defined HAVE_NET_IF_H \
3856 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
3857 || defined SIOCGIFFLAGS)) \
3858 || defined WINDOWSNT)
3859 return network_interface_info (ifname);
3860 #else
3861 return Qnil;
3862 #endif
3866 /* Turn off input and output for process PROC. */
3868 static void
3869 deactivate_process (Lisp_Object proc)
3871 int inchannel;
3872 struct Lisp_Process *p = XPROCESS (proc);
3873 int i;
3875 #ifdef HAVE_GNUTLS
3876 /* Delete GnuTLS structures in PROC, if any. */
3877 emacs_gnutls_deinit (proc);
3878 #endif /* HAVE_GNUTLS */
3880 #ifdef ADAPTIVE_READ_BUFFERING
3881 if (p->read_output_delay > 0)
3883 if (--process_output_delay_count < 0)
3884 process_output_delay_count = 0;
3885 p->read_output_delay = 0;
3886 p->read_output_skip = 0;
3888 #endif
3890 /* Beware SIGCHLD hereabouts. */
3892 for (i = 0; i < PROCESS_OPEN_FDS; i++)
3893 close_process_fd (&p->open_fd[i]);
3895 inchannel = p->infd;
3896 if (inchannel >= 0)
3898 p->infd = -1;
3899 p->outfd = -1;
3900 #ifdef DATAGRAM_SOCKETS
3901 if (DATAGRAM_CHAN_P (inchannel))
3903 xfree (datagram_address[inchannel].sa);
3904 datagram_address[inchannel].sa = 0;
3905 datagram_address[inchannel].len = 0;
3907 #endif
3908 chan_process[inchannel] = Qnil;
3909 FD_CLR (inchannel, &input_wait_mask);
3910 FD_CLR (inchannel, &non_keyboard_wait_mask);
3911 #ifdef NON_BLOCKING_CONNECT
3912 if (FD_ISSET (inchannel, &connect_wait_mask))
3914 FD_CLR (inchannel, &connect_wait_mask);
3915 FD_CLR (inchannel, &write_mask);
3916 if (--num_pending_connects < 0)
3917 emacs_abort ();
3919 #endif
3920 if (inchannel == max_process_desc)
3922 /* We just closed the highest-numbered process input descriptor,
3923 so recompute the highest-numbered one now. */
3924 int i = inchannel;
3926 i--;
3927 while (0 <= i && NILP (chan_process[i]));
3929 max_process_desc = i;
3935 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3936 0, 4, 0,
3937 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3938 It is given to their filter functions.
3939 Non-nil arg PROCESS means do not return until some output has been received
3940 from PROCESS.
3942 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
3943 and milliseconds to wait; return after that much time whether or not
3944 there is any subprocess output. If SECONDS is a floating point number,
3945 it specifies a fractional number of seconds to wait.
3946 The MILLISEC argument is obsolete and should be avoided.
3948 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
3949 from PROCESS, suspending reading output from other processes.
3950 If JUST-THIS-ONE is an integer, don't run any timers either.
3951 Return non-nil if we received any output before the timeout expired. */)
3952 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
3954 intmax_t secs;
3955 int nsecs;
3957 if (! NILP (process))
3958 CHECK_PROCESS (process);
3959 else
3960 just_this_one = Qnil;
3962 if (!NILP (millisec))
3963 { /* Obsolete calling convention using integers rather than floats. */
3964 CHECK_NUMBER (millisec);
3965 if (NILP (seconds))
3966 seconds = make_float (XINT (millisec) / 1000.0);
3967 else
3969 CHECK_NUMBER (seconds);
3970 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
3974 secs = 0;
3975 nsecs = -1;
3977 if (!NILP (seconds))
3979 if (INTEGERP (seconds))
3981 if (XINT (seconds) > 0)
3983 secs = XINT (seconds);
3984 nsecs = 0;
3987 else if (FLOATP (seconds))
3989 if (XFLOAT_DATA (seconds) > 0)
3991 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
3992 secs = min (t.tv_sec, WAIT_READING_MAX);
3993 nsecs = t.tv_nsec;
3996 else
3997 wrong_type_argument (Qnumberp, seconds);
3999 else if (! NILP (process))
4000 nsecs = 0;
4002 return
4003 (wait_reading_process_output (secs, nsecs, 0, 0,
4004 Qnil,
4005 !NILP (process) ? XPROCESS (process) : NULL,
4006 NILP (just_this_one) ? 0 :
4007 !INTEGERP (just_this_one) ? 1 : -1)
4008 ? Qt : Qnil);
4011 /* Accept a connection for server process SERVER on CHANNEL. */
4013 static EMACS_INT connect_counter = 0;
4015 static void
4016 server_accept_connection (Lisp_Object server, int channel)
4018 Lisp_Object proc, caller, name, buffer;
4019 Lisp_Object contact, host, service;
4020 struct Lisp_Process *ps= XPROCESS (server);
4021 struct Lisp_Process *p;
4022 int s;
4023 union u_sockaddr {
4024 struct sockaddr sa;
4025 struct sockaddr_in in;
4026 #ifdef AF_INET6
4027 struct sockaddr_in6 in6;
4028 #endif
4029 #ifdef HAVE_LOCAL_SOCKETS
4030 struct sockaddr_un un;
4031 #endif
4032 } saddr;
4033 socklen_t len = sizeof saddr;
4034 ptrdiff_t count;
4036 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4038 if (s < 0)
4040 int code = errno;
4042 if (code == EAGAIN)
4043 return;
4044 #ifdef EWOULDBLOCK
4045 if (code == EWOULDBLOCK)
4046 return;
4047 #endif
4049 if (!NILP (ps->log))
4050 call3 (ps->log, server, Qnil,
4051 concat3 (build_string ("accept failed with code"),
4052 Fnumber_to_string (make_number (code)),
4053 build_string ("\n")));
4054 return;
4057 count = SPECPDL_INDEX ();
4058 record_unwind_protect_int (close_file_unwind, s);
4060 connect_counter++;
4062 /* Setup a new process to handle the connection. */
4064 /* Generate a unique identification of the caller, and build contact
4065 information for this process. */
4066 host = Qt;
4067 service = Qnil;
4068 switch (saddr.sa.sa_family)
4070 case AF_INET:
4072 Lisp_Object args[5];
4073 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4074 args[0] = build_string ("%d.%d.%d.%d");
4075 args[1] = make_number (*ip++);
4076 args[2] = make_number (*ip++);
4077 args[3] = make_number (*ip++);
4078 args[4] = make_number (*ip++);
4079 host = Fformat (5, args);
4080 service = make_number (ntohs (saddr.in.sin_port));
4082 args[0] = build_string (" <%s:%d>");
4083 args[1] = host;
4084 args[2] = service;
4085 caller = Fformat (3, args);
4087 break;
4089 #ifdef AF_INET6
4090 case AF_INET6:
4092 Lisp_Object args[9];
4093 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4094 int i;
4095 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4096 for (i = 0; i < 8; i++)
4097 args[i+1] = make_number (ntohs (ip6[i]));
4098 host = Fformat (9, args);
4099 service = make_number (ntohs (saddr.in.sin_port));
4101 args[0] = build_string (" <[%s]:%d>");
4102 args[1] = host;
4103 args[2] = service;
4104 caller = Fformat (3, args);
4106 break;
4107 #endif
4109 #ifdef HAVE_LOCAL_SOCKETS
4110 case AF_LOCAL:
4111 #endif
4112 default:
4113 caller = Fnumber_to_string (make_number (connect_counter));
4114 caller = concat3 (build_string (" <"), caller, build_string (">"));
4115 break;
4118 /* Create a new buffer name for this process if it doesn't have a
4119 filter. The new buffer name is based on the buffer name or
4120 process name of the server process concatenated with the caller
4121 identification. */
4123 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4124 || EQ (ps->filter, Qt)))
4125 buffer = Qnil;
4126 else
4128 buffer = ps->buffer;
4129 if (!NILP (buffer))
4130 buffer = Fbuffer_name (buffer);
4131 else
4132 buffer = ps->name;
4133 if (!NILP (buffer))
4135 buffer = concat2 (buffer, caller);
4136 buffer = Fget_buffer_create (buffer);
4140 /* Generate a unique name for the new server process. Combine the
4141 server process name with the caller identification. */
4143 name = concat2 (ps->name, caller);
4144 proc = make_process (name);
4146 chan_process[s] = proc;
4148 fcntl (s, F_SETFL, O_NONBLOCK);
4150 p = XPROCESS (proc);
4152 /* Build new contact information for this setup. */
4153 contact = Fcopy_sequence (ps->childp);
4154 contact = Fplist_put (contact, QCserver, Qnil);
4155 contact = Fplist_put (contact, QChost, host);
4156 if (!NILP (service))
4157 contact = Fplist_put (contact, QCservice, service);
4158 contact = Fplist_put (contact, QCremote,
4159 conv_sockaddr_to_lisp (&saddr.sa, len));
4160 #ifdef HAVE_GETSOCKNAME
4161 len = sizeof saddr;
4162 if (getsockname (s, &saddr.sa, &len) == 0)
4163 contact = Fplist_put (contact, QClocal,
4164 conv_sockaddr_to_lisp (&saddr.sa, len));
4165 #endif
4167 pset_childp (p, contact);
4168 pset_plist (p, Fcopy_sequence (ps->plist));
4169 pset_type (p, Qnetwork);
4171 pset_buffer (p, buffer);
4172 pset_sentinel (p, ps->sentinel);
4173 pset_filter (p, ps->filter);
4174 pset_command (p, Qnil);
4175 p->pid = 0;
4177 /* Discard the unwind protect for closing S. */
4178 specpdl_ptr = specpdl + count;
4180 p->open_fd[SUBPROCESS_STDIN] = s;
4181 p->infd = s;
4182 p->outfd = s;
4183 pset_status (p, Qrun);
4185 /* Client processes for accepted connections are not stopped initially. */
4186 if (!EQ (p->filter, Qt))
4188 FD_SET (s, &input_wait_mask);
4189 FD_SET (s, &non_keyboard_wait_mask);
4192 if (s > max_process_desc)
4193 max_process_desc = s;
4195 /* Setup coding system for new process based on server process.
4196 This seems to be the proper thing to do, as the coding system
4197 of the new process should reflect the settings at the time the
4198 server socket was opened; not the current settings. */
4200 pset_decode_coding_system (p, ps->decode_coding_system);
4201 pset_encode_coding_system (p, ps->encode_coding_system);
4202 setup_process_coding_systems (proc);
4204 pset_decoding_buf (p, empty_unibyte_string);
4205 p->decoding_carryover = 0;
4206 pset_encoding_buf (p, empty_unibyte_string);
4208 p->inherit_coding_system_flag
4209 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4211 if (!NILP (ps->log))
4212 call3 (ps->log, server, proc,
4213 concat3 (build_string ("accept from "),
4214 (STRINGP (host) ? host : build_string ("-")),
4215 build_string ("\n")));
4217 exec_sentinel (proc,
4218 concat3 (build_string ("open from "),
4219 (STRINGP (host) ? host : build_string ("-")),
4220 build_string ("\n")));
4223 /* This variable is different from waiting_for_input in keyboard.c.
4224 It is used to communicate to a lisp process-filter/sentinel (via the
4225 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4226 for user-input when that process-filter was called.
4227 waiting_for_input cannot be used as that is by definition 0 when
4228 lisp code is being evalled.
4229 This is also used in record_asynch_buffer_change.
4230 For that purpose, this must be 0
4231 when not inside wait_reading_process_output. */
4232 static int waiting_for_user_input_p;
4234 static void
4235 wait_reading_process_output_unwind (int data)
4237 waiting_for_user_input_p = data;
4240 /* This is here so breakpoints can be put on it. */
4241 static void
4242 wait_reading_process_output_1 (void)
4246 /* Read and dispose of subprocess output while waiting for timeout to
4247 elapse and/or keyboard input to be available.
4249 TIME_LIMIT is:
4250 timeout in seconds
4251 If negative, gobble data immediately available but don't wait for any.
4253 NSECS is:
4254 an additional duration to wait, measured in nanoseconds
4255 If TIME_LIMIT is zero, then:
4256 If NSECS == 0, there is no limit.
4257 If NSECS > 0, the timeout consists of NSECS only.
4258 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4260 READ_KBD is:
4261 0 to ignore keyboard input, or
4262 1 to return when input is available, or
4263 -1 meaning caller will actually read the input, so don't throw to
4264 the quit handler, or
4266 DO_DISPLAY means redisplay should be done to show subprocess
4267 output that arrives.
4269 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4270 (and gobble terminal input into the buffer if any arrives).
4272 If WAIT_PROC is specified, wait until something arrives from that
4273 process. The return value is true if we read some input from
4274 that process.
4276 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4277 (suspending output from other processes). A negative value
4278 means don't run any timers either.
4280 If WAIT_PROC is specified, then the function returns true if we
4281 received input from that process before the timeout elapsed.
4282 Otherwise, return true if we received input from any process. */
4284 bool
4285 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4286 bool do_display,
4287 Lisp_Object wait_for_cell,
4288 struct Lisp_Process *wait_proc, int just_wait_proc)
4290 int channel, nfds;
4291 fd_set Available;
4292 fd_set Writeok;
4293 bool check_write;
4294 int check_delay;
4295 bool no_avail;
4296 int xerrno;
4297 Lisp_Object proc;
4298 struct timespec timeout, end_time;
4299 int wait_channel = -1;
4300 bool got_some_input = 0;
4301 ptrdiff_t count = SPECPDL_INDEX ();
4303 FD_ZERO (&Available);
4304 FD_ZERO (&Writeok);
4306 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4307 && !(CONSP (wait_proc->status)
4308 && EQ (XCAR (wait_proc->status), Qexit)))
4309 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4311 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4312 if (wait_proc != NULL)
4313 wait_channel = wait_proc->infd;
4315 record_unwind_protect_int (wait_reading_process_output_unwind,
4316 waiting_for_user_input_p);
4317 waiting_for_user_input_p = read_kbd;
4319 if (time_limit < 0)
4321 time_limit = 0;
4322 nsecs = -1;
4324 else if (TYPE_MAXIMUM (time_t) < time_limit)
4325 time_limit = TYPE_MAXIMUM (time_t);
4327 /* Since we may need to wait several times,
4328 compute the absolute time to return at. */
4329 if (time_limit || nsecs > 0)
4331 timeout = make_timespec (time_limit, nsecs);
4332 end_time = timespec_add (current_timespec (), timeout);
4335 while (1)
4337 bool timeout_reduced_for_timers = 0;
4339 /* If calling from keyboard input, do not quit
4340 since we want to return C-g as an input character.
4341 Otherwise, do pending quit if requested. */
4342 if (read_kbd >= 0)
4343 QUIT;
4344 else if (pending_signals)
4345 process_pending_signals ();
4347 /* Exit now if the cell we're waiting for became non-nil. */
4348 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4349 break;
4351 /* Compute time from now till when time limit is up. */
4352 /* Exit if already run out. */
4353 if (nsecs < 0)
4355 /* A negative timeout means
4356 gobble output available now
4357 but don't wait at all. */
4359 timeout = make_timespec (0, 0);
4361 else if (time_limit || nsecs > 0)
4363 struct timespec now = current_timespec ();
4364 if (timespec_cmp (end_time, now) <= 0)
4365 break;
4366 timeout = timespec_sub (end_time, now);
4368 else
4370 timeout = make_timespec (100000, 0);
4373 /* Normally we run timers here.
4374 But not if wait_for_cell; in those cases,
4375 the wait is supposed to be short,
4376 and those callers cannot handle running arbitrary Lisp code here. */
4377 if (NILP (wait_for_cell)
4378 && just_wait_proc >= 0)
4380 struct timespec timer_delay;
4384 unsigned old_timers_run = timers_run;
4385 struct buffer *old_buffer = current_buffer;
4386 Lisp_Object old_window = selected_window;
4388 timer_delay = timer_check ();
4390 /* If a timer has run, this might have changed buffers
4391 an alike. Make read_key_sequence aware of that. */
4392 if (timers_run != old_timers_run
4393 && (old_buffer != current_buffer
4394 || !EQ (old_window, selected_window))
4395 && waiting_for_user_input_p == -1)
4396 record_asynch_buffer_change ();
4398 if (timers_run != old_timers_run && do_display)
4399 /* We must retry, since a timer may have requeued itself
4400 and that could alter the time_delay. */
4401 redisplay_preserve_echo_area (9);
4402 else
4403 break;
4405 while (!detect_input_pending ());
4407 /* If there is unread keyboard input, also return. */
4408 if (read_kbd != 0
4409 && requeued_events_pending_p ())
4410 break;
4412 /* A negative timeout means do not wait at all. */
4413 if (nsecs >= 0)
4415 if (timespec_valid_p (timer_delay))
4417 if (timespec_cmp (timer_delay, timeout) < 0)
4419 timeout = timer_delay;
4420 timeout_reduced_for_timers = 1;
4423 else
4425 /* This is so a breakpoint can be put here. */
4426 wait_reading_process_output_1 ();
4431 /* Cause C-g and alarm signals to take immediate action,
4432 and cause input available signals to zero out timeout.
4434 It is important that we do this before checking for process
4435 activity. If we get a SIGCHLD after the explicit checks for
4436 process activity, timeout is the only way we will know. */
4437 if (read_kbd < 0)
4438 set_waiting_for_input (&timeout);
4440 /* If status of something has changed, and no input is
4441 available, notify the user of the change right away. After
4442 this explicit check, we'll let the SIGCHLD handler zap
4443 timeout to get our attention. */
4444 if (update_tick != process_tick)
4446 fd_set Atemp;
4447 fd_set Ctemp;
4449 if (kbd_on_hold_p ())
4450 FD_ZERO (&Atemp);
4451 else
4452 Atemp = input_wait_mask;
4453 Ctemp = write_mask;
4455 timeout = make_timespec (0, 0);
4456 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4457 &Atemp,
4458 #ifdef NON_BLOCKING_CONNECT
4459 (num_pending_connects > 0 ? &Ctemp : NULL),
4460 #else
4461 NULL,
4462 #endif
4463 NULL, &timeout, NULL)
4464 <= 0))
4466 /* It's okay for us to do this and then continue with
4467 the loop, since timeout has already been zeroed out. */
4468 clear_waiting_for_input ();
4469 status_notify (NULL);
4470 if (do_display) redisplay_preserve_echo_area (13);
4474 /* Don't wait for output from a non-running process. Just
4475 read whatever data has already been received. */
4476 if (wait_proc && wait_proc->raw_status_new)
4477 update_status (wait_proc);
4478 if (wait_proc
4479 && ! EQ (wait_proc->status, Qrun)
4480 && ! EQ (wait_proc->status, Qconnect))
4482 bool read_some_bytes = 0;
4484 clear_waiting_for_input ();
4485 XSETPROCESS (proc, wait_proc);
4487 /* Read data from the process, until we exhaust it. */
4488 while (wait_proc->infd >= 0)
4490 int nread = read_process_output (proc, wait_proc->infd);
4492 if (nread == 0)
4493 break;
4495 if (nread > 0)
4496 got_some_input = read_some_bytes = 1;
4497 else if (nread == -1 && (errno == EIO || errno == EAGAIN))
4498 break;
4499 #ifdef EWOULDBLOCK
4500 else if (nread == -1 && EWOULDBLOCK == errno)
4501 break;
4502 #endif
4504 if (read_some_bytes && do_display)
4505 redisplay_preserve_echo_area (10);
4507 break;
4510 /* Wait till there is something to do */
4512 if (wait_proc && just_wait_proc)
4514 if (wait_proc->infd < 0) /* Terminated */
4515 break;
4516 FD_SET (wait_proc->infd, &Available);
4517 check_delay = 0;
4518 check_write = 0;
4520 else if (!NILP (wait_for_cell))
4522 Available = non_process_wait_mask;
4523 check_delay = 0;
4524 check_write = 0;
4526 else
4528 if (! read_kbd)
4529 Available = non_keyboard_wait_mask;
4530 else
4531 Available = input_wait_mask;
4532 Writeok = write_mask;
4533 #ifdef SELECT_CANT_DO_WRITE_MASK
4534 check_write = 0;
4535 #else
4536 check_write = 1;
4537 #endif
4538 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4541 /* If frame size has changed or the window is newly mapped,
4542 redisplay now, before we start to wait. There is a race
4543 condition here; if a SIGIO arrives between now and the select
4544 and indicates that a frame is trashed, the select may block
4545 displaying a trashed screen. */
4546 if (frame_garbaged && do_display)
4548 clear_waiting_for_input ();
4549 redisplay_preserve_echo_area (11);
4550 if (read_kbd < 0)
4551 set_waiting_for_input (&timeout);
4554 /* Skip the `select' call if input is available and we're
4555 waiting for keyboard input or a cell change (which can be
4556 triggered by processing X events). In the latter case, set
4557 nfds to 1 to avoid breaking the loop. */
4558 no_avail = 0;
4559 if ((read_kbd || !NILP (wait_for_cell))
4560 && detect_input_pending ())
4562 nfds = read_kbd ? 0 : 1;
4563 no_avail = 1;
4566 if (!no_avail)
4569 #ifdef ADAPTIVE_READ_BUFFERING
4570 /* Set the timeout for adaptive read buffering if any
4571 process has non-zero read_output_skip and non-zero
4572 read_output_delay, and we are not reading output for a
4573 specific wait_channel. It is not executed if
4574 Vprocess_adaptive_read_buffering is nil. */
4575 if (process_output_skip && check_delay > 0)
4577 int nsecs = timeout.tv_nsec;
4578 if (timeout.tv_sec > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4579 nsecs = READ_OUTPUT_DELAY_MAX;
4580 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4582 proc = chan_process[channel];
4583 if (NILP (proc))
4584 continue;
4585 /* Find minimum non-zero read_output_delay among the
4586 processes with non-zero read_output_skip. */
4587 if (XPROCESS (proc)->read_output_delay > 0)
4589 check_delay--;
4590 if (!XPROCESS (proc)->read_output_skip)
4591 continue;
4592 FD_CLR (channel, &Available);
4593 XPROCESS (proc)->read_output_skip = 0;
4594 if (XPROCESS (proc)->read_output_delay < nsecs)
4595 nsecs = XPROCESS (proc)->read_output_delay;
4598 timeout = make_timespec (0, nsecs);
4599 process_output_skip = 0;
4601 #endif
4603 #if defined (HAVE_NS)
4604 nfds = ns_select
4605 #elif defined (HAVE_GLIB)
4606 nfds = xg_select
4607 #else
4608 nfds = pselect
4609 #endif
4610 (max (max_process_desc, max_input_desc) + 1,
4611 &Available,
4612 (check_write ? &Writeok : 0),
4613 NULL, &timeout, NULL);
4615 #ifdef HAVE_GNUTLS
4616 /* GnuTLS buffers data internally. In lowat mode it leaves
4617 some data in the TCP buffers so that select works, but
4618 with custom pull/push functions we need to check if some
4619 data is available in the buffers manually. */
4620 if (nfds == 0)
4622 if (! wait_proc)
4624 /* We're not waiting on a specific process, so loop
4625 through all the channels and check for data.
4626 This is a workaround needed for some versions of
4627 the gnutls library -- 2.12.14 has been confirmed
4628 to need it. See
4629 http://comments.gmane.org/gmane.emacs.devel/145074 */
4630 for (channel = 0; channel < FD_SETSIZE; ++channel)
4631 if (! NILP (chan_process[channel]))
4633 struct Lisp_Process *p =
4634 XPROCESS (chan_process[channel]);
4635 if (p && p->gnutls_p && p->gnutls_state && p->infd
4636 && ((emacs_gnutls_record_check_pending
4637 (p->gnutls_state))
4638 > 0))
4640 nfds++;
4641 FD_SET (p->infd, &Available);
4645 else
4647 /* Check this specific channel. */
4648 if (wait_proc->gnutls_p /* Check for valid process. */
4649 && wait_proc->gnutls_state
4650 /* Do we have pending data? */
4651 && ((emacs_gnutls_record_check_pending
4652 (wait_proc->gnutls_state))
4653 > 0))
4655 nfds = 1;
4656 /* Set to Available. */
4657 FD_SET (wait_proc->infd, &Available);
4661 #endif
4664 xerrno = errno;
4666 /* Make C-g and alarm signals set flags again */
4667 clear_waiting_for_input ();
4669 /* If we woke up due to SIGWINCH, actually change size now. */
4670 do_pending_window_change (0);
4672 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4673 /* We waited the full specified time, so return now. */
4674 break;
4675 if (nfds < 0)
4677 if (xerrno == EINTR)
4678 no_avail = 1;
4679 else if (xerrno == EBADF)
4680 emacs_abort ();
4681 else
4682 report_file_errno ("Failed select", Qnil, xerrno);
4685 if (no_avail)
4687 FD_ZERO (&Available);
4688 check_write = 0;
4691 /* Check for keyboard input */
4692 /* If there is any, return immediately
4693 to give it higher priority than subprocesses */
4695 if (read_kbd != 0)
4697 unsigned old_timers_run = timers_run;
4698 struct buffer *old_buffer = current_buffer;
4699 Lisp_Object old_window = selected_window;
4700 bool leave = 0;
4702 if (detect_input_pending_run_timers (do_display))
4704 swallow_events (do_display);
4705 if (detect_input_pending_run_timers (do_display))
4706 leave = 1;
4709 /* If a timer has run, this might have changed buffers
4710 an alike. Make read_key_sequence aware of that. */
4711 if (timers_run != old_timers_run
4712 && waiting_for_user_input_p == -1
4713 && (old_buffer != current_buffer
4714 || !EQ (old_window, selected_window)))
4715 record_asynch_buffer_change ();
4717 if (leave)
4718 break;
4721 /* If there is unread keyboard input, also return. */
4722 if (read_kbd != 0
4723 && requeued_events_pending_p ())
4724 break;
4726 /* If we are not checking for keyboard input now,
4727 do process events (but don't run any timers).
4728 This is so that X events will be processed.
4729 Otherwise they may have to wait until polling takes place.
4730 That would causes delays in pasting selections, for example.
4732 (We used to do this only if wait_for_cell.) */
4733 if (read_kbd == 0 && detect_input_pending ())
4735 swallow_events (do_display);
4736 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4737 if (detect_input_pending ())
4738 break;
4739 #endif
4742 /* Exit now if the cell we're waiting for became non-nil. */
4743 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4744 break;
4746 #ifdef USABLE_SIGIO
4747 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4748 go read it. This can happen with X on BSD after logging out.
4749 In that case, there really is no input and no SIGIO,
4750 but select says there is input. */
4752 if (read_kbd && interrupt_input
4753 && keyboard_bit_set (&Available) && ! noninteractive)
4754 handle_input_available_signal (SIGIO);
4755 #endif
4757 if (! wait_proc)
4758 got_some_input |= nfds > 0;
4760 /* If checking input just got us a size-change event from X,
4761 obey it now if we should. */
4762 if (read_kbd || ! NILP (wait_for_cell))
4763 do_pending_window_change (0);
4765 /* Check for data from a process. */
4766 if (no_avail || nfds == 0)
4767 continue;
4769 for (channel = 0; channel <= max_input_desc; ++channel)
4771 struct fd_callback_data *d = &fd_callback_info[channel];
4772 if (d->func
4773 && ((d->condition & FOR_READ
4774 && FD_ISSET (channel, &Available))
4775 || (d->condition & FOR_WRITE
4776 && FD_ISSET (channel, &write_mask))))
4777 d->func (channel, d->data);
4780 for (channel = 0; channel <= max_process_desc; channel++)
4782 if (FD_ISSET (channel, &Available)
4783 && FD_ISSET (channel, &non_keyboard_wait_mask)
4784 && !FD_ISSET (channel, &non_process_wait_mask))
4786 int nread;
4788 /* If waiting for this channel, arrange to return as
4789 soon as no more input to be processed. No more
4790 waiting. */
4791 if (wait_channel == channel)
4793 wait_channel = -1;
4794 nsecs = -1;
4795 got_some_input = 1;
4797 proc = chan_process[channel];
4798 if (NILP (proc))
4799 continue;
4801 /* If this is a server stream socket, accept connection. */
4802 if (EQ (XPROCESS (proc)->status, Qlisten))
4804 server_accept_connection (proc, channel);
4805 continue;
4808 /* Read data from the process, starting with our
4809 buffered-ahead character if we have one. */
4811 nread = read_process_output (proc, channel);
4812 if (nread > 0)
4814 /* Since read_process_output can run a filter,
4815 which can call accept-process-output,
4816 don't try to read from any other processes
4817 before doing the select again. */
4818 FD_ZERO (&Available);
4820 if (do_display)
4821 redisplay_preserve_echo_area (12);
4823 #ifdef EWOULDBLOCK
4824 else if (nread == -1 && errno == EWOULDBLOCK)
4826 #endif
4827 else if (nread == -1 && errno == EAGAIN)
4829 #ifdef WINDOWSNT
4830 /* FIXME: Is this special case still needed? */
4831 /* Note that we cannot distinguish between no input
4832 available now and a closed pipe.
4833 With luck, a closed pipe will be accompanied by
4834 subprocess termination and SIGCHLD. */
4835 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4837 #endif
4838 #ifdef HAVE_PTYS
4839 /* On some OSs with ptys, when the process on one end of
4840 a pty exits, the other end gets an error reading with
4841 errno = EIO instead of getting an EOF (0 bytes read).
4842 Therefore, if we get an error reading and errno =
4843 EIO, just continue, because the child process has
4844 exited and should clean itself up soon (e.g. when we
4845 get a SIGCHLD). */
4846 else if (nread == -1 && errno == EIO)
4848 struct Lisp_Process *p = XPROCESS (proc);
4850 /* Clear the descriptor now, so we only raise the
4851 signal once. */
4852 FD_CLR (channel, &input_wait_mask);
4853 FD_CLR (channel, &non_keyboard_wait_mask);
4855 if (p->pid == -2)
4857 /* If the EIO occurs on a pty, the SIGCHLD handler's
4858 waitpid call will not find the process object to
4859 delete. Do it here. */
4860 p->tick = ++process_tick;
4861 pset_status (p, Qfailed);
4864 #endif /* HAVE_PTYS */
4865 /* If we can detect process termination, don't consider the
4866 process gone just because its pipe is closed. */
4867 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4869 else
4871 /* Preserve status of processes already terminated. */
4872 XPROCESS (proc)->tick = ++process_tick;
4873 deactivate_process (proc);
4874 if (XPROCESS (proc)->raw_status_new)
4875 update_status (XPROCESS (proc));
4876 if (EQ (XPROCESS (proc)->status, Qrun))
4877 pset_status (XPROCESS (proc),
4878 list2 (Qexit, make_number (256)));
4881 #ifdef NON_BLOCKING_CONNECT
4882 if (FD_ISSET (channel, &Writeok)
4883 && FD_ISSET (channel, &connect_wait_mask))
4885 struct Lisp_Process *p;
4887 FD_CLR (channel, &connect_wait_mask);
4888 FD_CLR (channel, &write_mask);
4889 if (--num_pending_connects < 0)
4890 emacs_abort ();
4892 proc = chan_process[channel];
4893 if (NILP (proc))
4894 continue;
4896 p = XPROCESS (proc);
4898 #ifdef GNU_LINUX
4899 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4900 So only use it on systems where it is known to work. */
4902 socklen_t xlen = sizeof (xerrno);
4903 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4904 xerrno = errno;
4906 #else
4908 struct sockaddr pname;
4909 socklen_t pnamelen = sizeof (pname);
4911 /* If connection failed, getpeername will fail. */
4912 xerrno = 0;
4913 if (getpeername (channel, &pname, &pnamelen) < 0)
4915 /* Obtain connect failure code through error slippage. */
4916 char dummy;
4917 xerrno = errno;
4918 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
4919 xerrno = errno;
4922 #endif
4923 if (xerrno)
4925 p->tick = ++process_tick;
4926 pset_status (p, list2 (Qfailed, make_number (xerrno)));
4927 deactivate_process (proc);
4929 else
4931 pset_status (p, Qrun);
4932 /* Execute the sentinel here. If we had relied on
4933 status_notify to do it later, it will read input
4934 from the process before calling the sentinel. */
4935 exec_sentinel (proc, build_string ("open\n"));
4936 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
4938 FD_SET (p->infd, &input_wait_mask);
4939 FD_SET (p->infd, &non_keyboard_wait_mask);
4943 #endif /* NON_BLOCKING_CONNECT */
4944 } /* End for each file descriptor. */
4945 } /* End while exit conditions not met. */
4947 unbind_to (count, Qnil);
4949 /* If calling from keyboard input, do not quit
4950 since we want to return C-g as an input character.
4951 Otherwise, do pending quit if requested. */
4952 if (read_kbd >= 0)
4954 /* Prevent input_pending from remaining set if we quit. */
4955 clear_input_pending ();
4956 QUIT;
4959 return got_some_input;
4962 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4964 static Lisp_Object
4965 read_process_output_call (Lisp_Object fun_and_args)
4967 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4970 static Lisp_Object
4971 read_process_output_error_handler (Lisp_Object error_val)
4973 cmd_error_internal (error_val, "error in process filter: ");
4974 Vinhibit_quit = Qt;
4975 update_echo_area ();
4976 Fsleep_for (make_number (2), Qnil);
4977 return Qt;
4980 static void
4981 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
4982 ssize_t nbytes,
4983 struct coding_system *coding);
4985 /* Read pending output from the process channel,
4986 starting with our buffered-ahead character if we have one.
4987 Yield number of decoded characters read.
4989 This function reads at most 4096 characters.
4990 If you want to read all available subprocess output,
4991 you must call it repeatedly until it returns zero.
4993 The characters read are decoded according to PROC's coding-system
4994 for decoding. */
4996 static int
4997 read_process_output (Lisp_Object proc, register int channel)
4999 register ssize_t nbytes;
5000 char *chars;
5001 register struct Lisp_Process *p = XPROCESS (proc);
5002 struct coding_system *coding = proc_decode_coding_system[channel];
5003 int carryover = p->decoding_carryover;
5004 int readmax = 4096;
5005 ptrdiff_t count = SPECPDL_INDEX ();
5006 Lisp_Object odeactivate;
5008 chars = alloca (carryover + readmax);
5009 if (carryover)
5010 /* See the comment above. */
5011 memcpy (chars, SDATA (p->decoding_buf), carryover);
5013 #ifdef DATAGRAM_SOCKETS
5014 /* We have a working select, so proc_buffered_char is always -1. */
5015 if (DATAGRAM_CHAN_P (channel))
5017 socklen_t len = datagram_address[channel].len;
5018 nbytes = recvfrom (channel, chars + carryover, readmax,
5019 0, datagram_address[channel].sa, &len);
5021 else
5022 #endif
5024 bool buffered = proc_buffered_char[channel] >= 0;
5025 if (buffered)
5027 chars[carryover] = proc_buffered_char[channel];
5028 proc_buffered_char[channel] = -1;
5030 #ifdef HAVE_GNUTLS
5031 if (p->gnutls_p && p->gnutls_state)
5032 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5033 readmax - buffered);
5034 else
5035 #endif
5036 nbytes = emacs_read (channel, chars + carryover + buffered,
5037 readmax - buffered);
5038 #ifdef ADAPTIVE_READ_BUFFERING
5039 if (nbytes > 0 && p->adaptive_read_buffering)
5041 int delay = p->read_output_delay;
5042 if (nbytes < 256)
5044 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5046 if (delay == 0)
5047 process_output_delay_count++;
5048 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5051 else if (delay > 0 && nbytes == readmax - buffered)
5053 delay -= READ_OUTPUT_DELAY_INCREMENT;
5054 if (delay == 0)
5055 process_output_delay_count--;
5057 p->read_output_delay = delay;
5058 if (delay)
5060 p->read_output_skip = 1;
5061 process_output_skip = 1;
5064 #endif
5065 nbytes += buffered;
5066 nbytes += buffered && nbytes <= 0;
5069 p->decoding_carryover = 0;
5071 /* At this point, NBYTES holds number of bytes just received
5072 (including the one in proc_buffered_char[channel]). */
5073 if (nbytes <= 0)
5075 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5076 return nbytes;
5077 coding->mode |= CODING_MODE_LAST_BLOCK;
5080 /* Now set NBYTES how many bytes we must decode. */
5081 nbytes += carryover;
5083 odeactivate = Vdeactivate_mark;
5084 /* There's no good reason to let process filters change the current
5085 buffer, and many callers of accept-process-output, sit-for, and
5086 friends don't expect current-buffer to be changed from under them. */
5087 record_unwind_current_buffer ();
5089 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5091 /* Handling the process output should not deactivate the mark. */
5092 Vdeactivate_mark = odeactivate;
5094 unbind_to (count, Qnil);
5095 return nbytes;
5098 static void
5099 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5100 ssize_t nbytes,
5101 struct coding_system *coding)
5103 Lisp_Object outstream = p->filter;
5104 Lisp_Object text;
5105 bool outer_running_asynch_code = running_asynch_code;
5106 int waiting = waiting_for_user_input_p;
5108 /* No need to gcpro these, because all we do with them later
5109 is test them for EQness, and none of them should be a string. */
5110 #if 0
5111 Lisp_Object obuffer, okeymap;
5112 XSETBUFFER (obuffer, current_buffer);
5113 okeymap = BVAR (current_buffer, keymap);
5114 #endif
5116 /* We inhibit quit here instead of just catching it so that
5117 hitting ^G when a filter happens to be running won't screw
5118 it up. */
5119 specbind (Qinhibit_quit, Qt);
5120 specbind (Qlast_nonmenu_event, Qt);
5122 /* In case we get recursively called,
5123 and we already saved the match data nonrecursively,
5124 save the same match data in safely recursive fashion. */
5125 if (outer_running_asynch_code)
5127 Lisp_Object tem;
5128 /* Don't clobber the CURRENT match data, either! */
5129 tem = Fmatch_data (Qnil, Qnil, Qnil);
5130 restore_search_regs ();
5131 record_unwind_save_match_data ();
5132 Fset_match_data (tem, Qt);
5135 /* For speed, if a search happens within this code,
5136 save the match data in a special nonrecursive fashion. */
5137 running_asynch_code = 1;
5139 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5140 text = coding->dst_object;
5141 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5142 /* A new coding system might be found. */
5143 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5145 pset_decode_coding_system (p, Vlast_coding_system_used);
5147 /* Don't call setup_coding_system for
5148 proc_decode_coding_system[channel] here. It is done in
5149 detect_coding called via decode_coding above. */
5151 /* If a coding system for encoding is not yet decided, we set
5152 it as the same as coding-system for decoding.
5154 But, before doing that we must check if
5155 proc_encode_coding_system[p->outfd] surely points to a
5156 valid memory because p->outfd will be changed once EOF is
5157 sent to the process. */
5158 if (NILP (p->encode_coding_system)
5159 && proc_encode_coding_system[p->outfd])
5161 pset_encode_coding_system
5162 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5163 setup_coding_system (p->encode_coding_system,
5164 proc_encode_coding_system[p->outfd]);
5168 if (coding->carryover_bytes > 0)
5170 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5171 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5172 memcpy (SDATA (p->decoding_buf), coding->carryover,
5173 coding->carryover_bytes);
5174 p->decoding_carryover = coding->carryover_bytes;
5176 if (SBYTES (text) > 0)
5177 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5178 sometimes it's simply wrong to wrap (e.g. when called from
5179 accept-process-output). */
5180 internal_condition_case_1 (read_process_output_call,
5181 list3 (outstream, make_lisp_proc (p), text),
5182 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5183 read_process_output_error_handler);
5185 /* If we saved the match data nonrecursively, restore it now. */
5186 restore_search_regs ();
5187 running_asynch_code = outer_running_asynch_code;
5189 /* Restore waiting_for_user_input_p as it was
5190 when we were called, in case the filter clobbered it. */
5191 waiting_for_user_input_p = waiting;
5193 #if 0 /* Call record_asynch_buffer_change unconditionally,
5194 because we might have changed minor modes or other things
5195 that affect key bindings. */
5196 if (! EQ (Fcurrent_buffer (), obuffer)
5197 || ! EQ (current_buffer->keymap, okeymap))
5198 #endif
5199 /* But do it only if the caller is actually going to read events.
5200 Otherwise there's no need to make him wake up, and it could
5201 cause trouble (for example it would make sit_for return). */
5202 if (waiting_for_user_input_p == -1)
5203 record_asynch_buffer_change ();
5206 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5207 Sinternal_default_process_filter, 2, 2, 0,
5208 doc: /* Function used as default process filter.
5209 This inserts the process's output into its buffer, if there is one.
5210 Otherwise it discards the output. */)
5211 (Lisp_Object proc, Lisp_Object text)
5213 struct Lisp_Process *p;
5214 ptrdiff_t opoint;
5216 CHECK_PROCESS (proc);
5217 p = XPROCESS (proc);
5218 CHECK_STRING (text);
5220 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5222 Lisp_Object old_read_only;
5223 ptrdiff_t old_begv, old_zv;
5224 ptrdiff_t old_begv_byte, old_zv_byte;
5225 ptrdiff_t before, before_byte;
5226 ptrdiff_t opoint_byte;
5227 struct buffer *b;
5229 Fset_buffer (p->buffer);
5230 opoint = PT;
5231 opoint_byte = PT_BYTE;
5232 old_read_only = BVAR (current_buffer, read_only);
5233 old_begv = BEGV;
5234 old_zv = ZV;
5235 old_begv_byte = BEGV_BYTE;
5236 old_zv_byte = ZV_BYTE;
5238 bset_read_only (current_buffer, Qnil);
5240 /* Insert new output into buffer at the current end-of-output
5241 marker, thus preserving logical ordering of input and output. */
5242 if (XMARKER (p->mark)->buffer)
5243 set_point_from_marker (p->mark);
5244 else
5245 SET_PT_BOTH (ZV, ZV_BYTE);
5246 before = PT;
5247 before_byte = PT_BYTE;
5249 /* If the output marker is outside of the visible region, save
5250 the restriction and widen. */
5251 if (! (BEGV <= PT && PT <= ZV))
5252 Fwiden ();
5254 /* Adjust the multibyteness of TEXT to that of the buffer. */
5255 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5256 != ! STRING_MULTIBYTE (text))
5257 text = (STRING_MULTIBYTE (text)
5258 ? Fstring_as_unibyte (text)
5259 : Fstring_to_multibyte (text));
5260 /* Insert before markers in case we are inserting where
5261 the buffer's mark is, and the user's next command is Meta-y. */
5262 insert_from_string_before_markers (text, 0, 0,
5263 SCHARS (text), SBYTES (text), 0);
5265 /* Make sure the process marker's position is valid when the
5266 process buffer is changed in the signal_after_change above.
5267 W3 is known to do that. */
5268 if (BUFFERP (p->buffer)
5269 && (b = XBUFFER (p->buffer), b != current_buffer))
5270 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5271 else
5272 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5274 update_mode_lines = 23;
5276 /* Make sure opoint and the old restrictions
5277 float ahead of any new text just as point would. */
5278 if (opoint >= before)
5280 opoint += PT - before;
5281 opoint_byte += PT_BYTE - before_byte;
5283 if (old_begv > before)
5285 old_begv += PT - before;
5286 old_begv_byte += PT_BYTE - before_byte;
5288 if (old_zv >= before)
5290 old_zv += PT - before;
5291 old_zv_byte += PT_BYTE - before_byte;
5294 /* If the restriction isn't what it should be, set it. */
5295 if (old_begv != BEGV || old_zv != ZV)
5296 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5298 bset_read_only (current_buffer, old_read_only);
5299 SET_PT_BOTH (opoint, opoint_byte);
5301 return Qnil;
5304 /* Sending data to subprocess. */
5306 /* In send_process, when a write fails temporarily,
5307 wait_reading_process_output is called. It may execute user code,
5308 e.g. timers, that attempts to write new data to the same process.
5309 We must ensure that data is sent in the right order, and not
5310 interspersed half-completed with other writes (Bug#10815). This is
5311 handled by the write_queue element of struct process. It is a list
5312 with each entry having the form
5314 (string . (offset . length))
5316 where STRING is a lisp string, OFFSET is the offset into the
5317 string's byte sequence from which we should begin to send, and
5318 LENGTH is the number of bytes left to send. */
5320 /* Create a new entry in write_queue.
5321 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5322 BUF is a pointer to the string sequence of the input_obj or a C
5323 string in case of Qt or Qnil. */
5325 static void
5326 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5327 const char *buf, ptrdiff_t len, bool front)
5329 ptrdiff_t offset;
5330 Lisp_Object entry, obj;
5332 if (STRINGP (input_obj))
5334 offset = buf - SSDATA (input_obj);
5335 obj = input_obj;
5337 else
5339 offset = 0;
5340 obj = make_unibyte_string (buf, len);
5343 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5345 if (front)
5346 pset_write_queue (p, Fcons (entry, p->write_queue));
5347 else
5348 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5351 /* Remove the first element in the write_queue of process P, put its
5352 contents in OBJ, BUF and LEN, and return true. If the
5353 write_queue is empty, return false. */
5355 static bool
5356 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5357 const char **buf, ptrdiff_t *len)
5359 Lisp_Object entry, offset_length;
5360 ptrdiff_t offset;
5362 if (NILP (p->write_queue))
5363 return 0;
5365 entry = XCAR (p->write_queue);
5366 pset_write_queue (p, XCDR (p->write_queue));
5368 *obj = XCAR (entry);
5369 offset_length = XCDR (entry);
5371 *len = XINT (XCDR (offset_length));
5372 offset = XINT (XCAR (offset_length));
5373 *buf = SSDATA (*obj) + offset;
5375 return 1;
5378 /* Send some data to process PROC.
5379 BUF is the beginning of the data; LEN is the number of characters.
5380 OBJECT is the Lisp object that the data comes from. If OBJECT is
5381 nil or t, it means that the data comes from C string.
5383 If OBJECT is not nil, the data is encoded by PROC's coding-system
5384 for encoding before it is sent.
5386 This function can evaluate Lisp code and can garbage collect. */
5388 static void
5389 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5390 Lisp_Object object)
5392 struct Lisp_Process *p = XPROCESS (proc);
5393 ssize_t rv;
5394 struct coding_system *coding;
5396 if (p->raw_status_new)
5397 update_status (p);
5398 if (! EQ (p->status, Qrun))
5399 error ("Process %s not running", SDATA (p->name));
5400 if (p->outfd < 0)
5401 error ("Output file descriptor of %s is closed", SDATA (p->name));
5403 coding = proc_encode_coding_system[p->outfd];
5404 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5406 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5407 || (BUFFERP (object)
5408 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5409 || EQ (object, Qt))
5411 pset_encode_coding_system
5412 (p, complement_process_encoding_system (p->encode_coding_system));
5413 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5415 /* The coding system for encoding was changed to raw-text
5416 because we sent a unibyte text previously. Now we are
5417 sending a multibyte text, thus we must encode it by the
5418 original coding system specified for the current process.
5420 Another reason we come here is that the coding system
5421 was just complemented and a new one was returned by
5422 complement_process_encoding_system. */
5423 setup_coding_system (p->encode_coding_system, coding);
5424 Vlast_coding_system_used = p->encode_coding_system;
5426 coding->src_multibyte = 1;
5428 else
5430 coding->src_multibyte = 0;
5431 /* For sending a unibyte text, character code conversion should
5432 not take place but EOL conversion should. So, setup raw-text
5433 or one of the subsidiary if we have not yet done it. */
5434 if (CODING_REQUIRE_ENCODING (coding))
5436 if (CODING_REQUIRE_FLUSHING (coding))
5438 /* But, before changing the coding, we must flush out data. */
5439 coding->mode |= CODING_MODE_LAST_BLOCK;
5440 send_process (proc, "", 0, Qt);
5441 coding->mode &= CODING_MODE_LAST_BLOCK;
5443 setup_coding_system (raw_text_coding_system
5444 (Vlast_coding_system_used),
5445 coding);
5446 coding->src_multibyte = 0;
5449 coding->dst_multibyte = 0;
5451 if (CODING_REQUIRE_ENCODING (coding))
5453 coding->dst_object = Qt;
5454 if (BUFFERP (object))
5456 ptrdiff_t from_byte, from, to;
5457 ptrdiff_t save_pt, save_pt_byte;
5458 struct buffer *cur = current_buffer;
5460 set_buffer_internal (XBUFFER (object));
5461 save_pt = PT, save_pt_byte = PT_BYTE;
5463 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5464 from = BYTE_TO_CHAR (from_byte);
5465 to = BYTE_TO_CHAR (from_byte + len);
5466 TEMP_SET_PT_BOTH (from, from_byte);
5467 encode_coding_object (coding, object, from, from_byte,
5468 to, from_byte + len, Qt);
5469 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5470 set_buffer_internal (cur);
5472 else if (STRINGP (object))
5474 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5475 SBYTES (object), Qt);
5477 else
5479 coding->dst_object = make_unibyte_string (buf, len);
5480 coding->produced = len;
5483 len = coding->produced;
5484 object = coding->dst_object;
5485 buf = SSDATA (object);
5488 /* If there is already data in the write_queue, put the new data
5489 in the back of queue. Otherwise, ignore it. */
5490 if (!NILP (p->write_queue))
5491 write_queue_push (p, object, buf, len, 0);
5493 do /* while !NILP (p->write_queue) */
5495 ptrdiff_t cur_len = -1;
5496 const char *cur_buf;
5497 Lisp_Object cur_object;
5499 /* If write_queue is empty, ignore it. */
5500 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5502 cur_len = len;
5503 cur_buf = buf;
5504 cur_object = object;
5507 while (cur_len > 0)
5509 /* Send this batch, using one or more write calls. */
5510 ptrdiff_t written = 0;
5511 int outfd = p->outfd;
5512 #ifdef DATAGRAM_SOCKETS
5513 if (DATAGRAM_CHAN_P (outfd))
5515 rv = sendto (outfd, cur_buf, cur_len,
5516 0, datagram_address[outfd].sa,
5517 datagram_address[outfd].len);
5518 if (rv >= 0)
5519 written = rv;
5520 else if (errno == EMSGSIZE)
5521 report_file_error ("Sending datagram", proc);
5523 else
5524 #endif
5526 #ifdef HAVE_GNUTLS
5527 if (p->gnutls_p && p->gnutls_state)
5528 written = emacs_gnutls_write (p, cur_buf, cur_len);
5529 else
5530 #endif
5531 written = emacs_write_sig (outfd, cur_buf, cur_len);
5532 rv = (written ? 0 : -1);
5533 #ifdef ADAPTIVE_READ_BUFFERING
5534 if (p->read_output_delay > 0
5535 && p->adaptive_read_buffering == 1)
5537 p->read_output_delay = 0;
5538 process_output_delay_count--;
5539 p->read_output_skip = 0;
5541 #endif
5544 if (rv < 0)
5546 if (errno == EAGAIN
5547 #ifdef EWOULDBLOCK
5548 || errno == EWOULDBLOCK
5549 #endif
5551 /* Buffer is full. Wait, accepting input;
5552 that may allow the program
5553 to finish doing output and read more. */
5555 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5556 /* A gross hack to work around a bug in FreeBSD.
5557 In the following sequence, read(2) returns
5558 bogus data:
5560 write(2) 1022 bytes
5561 write(2) 954 bytes, get EAGAIN
5562 read(2) 1024 bytes in process_read_output
5563 read(2) 11 bytes in process_read_output
5565 That is, read(2) returns more bytes than have
5566 ever been written successfully. The 1033 bytes
5567 read are the 1022 bytes written successfully
5568 after processing (for example with CRs added if
5569 the terminal is set up that way which it is
5570 here). The same bytes will be seen again in a
5571 later read(2), without the CRs. */
5573 if (errno == EAGAIN)
5575 int flags = FWRITE;
5576 ioctl (p->outfd, TIOCFLUSH, &flags);
5578 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5580 /* Put what we should have written in wait_queue. */
5581 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5582 wait_reading_process_output (0, 20 * 1000 * 1000,
5583 0, 0, Qnil, NULL, 0);
5584 /* Reread queue, to see what is left. */
5585 break;
5587 else if (errno == EPIPE)
5589 p->raw_status_new = 0;
5590 pset_status (p, list2 (Qexit, make_number (256)));
5591 p->tick = ++process_tick;
5592 deactivate_process (proc);
5593 error ("process %s no longer connected to pipe; closed it",
5594 SDATA (p->name));
5596 else
5597 /* This is a real error. */
5598 report_file_error ("Writing to process", proc);
5600 cur_buf += written;
5601 cur_len -= written;
5604 while (!NILP (p->write_queue));
5607 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5608 3, 3, 0,
5609 doc: /* Send current contents of region as input to PROCESS.
5610 PROCESS may be a process, a buffer, the name of a process or buffer, or
5611 nil, indicating the current buffer's process.
5612 Called from program, takes three arguments, PROCESS, START and END.
5613 If the region is more than 500 characters long,
5614 it is sent in several bunches. This may happen even for shorter regions.
5615 Output from processes can arrive in between bunches. */)
5616 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5618 Lisp_Object proc = get_process (process);
5619 ptrdiff_t start_byte, end_byte;
5621 validate_region (&start, &end);
5623 start_byte = CHAR_TO_BYTE (XINT (start));
5624 end_byte = CHAR_TO_BYTE (XINT (end));
5626 if (XINT (start) < GPT && XINT (end) > GPT)
5627 move_gap_both (XINT (start), start_byte);
5629 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5630 end_byte - start_byte, Fcurrent_buffer ());
5632 return Qnil;
5635 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5636 2, 2, 0,
5637 doc: /* Send PROCESS the contents of STRING as input.
5638 PROCESS may be a process, a buffer, the name of a process or buffer, or
5639 nil, indicating the current buffer's process.
5640 If STRING is more than 500 characters long,
5641 it is sent in several bunches. This may happen even for shorter strings.
5642 Output from processes can arrive in between bunches. */)
5643 (Lisp_Object process, Lisp_Object string)
5645 Lisp_Object proc;
5646 CHECK_STRING (string);
5647 proc = get_process (process);
5648 send_process (proc, SSDATA (string),
5649 SBYTES (string), string);
5650 return Qnil;
5653 /* Return the foreground process group for the tty/pty that
5654 the process P uses. */
5655 static pid_t
5656 emacs_get_tty_pgrp (struct Lisp_Process *p)
5658 pid_t gid = -1;
5660 #ifdef TIOCGPGRP
5661 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5663 int fd;
5664 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5665 master side. Try the slave side. */
5666 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5668 if (fd != -1)
5670 ioctl (fd, TIOCGPGRP, &gid);
5671 emacs_close (fd);
5674 #endif /* defined (TIOCGPGRP ) */
5676 return gid;
5679 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5680 Sprocess_running_child_p, 0, 1, 0,
5681 doc: /* Return t if PROCESS has given the terminal to a child.
5682 If the operating system does not make it possible to find out,
5683 return t unconditionally. */)
5684 (Lisp_Object process)
5686 /* Initialize in case ioctl doesn't exist or gives an error,
5687 in a way that will cause returning t. */
5688 pid_t gid;
5689 Lisp_Object proc;
5690 struct Lisp_Process *p;
5692 proc = get_process (process);
5693 p = XPROCESS (proc);
5695 if (!EQ (p->type, Qreal))
5696 error ("Process %s is not a subprocess",
5697 SDATA (p->name));
5698 if (p->infd < 0)
5699 error ("Process %s is not active",
5700 SDATA (p->name));
5702 gid = emacs_get_tty_pgrp (p);
5704 if (gid == p->pid)
5705 return Qnil;
5706 return Qt;
5709 /* send a signal number SIGNO to PROCESS.
5710 If CURRENT_GROUP is t, that means send to the process group
5711 that currently owns the terminal being used to communicate with PROCESS.
5712 This is used for various commands in shell mode.
5713 If CURRENT_GROUP is lambda, that means send to the process group
5714 that currently owns the terminal, but only if it is NOT the shell itself.
5716 If NOMSG is false, insert signal-announcements into process's buffers
5717 right away.
5719 If we can, we try to signal PROCESS by sending control characters
5720 down the pty. This allows us to signal inferiors who have changed
5721 their uid, for which kill would return an EPERM error. */
5723 static void
5724 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5725 bool nomsg)
5727 Lisp_Object proc;
5728 struct Lisp_Process *p;
5729 pid_t gid;
5730 bool no_pgrp = 0;
5732 proc = get_process (process);
5733 p = XPROCESS (proc);
5735 if (!EQ (p->type, Qreal))
5736 error ("Process %s is not a subprocess",
5737 SDATA (p->name));
5738 if (p->infd < 0)
5739 error ("Process %s is not active",
5740 SDATA (p->name));
5742 if (!p->pty_flag)
5743 current_group = Qnil;
5745 /* If we are using pgrps, get a pgrp number and make it negative. */
5746 if (NILP (current_group))
5747 /* Send the signal to the shell's process group. */
5748 gid = p->pid;
5749 else
5751 #ifdef SIGNALS_VIA_CHARACTERS
5752 /* If possible, send signals to the entire pgrp
5753 by sending an input character to it. */
5755 struct termios t;
5756 cc_t *sig_char = NULL;
5758 tcgetattr (p->infd, &t);
5760 switch (signo)
5762 case SIGINT:
5763 sig_char = &t.c_cc[VINTR];
5764 break;
5766 case SIGQUIT:
5767 sig_char = &t.c_cc[VQUIT];
5768 break;
5770 case SIGTSTP:
5771 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5772 sig_char = &t.c_cc[VSWTCH];
5773 #else
5774 sig_char = &t.c_cc[VSUSP];
5775 #endif
5776 break;
5779 if (sig_char && *sig_char != CDISABLE)
5781 send_process (proc, (char *) sig_char, 1, Qnil);
5782 return;
5784 /* If we can't send the signal with a character,
5785 fall through and send it another way. */
5787 /* The code above may fall through if it can't
5788 handle the signal. */
5789 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5791 #ifdef TIOCGPGRP
5792 /* Get the current pgrp using the tty itself, if we have that.
5793 Otherwise, use the pty to get the pgrp.
5794 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5795 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5796 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5797 His patch indicates that if TIOCGPGRP returns an error, then
5798 we should just assume that p->pid is also the process group id. */
5800 gid = emacs_get_tty_pgrp (p);
5802 if (gid == -1)
5803 /* If we can't get the information, assume
5804 the shell owns the tty. */
5805 gid = p->pid;
5807 /* It is not clear whether anything really can set GID to -1.
5808 Perhaps on some system one of those ioctls can or could do so.
5809 Or perhaps this is vestigial. */
5810 if (gid == -1)
5811 no_pgrp = 1;
5812 #else /* ! defined (TIOCGPGRP ) */
5813 /* Can't select pgrps on this system, so we know that
5814 the child itself heads the pgrp. */
5815 gid = p->pid;
5816 #endif /* ! defined (TIOCGPGRP ) */
5818 /* If current_group is lambda, and the shell owns the terminal,
5819 don't send any signal. */
5820 if (EQ (current_group, Qlambda) && gid == p->pid)
5821 return;
5824 #ifdef SIGCONT
5825 if (signo == SIGCONT)
5827 p->raw_status_new = 0;
5828 pset_status (p, Qrun);
5829 p->tick = ++process_tick;
5830 if (!nomsg)
5832 status_notify (NULL);
5833 redisplay_preserve_echo_area (13);
5836 #endif
5838 /* If we don't have process groups, send the signal to the immediate
5839 subprocess. That isn't really right, but it's better than any
5840 obvious alternative. */
5841 if (no_pgrp)
5843 kill (p->pid, signo);
5844 return;
5847 /* gid may be a pid, or minus a pgrp's number */
5848 #ifdef TIOCSIGSEND
5849 if (!NILP (current_group))
5851 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
5852 kill (-gid, signo);
5854 else
5856 gid = - p->pid;
5857 kill (gid, signo);
5859 #else /* ! defined (TIOCSIGSEND) */
5860 kill (-gid, signo);
5861 #endif /* ! defined (TIOCSIGSEND) */
5864 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5865 doc: /* Interrupt process PROCESS.
5866 PROCESS may be a process, a buffer, or the name of a process or buffer.
5867 No arg or nil means current buffer's process.
5868 Second arg CURRENT-GROUP non-nil means send signal to
5869 the current process-group of the process's controlling terminal
5870 rather than to the process's own process group.
5871 If the process is a shell, this means interrupt current subjob
5872 rather than the shell.
5874 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5875 don't send the signal. */)
5876 (Lisp_Object process, Lisp_Object current_group)
5878 process_send_signal (process, SIGINT, current_group, 0);
5879 return process;
5882 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5883 doc: /* Kill process PROCESS. May be process or name of one.
5884 See function `interrupt-process' for more details on usage. */)
5885 (Lisp_Object process, Lisp_Object current_group)
5887 process_send_signal (process, SIGKILL, current_group, 0);
5888 return process;
5891 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5892 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5893 See function `interrupt-process' for more details on usage. */)
5894 (Lisp_Object process, Lisp_Object current_group)
5896 process_send_signal (process, SIGQUIT, current_group, 0);
5897 return process;
5900 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
5901 doc: /* Stop process PROCESS. May be process or name of one.
5902 See function `interrupt-process' for more details on usage.
5903 If PROCESS is a network or serial process, inhibit handling of incoming
5904 traffic. */)
5905 (Lisp_Object process, Lisp_Object current_group)
5907 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5909 struct Lisp_Process *p;
5911 p = XPROCESS (process);
5912 if (NILP (p->command)
5913 && p->infd >= 0)
5915 FD_CLR (p->infd, &input_wait_mask);
5916 FD_CLR (p->infd, &non_keyboard_wait_mask);
5918 pset_command (p, Qt);
5919 return process;
5921 #ifndef SIGTSTP
5922 error ("No SIGTSTP support");
5923 #else
5924 process_send_signal (process, SIGTSTP, current_group, 0);
5925 #endif
5926 return process;
5929 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
5930 doc: /* Continue process PROCESS. May be process or name of one.
5931 See function `interrupt-process' for more details on usage.
5932 If PROCESS is a network or serial process, resume handling of incoming
5933 traffic. */)
5934 (Lisp_Object process, Lisp_Object current_group)
5936 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5938 struct Lisp_Process *p;
5940 p = XPROCESS (process);
5941 if (EQ (p->command, Qt)
5942 && p->infd >= 0
5943 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
5945 FD_SET (p->infd, &input_wait_mask);
5946 FD_SET (p->infd, &non_keyboard_wait_mask);
5947 #ifdef WINDOWSNT
5948 if (fd_info[ p->infd ].flags & FILE_SERIAL)
5949 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
5950 #else /* not WINDOWSNT */
5951 tcflush (p->infd, TCIFLUSH);
5952 #endif /* not WINDOWSNT */
5954 pset_command (p, Qnil);
5955 return process;
5957 #ifdef SIGCONT
5958 process_send_signal (process, SIGCONT, current_group, 0);
5959 #else
5960 error ("No SIGCONT support");
5961 #endif
5962 return process;
5965 /* Return the integer value of the signal whose abbreviation is ABBR,
5966 or a negative number if there is no such signal. */
5967 static int
5968 abbr_to_signal (char const *name)
5970 int i, signo;
5971 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
5973 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
5974 name += 3;
5976 for (i = 0; i < sizeof sigbuf; i++)
5978 sigbuf[i] = c_toupper (name[i]);
5979 if (! sigbuf[i])
5980 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
5983 return -1;
5986 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
5987 2, 2, "sProcess (name or number): \nnSignal code: ",
5988 doc: /* Send PROCESS the signal with code SIGCODE.
5989 PROCESS may also be a number specifying the process id of the
5990 process to signal; in this case, the process need not be a child of
5991 this Emacs.
5992 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5993 (Lisp_Object process, Lisp_Object sigcode)
5995 pid_t pid;
5996 int signo;
5998 if (STRINGP (process))
6000 Lisp_Object tem = Fget_process (process);
6001 if (NILP (tem))
6003 Lisp_Object process_number =
6004 string_to_number (SSDATA (process), 10, 1);
6005 if (INTEGERP (process_number) || FLOATP (process_number))
6006 tem = process_number;
6008 process = tem;
6010 else if (!NUMBERP (process))
6011 process = get_process (process);
6013 if (NILP (process))
6014 return process;
6016 if (NUMBERP (process))
6017 CONS_TO_INTEGER (process, pid_t, pid);
6018 else
6020 CHECK_PROCESS (process);
6021 pid = XPROCESS (process)->pid;
6022 if (pid <= 0)
6023 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6026 if (INTEGERP (sigcode))
6028 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6029 signo = XINT (sigcode);
6031 else
6033 char *name;
6035 CHECK_SYMBOL (sigcode);
6036 name = SSDATA (SYMBOL_NAME (sigcode));
6038 signo = abbr_to_signal (name);
6039 if (signo < 0)
6040 error ("Undefined signal name %s", name);
6043 return make_number (kill (pid, signo));
6046 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6047 doc: /* Make PROCESS see end-of-file in its input.
6048 EOF comes after any text already sent to it.
6049 PROCESS may be a process, a buffer, the name of a process or buffer, or
6050 nil, indicating the current buffer's process.
6051 If PROCESS is a network connection, or is a process communicating
6052 through a pipe (as opposed to a pty), then you cannot send any more
6053 text to PROCESS after you call this function.
6054 If PROCESS is a serial process, wait until all output written to the
6055 process has been transmitted to the serial port. */)
6056 (Lisp_Object process)
6058 Lisp_Object proc;
6059 struct coding_system *coding = NULL;
6060 int outfd;
6062 if (DATAGRAM_CONN_P (process))
6063 return process;
6065 proc = get_process (process);
6066 outfd = XPROCESS (proc)->outfd;
6067 if (outfd >= 0)
6068 coding = proc_encode_coding_system[outfd];
6070 /* Make sure the process is really alive. */
6071 if (XPROCESS (proc)->raw_status_new)
6072 update_status (XPROCESS (proc));
6073 if (! EQ (XPROCESS (proc)->status, Qrun))
6074 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6076 if (coding && CODING_REQUIRE_FLUSHING (coding))
6078 coding->mode |= CODING_MODE_LAST_BLOCK;
6079 send_process (proc, "", 0, Qnil);
6082 if (XPROCESS (proc)->pty_flag)
6083 send_process (proc, "\004", 1, Qnil);
6084 else if (EQ (XPROCESS (proc)->type, Qserial))
6086 #ifndef WINDOWSNT
6087 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6088 report_file_error ("Failed tcdrain", Qnil);
6089 #endif /* not WINDOWSNT */
6090 /* Do nothing on Windows because writes are blocking. */
6092 else
6094 struct Lisp_Process *p = XPROCESS (proc);
6095 int old_outfd = p->outfd;
6096 int new_outfd;
6098 #ifdef HAVE_SHUTDOWN
6099 /* If this is a network connection, or socketpair is used
6100 for communication with the subprocess, call shutdown to cause EOF.
6101 (In some old system, shutdown to socketpair doesn't work.
6102 Then we just can't win.) */
6103 if (EQ (p->type, Qnetwork)
6104 || p->infd == old_outfd)
6105 shutdown (old_outfd, 1);
6106 #endif
6107 close_process_fd (&p->open_fd[WRITE_TO_SUBPROCESS]);
6108 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6109 if (new_outfd < 0)
6110 report_file_error ("Opening null device", Qnil);
6111 p->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6112 p->outfd = new_outfd;
6114 if (!proc_encode_coding_system[new_outfd])
6115 proc_encode_coding_system[new_outfd]
6116 = xmalloc (sizeof (struct coding_system));
6117 if (old_outfd >= 0)
6119 *proc_encode_coding_system[new_outfd]
6120 = *proc_encode_coding_system[old_outfd];
6121 memset (proc_encode_coding_system[old_outfd], 0,
6122 sizeof (struct coding_system));
6124 else
6125 setup_coding_system (p->encode_coding_system,
6126 proc_encode_coding_system[new_outfd]);
6128 return process;
6131 /* The main Emacs thread records child processes in three places:
6133 - Vprocess_alist, for asynchronous subprocesses, which are child
6134 processes visible to Lisp.
6136 - deleted_pid_list, for child processes invisible to Lisp,
6137 typically because of delete-process. These are recorded so that
6138 the processes can be reaped when they exit, so that the operating
6139 system's process table is not cluttered by zombies.
6141 - the local variable PID in Fcall_process, call_process_cleanup and
6142 call_process_kill, for synchronous subprocesses.
6143 record_unwind_protect is used to make sure this process is not
6144 forgotten: if the user interrupts call-process and the child
6145 process refuses to exit immediately even with two C-g's,
6146 call_process_kill adds PID's contents to deleted_pid_list before
6147 returning.
6149 The main Emacs thread invokes waitpid only on child processes that
6150 it creates and that have not been reaped. This avoid races on
6151 platforms such as GTK, where other threads create their own
6152 subprocesses which the main thread should not reap. For example,
6153 if the main thread attempted to reap an already-reaped child, it
6154 might inadvertently reap a GTK-created process that happened to
6155 have the same process ID. */
6157 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6158 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6159 keep track of its own children. GNUstep is similar. */
6161 static void dummy_handler (int sig) {}
6162 static signal_handler_t volatile lib_child_handler;
6164 /* Handle a SIGCHLD signal by looking for known child processes of
6165 Emacs whose status have changed. For each one found, record its
6166 new status.
6168 All we do is change the status; we do not run sentinels or print
6169 notifications. That is saved for the next time keyboard input is
6170 done, in order to avoid timing errors.
6172 ** WARNING: this can be called during garbage collection.
6173 Therefore, it must not be fooled by the presence of mark bits in
6174 Lisp objects.
6176 ** USG WARNING: Although it is not obvious from the documentation
6177 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6178 signal() before executing at least one wait(), otherwise the
6179 handler will be called again, resulting in an infinite loop. The
6180 relevant portion of the documentation reads "SIGCLD signals will be
6181 queued and the signal-catching function will be continually
6182 reentered until the queue is empty". Invoking signal() causes the
6183 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6184 Inc.
6186 ** Malloc WARNING: This should never call malloc either directly or
6187 indirectly; if it does, that is a bug */
6189 static void
6190 handle_child_signal (int sig)
6192 Lisp_Object tail, proc;
6194 /* Find the process that signaled us, and record its status. */
6196 /* The process can have been deleted by Fdelete_process, or have
6197 been started asynchronously by Fcall_process. */
6198 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6200 bool all_pids_are_fixnums
6201 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6202 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6203 Lisp_Object head = XCAR (tail);
6204 Lisp_Object xpid;
6205 if (! CONSP (head))
6206 continue;
6207 xpid = XCAR (head);
6208 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6210 pid_t deleted_pid;
6211 if (INTEGERP (xpid))
6212 deleted_pid = XINT (xpid);
6213 else
6214 deleted_pid = XFLOAT_DATA (xpid);
6215 if (child_status_changed (deleted_pid, 0, 0))
6217 if (STRINGP (XCDR (head)))
6218 unlink (SSDATA (XCDR (head)));
6219 XSETCAR (tail, Qnil);
6224 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6225 FOR_EACH_PROCESS (tail, proc)
6227 struct Lisp_Process *p = XPROCESS (proc);
6228 int status;
6230 if (p->alive
6231 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6233 /* Change the status of the process that was found. */
6234 p->tick = ++process_tick;
6235 p->raw_status = status;
6236 p->raw_status_new = 1;
6238 /* If process has terminated, stop waiting for its output. */
6239 if (WIFSIGNALED (status) || WIFEXITED (status))
6241 bool clear_desc_flag = 0;
6242 p->alive = 0;
6243 if (p->infd >= 0)
6244 clear_desc_flag = 1;
6246 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6247 if (clear_desc_flag)
6249 FD_CLR (p->infd, &input_wait_mask);
6250 FD_CLR (p->infd, &non_keyboard_wait_mask);
6256 lib_child_handler (sig);
6257 #ifdef NS_IMPL_GNUSTEP
6258 /* NSTask in GNUstep sets its child handler each time it is called.
6259 So we must re-set ours. */
6260 catch_child_signal();
6261 #endif
6264 static void
6265 deliver_child_signal (int sig)
6267 deliver_process_signal (sig, handle_child_signal);
6271 static Lisp_Object
6272 exec_sentinel_error_handler (Lisp_Object error_val)
6274 cmd_error_internal (error_val, "error in process sentinel: ");
6275 Vinhibit_quit = Qt;
6276 update_echo_area ();
6277 Fsleep_for (make_number (2), Qnil);
6278 return Qt;
6281 static void
6282 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6284 Lisp_Object sentinel, odeactivate;
6285 struct Lisp_Process *p = XPROCESS (proc);
6286 ptrdiff_t count = SPECPDL_INDEX ();
6287 bool outer_running_asynch_code = running_asynch_code;
6288 int waiting = waiting_for_user_input_p;
6290 if (inhibit_sentinels)
6291 return;
6293 /* No need to gcpro these, because all we do with them later
6294 is test them for EQness, and none of them should be a string. */
6295 odeactivate = Vdeactivate_mark;
6296 #if 0
6297 Lisp_Object obuffer, okeymap;
6298 XSETBUFFER (obuffer, current_buffer);
6299 okeymap = BVAR (current_buffer, keymap);
6300 #endif
6302 /* There's no good reason to let sentinels change the current
6303 buffer, and many callers of accept-process-output, sit-for, and
6304 friends don't expect current-buffer to be changed from under them. */
6305 record_unwind_current_buffer ();
6307 sentinel = p->sentinel;
6309 /* Inhibit quit so that random quits don't screw up a running filter. */
6310 specbind (Qinhibit_quit, Qt);
6311 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6313 /* In case we get recursively called,
6314 and we already saved the match data nonrecursively,
6315 save the same match data in safely recursive fashion. */
6316 if (outer_running_asynch_code)
6318 Lisp_Object tem;
6319 tem = Fmatch_data (Qnil, Qnil, Qnil);
6320 restore_search_regs ();
6321 record_unwind_save_match_data ();
6322 Fset_match_data (tem, Qt);
6325 /* For speed, if a search happens within this code,
6326 save the match data in a special nonrecursive fashion. */
6327 running_asynch_code = 1;
6329 internal_condition_case_1 (read_process_output_call,
6330 list3 (sentinel, proc, reason),
6331 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6332 exec_sentinel_error_handler);
6334 /* If we saved the match data nonrecursively, restore it now. */
6335 restore_search_regs ();
6336 running_asynch_code = outer_running_asynch_code;
6338 Vdeactivate_mark = odeactivate;
6340 /* Restore waiting_for_user_input_p as it was
6341 when we were called, in case the filter clobbered it. */
6342 waiting_for_user_input_p = waiting;
6344 #if 0
6345 if (! EQ (Fcurrent_buffer (), obuffer)
6346 || ! EQ (current_buffer->keymap, okeymap))
6347 #endif
6348 /* But do it only if the caller is actually going to read events.
6349 Otherwise there's no need to make him wake up, and it could
6350 cause trouble (for example it would make sit_for return). */
6351 if (waiting_for_user_input_p == -1)
6352 record_asynch_buffer_change ();
6354 unbind_to (count, Qnil);
6357 /* Report all recent events of a change in process status
6358 (either run the sentinel or output a message).
6359 This is usually done while Emacs is waiting for keyboard input
6360 but can be done at other times. */
6362 static void
6363 status_notify (struct Lisp_Process *deleting_process)
6365 register Lisp_Object proc;
6366 Lisp_Object tail, msg;
6367 struct gcpro gcpro1, gcpro2;
6369 tail = Qnil;
6370 msg = Qnil;
6371 /* We need to gcpro tail; if read_process_output calls a filter
6372 which deletes a process and removes the cons to which tail points
6373 from Vprocess_alist, and then causes a GC, tail is an unprotected
6374 reference. */
6375 GCPRO2 (tail, msg);
6377 /* Set this now, so that if new processes are created by sentinels
6378 that we run, we get called again to handle their status changes. */
6379 update_tick = process_tick;
6381 FOR_EACH_PROCESS (tail, proc)
6383 Lisp_Object symbol;
6384 register struct Lisp_Process *p = XPROCESS (proc);
6386 if (p->tick != p->update_tick)
6388 p->update_tick = p->tick;
6390 /* If process is still active, read any output that remains. */
6391 while (! EQ (p->filter, Qt)
6392 && ! EQ (p->status, Qconnect)
6393 && ! EQ (p->status, Qlisten)
6394 /* Network or serial process not stopped: */
6395 && ! EQ (p->command, Qt)
6396 && p->infd >= 0
6397 && p != deleting_process
6398 && read_process_output (proc, p->infd) > 0);
6400 /* Get the text to use for the message. */
6401 if (p->raw_status_new)
6402 update_status (p);
6403 msg = status_message (p);
6405 /* If process is terminated, deactivate it or delete it. */
6406 symbol = p->status;
6407 if (CONSP (p->status))
6408 symbol = XCAR (p->status);
6410 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6411 || EQ (symbol, Qclosed))
6413 if (delete_exited_processes)
6414 remove_process (proc);
6415 else
6416 deactivate_process (proc);
6419 /* The actions above may have further incremented p->tick.
6420 So set p->update_tick again so that an error in the sentinel will
6421 not cause this code to be run again. */
6422 p->update_tick = p->tick;
6423 /* Now output the message suitably. */
6424 exec_sentinel (proc, msg);
6426 } /* end for */
6428 update_mode_lines = 24; /* In case buffers use %s in mode-line-format. */
6429 UNGCPRO;
6432 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6433 Sinternal_default_process_sentinel, 2, 2, 0,
6434 doc: /* Function used as default sentinel for processes.
6435 This inserts a status message into the process's buffer, if there is one. */)
6436 (Lisp_Object proc, Lisp_Object msg)
6438 Lisp_Object buffer, symbol;
6439 struct Lisp_Process *p;
6440 CHECK_PROCESS (proc);
6441 p = XPROCESS (proc);
6442 buffer = p->buffer;
6443 symbol = p->status;
6444 if (CONSP (symbol))
6445 symbol = XCAR (symbol);
6447 if (!EQ (symbol, Qrun) && !NILP (buffer))
6449 Lisp_Object tem;
6450 struct buffer *old = current_buffer;
6451 ptrdiff_t opoint, opoint_byte;
6452 ptrdiff_t before, before_byte;
6454 /* Avoid error if buffer is deleted
6455 (probably that's why the process is dead, too). */
6456 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6457 return Qnil;
6458 Fset_buffer (buffer);
6460 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6461 msg = (code_convert_string_norecord
6462 (msg, Vlocale_coding_system, 1));
6464 opoint = PT;
6465 opoint_byte = PT_BYTE;
6466 /* Insert new output into buffer
6467 at the current end-of-output marker,
6468 thus preserving logical ordering of input and output. */
6469 if (XMARKER (p->mark)->buffer)
6470 Fgoto_char (p->mark);
6471 else
6472 SET_PT_BOTH (ZV, ZV_BYTE);
6474 before = PT;
6475 before_byte = PT_BYTE;
6477 tem = BVAR (current_buffer, read_only);
6478 bset_read_only (current_buffer, Qnil);
6479 insert_string ("\nProcess ");
6480 { /* FIXME: temporary kludge. */
6481 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6482 insert_string (" ");
6483 Finsert (1, &msg);
6484 bset_read_only (current_buffer, tem);
6485 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6487 if (opoint >= before)
6488 SET_PT_BOTH (opoint + (PT - before),
6489 opoint_byte + (PT_BYTE - before_byte));
6490 else
6491 SET_PT_BOTH (opoint, opoint_byte);
6493 set_buffer_internal (old);
6495 return Qnil;
6499 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6500 Sset_process_coding_system, 1, 3, 0,
6501 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6502 DECODING will be used to decode subprocess output and ENCODING to
6503 encode subprocess input. */)
6504 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6506 register struct Lisp_Process *p;
6508 CHECK_PROCESS (process);
6509 p = XPROCESS (process);
6510 if (p->infd < 0)
6511 error ("Input file descriptor of %s closed", SDATA (p->name));
6512 if (p->outfd < 0)
6513 error ("Output file descriptor of %s closed", SDATA (p->name));
6514 Fcheck_coding_system (decoding);
6515 Fcheck_coding_system (encoding);
6516 encoding = coding_inherit_eol_type (encoding, Qnil);
6517 pset_decode_coding_system (p, decoding);
6518 pset_encode_coding_system (p, encoding);
6519 setup_process_coding_systems (process);
6521 return Qnil;
6524 DEFUN ("process-coding-system",
6525 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6526 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6527 (register Lisp_Object process)
6529 CHECK_PROCESS (process);
6530 return Fcons (XPROCESS (process)->decode_coding_system,
6531 XPROCESS (process)->encode_coding_system);
6534 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6535 Sset_process_filter_multibyte, 2, 2, 0,
6536 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6537 If FLAG is non-nil, the filter is given multibyte strings.
6538 If FLAG is nil, the filter is given unibyte strings. In this case,
6539 all character code conversion except for end-of-line conversion is
6540 suppressed. */)
6541 (Lisp_Object process, Lisp_Object flag)
6543 register struct Lisp_Process *p;
6545 CHECK_PROCESS (process);
6546 p = XPROCESS (process);
6547 if (NILP (flag))
6548 pset_decode_coding_system
6549 (p, raw_text_coding_system (p->decode_coding_system));
6550 setup_process_coding_systems (process);
6552 return Qnil;
6555 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6556 Sprocess_filter_multibyte_p, 1, 1, 0,
6557 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6558 (Lisp_Object process)
6560 register struct Lisp_Process *p;
6561 struct coding_system *coding;
6563 CHECK_PROCESS (process);
6564 p = XPROCESS (process);
6565 coding = proc_decode_coding_system[p->infd];
6566 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6572 # ifdef HAVE_GPM
6574 void
6575 add_gpm_wait_descriptor (int desc)
6577 add_keyboard_wait_descriptor (desc);
6580 void
6581 delete_gpm_wait_descriptor (int desc)
6583 delete_keyboard_wait_descriptor (desc);
6586 # endif
6588 # ifdef USABLE_SIGIO
6590 /* Return true if *MASK has a bit set
6591 that corresponds to one of the keyboard input descriptors. */
6593 static bool
6594 keyboard_bit_set (fd_set *mask)
6596 int fd;
6598 for (fd = 0; fd <= max_input_desc; fd++)
6599 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6600 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6601 return 1;
6603 return 0;
6605 # endif
6607 #else /* not subprocesses */
6609 /* Defined on msdos.c. */
6610 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6611 struct timespec *, void *);
6613 /* Implementation of wait_reading_process_output, assuming that there
6614 are no subprocesses. Used only by the MS-DOS build.
6616 Wait for timeout to elapse and/or keyboard input to be available.
6618 TIME_LIMIT is:
6619 timeout in seconds
6620 If negative, gobble data immediately available but don't wait for any.
6622 NSECS is:
6623 an additional duration to wait, measured in nanoseconds
6624 If TIME_LIMIT is zero, then:
6625 If NSECS == 0, there is no limit.
6626 If NSECS > 0, the timeout consists of NSECS only.
6627 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6629 READ_KBD is:
6630 0 to ignore keyboard input, or
6631 1 to return when input is available, or
6632 -1 means caller will actually read the input, so don't throw to
6633 the quit handler.
6635 see full version for other parameters. We know that wait_proc will
6636 always be NULL, since `subprocesses' isn't defined.
6638 DO_DISPLAY means redisplay should be done to show subprocess
6639 output that arrives.
6641 Return true if we received input from any process. */
6643 bool
6644 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6645 bool do_display,
6646 Lisp_Object wait_for_cell,
6647 struct Lisp_Process *wait_proc, int just_wait_proc)
6649 register int nfds;
6650 struct timespec end_time, timeout;
6652 if (time_limit < 0)
6654 time_limit = 0;
6655 nsecs = -1;
6657 else if (TYPE_MAXIMUM (time_t) < time_limit)
6658 time_limit = TYPE_MAXIMUM (time_t);
6660 /* What does time_limit really mean? */
6661 if (time_limit || nsecs > 0)
6663 timeout = make_timespec (time_limit, nsecs);
6664 end_time = timespec_add (current_timespec (), timeout);
6667 /* Turn off periodic alarms (in case they are in use)
6668 and then turn off any other atimers,
6669 because the select emulator uses alarms. */
6670 stop_polling ();
6671 turn_on_atimers (0);
6673 while (1)
6675 bool timeout_reduced_for_timers = 0;
6676 fd_set waitchannels;
6677 int xerrno;
6679 /* If calling from keyboard input, do not quit
6680 since we want to return C-g as an input character.
6681 Otherwise, do pending quit if requested. */
6682 if (read_kbd >= 0)
6683 QUIT;
6685 /* Exit now if the cell we're waiting for became non-nil. */
6686 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6687 break;
6689 /* Compute time from now till when time limit is up. */
6690 /* Exit if already run out. */
6691 if (nsecs < 0)
6693 /* A negative timeout means
6694 gobble output available now
6695 but don't wait at all. */
6697 timeout = make_timespec (0, 0);
6699 else if (time_limit || nsecs > 0)
6701 struct timespec now = current_timespec ();
6702 if (timespec_cmp (end_time, now) <= 0)
6703 break;
6704 timeout = timespec_sub (end_time, now);
6706 else
6708 timeout = make_timespec (100000, 0);
6711 /* If our caller will not immediately handle keyboard events,
6712 run timer events directly.
6713 (Callers that will immediately read keyboard events
6714 call timer_delay on their own.) */
6715 if (NILP (wait_for_cell))
6717 struct timespec timer_delay;
6721 unsigned old_timers_run = timers_run;
6722 timer_delay = timer_check ();
6723 if (timers_run != old_timers_run && do_display)
6724 /* We must retry, since a timer may have requeued itself
6725 and that could alter the time delay. */
6726 redisplay_preserve_echo_area (14);
6727 else
6728 break;
6730 while (!detect_input_pending ());
6732 /* If there is unread keyboard input, also return. */
6733 if (read_kbd != 0
6734 && requeued_events_pending_p ())
6735 break;
6737 if (timespec_valid_p (timer_delay) && nsecs >= 0)
6739 if (timespec_cmp (timer_delay, timeout) < 0)
6741 timeout = timer_delay;
6742 timeout_reduced_for_timers = 1;
6747 /* Cause C-g and alarm signals to take immediate action,
6748 and cause input available signals to zero out timeout. */
6749 if (read_kbd < 0)
6750 set_waiting_for_input (&timeout);
6752 /* If a frame has been newly mapped and needs updating,
6753 reprocess its display stuff. */
6754 if (frame_garbaged && do_display)
6756 clear_waiting_for_input ();
6757 redisplay_preserve_echo_area (15);
6758 if (read_kbd < 0)
6759 set_waiting_for_input (&timeout);
6762 /* Wait till there is something to do. */
6763 FD_ZERO (&waitchannels);
6764 if (read_kbd && detect_input_pending ())
6765 nfds = 0;
6766 else
6768 if (read_kbd || !NILP (wait_for_cell))
6769 FD_SET (0, &waitchannels);
6770 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
6773 xerrno = errno;
6775 /* Make C-g and alarm signals set flags again */
6776 clear_waiting_for_input ();
6778 /* If we woke up due to SIGWINCH, actually change size now. */
6779 do_pending_window_change (0);
6781 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
6782 /* We waited the full specified time, so return now. */
6783 break;
6785 if (nfds == -1)
6787 /* If the system call was interrupted, then go around the
6788 loop again. */
6789 if (xerrno == EINTR)
6790 FD_ZERO (&waitchannels);
6791 else
6792 report_file_errno ("Failed select", Qnil, xerrno);
6795 /* Check for keyboard input */
6797 if (read_kbd
6798 && detect_input_pending_run_timers (do_display))
6800 swallow_events (do_display);
6801 if (detect_input_pending_run_timers (do_display))
6802 break;
6805 /* If there is unread keyboard input, also return. */
6806 if (read_kbd
6807 && requeued_events_pending_p ())
6808 break;
6810 /* If wait_for_cell. check for keyboard input
6811 but don't run any timers.
6812 ??? (It seems wrong to me to check for keyboard
6813 input at all when wait_for_cell, but the code
6814 has been this way since July 1994.
6815 Try changing this after version 19.31.) */
6816 if (! NILP (wait_for_cell)
6817 && detect_input_pending ())
6819 swallow_events (do_display);
6820 if (detect_input_pending ())
6821 break;
6824 /* Exit now if the cell we're waiting for became non-nil. */
6825 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6826 break;
6829 start_polling ();
6831 return 0;
6834 #endif /* not subprocesses */
6836 /* The following functions are needed even if async subprocesses are
6837 not supported. Some of them are no-op stubs in that case. */
6839 /* Add DESC to the set of keyboard input descriptors. */
6841 void
6842 add_keyboard_wait_descriptor (int desc)
6844 #ifdef subprocesses /* actually means "not MSDOS" */
6845 FD_SET (desc, &input_wait_mask);
6846 FD_SET (desc, &non_process_wait_mask);
6847 if (desc > max_input_desc)
6848 max_input_desc = desc;
6849 #endif
6852 /* From now on, do not expect DESC to give keyboard input. */
6854 void
6855 delete_keyboard_wait_descriptor (int desc)
6857 #ifdef subprocesses
6858 FD_CLR (desc, &input_wait_mask);
6859 FD_CLR (desc, &non_process_wait_mask);
6860 delete_input_desc (desc);
6861 #endif
6864 /* Setup coding systems of PROCESS. */
6866 void
6867 setup_process_coding_systems (Lisp_Object process)
6869 #ifdef subprocesses
6870 struct Lisp_Process *p = XPROCESS (process);
6871 int inch = p->infd;
6872 int outch = p->outfd;
6873 Lisp_Object coding_system;
6875 if (inch < 0 || outch < 0)
6876 return;
6878 if (!proc_decode_coding_system[inch])
6879 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
6880 coding_system = p->decode_coding_system;
6881 if (EQ (p->filter, Qinternal_default_process_filter)
6882 && BUFFERP (p->buffer))
6884 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
6885 coding_system = raw_text_coding_system (coding_system);
6887 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
6889 if (!proc_encode_coding_system[outch])
6890 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
6891 setup_coding_system (p->encode_coding_system,
6892 proc_encode_coding_system[outch]);
6893 #endif
6896 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
6897 doc: /* Return the (or a) process associated with BUFFER.
6898 BUFFER may be a buffer or the name of one. */)
6899 (register Lisp_Object buffer)
6901 #ifdef subprocesses
6902 register Lisp_Object buf, tail, proc;
6904 if (NILP (buffer)) return Qnil;
6905 buf = Fget_buffer (buffer);
6906 if (NILP (buf)) return Qnil;
6908 FOR_EACH_PROCESS (tail, proc)
6909 if (EQ (XPROCESS (proc)->buffer, buf))
6910 return proc;
6911 #endif /* subprocesses */
6912 return Qnil;
6915 DEFUN ("process-inherit-coding-system-flag",
6916 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
6917 1, 1, 0,
6918 doc: /* Return the value of inherit-coding-system flag for PROCESS.
6919 If this flag is t, `buffer-file-coding-system' of the buffer
6920 associated with PROCESS will inherit the coding system used to decode
6921 the process output. */)
6922 (register Lisp_Object process)
6924 #ifdef subprocesses
6925 CHECK_PROCESS (process);
6926 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
6927 #else
6928 /* Ignore the argument and return the value of
6929 inherit-process-coding-system. */
6930 return inherit_process_coding_system ? Qt : Qnil;
6931 #endif
6934 /* Kill all processes associated with `buffer'.
6935 If `buffer' is nil, kill all processes */
6937 void
6938 kill_buffer_processes (Lisp_Object buffer)
6940 #ifdef subprocesses
6941 Lisp_Object tail, proc;
6943 FOR_EACH_PROCESS (tail, proc)
6944 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
6946 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6947 Fdelete_process (proc);
6948 else if (XPROCESS (proc)->infd >= 0)
6949 process_send_signal (proc, SIGHUP, Qnil, 1);
6951 #else /* subprocesses */
6952 /* Since we have no subprocesses, this does nothing. */
6953 #endif /* subprocesses */
6956 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
6957 Swaiting_for_user_input_p, 0, 0, 0,
6958 doc: /* Return non-nil if Emacs is waiting for input from the user.
6959 This is intended for use by asynchronous process output filters and sentinels. */)
6960 (void)
6962 #ifdef subprocesses
6963 return (waiting_for_user_input_p ? Qt : Qnil);
6964 #else
6965 return Qnil;
6966 #endif
6969 /* Stop reading input from keyboard sources. */
6971 void
6972 hold_keyboard_input (void)
6974 kbd_is_on_hold = 1;
6977 /* Resume reading input from keyboard sources. */
6979 void
6980 unhold_keyboard_input (void)
6982 kbd_is_on_hold = 0;
6985 /* Return true if keyboard input is on hold, zero otherwise. */
6987 bool
6988 kbd_on_hold_p (void)
6990 return kbd_is_on_hold;
6994 /* Enumeration of and access to system processes a-la ps(1). */
6996 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
6997 0, 0, 0,
6998 doc: /* Return a list of numerical process IDs of all running processes.
6999 If this functionality is unsupported, return nil.
7001 See `process-attributes' for getting attributes of a process given its ID. */)
7002 (void)
7004 return list_system_processes ();
7007 DEFUN ("process-attributes", Fprocess_attributes,
7008 Sprocess_attributes, 1, 1, 0,
7009 doc: /* Return attributes of the process given by its PID, a number.
7011 Value is an alist where each element is a cons cell of the form
7013 \(KEY . VALUE)
7015 If this functionality is unsupported, the value is nil.
7017 See `list-system-processes' for getting a list of all process IDs.
7019 The KEYs of the attributes that this function may return are listed
7020 below, together with the type of the associated VALUE (in parentheses).
7021 Not all platforms support all of these attributes; unsupported
7022 attributes will not appear in the returned alist.
7023 Unless explicitly indicated otherwise, numbers can have either
7024 integer or floating point values.
7026 euid -- Effective user User ID of the process (number)
7027 user -- User name corresponding to euid (string)
7028 egid -- Effective user Group ID of the process (number)
7029 group -- Group name corresponding to egid (string)
7030 comm -- Command name (executable name only) (string)
7031 state -- Process state code, such as "S", "R", or "T" (string)
7032 ppid -- Parent process ID (number)
7033 pgrp -- Process group ID (number)
7034 sess -- Session ID, i.e. process ID of session leader (number)
7035 ttname -- Controlling tty name (string)
7036 tpgid -- ID of foreground process group on the process's tty (number)
7037 minflt -- number of minor page faults (number)
7038 majflt -- number of major page faults (number)
7039 cminflt -- cumulative number of minor page faults (number)
7040 cmajflt -- cumulative number of major page faults (number)
7041 utime -- user time used by the process, in (current-time) format,
7042 which is a list of integers (HIGH LOW USEC PSEC)
7043 stime -- system time used by the process (current-time)
7044 time -- sum of utime and stime (current-time)
7045 cutime -- user time used by the process and its children (current-time)
7046 cstime -- system time used by the process and its children (current-time)
7047 ctime -- sum of cutime and cstime (current-time)
7048 pri -- priority of the process (number)
7049 nice -- nice value of the process (number)
7050 thcount -- process thread count (number)
7051 start -- time the process started (current-time)
7052 vsize -- virtual memory size of the process in KB's (number)
7053 rss -- resident set size of the process in KB's (number)
7054 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7055 pcpu -- percents of CPU time used by the process (floating-point number)
7056 pmem -- percents of total physical memory used by process's resident set
7057 (floating-point number)
7058 args -- command line which invoked the process (string). */)
7059 ( Lisp_Object pid)
7061 return system_process_attributes (pid);
7064 #ifdef subprocesses
7065 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7066 Invoke this after init_process_emacs, and after glib and/or GNUstep
7067 futz with the SIGCHLD handler, but before Emacs forks any children.
7068 This function's caller should block SIGCHLD. */
7070 #ifndef NS_IMPL_GNUSTEP
7071 static
7072 #endif
7073 void
7074 catch_child_signal (void)
7076 struct sigaction action, old_action;
7077 emacs_sigaction_init (&action, deliver_child_signal);
7078 block_child_signal ();
7079 sigaction (SIGCHLD, &action, &old_action);
7080 eassert (! (old_action.sa_flags & SA_SIGINFO));
7082 if (old_action.sa_handler != deliver_child_signal)
7083 lib_child_handler
7084 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7085 ? dummy_handler
7086 : old_action.sa_handler);
7087 unblock_child_signal ();
7089 #endif /* subprocesses */
7092 /* This is not called "init_process" because that is the name of a
7093 Mach system call, so it would cause problems on Darwin systems. */
7094 void
7095 init_process_emacs (void)
7097 #ifdef subprocesses
7098 register int i;
7100 inhibit_sentinels = 0;
7102 #ifndef CANNOT_DUMP
7103 if (! noninteractive || initialized)
7104 #endif
7106 #if defined HAVE_GLIB && !defined WINDOWSNT
7107 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7108 this should always fail, but is enough to initialize glib's
7109 private SIGCHLD handler, allowing catch_child_signal to copy
7110 it into lib_child_handler. */
7111 g_source_unref (g_child_watch_source_new (getpid ()));
7112 #endif
7113 catch_child_signal ();
7116 FD_ZERO (&input_wait_mask);
7117 FD_ZERO (&non_keyboard_wait_mask);
7118 FD_ZERO (&non_process_wait_mask);
7119 FD_ZERO (&write_mask);
7120 max_process_desc = max_input_desc = -1;
7121 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7123 #ifdef NON_BLOCKING_CONNECT
7124 FD_ZERO (&connect_wait_mask);
7125 num_pending_connects = 0;
7126 #endif
7128 #ifdef ADAPTIVE_READ_BUFFERING
7129 process_output_delay_count = 0;
7130 process_output_skip = 0;
7131 #endif
7133 /* Don't do this, it caused infinite select loops. The display
7134 method should call add_keyboard_wait_descriptor on stdin if it
7135 needs that. */
7136 #if 0
7137 FD_SET (0, &input_wait_mask);
7138 #endif
7140 Vprocess_alist = Qnil;
7141 deleted_pid_list = Qnil;
7142 for (i = 0; i < FD_SETSIZE; i++)
7144 chan_process[i] = Qnil;
7145 proc_buffered_char[i] = -1;
7147 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7148 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7149 #ifdef DATAGRAM_SOCKETS
7150 memset (datagram_address, 0, sizeof datagram_address);
7151 #endif
7154 Lisp_Object subfeatures = Qnil;
7155 const struct socket_options *sopt;
7157 #define ADD_SUBFEATURE(key, val) \
7158 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7160 #ifdef NON_BLOCKING_CONNECT
7161 ADD_SUBFEATURE (QCnowait, Qt);
7162 #endif
7163 #ifdef DATAGRAM_SOCKETS
7164 ADD_SUBFEATURE (QCtype, Qdatagram);
7165 #endif
7166 #ifdef HAVE_SEQPACKET
7167 ADD_SUBFEATURE (QCtype, Qseqpacket);
7168 #endif
7169 #ifdef HAVE_LOCAL_SOCKETS
7170 ADD_SUBFEATURE (QCfamily, Qlocal);
7171 #endif
7172 ADD_SUBFEATURE (QCfamily, Qipv4);
7173 #ifdef AF_INET6
7174 ADD_SUBFEATURE (QCfamily, Qipv6);
7175 #endif
7176 #ifdef HAVE_GETSOCKNAME
7177 ADD_SUBFEATURE (QCservice, Qt);
7178 #endif
7179 ADD_SUBFEATURE (QCserver, Qt);
7181 for (sopt = socket_options; sopt->name; sopt++)
7182 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7184 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7187 #if defined (DARWIN_OS)
7188 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7189 processes. As such, we only change the default value. */
7190 if (initialized)
7192 char const *release = (STRINGP (Voperating_system_release)
7193 ? SSDATA (Voperating_system_release)
7194 : 0);
7195 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7196 Vprocess_connection_type = Qnil;
7199 #endif
7200 #endif /* subprocesses */
7201 kbd_is_on_hold = 0;
7204 void
7205 syms_of_process (void)
7207 #ifdef subprocesses
7209 DEFSYM (Qprocessp, "processp");
7210 DEFSYM (Qrun, "run");
7211 DEFSYM (Qstop, "stop");
7212 DEFSYM (Qsignal, "signal");
7214 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7215 here again.
7217 Qexit = intern_c_string ("exit");
7218 staticpro (&Qexit); */
7220 DEFSYM (Qopen, "open");
7221 DEFSYM (Qclosed, "closed");
7222 DEFSYM (Qconnect, "connect");
7223 DEFSYM (Qfailed, "failed");
7224 DEFSYM (Qlisten, "listen");
7225 DEFSYM (Qlocal, "local");
7226 DEFSYM (Qipv4, "ipv4");
7227 #ifdef AF_INET6
7228 DEFSYM (Qipv6, "ipv6");
7229 #endif
7230 DEFSYM (Qdatagram, "datagram");
7231 DEFSYM (Qseqpacket, "seqpacket");
7233 DEFSYM (QCport, ":port");
7234 DEFSYM (QCspeed, ":speed");
7235 DEFSYM (QCprocess, ":process");
7237 DEFSYM (QCbytesize, ":bytesize");
7238 DEFSYM (QCstopbits, ":stopbits");
7239 DEFSYM (QCparity, ":parity");
7240 DEFSYM (Qodd, "odd");
7241 DEFSYM (Qeven, "even");
7242 DEFSYM (QCflowcontrol, ":flowcontrol");
7243 DEFSYM (Qhw, "hw");
7244 DEFSYM (Qsw, "sw");
7245 DEFSYM (QCsummary, ":summary");
7247 DEFSYM (Qreal, "real");
7248 DEFSYM (Qnetwork, "network");
7249 DEFSYM (Qserial, "serial");
7250 DEFSYM (QCbuffer, ":buffer");
7251 DEFSYM (QChost, ":host");
7252 DEFSYM (QCservice, ":service");
7253 DEFSYM (QClocal, ":local");
7254 DEFSYM (QCremote, ":remote");
7255 DEFSYM (QCcoding, ":coding");
7256 DEFSYM (QCserver, ":server");
7257 DEFSYM (QCnowait, ":nowait");
7258 DEFSYM (QCsentinel, ":sentinel");
7259 DEFSYM (QClog, ":log");
7260 DEFSYM (QCnoquery, ":noquery");
7261 DEFSYM (QCstop, ":stop");
7262 DEFSYM (QCoptions, ":options");
7263 DEFSYM (QCplist, ":plist");
7265 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7267 staticpro (&Vprocess_alist);
7268 staticpro (&deleted_pid_list);
7270 #endif /* subprocesses */
7272 DEFSYM (QCname, ":name");
7273 DEFSYM (QCtype, ":type");
7275 DEFSYM (Qeuid, "euid");
7276 DEFSYM (Qegid, "egid");
7277 DEFSYM (Quser, "user");
7278 DEFSYM (Qgroup, "group");
7279 DEFSYM (Qcomm, "comm");
7280 DEFSYM (Qstate, "state");
7281 DEFSYM (Qppid, "ppid");
7282 DEFSYM (Qpgrp, "pgrp");
7283 DEFSYM (Qsess, "sess");
7284 DEFSYM (Qttname, "ttname");
7285 DEFSYM (Qtpgid, "tpgid");
7286 DEFSYM (Qminflt, "minflt");
7287 DEFSYM (Qmajflt, "majflt");
7288 DEFSYM (Qcminflt, "cminflt");
7289 DEFSYM (Qcmajflt, "cmajflt");
7290 DEFSYM (Qutime, "utime");
7291 DEFSYM (Qstime, "stime");
7292 DEFSYM (Qtime, "time");
7293 DEFSYM (Qcutime, "cutime");
7294 DEFSYM (Qcstime, "cstime");
7295 DEFSYM (Qctime, "ctime");
7296 #ifdef subprocesses
7297 DEFSYM (Qinternal_default_process_sentinel,
7298 "internal-default-process-sentinel");
7299 DEFSYM (Qinternal_default_process_filter,
7300 "internal-default-process-filter");
7301 #endif
7302 DEFSYM (Qpri, "pri");
7303 DEFSYM (Qnice, "nice");
7304 DEFSYM (Qthcount, "thcount");
7305 DEFSYM (Qstart, "start");
7306 DEFSYM (Qvsize, "vsize");
7307 DEFSYM (Qrss, "rss");
7308 DEFSYM (Qetime, "etime");
7309 DEFSYM (Qpcpu, "pcpu");
7310 DEFSYM (Qpmem, "pmem");
7311 DEFSYM (Qargs, "args");
7313 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7314 doc: /* Non-nil means delete processes immediately when they exit.
7315 A value of nil means don't delete them until `list-processes' is run. */);
7317 delete_exited_processes = 1;
7319 #ifdef subprocesses
7320 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7321 doc: /* Control type of device used to communicate with subprocesses.
7322 Values are nil to use a pipe, or t or `pty' to use a pty.
7323 The value has no effect if the system has no ptys or if all ptys are busy:
7324 then a pipe is used in any case.
7325 The value takes effect when `start-process' is called. */);
7326 Vprocess_connection_type = Qt;
7328 #ifdef ADAPTIVE_READ_BUFFERING
7329 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7330 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7331 On some systems, when Emacs reads the output from a subprocess, the output data
7332 is read in very small blocks, potentially resulting in very poor performance.
7333 This behavior can be remedied to some extent by setting this variable to a
7334 non-nil value, as it will automatically delay reading from such processes, to
7335 allow them to produce more output before Emacs tries to read it.
7336 If the value is t, the delay is reset after each write to the process; any other
7337 non-nil value means that the delay is not reset on write.
7338 The variable takes effect when `start-process' is called. */);
7339 Vprocess_adaptive_read_buffering = Qt;
7340 #endif
7342 defsubr (&Sprocessp);
7343 defsubr (&Sget_process);
7344 defsubr (&Sdelete_process);
7345 defsubr (&Sprocess_status);
7346 defsubr (&Sprocess_exit_status);
7347 defsubr (&Sprocess_id);
7348 defsubr (&Sprocess_name);
7349 defsubr (&Sprocess_tty_name);
7350 defsubr (&Sprocess_command);
7351 defsubr (&Sset_process_buffer);
7352 defsubr (&Sprocess_buffer);
7353 defsubr (&Sprocess_mark);
7354 defsubr (&Sset_process_filter);
7355 defsubr (&Sprocess_filter);
7356 defsubr (&Sset_process_sentinel);
7357 defsubr (&Sprocess_sentinel);
7358 defsubr (&Sset_process_window_size);
7359 defsubr (&Sset_process_inherit_coding_system_flag);
7360 defsubr (&Sset_process_query_on_exit_flag);
7361 defsubr (&Sprocess_query_on_exit_flag);
7362 defsubr (&Sprocess_contact);
7363 defsubr (&Sprocess_plist);
7364 defsubr (&Sset_process_plist);
7365 defsubr (&Sprocess_list);
7366 defsubr (&Sstart_process);
7367 defsubr (&Sserial_process_configure);
7368 defsubr (&Smake_serial_process);
7369 defsubr (&Sset_network_process_option);
7370 defsubr (&Smake_network_process);
7371 defsubr (&Sformat_network_address);
7372 defsubr (&Snetwork_interface_list);
7373 defsubr (&Snetwork_interface_info);
7374 #ifdef DATAGRAM_SOCKETS
7375 defsubr (&Sprocess_datagram_address);
7376 defsubr (&Sset_process_datagram_address);
7377 #endif
7378 defsubr (&Saccept_process_output);
7379 defsubr (&Sprocess_send_region);
7380 defsubr (&Sprocess_send_string);
7381 defsubr (&Sinterrupt_process);
7382 defsubr (&Skill_process);
7383 defsubr (&Squit_process);
7384 defsubr (&Sstop_process);
7385 defsubr (&Scontinue_process);
7386 defsubr (&Sprocess_running_child_p);
7387 defsubr (&Sprocess_send_eof);
7388 defsubr (&Ssignal_process);
7389 defsubr (&Swaiting_for_user_input_p);
7390 defsubr (&Sprocess_type);
7391 defsubr (&Sinternal_default_process_sentinel);
7392 defsubr (&Sinternal_default_process_filter);
7393 defsubr (&Sset_process_coding_system);
7394 defsubr (&Sprocess_coding_system);
7395 defsubr (&Sset_process_filter_multibyte);
7396 defsubr (&Sprocess_filter_multibyte_p);
7398 #endif /* subprocesses */
7400 defsubr (&Sget_buffer_process);
7401 defsubr (&Sprocess_inherit_coding_system_flag);
7402 defsubr (&Slist_system_processes);
7403 defsubr (&Sprocess_attributes);