Port to Solaris 10 and its bundled GCC.
[emacs.git] / src / process.c
blob91bc090e76ee491dea9a07888bbff945ead4c3f1
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2013 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
27 #include <sys/file.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30 #include <fcntl.h>
32 #include "lisp.h"
34 /* Only MS-DOS does not define `subprocesses'. */
35 #ifdef subprocesses
37 #include <sys/socket.h>
38 #include <netdb.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
42 /* Are local (unix) sockets supported? */
43 #if defined (HAVE_SYS_UN_H)
44 #if !defined (AF_LOCAL) && defined (AF_UNIX)
45 #define AF_LOCAL AF_UNIX
46 #endif
47 #ifdef AF_LOCAL
48 #define HAVE_LOCAL_SOCKETS
49 #include <sys/un.h>
50 #endif
51 #endif
53 #include <sys/ioctl.h>
54 #if defined (HAVE_NET_IF_H)
55 #include <net/if.h>
56 #endif /* HAVE_NET_IF_H */
58 #if defined (HAVE_IFADDRS_H)
59 /* Must be after net/if.h */
60 #include <ifaddrs.h>
62 /* We only use structs from this header when we use getifaddrs. */
63 #if defined (HAVE_NET_IF_DL_H)
64 #include <net/if_dl.h>
65 #endif
67 #endif
69 #ifdef NEED_BSDTTY
70 #include <bsdtty.h>
71 #endif
73 #ifdef USG5_4
74 # include <sys/stream.h>
75 # include <sys/stropts.h>
76 #endif
78 #ifdef HAVE_RES_INIT
79 #include <arpa/nameser.h>
80 #include <resolv.h>
81 #endif
83 #ifdef HAVE_UTIL_H
84 #include <util.h>
85 #endif
87 #ifdef HAVE_PTY_H
88 #include <pty.h>
89 #endif
91 #include <c-ctype.h>
92 #include <sig2str.h>
93 #include <verify.h>
95 #endif /* subprocesses */
97 #include "systime.h"
98 #include "systty.h"
100 #include "window.h"
101 #include "character.h"
102 #include "buffer.h"
103 #include "coding.h"
104 #include "process.h"
105 #include "frame.h"
106 #include "termhooks.h"
107 #include "termopts.h"
108 #include "commands.h"
109 #include "keyboard.h"
110 #include "blockinput.h"
111 #include "dispextern.h"
112 #include "composite.h"
113 #include "atimer.h"
114 #include "sysselect.h"
115 #include "syssignal.h"
116 #include "syswait.h"
117 #ifdef HAVE_GNUTLS
118 #include "gnutls.h"
119 #endif
121 #ifdef HAVE_WINDOW_SYSTEM
122 #include TERM_HEADER
123 #endif /* HAVE_WINDOW_SYSTEM */
125 #ifdef HAVE_GLIB
126 #include "xgselect.h"
127 #ifndef WINDOWSNT
128 #include <glib.h>
129 #endif
130 #endif
132 #ifdef WINDOWSNT
133 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
134 struct timespec *, void *);
135 #endif
137 #ifndef SOCK_CLOEXEC
138 # define SOCK_CLOEXEC 0
139 #endif
141 #ifndef HAVE_ACCEPT4
143 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
145 static int
146 close_on_exec (int fd)
148 if (0 <= fd)
149 fcntl (fd, F_SETFD, FD_CLOEXEC);
150 return fd;
153 static int
154 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
156 return close_on_exec (accept (sockfd, addr, addrlen));
159 static int
160 process_socket (int domain, int type, int protocol)
162 return close_on_exec (socket (domain, type, protocol));
164 # undef socket
165 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
166 #endif
168 /* Work around GCC 4.7.0 bug with strict overflow checking; see
169 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
170 These lines can be removed once the GCC bug is fixed. */
171 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
172 # pragma GCC diagnostic ignored "-Wstrict-overflow"
173 #endif
175 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
176 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
177 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
178 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
179 Lisp_Object QCname, QCtype;
181 /* True if keyboard input is on hold, zero otherwise. */
183 static bool kbd_is_on_hold;
185 /* Nonzero means don't run process sentinels. This is used
186 when exiting. */
187 bool inhibit_sentinels;
189 #ifdef subprocesses
191 Lisp_Object Qprocessp;
192 static Lisp_Object Qrun, Qstop, Qsignal;
193 static Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
194 Lisp_Object Qlocal;
195 static Lisp_Object Qipv4, Qdatagram, Qseqpacket;
196 static Lisp_Object Qreal, Qnetwork, Qserial;
197 #ifdef AF_INET6
198 static Lisp_Object Qipv6;
199 #endif
200 static Lisp_Object QCport, QCprocess;
201 Lisp_Object QCspeed;
202 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
203 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
204 static Lisp_Object QCbuffer, QChost, QCservice;
205 static Lisp_Object QClocal, QCremote, QCcoding;
206 static Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
207 static Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
208 static Lisp_Object Qlast_nonmenu_event;
209 static Lisp_Object Qinternal_default_process_sentinel;
210 static Lisp_Object Qinternal_default_process_filter;
212 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
213 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
214 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
215 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
217 /* Number of events of change of status of a process. */
218 static EMACS_INT process_tick;
219 /* Number of events for which the user or sentinel has been notified. */
220 static EMACS_INT update_tick;
222 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
224 /* Only W32 has this, it really means that select can't take write mask. */
225 #ifdef BROKEN_NON_BLOCKING_CONNECT
226 #undef NON_BLOCKING_CONNECT
227 #define SELECT_CANT_DO_WRITE_MASK
228 #else
229 #ifndef NON_BLOCKING_CONNECT
230 #ifdef HAVE_SELECT
231 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
232 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
233 #define NON_BLOCKING_CONNECT
234 #endif /* EWOULDBLOCK || EINPROGRESS */
235 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
236 #endif /* HAVE_SELECT */
237 #endif /* NON_BLOCKING_CONNECT */
238 #endif /* BROKEN_NON_BLOCKING_CONNECT */
240 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
241 this system. We need to read full packets, so we need a
242 "non-destructive" select. So we require either native select,
243 or emulation of select using FIONREAD. */
245 #ifndef BROKEN_DATAGRAM_SOCKETS
246 # if defined HAVE_SELECT || defined USABLE_FIONREAD
247 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
248 # define DATAGRAM_SOCKETS
249 # endif
250 # endif
251 #endif
253 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
254 # define HAVE_SEQPACKET
255 #endif
257 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
258 #define ADAPTIVE_READ_BUFFERING
259 #endif
261 #ifdef ADAPTIVE_READ_BUFFERING
262 #define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_RESOLUTION / 100)
263 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
264 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
266 /* Number of processes which have a non-zero read_output_delay,
267 and therefore might be delayed for adaptive read buffering. */
269 static int process_output_delay_count;
271 /* True if any process has non-nil read_output_skip. */
273 static bool process_output_skip;
275 #else
276 #define process_output_delay_count 0
277 #endif
279 static void create_process (Lisp_Object, char **, Lisp_Object);
280 #ifdef USABLE_SIGIO
281 static bool keyboard_bit_set (fd_set *);
282 #endif
283 static void deactivate_process (Lisp_Object);
284 static void status_notify (struct Lisp_Process *);
285 static int read_process_output (Lisp_Object, int);
286 static void handle_child_signal (int);
287 static void create_pty (Lisp_Object);
289 /* If we support a window system, turn on the code to poll periodically
290 to detect C-g. It isn't actually used when doing interrupt input. */
291 #ifdef HAVE_WINDOW_SYSTEM
292 #define POLL_FOR_INPUT
293 #endif
295 static Lisp_Object get_process (register Lisp_Object name);
296 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
298 /* Mask of bits indicating the descriptors that we wait for input on. */
300 static fd_set input_wait_mask;
302 /* Mask that excludes keyboard input descriptor(s). */
304 static fd_set non_keyboard_wait_mask;
306 /* Mask that excludes process input descriptor(s). */
308 static fd_set non_process_wait_mask;
310 /* Mask for selecting for write. */
312 static fd_set write_mask;
314 #ifdef NON_BLOCKING_CONNECT
315 /* Mask of bits indicating the descriptors that we wait for connect to
316 complete on. Once they complete, they are removed from this mask
317 and added to the input_wait_mask and non_keyboard_wait_mask. */
319 static fd_set connect_wait_mask;
321 /* Number of bits set in connect_wait_mask. */
322 static int num_pending_connects;
323 #endif /* NON_BLOCKING_CONNECT */
325 /* The largest descriptor currently in use for a process object; -1 if none. */
326 static int max_process_desc;
328 /* The largest descriptor currently in use for input; -1 if none. */
329 static int max_input_desc;
331 /* Indexed by descriptor, gives the process (if any) for that descriptor */
332 static Lisp_Object chan_process[FD_SETSIZE];
334 /* Alist of elements (NAME . PROCESS) */
335 static Lisp_Object Vprocess_alist;
337 /* Buffered-ahead input char from process, indexed by channel.
338 -1 means empty (no char is buffered).
339 Used on sys V where the only way to tell if there is any
340 output from the process is to read at least one char.
341 Always -1 on systems that support FIONREAD. */
343 static int proc_buffered_char[FD_SETSIZE];
345 /* Table of `struct coding-system' for each process. */
346 static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
347 static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
349 #ifdef DATAGRAM_SOCKETS
350 /* Table of `partner address' for datagram sockets. */
351 static struct sockaddr_and_len {
352 struct sockaddr *sa;
353 int len;
354 } datagram_address[FD_SETSIZE];
355 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
356 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
357 #else
358 #define DATAGRAM_CHAN_P(chan) (0)
359 #define DATAGRAM_CONN_P(proc) (0)
360 #endif
362 /* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
363 a `for' loop which iterates over processes from Vprocess_alist. */
365 #define FOR_EACH_PROCESS(list_var, proc_var) \
366 FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)
368 /* These setters are used only in this file, so they can be private. */
369 static void
370 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
372 p->buffer = val;
374 static void
375 pset_command (struct Lisp_Process *p, Lisp_Object val)
377 p->command = val;
379 static void
380 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
382 p->decode_coding_system = val;
384 static void
385 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
387 p->decoding_buf = val;
389 static void
390 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
392 p->encode_coding_system = val;
394 static void
395 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
397 p->encoding_buf = val;
399 static void
400 pset_filter (struct Lisp_Process *p, Lisp_Object val)
402 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
404 static void
405 pset_log (struct Lisp_Process *p, Lisp_Object val)
407 p->log = val;
409 static void
410 pset_mark (struct Lisp_Process *p, Lisp_Object val)
412 p->mark = val;
414 static void
415 pset_name (struct Lisp_Process *p, Lisp_Object val)
417 p->name = val;
419 static void
420 pset_plist (struct Lisp_Process *p, Lisp_Object val)
422 p->plist = val;
424 static void
425 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
427 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
429 static void
430 pset_status (struct Lisp_Process *p, Lisp_Object val)
432 p->status = val;
434 static void
435 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
437 p->tty_name = val;
439 static void
440 pset_type (struct Lisp_Process *p, Lisp_Object val)
442 p->type = val;
444 static void
445 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
447 p->write_queue = val;
452 static struct fd_callback_data
454 fd_callback func;
455 void *data;
456 #define FOR_READ 1
457 #define FOR_WRITE 2
458 int condition; /* mask of the defines above. */
459 } fd_callback_info[FD_SETSIZE];
462 /* Add a file descriptor FD to be monitored for when read is possible.
463 When read is possible, call FUNC with argument DATA. */
465 void
466 add_read_fd (int fd, fd_callback func, void *data)
468 eassert (fd < FD_SETSIZE);
469 add_keyboard_wait_descriptor (fd);
471 fd_callback_info[fd].func = func;
472 fd_callback_info[fd].data = data;
473 fd_callback_info[fd].condition |= FOR_READ;
476 /* Stop monitoring file descriptor FD for when read is possible. */
478 void
479 delete_read_fd (int fd)
481 eassert (fd < FD_SETSIZE);
482 delete_keyboard_wait_descriptor (fd);
484 fd_callback_info[fd].condition &= ~FOR_READ;
485 if (fd_callback_info[fd].condition == 0)
487 fd_callback_info[fd].func = 0;
488 fd_callback_info[fd].data = 0;
492 /* Add a file descriptor FD to be monitored for when write is possible.
493 When write is possible, call FUNC with argument DATA. */
495 void
496 add_write_fd (int fd, fd_callback func, void *data)
498 eassert (fd < FD_SETSIZE);
499 FD_SET (fd, &write_mask);
500 if (fd > max_input_desc)
501 max_input_desc = fd;
503 fd_callback_info[fd].func = func;
504 fd_callback_info[fd].data = data;
505 fd_callback_info[fd].condition |= FOR_WRITE;
508 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
510 static void
511 delete_input_desc (int fd)
513 if (fd == max_input_desc)
516 fd--;
517 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
518 || FD_ISSET (fd, &write_mask)));
520 max_input_desc = fd;
524 /* Stop monitoring file descriptor FD for when write is possible. */
526 void
527 delete_write_fd (int fd)
529 eassert (fd < FD_SETSIZE);
530 FD_CLR (fd, &write_mask);
531 fd_callback_info[fd].condition &= ~FOR_WRITE;
532 if (fd_callback_info[fd].condition == 0)
534 fd_callback_info[fd].func = 0;
535 fd_callback_info[fd].data = 0;
536 delete_input_desc (fd);
541 /* Compute the Lisp form of the process status, p->status, from
542 the numeric status that was returned by `wait'. */
544 static Lisp_Object status_convert (int);
546 static void
547 update_status (struct Lisp_Process *p)
549 eassert (p->raw_status_new);
550 pset_status (p, status_convert (p->raw_status));
551 p->raw_status_new = 0;
554 /* Convert a process status word in Unix format to
555 the list that we use internally. */
557 static Lisp_Object
558 status_convert (int w)
560 if (WIFSTOPPED (w))
561 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
562 else if (WIFEXITED (w))
563 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
564 WCOREDUMP (w) ? Qt : Qnil));
565 else if (WIFSIGNALED (w))
566 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
567 WCOREDUMP (w) ? Qt : Qnil));
568 else
569 return Qrun;
572 /* Given a status-list, extract the three pieces of information
573 and store them individually through the three pointers. */
575 static void
576 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
578 Lisp_Object tem;
580 if (SYMBOLP (l))
582 *symbol = l;
583 *code = 0;
584 *coredump = 0;
586 else
588 *symbol = XCAR (l);
589 tem = XCDR (l);
590 *code = XFASTINT (XCAR (tem));
591 tem = XCDR (tem);
592 *coredump = !NILP (tem);
596 /* Return a string describing a process status list. */
598 static Lisp_Object
599 status_message (struct Lisp_Process *p)
601 Lisp_Object status = p->status;
602 Lisp_Object symbol;
603 int code;
604 bool coredump;
605 Lisp_Object string, string2;
607 decode_status (status, &symbol, &code, &coredump);
609 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
611 char const *signame;
612 synchronize_system_messages_locale ();
613 signame = strsignal (code);
614 if (signame == 0)
615 string = build_string ("unknown");
616 else
618 int c1, c2;
620 string = build_unibyte_string (signame);
621 if (! NILP (Vlocale_coding_system))
622 string = (code_convert_string_norecord
623 (string, Vlocale_coding_system, 0));
624 c1 = STRING_CHAR (SDATA (string));
625 c2 = downcase (c1);
626 if (c1 != c2)
627 Faset (string, make_number (0), make_number (c2));
629 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
630 return concat2 (string, string2);
632 else if (EQ (symbol, Qexit))
634 if (NETCONN1_P (p))
635 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
636 if (code == 0)
637 return build_string ("finished\n");
638 string = Fnumber_to_string (make_number (code));
639 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
640 return concat3 (build_string ("exited abnormally with code "),
641 string, string2);
643 else if (EQ (symbol, Qfailed))
645 string = Fnumber_to_string (make_number (code));
646 string2 = build_string ("\n");
647 return concat3 (build_string ("failed with code "),
648 string, string2);
650 else
651 return Fcopy_sequence (Fsymbol_name (symbol));
654 enum { PTY_NAME_SIZE = 24 };
656 /* Open an available pty, returning a file descriptor.
657 Store into PTY_NAME the file name of the terminal corresponding to the pty.
658 Return -1 on failure. */
660 static int
661 allocate_pty (char pty_name[PTY_NAME_SIZE])
663 #ifdef HAVE_PTYS
664 int fd;
666 #ifdef PTY_ITERATION
667 PTY_ITERATION
668 #else
669 register int c, i;
670 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
671 for (i = 0; i < 16; i++)
672 #endif
674 #ifdef PTY_NAME_SPRINTF
675 PTY_NAME_SPRINTF
676 #else
677 sprintf (pty_name, "/dev/pty%c%x", c, i);
678 #endif /* no PTY_NAME_SPRINTF */
680 #ifdef PTY_OPEN
681 PTY_OPEN;
682 #else /* no PTY_OPEN */
683 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
684 #endif /* no PTY_OPEN */
686 if (fd >= 0)
688 #ifdef PTY_OPEN
689 /* Set FD's close-on-exec flag. This is needed even if
690 PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
691 doesn't require support for that combination.
692 Multithreaded platforms where posix_openpt ignores
693 O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
694 have a race condition between the PTY_OPEN and here. */
695 fcntl (fd, F_SETFD, FD_CLOEXEC);
696 #endif
697 /* check to make certain that both sides are available
698 this avoids a nasty yet stupid bug in rlogins */
699 #ifdef PTY_TTY_NAME_SPRINTF
700 PTY_TTY_NAME_SPRINTF
701 #else
702 sprintf (pty_name, "/dev/tty%c%x", c, i);
703 #endif /* no PTY_TTY_NAME_SPRINTF */
704 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
706 emacs_close (fd);
707 # ifndef __sgi
708 continue;
709 # else
710 return -1;
711 # endif /* __sgi */
713 setup_pty (fd);
714 return fd;
717 #endif /* HAVE_PTYS */
718 return -1;
721 static Lisp_Object
722 make_process (Lisp_Object name)
724 register Lisp_Object val, tem, name1;
725 register struct Lisp_Process *p;
726 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
727 printmax_t i;
729 p = allocate_process ();
730 /* Initialize Lisp data. Note that allocate_process initializes all
731 Lisp data to nil, so do it only for slots which should not be nil. */
732 pset_status (p, Qrun);
733 pset_mark (p, Fmake_marker ());
735 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
736 non-Lisp data, so do it only for slots which should not be zero. */
737 p->infd = -1;
738 p->outfd = -1;
739 for (i = 0; i < PROCESS_OPEN_FDS; i++)
740 p->open_fd[i] = -1;
742 #ifdef HAVE_GNUTLS
743 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
744 #endif
746 /* If name is already in use, modify it until it is unused. */
748 name1 = name;
749 for (i = 1; ; i++)
751 tem = Fget_process (name1);
752 if (NILP (tem)) break;
753 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
755 name = name1;
756 pset_name (p, name);
757 pset_sentinel (p, Qinternal_default_process_sentinel);
758 pset_filter (p, Qinternal_default_process_filter);
759 XSETPROCESS (val, p);
760 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
761 return val;
764 static void
765 remove_process (register Lisp_Object proc)
767 register Lisp_Object pair;
769 pair = Frassq (proc, Vprocess_alist);
770 Vprocess_alist = Fdelq (pair, Vprocess_alist);
772 deactivate_process (proc);
776 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
777 doc: /* Return t if OBJECT is a process. */)
778 (Lisp_Object object)
780 return PROCESSP (object) ? Qt : Qnil;
783 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
784 doc: /* Return the process named NAME, or nil if there is none. */)
785 (register Lisp_Object name)
787 if (PROCESSP (name))
788 return name;
789 CHECK_STRING (name);
790 return Fcdr (Fassoc (name, Vprocess_alist));
793 /* This is how commands for the user decode process arguments. It
794 accepts a process, a process name, a buffer, a buffer name, or nil.
795 Buffers denote the first process in the buffer, and nil denotes the
796 current buffer. */
798 static Lisp_Object
799 get_process (register Lisp_Object name)
801 register Lisp_Object proc, obj;
802 if (STRINGP (name))
804 obj = Fget_process (name);
805 if (NILP (obj))
806 obj = Fget_buffer (name);
807 if (NILP (obj))
808 error ("Process %s does not exist", SDATA (name));
810 else if (NILP (name))
811 obj = Fcurrent_buffer ();
812 else
813 obj = name;
815 /* Now obj should be either a buffer object or a process object.
817 if (BUFFERP (obj))
819 proc = Fget_buffer_process (obj);
820 if (NILP (proc))
821 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
823 else
825 CHECK_PROCESS (obj);
826 proc = obj;
828 return proc;
832 /* Fdelete_process promises to immediately forget about the process, but in
833 reality, Emacs needs to remember those processes until they have been
834 treated by the SIGCHLD handler and waitpid has been invoked on them;
835 otherwise they might fill up the kernel's process table.
837 Some processes created by call-process are also put onto this list.
839 Members of this list are (process-ID . filename) pairs. The
840 process-ID is a number; the filename, if a string, is a file that
841 needs to be removed after the process exits. */
842 static Lisp_Object deleted_pid_list;
844 void
845 record_deleted_pid (pid_t pid, Lisp_Object filename)
847 deleted_pid_list = Fcons (Fcons (make_fixnum_or_float (pid), filename),
848 /* GC treated elements set to nil. */
849 Fdelq (Qnil, deleted_pid_list));
853 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
854 doc: /* Delete PROCESS: kill it and forget about it immediately.
855 PROCESS may be a process, a buffer, the name of a process or buffer, or
856 nil, indicating the current buffer's process. */)
857 (register Lisp_Object process)
859 register struct Lisp_Process *p;
861 process = get_process (process);
862 p = XPROCESS (process);
864 p->raw_status_new = 0;
865 if (NETCONN1_P (p) || SERIALCONN1_P (p))
867 pset_status (p, list2 (Qexit, make_number (0)));
868 p->tick = ++process_tick;
869 status_notify (p);
870 redisplay_preserve_echo_area (13);
872 else
874 if (p->alive)
875 record_kill_process (p, Qnil);
877 if (p->infd >= 0)
879 /* Update P's status, since record_kill_process will make the
880 SIGCHLD handler update deleted_pid_list, not *P. */
881 Lisp_Object symbol;
882 if (p->raw_status_new)
883 update_status (p);
884 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
885 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
886 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
888 p->tick = ++process_tick;
889 status_notify (p);
890 redisplay_preserve_echo_area (13);
893 remove_process (process);
894 return Qnil;
897 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
898 doc: /* Return the status of PROCESS.
899 The returned value is one of the following symbols:
900 run -- for a process that is running.
901 stop -- for a process stopped but continuable.
902 exit -- for a process that has exited.
903 signal -- for a process that has got a fatal signal.
904 open -- for a network stream connection that is open.
905 listen -- for a network stream server that is listening.
906 closed -- for a network stream connection that is closed.
907 connect -- when waiting for a non-blocking connection to complete.
908 failed -- when a non-blocking connection has failed.
909 nil -- if arg is a process name and no such process exists.
910 PROCESS may be a process, a buffer, the name of a process, or
911 nil, indicating the current buffer's process. */)
912 (register Lisp_Object process)
914 register struct Lisp_Process *p;
915 register Lisp_Object status;
917 if (STRINGP (process))
918 process = Fget_process (process);
919 else
920 process = get_process (process);
922 if (NILP (process))
923 return process;
925 p = XPROCESS (process);
926 if (p->raw_status_new)
927 update_status (p);
928 status = p->status;
929 if (CONSP (status))
930 status = XCAR (status);
931 if (NETCONN1_P (p) || SERIALCONN1_P (p))
933 if (EQ (status, Qexit))
934 status = Qclosed;
935 else if (EQ (p->command, Qt))
936 status = Qstop;
937 else if (EQ (status, Qrun))
938 status = Qopen;
940 return status;
943 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
944 1, 1, 0,
945 doc: /* Return the exit status of PROCESS or the signal number that killed it.
946 If PROCESS has not yet exited or died, return 0. */)
947 (register Lisp_Object process)
949 CHECK_PROCESS (process);
950 if (XPROCESS (process)->raw_status_new)
951 update_status (XPROCESS (process));
952 if (CONSP (XPROCESS (process)->status))
953 return XCAR (XCDR (XPROCESS (process)->status));
954 return make_number (0);
957 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
958 doc: /* Return the process id of PROCESS.
959 This is the pid of the external process which PROCESS uses or talks to.
960 For a network connection, this value is nil. */)
961 (register Lisp_Object process)
963 pid_t pid;
965 CHECK_PROCESS (process);
966 pid = XPROCESS (process)->pid;
967 return (pid ? make_fixnum_or_float (pid) : Qnil);
970 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
971 doc: /* Return the name of PROCESS, as a string.
972 This is the name of the program invoked in PROCESS,
973 possibly modified to make it unique among process names. */)
974 (register Lisp_Object process)
976 CHECK_PROCESS (process);
977 return XPROCESS (process)->name;
980 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
981 doc: /* Return the command that was executed to start PROCESS.
982 This is a list of strings, the first string being the program executed
983 and the rest of the strings being the arguments given to it.
984 For a network or serial process, this is nil (process is running) or t
985 \(process is stopped). */)
986 (register Lisp_Object process)
988 CHECK_PROCESS (process);
989 return XPROCESS (process)->command;
992 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
993 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
994 This is the terminal that the process itself reads and writes on,
995 not the name of the pty that Emacs uses to talk with that terminal. */)
996 (register Lisp_Object process)
998 CHECK_PROCESS (process);
999 return XPROCESS (process)->tty_name;
1002 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
1003 2, 2, 0,
1004 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
1005 Return BUFFER. */)
1006 (register Lisp_Object process, Lisp_Object buffer)
1008 struct Lisp_Process *p;
1010 CHECK_PROCESS (process);
1011 if (!NILP (buffer))
1012 CHECK_BUFFER (buffer);
1013 p = XPROCESS (process);
1014 pset_buffer (p, buffer);
1015 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1016 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
1017 setup_process_coding_systems (process);
1018 return buffer;
1021 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1022 1, 1, 0,
1023 doc: /* Return the buffer PROCESS is associated with.
1024 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
1025 (register Lisp_Object process)
1027 CHECK_PROCESS (process);
1028 return XPROCESS (process)->buffer;
1031 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1032 1, 1, 0,
1033 doc: /* Return the marker for the end of the last output from PROCESS. */)
1034 (register Lisp_Object process)
1036 CHECK_PROCESS (process);
1037 return XPROCESS (process)->mark;
1040 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1041 2, 2, 0,
1042 doc: /* Give PROCESS the filter function FILTER; nil means default.
1043 A value of t means stop accepting output from the process.
1045 When a process has a non-default filter, its buffer is not used for output.
1046 Instead, each time it does output, the entire string of output is
1047 passed to the filter.
1049 The filter gets two arguments: the process and the string of output.
1050 The string argument is normally a multibyte string, except:
1051 - if the process' input coding system is no-conversion or raw-text,
1052 it is a unibyte string (the non-converted input), or else
1053 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1054 string (the result of converting the decoded input multibyte
1055 string to unibyte with `string-make-unibyte'). */)
1056 (register Lisp_Object process, Lisp_Object filter)
1058 struct Lisp_Process *p;
1060 CHECK_PROCESS (process);
1061 p = XPROCESS (process);
1063 /* Don't signal an error if the process' input file descriptor
1064 is closed. This could make debugging Lisp more difficult,
1065 for example when doing something like
1067 (setq process (start-process ...))
1068 (debug)
1069 (set-process-filter process ...) */
1071 if (NILP (filter))
1072 filter = Qinternal_default_process_filter;
1074 if (p->infd >= 0)
1076 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1078 FD_CLR (p->infd, &input_wait_mask);
1079 FD_CLR (p->infd, &non_keyboard_wait_mask);
1081 else if (EQ (p->filter, Qt)
1082 /* Network or serial process not stopped: */
1083 && !EQ (p->command, Qt))
1085 FD_SET (p->infd, &input_wait_mask);
1086 FD_SET (p->infd, &non_keyboard_wait_mask);
1090 pset_filter (p, filter);
1091 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1092 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1093 setup_process_coding_systems (process);
1094 return filter;
1097 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1098 1, 1, 0,
1099 doc: /* Return the filter function of PROCESS.
1100 See `set-process-filter' for more info on filter functions. */)
1101 (register Lisp_Object process)
1103 CHECK_PROCESS (process);
1104 return XPROCESS (process)->filter;
1107 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1108 2, 2, 0,
1109 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1110 The sentinel is called as a function when the process changes state.
1111 It gets two arguments: the process, and a string describing the change. */)
1112 (register Lisp_Object process, Lisp_Object sentinel)
1114 struct Lisp_Process *p;
1116 CHECK_PROCESS (process);
1117 p = XPROCESS (process);
1119 if (NILP (sentinel))
1120 sentinel = Qinternal_default_process_sentinel;
1122 pset_sentinel (p, sentinel);
1123 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1124 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1125 return sentinel;
1128 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1129 1, 1, 0,
1130 doc: /* Return the sentinel of PROCESS.
1131 See `set-process-sentinel' for more info on sentinels. */)
1132 (register Lisp_Object process)
1134 CHECK_PROCESS (process);
1135 return XPROCESS (process)->sentinel;
1138 DEFUN ("set-process-window-size", Fset_process_window_size,
1139 Sset_process_window_size, 3, 3, 0,
1140 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1141 (Lisp_Object process, Lisp_Object height, Lisp_Object width)
1143 CHECK_PROCESS (process);
1145 /* All known platforms store window sizes as 'unsigned short'. */
1146 CHECK_RANGED_INTEGER (height, 0, USHRT_MAX);
1147 CHECK_RANGED_INTEGER (width, 0, USHRT_MAX);
1149 if (XPROCESS (process)->infd < 0
1150 || (set_window_size (XPROCESS (process)->infd,
1151 XINT (height), XINT (width))
1152 < 0))
1153 return Qnil;
1154 else
1155 return Qt;
1158 DEFUN ("set-process-inherit-coding-system-flag",
1159 Fset_process_inherit_coding_system_flag,
1160 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1161 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1162 If the second argument FLAG is non-nil, then the variable
1163 `buffer-file-coding-system' of the buffer associated with PROCESS
1164 will be bound to the value of the coding system used to decode
1165 the process output.
1167 This is useful when the coding system specified for the process buffer
1168 leaves either the character code conversion or the end-of-line conversion
1169 unspecified, or if the coding system used to decode the process output
1170 is more appropriate for saving the process buffer.
1172 Binding the variable `inherit-process-coding-system' to non-nil before
1173 starting the process is an alternative way of setting the inherit flag
1174 for the process which will run.
1176 This function returns FLAG. */)
1177 (register Lisp_Object process, Lisp_Object flag)
1179 CHECK_PROCESS (process);
1180 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1181 return flag;
1184 DEFUN ("set-process-query-on-exit-flag",
1185 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1186 2, 2, 0,
1187 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1188 If the second argument FLAG is non-nil, Emacs will query the user before
1189 exiting or killing a buffer if PROCESS is running. This function
1190 returns FLAG. */)
1191 (register Lisp_Object process, Lisp_Object flag)
1193 CHECK_PROCESS (process);
1194 XPROCESS (process)->kill_without_query = NILP (flag);
1195 return flag;
1198 DEFUN ("process-query-on-exit-flag",
1199 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1200 1, 1, 0,
1201 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1202 (register Lisp_Object process)
1204 CHECK_PROCESS (process);
1205 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1208 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1209 1, 2, 0,
1210 doc: /* Return the contact info of PROCESS; t for a real child.
1211 For a network or serial connection, the value depends on the optional
1212 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1213 SERVICE) for a network connection or (PORT SPEED) for a serial
1214 connection. If KEY is t, the complete contact information for the
1215 connection is returned, else the specific value for the keyword KEY is
1216 returned. See `make-network-process' or `make-serial-process' for a
1217 list of keywords. */)
1218 (register Lisp_Object process, Lisp_Object key)
1220 Lisp_Object contact;
1222 CHECK_PROCESS (process);
1223 contact = XPROCESS (process)->childp;
1225 #ifdef DATAGRAM_SOCKETS
1226 if (DATAGRAM_CONN_P (process)
1227 && (EQ (key, Qt) || EQ (key, QCremote)))
1228 contact = Fplist_put (contact, QCremote,
1229 Fprocess_datagram_address (process));
1230 #endif
1232 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1233 return contact;
1234 if (NILP (key) && NETCONN_P (process))
1235 return list2 (Fplist_get (contact, QChost),
1236 Fplist_get (contact, QCservice));
1237 if (NILP (key) && SERIALCONN_P (process))
1238 return list2 (Fplist_get (contact, QCport),
1239 Fplist_get (contact, QCspeed));
1240 return Fplist_get (contact, key);
1243 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1244 1, 1, 0,
1245 doc: /* Return the plist of PROCESS. */)
1246 (register Lisp_Object process)
1248 CHECK_PROCESS (process);
1249 return XPROCESS (process)->plist;
1252 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1253 2, 2, 0,
1254 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1255 (register Lisp_Object process, Lisp_Object plist)
1257 CHECK_PROCESS (process);
1258 CHECK_LIST (plist);
1260 pset_plist (XPROCESS (process), plist);
1261 return plist;
1264 #if 0 /* Turned off because we don't currently record this info
1265 in the process. Perhaps add it. */
1266 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1267 doc: /* Return the connection type of PROCESS.
1268 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1269 a socket connection. */)
1270 (Lisp_Object process)
1272 return XPROCESS (process)->type;
1274 #endif
1276 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1277 doc: /* Return the connection type of PROCESS.
1278 The value is either the symbol `real', `network', or `serial'.
1279 PROCESS may be a process, a buffer, the name of a process or buffer, or
1280 nil, indicating the current buffer's process. */)
1281 (Lisp_Object process)
1283 Lisp_Object proc;
1284 proc = get_process (process);
1285 return XPROCESS (proc)->type;
1288 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1289 1, 2, 0,
1290 doc: /* Convert network ADDRESS from internal format to a string.
1291 A 4 or 5 element vector represents an IPv4 address (with port number).
1292 An 8 or 9 element vector represents an IPv6 address (with port number).
1293 If optional second argument OMIT-PORT is non-nil, don't include a port
1294 number in the string, even when present in ADDRESS.
1295 Returns nil if format of ADDRESS is invalid. */)
1296 (Lisp_Object address, Lisp_Object omit_port)
1298 if (NILP (address))
1299 return Qnil;
1301 if (STRINGP (address)) /* AF_LOCAL */
1302 return address;
1304 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1306 register struct Lisp_Vector *p = XVECTOR (address);
1307 ptrdiff_t size = p->header.size;
1308 Lisp_Object args[10];
1309 int nargs, i;
1311 if (size == 4 || (size == 5 && !NILP (omit_port)))
1313 args[0] = build_string ("%d.%d.%d.%d");
1314 nargs = 4;
1316 else if (size == 5)
1318 args[0] = build_string ("%d.%d.%d.%d:%d");
1319 nargs = 5;
1321 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1323 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1324 nargs = 8;
1326 else if (size == 9)
1328 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1329 nargs = 9;
1331 else
1332 return Qnil;
1334 for (i = 0; i < nargs; i++)
1336 if (! RANGED_INTEGERP (0, p->u.contents[i], 65535))
1337 return Qnil;
1339 if (nargs <= 5 /* IPv4 */
1340 && i < 4 /* host, not port */
1341 && XINT (p->u.contents[i]) > 255)
1342 return Qnil;
1344 args[i+1] = p->u.contents[i];
1347 return Fformat (nargs+1, args);
1350 if (CONSP (address))
1352 Lisp_Object args[2];
1353 args[0] = build_string ("<Family %d>");
1354 args[1] = Fcar (address);
1355 return Fformat (2, args);
1358 return Qnil;
1361 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1362 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1363 (void)
1365 return Fmapcar (Qcdr, Vprocess_alist);
1368 /* Starting asynchronous inferior processes. */
1370 static void start_process_unwind (Lisp_Object proc);
1372 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1373 doc: /* Start a program in a subprocess. Return the process object for it.
1374 NAME is name for process. It is modified if necessary to make it unique.
1375 BUFFER is the buffer (or buffer name) to associate with the process.
1377 Process output (both standard output and standard error streams) goes
1378 at end of BUFFER, unless you specify an output stream or filter
1379 function to handle the output. BUFFER may also be nil, meaning that
1380 this process is not associated with any buffer.
1382 PROGRAM is the program file name. It is searched for in `exec-path'
1383 (which see). If nil, just associate a pty with the buffer. Remaining
1384 arguments are strings to give program as arguments.
1386 If you want to separate standard output from standard error, invoke
1387 the command through a shell and redirect one of them using the shell
1388 syntax.
1390 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1391 (ptrdiff_t nargs, Lisp_Object *args)
1393 Lisp_Object buffer, name, program, proc, current_dir, tem;
1394 register unsigned char **new_argv;
1395 ptrdiff_t i;
1396 ptrdiff_t count = SPECPDL_INDEX ();
1398 buffer = args[1];
1399 if (!NILP (buffer))
1400 buffer = Fget_buffer_create (buffer);
1402 /* Make sure that the child will be able to chdir to the current
1403 buffer's current directory, or its unhandled equivalent. We
1404 can't just have the child check for an error when it does the
1405 chdir, since it's in a vfork.
1407 We have to GCPRO around this because Fexpand_file_name and
1408 Funhandled_file_name_directory might call a file name handling
1409 function. The argument list is protected by the caller, so all
1410 we really have to worry about is buffer. */
1412 struct gcpro gcpro1;
1413 GCPRO1 (buffer);
1414 current_dir = encode_current_directory ();
1415 UNGCPRO;
1418 name = args[0];
1419 CHECK_STRING (name);
1421 program = args[2];
1423 if (!NILP (program))
1424 CHECK_STRING (program);
1426 proc = make_process (name);
1427 /* If an error occurs and we can't start the process, we want to
1428 remove it from the process list. This means that each error
1429 check in create_process doesn't need to call remove_process
1430 itself; it's all taken care of here. */
1431 record_unwind_protect (start_process_unwind, proc);
1433 pset_childp (XPROCESS (proc), Qt);
1434 pset_plist (XPROCESS (proc), Qnil);
1435 pset_type (XPROCESS (proc), Qreal);
1436 pset_buffer (XPROCESS (proc), buffer);
1437 pset_sentinel (XPROCESS (proc), Qinternal_default_process_sentinel);
1438 pset_filter (XPROCESS (proc), Qinternal_default_process_filter);
1439 pset_command (XPROCESS (proc), Flist (nargs - 2, args + 2));
1441 #ifdef HAVE_GNUTLS
1442 /* AKA GNUTLS_INITSTAGE(proc). */
1443 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1444 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1445 #endif
1447 #ifdef ADAPTIVE_READ_BUFFERING
1448 XPROCESS (proc)->adaptive_read_buffering
1449 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1450 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1451 #endif
1453 /* Make the process marker point into the process buffer (if any). */
1454 if (BUFFERP (buffer))
1455 set_marker_both (XPROCESS (proc)->mark, buffer,
1456 BUF_ZV (XBUFFER (buffer)),
1457 BUF_ZV_BYTE (XBUFFER (buffer)));
1460 /* Decide coding systems for communicating with the process. Here
1461 we don't setup the structure coding_system nor pay attention to
1462 unibyte mode. They are done in create_process. */
1464 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1465 Lisp_Object coding_systems = Qt;
1466 Lisp_Object val, *args2;
1467 struct gcpro gcpro1, gcpro2;
1469 val = Vcoding_system_for_read;
1470 if (NILP (val))
1472 args2 = alloca ((nargs + 1) * sizeof *args2);
1473 args2[0] = Qstart_process;
1474 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1475 GCPRO2 (proc, current_dir);
1476 if (!NILP (program))
1477 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1478 UNGCPRO;
1479 if (CONSP (coding_systems))
1480 val = XCAR (coding_systems);
1481 else if (CONSP (Vdefault_process_coding_system))
1482 val = XCAR (Vdefault_process_coding_system);
1484 pset_decode_coding_system (XPROCESS (proc), val);
1486 val = Vcoding_system_for_write;
1487 if (NILP (val))
1489 if (EQ (coding_systems, Qt))
1491 args2 = alloca ((nargs + 1) * sizeof *args2);
1492 args2[0] = Qstart_process;
1493 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1494 GCPRO2 (proc, current_dir);
1495 if (!NILP (program))
1496 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1497 UNGCPRO;
1499 if (CONSP (coding_systems))
1500 val = XCDR (coding_systems);
1501 else if (CONSP (Vdefault_process_coding_system))
1502 val = XCDR (Vdefault_process_coding_system);
1504 pset_encode_coding_system (XPROCESS (proc), val);
1505 /* Note: At this moment, the above coding system may leave
1506 text-conversion or eol-conversion unspecified. They will be
1507 decided after we read output from the process and decode it by
1508 some coding system, or just before we actually send a text to
1509 the process. */
1513 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1514 XPROCESS (proc)->decoding_carryover = 0;
1515 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1517 XPROCESS (proc)->inherit_coding_system_flag
1518 = !(NILP (buffer) || !inherit_process_coding_system);
1520 if (!NILP (program))
1522 /* If program file name is not absolute, search our path for it.
1523 Put the name we will really use in TEM. */
1524 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1525 && !(SCHARS (program) > 1
1526 && IS_DEVICE_SEP (SREF (program, 1))))
1528 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1530 tem = Qnil;
1531 GCPRO4 (name, program, buffer, current_dir);
1532 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1533 UNGCPRO;
1534 if (NILP (tem))
1535 report_file_error ("Searching for program", program);
1536 tem = Fexpand_file_name (tem, Qnil);
1538 else
1540 if (!NILP (Ffile_directory_p (program)))
1541 error ("Specified program for new process is a directory");
1542 tem = program;
1545 /* If program file name starts with /: for quoting a magic name,
1546 discard that. */
1547 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1548 && SREF (tem, 1) == ':')
1549 tem = Fsubstring (tem, make_number (2), Qnil);
1552 Lisp_Object arg_encoding = Qnil;
1553 struct gcpro gcpro1;
1554 GCPRO1 (tem);
1556 /* Encode the file name and put it in NEW_ARGV.
1557 That's where the child will use it to execute the program. */
1558 tem = list1 (ENCODE_FILE (tem));
1560 /* Here we encode arguments by the coding system used for sending
1561 data to the process. We don't support using different coding
1562 systems for encoding arguments and for encoding data sent to the
1563 process. */
1565 for (i = 3; i < nargs; i++)
1567 tem = Fcons (args[i], tem);
1568 CHECK_STRING (XCAR (tem));
1569 if (STRING_MULTIBYTE (XCAR (tem)))
1571 if (NILP (arg_encoding))
1572 arg_encoding = (complement_process_encoding_system
1573 (XPROCESS (proc)->encode_coding_system));
1574 XSETCAR (tem,
1575 code_convert_string_norecord
1576 (XCAR (tem), arg_encoding, 1));
1580 UNGCPRO;
1583 /* Now that everything is encoded we can collect the strings into
1584 NEW_ARGV. */
1585 new_argv = alloca ((nargs - 1) * sizeof *new_argv);
1586 new_argv[nargs - 2] = 0;
1588 for (i = nargs - 2; i-- != 0; )
1590 new_argv[i] = SDATA (XCAR (tem));
1591 tem = XCDR (tem);
1594 create_process (proc, (char **) new_argv, current_dir);
1596 else
1597 create_pty (proc);
1599 return unbind_to (count, proc);
1602 /* This function is the unwind_protect form for Fstart_process. If
1603 PROC doesn't have its pid set, then we know someone has signaled
1604 an error and the process wasn't started successfully, so we should
1605 remove it from the process list. */
1606 static void
1607 start_process_unwind (Lisp_Object proc)
1609 if (!PROCESSP (proc))
1610 emacs_abort ();
1612 /* Was PROC started successfully?
1613 -2 is used for a pty with no process, eg for gdb. */
1614 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1615 remove_process (proc);
1618 /* If *FD_ADDR is nonnegative, close it, and mark it as closed. */
1620 static void
1621 close_process_fd (int *fd_addr)
1623 int fd = *fd_addr;
1624 if (0 <= fd)
1626 *fd_addr = -1;
1627 emacs_close (fd);
1631 /* Indexes of file descriptors in open_fds. */
1632 enum
1634 /* The pipe from Emacs to its subprocess. */
1635 SUBPROCESS_STDIN,
1636 WRITE_TO_SUBPROCESS,
1638 /* The main pipe from the subprocess to Emacs. */
1639 READ_FROM_SUBPROCESS,
1640 SUBPROCESS_STDOUT,
1642 /* The pipe from the subprocess to Emacs that is closed when the
1643 subprocess execs. */
1644 READ_FROM_EXEC_MONITOR,
1645 EXEC_MONITOR_OUTPUT
1648 verify (PROCESS_OPEN_FDS == EXEC_MONITOR_OUTPUT + 1);
1650 static void
1651 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1653 struct Lisp_Process *p = XPROCESS (process);
1654 int inchannel, outchannel;
1655 pid_t pid;
1656 int vfork_errno;
1657 int forkin, forkout;
1658 bool pty_flag = 0;
1659 char pty_name[PTY_NAME_SIZE];
1660 Lisp_Object lisp_pty_name = Qnil;
1662 inchannel = outchannel = -1;
1664 if (!NILP (Vprocess_connection_type))
1665 outchannel = inchannel = allocate_pty (pty_name);
1667 if (inchannel >= 0)
1669 p->open_fd[READ_FROM_SUBPROCESS] = inchannel;
1670 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1671 /* On most USG systems it does not work to open the pty's tty here,
1672 then close it and reopen it in the child. */
1673 /* Don't let this terminal become our controlling terminal
1674 (in case we don't have one). */
1675 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1676 if (forkin < 0)
1677 report_file_error ("Opening pty", Qnil);
1678 p->open_fd[SUBPROCESS_STDIN] = forkin;
1679 #else
1680 forkin = forkout = -1;
1681 #endif /* not USG, or USG_SUBTTY_WORKS */
1682 pty_flag = 1;
1683 lisp_pty_name = build_string (pty_name);
1685 else
1687 if (emacs_pipe (p->open_fd + SUBPROCESS_STDIN) != 0
1688 || emacs_pipe (p->open_fd + READ_FROM_SUBPROCESS) != 0)
1689 report_file_error ("Creating pipe", Qnil);
1690 forkin = p->open_fd[SUBPROCESS_STDIN];
1691 outchannel = p->open_fd[WRITE_TO_SUBPROCESS];
1692 inchannel = p->open_fd[READ_FROM_SUBPROCESS];
1693 forkout = p->open_fd[SUBPROCESS_STDOUT];
1696 #ifndef WINDOWSNT
1697 if (emacs_pipe (p->open_fd + READ_FROM_EXEC_MONITOR) != 0)
1698 report_file_error ("Creating pipe", Qnil);
1699 #endif
1701 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1702 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1704 /* Record this as an active process, with its channels. */
1705 chan_process[inchannel] = process;
1706 p->infd = inchannel;
1707 p->outfd = outchannel;
1709 /* Previously we recorded the tty descriptor used in the subprocess.
1710 It was only used for getting the foreground tty process, so now
1711 we just reopen the device (see emacs_get_tty_pgrp) as this is
1712 more portable (see USG_SUBTTY_WORKS above). */
1714 p->pty_flag = pty_flag;
1715 pset_status (p, Qrun);
1717 FD_SET (inchannel, &input_wait_mask);
1718 FD_SET (inchannel, &non_keyboard_wait_mask);
1719 if (inchannel > max_process_desc)
1720 max_process_desc = inchannel;
1722 /* This may signal an error. */
1723 setup_process_coding_systems (process);
1725 block_input ();
1726 block_child_signal ();
1728 #ifndef WINDOWSNT
1729 /* vfork, and prevent local vars from being clobbered by the vfork. */
1731 Lisp_Object volatile current_dir_volatile = current_dir;
1732 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1733 char **volatile new_argv_volatile = new_argv;
1734 int volatile forkin_volatile = forkin;
1735 int volatile forkout_volatile = forkout;
1736 struct Lisp_Process *p_volatile = p;
1738 pid = vfork ();
1740 current_dir = current_dir_volatile;
1741 lisp_pty_name = lisp_pty_name_volatile;
1742 new_argv = new_argv_volatile;
1743 forkin = forkin_volatile;
1744 forkout = forkout_volatile;
1745 p = p_volatile;
1747 pty_flag = p->pty_flag;
1750 if (pid == 0)
1751 #endif /* not WINDOWSNT */
1753 int xforkin = forkin;
1754 int xforkout = forkout;
1756 /* Make the pty be the controlling terminal of the process. */
1757 #ifdef HAVE_PTYS
1758 /* First, disconnect its current controlling terminal. */
1759 /* We tried doing setsid only if pty_flag, but it caused
1760 process_set_signal to fail on SGI when using a pipe. */
1761 setsid ();
1762 /* Make the pty's terminal the controlling terminal. */
1763 if (pty_flag && xforkin >= 0)
1765 #ifdef TIOCSCTTY
1766 /* We ignore the return value
1767 because faith@cs.unc.edu says that is necessary on Linux. */
1768 ioctl (xforkin, TIOCSCTTY, 0);
1769 #endif
1771 #if defined (LDISC1)
1772 if (pty_flag && xforkin >= 0)
1774 struct termios t;
1775 tcgetattr (xforkin, &t);
1776 t.c_lflag = LDISC1;
1777 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1778 emacs_perror ("create_process/tcsetattr LDISC1");
1780 #else
1781 #if defined (NTTYDISC) && defined (TIOCSETD)
1782 if (pty_flag && xforkin >= 0)
1784 /* Use new line discipline. */
1785 int ldisc = NTTYDISC;
1786 ioctl (xforkin, TIOCSETD, &ldisc);
1788 #endif
1789 #endif
1790 #ifdef TIOCNOTTY
1791 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1792 can do TIOCSPGRP only to the process's controlling tty. */
1793 if (pty_flag)
1795 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1796 I can't test it since I don't have 4.3. */
1797 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1798 if (j >= 0)
1800 ioctl (j, TIOCNOTTY, 0);
1801 emacs_close (j);
1804 #endif /* TIOCNOTTY */
1806 #if !defined (DONT_REOPEN_PTY)
1807 /*** There is a suggestion that this ought to be a
1808 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1809 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1810 that system does seem to need this code, even though
1811 both TIOCSCTTY is defined. */
1812 /* Now close the pty (if we had it open) and reopen it.
1813 This makes the pty the controlling terminal of the subprocess. */
1814 if (pty_flag)
1817 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1818 would work? */
1819 if (xforkin >= 0)
1820 emacs_close (xforkin);
1821 xforkout = xforkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1823 if (xforkin < 0)
1825 emacs_perror (SSDATA (lisp_pty_name));
1826 _exit (EXIT_CANCELED);
1830 #endif /* not DONT_REOPEN_PTY */
1832 #ifdef SETUP_SLAVE_PTY
1833 if (pty_flag)
1835 SETUP_SLAVE_PTY;
1837 #endif /* SETUP_SLAVE_PTY */
1838 #endif /* HAVE_PTYS */
1840 signal (SIGINT, SIG_DFL);
1841 signal (SIGQUIT, SIG_DFL);
1843 /* Emacs ignores SIGPIPE, but the child should not. */
1844 signal (SIGPIPE, SIG_DFL);
1846 /* Stop blocking SIGCHLD in the child. */
1847 unblock_child_signal ();
1849 if (pty_flag)
1850 child_setup_tty (xforkout);
1851 #ifdef WINDOWSNT
1852 pid = child_setup (xforkin, xforkout, xforkout, new_argv, 1, current_dir);
1853 #else /* not WINDOWSNT */
1854 child_setup (xforkin, xforkout, xforkout, new_argv, 1, current_dir);
1855 #endif /* not WINDOWSNT */
1858 /* Back in the parent process. */
1860 vfork_errno = errno;
1861 p->pid = pid;
1862 if (pid >= 0)
1863 p->alive = 1;
1865 /* Stop blocking in the parent. */
1866 unblock_child_signal ();
1867 unblock_input ();
1869 if (pid < 0)
1870 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1871 else
1873 /* vfork succeeded. */
1875 /* Close the pipe ends that the child uses, or the child's pty. */
1876 close_process_fd (&p->open_fd[SUBPROCESS_STDIN]);
1877 close_process_fd (&p->open_fd[SUBPROCESS_STDOUT]);
1879 #ifdef WINDOWSNT
1880 register_child (pid, inchannel);
1881 #endif /* WINDOWSNT */
1883 pset_tty_name (p, lisp_pty_name);
1885 #ifndef WINDOWSNT
1886 /* Wait for child_setup to complete in case that vfork is
1887 actually defined as fork. The descriptor
1888 XPROCESS (proc)->open_fd[EXEC_MONITOR_OUTPUT]
1889 of a pipe is closed at the child side either by close-on-exec
1890 on successful execve or the _exit call in child_setup. */
1892 char dummy;
1894 close_process_fd (&p->open_fd[EXEC_MONITOR_OUTPUT]);
1895 emacs_read (p->open_fd[READ_FROM_EXEC_MONITOR], &dummy, 1);
1896 close_process_fd (&p->open_fd[READ_FROM_EXEC_MONITOR]);
1898 #endif
1902 static void
1903 create_pty (Lisp_Object process)
1905 struct Lisp_Process *p = XPROCESS (process);
1906 char pty_name[PTY_NAME_SIZE];
1907 int pty_fd = NILP (Vprocess_connection_type) ? -1 : allocate_pty (pty_name);
1909 if (pty_fd >= 0)
1911 p->open_fd[SUBPROCESS_STDIN] = pty_fd;
1912 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1913 /* On most USG systems it does not work to open the pty's tty here,
1914 then close it and reopen it in the child. */
1915 /* Don't let this terminal become our controlling terminal
1916 (in case we don't have one). */
1917 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1918 if (forkout < 0)
1919 report_file_error ("Opening pty", Qnil);
1920 p->open_fd[WRITE_TO_SUBPROCESS] = forkout;
1921 #if defined (DONT_REOPEN_PTY)
1922 /* In the case that vfork is defined as fork, the parent process
1923 (Emacs) may send some data before the child process completes
1924 tty options setup. So we setup tty before forking. */
1925 child_setup_tty (forkout);
1926 #endif /* DONT_REOPEN_PTY */
1927 #endif /* not USG, or USG_SUBTTY_WORKS */
1929 fcntl (pty_fd, F_SETFL, O_NONBLOCK);
1931 /* Record this as an active process, with its channels.
1932 As a result, child_setup will close Emacs's side of the pipes. */
1933 chan_process[pty_fd] = process;
1934 p->infd = pty_fd;
1935 p->outfd = pty_fd;
1937 /* Previously we recorded the tty descriptor used in the subprocess.
1938 It was only used for getting the foreground tty process, so now
1939 we just reopen the device (see emacs_get_tty_pgrp) as this is
1940 more portable (see USG_SUBTTY_WORKS above). */
1942 p->pty_flag = 1;
1943 pset_status (p, Qrun);
1944 setup_process_coding_systems (process);
1946 FD_SET (pty_fd, &input_wait_mask);
1947 FD_SET (pty_fd, &non_keyboard_wait_mask);
1948 if (pty_fd > max_process_desc)
1949 max_process_desc = pty_fd;
1951 pset_tty_name (p, build_string (pty_name));
1954 p->pid = -2;
1958 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1959 The address family of sa is not included in the result. */
1961 #ifndef WINDOWSNT
1962 static
1963 #endif
1964 Lisp_Object
1965 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
1967 Lisp_Object address;
1968 int i;
1969 unsigned char *cp;
1970 register struct Lisp_Vector *p;
1972 /* Workaround for a bug in getsockname on BSD: Names bound to
1973 sockets in the UNIX domain are inaccessible; getsockname returns
1974 a zero length name. */
1975 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
1976 return empty_unibyte_string;
1978 switch (sa->sa_family)
1980 case AF_INET:
1982 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
1983 len = sizeof (sin->sin_addr) + 1;
1984 address = Fmake_vector (make_number (len), Qnil);
1985 p = XVECTOR (address);
1986 p->u.contents[--len] = make_number (ntohs (sin->sin_port));
1987 cp = (unsigned char *) &sin->sin_addr;
1988 break;
1990 #ifdef AF_INET6
1991 case AF_INET6:
1993 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
1994 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
1995 len = sizeof (sin6->sin6_addr)/2 + 1;
1996 address = Fmake_vector (make_number (len), Qnil);
1997 p = XVECTOR (address);
1998 p->u.contents[--len] = make_number (ntohs (sin6->sin6_port));
1999 for (i = 0; i < len; i++)
2000 p->u.contents[i] = make_number (ntohs (ip6[i]));
2001 return address;
2003 #endif
2004 #ifdef HAVE_LOCAL_SOCKETS
2005 case AF_LOCAL:
2007 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2008 for (i = 0; i < sizeof (sockun->sun_path); i++)
2009 if (sockun->sun_path[i] == 0)
2010 break;
2011 return make_unibyte_string (sockun->sun_path, i);
2013 #endif
2014 default:
2015 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2016 address = Fcons (make_number (sa->sa_family),
2017 Fmake_vector (make_number (len), Qnil));
2018 p = XVECTOR (XCDR (address));
2019 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2020 break;
2023 i = 0;
2024 while (i < len)
2025 p->u.contents[i++] = make_number (*cp++);
2027 return address;
2031 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2033 static int
2034 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2036 register struct Lisp_Vector *p;
2038 if (VECTORP (address))
2040 p = XVECTOR (address);
2041 if (p->header.size == 5)
2043 *familyp = AF_INET;
2044 return sizeof (struct sockaddr_in);
2046 #ifdef AF_INET6
2047 else if (p->header.size == 9)
2049 *familyp = AF_INET6;
2050 return sizeof (struct sockaddr_in6);
2052 #endif
2054 #ifdef HAVE_LOCAL_SOCKETS
2055 else if (STRINGP (address))
2057 *familyp = AF_LOCAL;
2058 return sizeof (struct sockaddr_un);
2060 #endif
2061 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2062 && VECTORP (XCDR (address)))
2064 struct sockaddr *sa;
2065 *familyp = XINT (XCAR (address));
2066 p = XVECTOR (XCDR (address));
2067 return p->header.size + sizeof (sa->sa_family);
2069 return 0;
2072 /* Convert an address object (vector or string) to an internal sockaddr.
2074 The address format has been basically validated by
2075 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2076 it could have come from user data. So if FAMILY is not valid,
2077 we return after zeroing *SA. */
2079 static void
2080 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2082 register struct Lisp_Vector *p;
2083 register unsigned char *cp = NULL;
2084 register int i;
2085 EMACS_INT hostport;
2087 memset (sa, 0, len);
2089 if (VECTORP (address))
2091 p = XVECTOR (address);
2092 if (family == AF_INET)
2094 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2095 len = sizeof (sin->sin_addr) + 1;
2096 hostport = XINT (p->u.contents[--len]);
2097 sin->sin_port = htons (hostport);
2098 cp = (unsigned char *)&sin->sin_addr;
2099 sa->sa_family = family;
2101 #ifdef AF_INET6
2102 else if (family == AF_INET6)
2104 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2105 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2106 len = sizeof (sin6->sin6_addr) + 1;
2107 hostport = XINT (p->u.contents[--len]);
2108 sin6->sin6_port = htons (hostport);
2109 for (i = 0; i < len; i++)
2110 if (INTEGERP (p->u.contents[i]))
2112 int j = XFASTINT (p->u.contents[i]) & 0xffff;
2113 ip6[i] = ntohs (j);
2115 sa->sa_family = family;
2116 return;
2118 #endif
2119 else
2120 return;
2122 else if (STRINGP (address))
2124 #ifdef HAVE_LOCAL_SOCKETS
2125 if (family == AF_LOCAL)
2127 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2128 cp = SDATA (address);
2129 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2130 sockun->sun_path[i] = *cp++;
2131 sa->sa_family = family;
2133 #endif
2134 return;
2136 else
2138 p = XVECTOR (XCDR (address));
2139 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2142 for (i = 0; i < len; i++)
2143 if (INTEGERP (p->u.contents[i]))
2144 *cp++ = XFASTINT (p->u.contents[i]) & 0xff;
2147 #ifdef DATAGRAM_SOCKETS
2148 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2149 1, 1, 0,
2150 doc: /* Get the current datagram address associated with PROCESS. */)
2151 (Lisp_Object process)
2153 int channel;
2155 CHECK_PROCESS (process);
2157 if (!DATAGRAM_CONN_P (process))
2158 return Qnil;
2160 channel = XPROCESS (process)->infd;
2161 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2162 datagram_address[channel].len);
2165 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2166 2, 2, 0,
2167 doc: /* Set the datagram address for PROCESS to ADDRESS.
2168 Returns nil upon error setting address, ADDRESS otherwise. */)
2169 (Lisp_Object process, Lisp_Object address)
2171 int channel;
2172 int family, len;
2174 CHECK_PROCESS (process);
2176 if (!DATAGRAM_CONN_P (process))
2177 return Qnil;
2179 channel = XPROCESS (process)->infd;
2181 len = get_lisp_to_sockaddr_size (address, &family);
2182 if (len == 0 || datagram_address[channel].len != len)
2183 return Qnil;
2184 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2185 return address;
2187 #endif
2190 static const struct socket_options {
2191 /* The name of this option. Should be lowercase version of option
2192 name without SO_ prefix. */
2193 const char *name;
2194 /* Option level SOL_... */
2195 int optlevel;
2196 /* Option number SO_... */
2197 int optnum;
2198 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2199 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2200 } socket_options[] =
2202 #ifdef SO_BINDTODEVICE
2203 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2204 #endif
2205 #ifdef SO_BROADCAST
2206 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2207 #endif
2208 #ifdef SO_DONTROUTE
2209 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2210 #endif
2211 #ifdef SO_KEEPALIVE
2212 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2213 #endif
2214 #ifdef SO_LINGER
2215 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2216 #endif
2217 #ifdef SO_OOBINLINE
2218 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2219 #endif
2220 #ifdef SO_PRIORITY
2221 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2222 #endif
2223 #ifdef SO_REUSEADDR
2224 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2225 #endif
2226 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2229 /* Set option OPT to value VAL on socket S.
2231 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2232 Signals an error if setting a known option fails.
2235 static int
2236 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2238 char *name;
2239 const struct socket_options *sopt;
2240 int ret = 0;
2242 CHECK_SYMBOL (opt);
2244 name = SSDATA (SYMBOL_NAME (opt));
2245 for (sopt = socket_options; sopt->name; sopt++)
2246 if (strcmp (name, sopt->name) == 0)
2247 break;
2249 switch (sopt->opttype)
2251 case SOPT_BOOL:
2253 int optval;
2254 optval = NILP (val) ? 0 : 1;
2255 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2256 &optval, sizeof (optval));
2257 break;
2260 case SOPT_INT:
2262 int optval;
2263 if (TYPE_RANGED_INTEGERP (int, val))
2264 optval = XINT (val);
2265 else
2266 error ("Bad option value for %s", name);
2267 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2268 &optval, sizeof (optval));
2269 break;
2272 #ifdef SO_BINDTODEVICE
2273 case SOPT_IFNAME:
2275 char devname[IFNAMSIZ+1];
2277 /* This is broken, at least in the Linux 2.4 kernel.
2278 To unbind, the arg must be a zero integer, not the empty string.
2279 This should work on all systems. KFS. 2003-09-23. */
2280 memset (devname, 0, sizeof devname);
2281 if (STRINGP (val))
2283 char *arg = SSDATA (val);
2284 int len = min (strlen (arg), IFNAMSIZ);
2285 memcpy (devname, arg, len);
2287 else if (!NILP (val))
2288 error ("Bad option value for %s", name);
2289 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2290 devname, IFNAMSIZ);
2291 break;
2293 #endif
2295 #ifdef SO_LINGER
2296 case SOPT_LINGER:
2298 struct linger linger;
2300 linger.l_onoff = 1;
2301 linger.l_linger = 0;
2302 if (TYPE_RANGED_INTEGERP (int, val))
2303 linger.l_linger = XINT (val);
2304 else
2305 linger.l_onoff = NILP (val) ? 0 : 1;
2306 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2307 &linger, sizeof (linger));
2308 break;
2310 #endif
2312 default:
2313 return 0;
2316 if (ret < 0)
2318 int setsockopt_errno = errno;
2319 report_file_errno ("Cannot set network option", list2 (opt, val),
2320 setsockopt_errno);
2323 return (1 << sopt->optbit);
2327 DEFUN ("set-network-process-option",
2328 Fset_network_process_option, Sset_network_process_option,
2329 3, 4, 0,
2330 doc: /* For network process PROCESS set option OPTION to value VALUE.
2331 See `make-network-process' for a list of options and values.
2332 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2333 OPTION is not a supported option, return nil instead; otherwise return t. */)
2334 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2336 int s;
2337 struct Lisp_Process *p;
2339 CHECK_PROCESS (process);
2340 p = XPROCESS (process);
2341 if (!NETCONN1_P (p))
2342 error ("Process is not a network process");
2344 s = p->infd;
2345 if (s < 0)
2346 error ("Process is not running");
2348 if (set_socket_option (s, option, value))
2350 pset_childp (p, Fplist_put (p->childp, option, value));
2351 return Qt;
2354 if (NILP (no_error))
2355 error ("Unknown or unsupported option");
2357 return Qnil;
2361 DEFUN ("serial-process-configure",
2362 Fserial_process_configure,
2363 Sserial_process_configure,
2364 0, MANY, 0,
2365 doc: /* Configure speed, bytesize, etc. of a serial process.
2367 Arguments are specified as keyword/argument pairs. Attributes that
2368 are not given are re-initialized from the process's current
2369 configuration (available via the function `process-contact') or set to
2370 reasonable default values. The following arguments are defined:
2372 :process PROCESS
2373 :name NAME
2374 :buffer BUFFER
2375 :port PORT
2376 -- Any of these arguments can be given to identify the process that is
2377 to be configured. If none of these arguments is given, the current
2378 buffer's process is used.
2380 :speed SPEED -- SPEED is the speed of the serial port in bits per
2381 second, also called baud rate. Any value can be given for SPEED, but
2382 most serial ports work only at a few defined values between 1200 and
2383 115200, with 9600 being the most common value. If SPEED is nil, the
2384 serial port is not configured any further, i.e., all other arguments
2385 are ignored. This may be useful for special serial ports such as
2386 Bluetooth-to-serial converters which can only be configured through AT
2387 commands. A value of nil for SPEED can be used only when passed
2388 through `make-serial-process' or `serial-term'.
2390 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2391 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2393 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2394 `odd' (use odd parity), or the symbol `even' (use even parity). If
2395 PARITY is not given, no parity is used.
2397 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2398 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2399 is not given or nil, 1 stopbit is used.
2401 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2402 flowcontrol to be used, which is either nil (don't use flowcontrol),
2403 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2404 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2405 flowcontrol is used.
2407 `serial-process-configure' is called by `make-serial-process' for the
2408 initial configuration of the serial port.
2410 Examples:
2412 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2414 \(serial-process-configure
2415 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2417 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2419 usage: (serial-process-configure &rest ARGS) */)
2420 (ptrdiff_t nargs, Lisp_Object *args)
2422 struct Lisp_Process *p;
2423 Lisp_Object contact = Qnil;
2424 Lisp_Object proc = Qnil;
2425 struct gcpro gcpro1;
2427 contact = Flist (nargs, args);
2428 GCPRO1 (contact);
2430 proc = Fplist_get (contact, QCprocess);
2431 if (NILP (proc))
2432 proc = Fplist_get (contact, QCname);
2433 if (NILP (proc))
2434 proc = Fplist_get (contact, QCbuffer);
2435 if (NILP (proc))
2436 proc = Fplist_get (contact, QCport);
2437 proc = get_process (proc);
2438 p = XPROCESS (proc);
2439 if (!EQ (p->type, Qserial))
2440 error ("Not a serial process");
2442 if (NILP (Fplist_get (p->childp, QCspeed)))
2444 UNGCPRO;
2445 return Qnil;
2448 serial_configure (p, contact);
2450 UNGCPRO;
2451 return Qnil;
2454 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2455 0, MANY, 0,
2456 doc: /* Create and return a serial port process.
2458 In Emacs, serial port connections are represented by process objects,
2459 so input and output work as for subprocesses, and `delete-process'
2460 closes a serial port connection. However, a serial process has no
2461 process id, it cannot be signaled, and the status codes are different
2462 from normal processes.
2464 `make-serial-process' creates a process and a buffer, on which you
2465 probably want to use `process-send-string'. Try \\[serial-term] for
2466 an interactive terminal. See below for examples.
2468 Arguments are specified as keyword/argument pairs. The following
2469 arguments are defined:
2471 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2472 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2473 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2474 the backslashes in strings).
2476 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2477 which this function calls.
2479 :name NAME -- NAME is the name of the process. If NAME is not given,
2480 the value of PORT is used.
2482 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2483 with the process. Process output goes at the end of that buffer,
2484 unless you specify an output stream or filter function to handle the
2485 output. If BUFFER is not given, the value of NAME is used.
2487 :coding CODING -- If CODING is a symbol, it specifies the coding
2488 system used for both reading and writing for this process. If CODING
2489 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2490 ENCODING is used for writing.
2492 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2493 the process is running. If BOOL is not given, query before exiting.
2495 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2496 In the stopped state, a serial process does not accept incoming data,
2497 but you can send outgoing data. The stopped state is cleared by
2498 `continue-process' and set by `stop-process'.
2500 :filter FILTER -- Install FILTER as the process filter.
2502 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2504 :plist PLIST -- Install PLIST as the initial plist of the process.
2506 :bytesize
2507 :parity
2508 :stopbits
2509 :flowcontrol
2510 -- This function calls `serial-process-configure' to handle these
2511 arguments.
2513 The original argument list, possibly modified by later configuration,
2514 is available via the function `process-contact'.
2516 Examples:
2518 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2520 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2522 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2524 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2526 usage: (make-serial-process &rest ARGS) */)
2527 (ptrdiff_t nargs, Lisp_Object *args)
2529 int fd = -1;
2530 Lisp_Object proc, contact, port;
2531 struct Lisp_Process *p;
2532 struct gcpro gcpro1;
2533 Lisp_Object name, buffer;
2534 Lisp_Object tem, val;
2535 ptrdiff_t specpdl_count;
2537 if (nargs == 0)
2538 return Qnil;
2540 contact = Flist (nargs, args);
2541 GCPRO1 (contact);
2543 port = Fplist_get (contact, QCport);
2544 if (NILP (port))
2545 error ("No port specified");
2546 CHECK_STRING (port);
2548 if (NILP (Fplist_member (contact, QCspeed)))
2549 error (":speed not specified");
2550 if (!NILP (Fplist_get (contact, QCspeed)))
2551 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2553 name = Fplist_get (contact, QCname);
2554 if (NILP (name))
2555 name = port;
2556 CHECK_STRING (name);
2557 proc = make_process (name);
2558 specpdl_count = SPECPDL_INDEX ();
2559 record_unwind_protect (remove_process, proc);
2560 p = XPROCESS (proc);
2562 fd = serial_open (port);
2563 p->open_fd[SUBPROCESS_STDIN] = fd;
2564 p->infd = fd;
2565 p->outfd = fd;
2566 if (fd > max_process_desc)
2567 max_process_desc = fd;
2568 chan_process[fd] = proc;
2570 buffer = Fplist_get (contact, QCbuffer);
2571 if (NILP (buffer))
2572 buffer = name;
2573 buffer = Fget_buffer_create (buffer);
2574 pset_buffer (p, buffer);
2576 pset_childp (p, contact);
2577 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2578 pset_type (p, Qserial);
2579 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2580 pset_filter (p, Fplist_get (contact, QCfilter));
2581 pset_log (p, Qnil);
2582 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2583 p->kill_without_query = 1;
2584 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2585 pset_command (p, Qt);
2586 eassert (! p->pty_flag);
2588 if (!EQ (p->command, Qt))
2590 FD_SET (fd, &input_wait_mask);
2591 FD_SET (fd, &non_keyboard_wait_mask);
2594 if (BUFFERP (buffer))
2596 set_marker_both (p->mark, buffer,
2597 BUF_ZV (XBUFFER (buffer)),
2598 BUF_ZV_BYTE (XBUFFER (buffer)));
2601 tem = Fplist_member (contact, QCcoding);
2602 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2603 tem = Qnil;
2605 val = Qnil;
2606 if (!NILP (tem))
2608 val = XCAR (XCDR (tem));
2609 if (CONSP (val))
2610 val = XCAR (val);
2612 else if (!NILP (Vcoding_system_for_read))
2613 val = Vcoding_system_for_read;
2614 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2615 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2616 val = Qnil;
2617 pset_decode_coding_system (p, val);
2619 val = Qnil;
2620 if (!NILP (tem))
2622 val = XCAR (XCDR (tem));
2623 if (CONSP (val))
2624 val = XCDR (val);
2626 else if (!NILP (Vcoding_system_for_write))
2627 val = Vcoding_system_for_write;
2628 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2629 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2630 val = Qnil;
2631 pset_encode_coding_system (p, val);
2633 setup_process_coding_systems (proc);
2634 pset_decoding_buf (p, empty_unibyte_string);
2635 p->decoding_carryover = 0;
2636 pset_encoding_buf (p, empty_unibyte_string);
2637 p->inherit_coding_system_flag
2638 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2640 Fserial_process_configure (nargs, args);
2642 specpdl_ptr = specpdl + specpdl_count;
2644 UNGCPRO;
2645 return proc;
2648 /* Create a network stream/datagram client/server process. Treated
2649 exactly like a normal process when reading and writing. Primary
2650 differences are in status display and process deletion. A network
2651 connection has no PID; you cannot signal it. All you can do is
2652 stop/continue it and deactivate/close it via delete-process */
2654 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2655 0, MANY, 0,
2656 doc: /* Create and return a network server or client process.
2658 In Emacs, network connections are represented by process objects, so
2659 input and output work as for subprocesses and `delete-process' closes
2660 a network connection. However, a network process has no process id,
2661 it cannot be signaled, and the status codes are different from normal
2662 processes.
2664 Arguments are specified as keyword/argument pairs. The following
2665 arguments are defined:
2667 :name NAME -- NAME is name for process. It is modified if necessary
2668 to make it unique.
2670 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2671 with the process. Process output goes at end of that buffer, unless
2672 you specify an output stream or filter function to handle the output.
2673 BUFFER may be also nil, meaning that this process is not associated
2674 with any buffer.
2676 :host HOST -- HOST is name of the host to connect to, or its IP
2677 address. The symbol `local' specifies the local host. If specified
2678 for a server process, it must be a valid name or address for the local
2679 host, and only clients connecting to that address will be accepted.
2681 :service SERVICE -- SERVICE is name of the service desired, or an
2682 integer specifying a port number to connect to. If SERVICE is t,
2683 a random port number is selected for the server. (If Emacs was
2684 compiled with getaddrinfo, a port number can also be specified as a
2685 string, e.g. "80", as well as an integer. This is not portable.)
2687 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2688 stream type connection, `datagram' creates a datagram type connection,
2689 `seqpacket' creates a reliable datagram connection.
2691 :family FAMILY -- FAMILY is the address (and protocol) family for the
2692 service specified by HOST and SERVICE. The default (nil) is to use
2693 whatever address family (IPv4 or IPv6) that is defined for the host
2694 and port number specified by HOST and SERVICE. Other address families
2695 supported are:
2696 local -- for a local (i.e. UNIX) address specified by SERVICE.
2697 ipv4 -- use IPv4 address family only.
2698 ipv6 -- use IPv6 address family only.
2700 :local ADDRESS -- ADDRESS is the local address used for the connection.
2701 This parameter is ignored when opening a client process. When specified
2702 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2704 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2705 connection. This parameter is ignored when opening a stream server
2706 process. For a datagram server process, it specifies the initial
2707 setting of the remote datagram address. When specified for a client
2708 process, the FAMILY, HOST, and SERVICE args are ignored.
2710 The format of ADDRESS depends on the address family:
2711 - An IPv4 address is represented as an vector of integers [A B C D P]
2712 corresponding to numeric IP address A.B.C.D and port number P.
2713 - A local address is represented as a string with the address in the
2714 local address space.
2715 - An "unsupported family" address is represented by a cons (F . AV)
2716 where F is the family number and AV is a vector containing the socket
2717 address data with one element per address data byte. Do not rely on
2718 this format in portable code, as it may depend on implementation
2719 defined constants, data sizes, and data structure alignment.
2721 :coding CODING -- If CODING is a symbol, it specifies the coding
2722 system used for both reading and writing for this process. If CODING
2723 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2724 ENCODING is used for writing.
2726 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2727 return without waiting for the connection to complete; instead, the
2728 sentinel function will be called with second arg matching "open" (if
2729 successful) or "failed" when the connect completes. Default is to use
2730 a blocking connect (i.e. wait) for stream type connections.
2732 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2733 running when Emacs is exited.
2735 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2736 In the stopped state, a server process does not accept new
2737 connections, and a client process does not handle incoming traffic.
2738 The stopped state is cleared by `continue-process' and set by
2739 `stop-process'.
2741 :filter FILTER -- Install FILTER as the process filter.
2743 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2744 process filter are multibyte, otherwise they are unibyte.
2745 If this keyword is not specified, the strings are multibyte if
2746 the default value of `enable-multibyte-characters' is non-nil.
2748 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2750 :log LOG -- Install LOG as the server process log function. This
2751 function is called when the server accepts a network connection from a
2752 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2753 is the server process, CLIENT is the new process for the connection,
2754 and MESSAGE is a string.
2756 :plist PLIST -- Install PLIST as the new process' initial plist.
2758 :server QLEN -- if QLEN is non-nil, create a server process for the
2759 specified FAMILY, SERVICE, and connection type (stream or datagram).
2760 If QLEN is an integer, it is used as the max. length of the server's
2761 pending connection queue (also known as the backlog); the default
2762 queue length is 5. Default is to create a client process.
2764 The following network options can be specified for this connection:
2766 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2767 :dontroute BOOL -- Only send to directly connected hosts.
2768 :keepalive BOOL -- Send keep-alive messages on network stream.
2769 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2770 :oobinline BOOL -- Place out-of-band data in receive data stream.
2771 :priority INT -- Set protocol defined priority for sent packets.
2772 :reuseaddr BOOL -- Allow reusing a recently used local address
2773 (this is allowed by default for a server process).
2774 :bindtodevice NAME -- bind to interface NAME. Using this may require
2775 special privileges on some systems.
2777 Consult the relevant system programmer's manual pages for more
2778 information on using these options.
2781 A server process will listen for and accept connections from clients.
2782 When a client connection is accepted, a new network process is created
2783 for the connection with the following parameters:
2785 - The client's process name is constructed by concatenating the server
2786 process' NAME and a client identification string.
2787 - If the FILTER argument is non-nil, the client process will not get a
2788 separate process buffer; otherwise, the client's process buffer is a newly
2789 created buffer named after the server process' BUFFER name or process
2790 NAME concatenated with the client identification string.
2791 - The connection type and the process filter and sentinel parameters are
2792 inherited from the server process' TYPE, FILTER and SENTINEL.
2793 - The client process' contact info is set according to the client's
2794 addressing information (typically an IP address and a port number).
2795 - The client process' plist is initialized from the server's plist.
2797 Notice that the FILTER and SENTINEL args are never used directly by
2798 the server process. Also, the BUFFER argument is not used directly by
2799 the server process, but via the optional :log function, accepted (and
2800 failed) connections may be logged in the server process' buffer.
2802 The original argument list, modified with the actual connection
2803 information, is available via the `process-contact' function.
2805 usage: (make-network-process &rest ARGS) */)
2806 (ptrdiff_t nargs, Lisp_Object *args)
2808 Lisp_Object proc;
2809 Lisp_Object contact;
2810 struct Lisp_Process *p;
2811 #ifdef HAVE_GETADDRINFO
2812 struct addrinfo ai, *res, *lres;
2813 struct addrinfo hints;
2814 const char *portstring;
2815 char portbuf[128];
2816 #else /* HAVE_GETADDRINFO */
2817 struct _emacs_addrinfo
2819 int ai_family;
2820 int ai_socktype;
2821 int ai_protocol;
2822 int ai_addrlen;
2823 struct sockaddr *ai_addr;
2824 struct _emacs_addrinfo *ai_next;
2825 } ai, *res, *lres;
2826 #endif /* HAVE_GETADDRINFO */
2827 struct sockaddr_in address_in;
2828 #ifdef HAVE_LOCAL_SOCKETS
2829 struct sockaddr_un address_un;
2830 #endif
2831 int port;
2832 int ret = 0;
2833 int xerrno = 0;
2834 int s = -1, outch, inch;
2835 struct gcpro gcpro1;
2836 ptrdiff_t count = SPECPDL_INDEX ();
2837 ptrdiff_t count1;
2838 Lisp_Object QCaddress; /* one of QClocal or QCremote */
2839 Lisp_Object tem;
2840 Lisp_Object name, buffer, host, service, address;
2841 Lisp_Object filter, sentinel;
2842 bool is_non_blocking_client = 0;
2843 bool is_server = 0;
2844 int backlog = 5;
2845 int socktype;
2846 int family = -1;
2848 if (nargs == 0)
2849 return Qnil;
2851 /* Save arguments for process-contact and clone-process. */
2852 contact = Flist (nargs, args);
2853 GCPRO1 (contact);
2855 #ifdef WINDOWSNT
2856 /* Ensure socket support is loaded if available. */
2857 init_winsock (TRUE);
2858 #endif
2860 /* :type TYPE (nil: stream, datagram */
2861 tem = Fplist_get (contact, QCtype);
2862 if (NILP (tem))
2863 socktype = SOCK_STREAM;
2864 #ifdef DATAGRAM_SOCKETS
2865 else if (EQ (tem, Qdatagram))
2866 socktype = SOCK_DGRAM;
2867 #endif
2868 #ifdef HAVE_SEQPACKET
2869 else if (EQ (tem, Qseqpacket))
2870 socktype = SOCK_SEQPACKET;
2871 #endif
2872 else
2873 error ("Unsupported connection type");
2875 /* :server BOOL */
2876 tem = Fplist_get (contact, QCserver);
2877 if (!NILP (tem))
2879 /* Don't support network sockets when non-blocking mode is
2880 not available, since a blocked Emacs is not useful. */
2881 is_server = 1;
2882 if (TYPE_RANGED_INTEGERP (int, tem))
2883 backlog = XINT (tem);
2886 /* Make QCaddress an alias for :local (server) or :remote (client). */
2887 QCaddress = is_server ? QClocal : QCremote;
2889 /* :nowait BOOL */
2890 if (!is_server && socktype != SOCK_DGRAM
2891 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2893 #ifndef NON_BLOCKING_CONNECT
2894 error ("Non-blocking connect not supported");
2895 #else
2896 is_non_blocking_client = 1;
2897 #endif
2900 name = Fplist_get (contact, QCname);
2901 buffer = Fplist_get (contact, QCbuffer);
2902 filter = Fplist_get (contact, QCfilter);
2903 sentinel = Fplist_get (contact, QCsentinel);
2905 CHECK_STRING (name);
2907 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2908 ai.ai_socktype = socktype;
2909 ai.ai_protocol = 0;
2910 ai.ai_next = NULL;
2911 res = &ai;
2913 /* :local ADDRESS or :remote ADDRESS */
2914 address = Fplist_get (contact, QCaddress);
2915 if (!NILP (address))
2917 host = service = Qnil;
2919 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2920 error ("Malformed :address");
2921 ai.ai_family = family;
2922 ai.ai_addr = alloca (ai.ai_addrlen);
2923 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
2924 goto open_socket;
2927 /* :family FAMILY -- nil (for Inet), local, or integer. */
2928 tem = Fplist_get (contact, QCfamily);
2929 if (NILP (tem))
2931 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
2932 family = AF_UNSPEC;
2933 #else
2934 family = AF_INET;
2935 #endif
2937 #ifdef HAVE_LOCAL_SOCKETS
2938 else if (EQ (tem, Qlocal))
2939 family = AF_LOCAL;
2940 #endif
2941 #ifdef AF_INET6
2942 else if (EQ (tem, Qipv6))
2943 family = AF_INET6;
2944 #endif
2945 else if (EQ (tem, Qipv4))
2946 family = AF_INET;
2947 else if (TYPE_RANGED_INTEGERP (int, tem))
2948 family = XINT (tem);
2949 else
2950 error ("Unknown address family");
2952 ai.ai_family = family;
2954 /* :service SERVICE -- string, integer (port number), or t (random port). */
2955 service = Fplist_get (contact, QCservice);
2957 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2958 host = Fplist_get (contact, QChost);
2959 if (!NILP (host))
2961 if (EQ (host, Qlocal))
2962 /* Depending on setup, "localhost" may map to different IPv4 and/or
2963 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
2964 host = build_string ("127.0.0.1");
2965 CHECK_STRING (host);
2968 #ifdef HAVE_LOCAL_SOCKETS
2969 if (family == AF_LOCAL)
2971 if (!NILP (host))
2973 message (":family local ignores the :host \"%s\" property",
2974 SDATA (host));
2975 contact = Fplist_put (contact, QChost, Qnil);
2976 host = Qnil;
2978 CHECK_STRING (service);
2979 memset (&address_un, 0, sizeof address_un);
2980 address_un.sun_family = AF_LOCAL;
2981 if (sizeof address_un.sun_path <= SBYTES (service))
2982 error ("Service name too long");
2983 strcpy (address_un.sun_path, SSDATA (service));
2984 ai.ai_addr = (struct sockaddr *) &address_un;
2985 ai.ai_addrlen = sizeof address_un;
2986 goto open_socket;
2988 #endif
2990 /* Slow down polling to every ten seconds.
2991 Some kernels have a bug which causes retrying connect to fail
2992 after a connect. Polling can interfere with gethostbyname too. */
2993 #ifdef POLL_FOR_INPUT
2994 if (socktype != SOCK_DGRAM)
2996 record_unwind_protect_void (run_all_atimers);
2997 bind_polling_period (10);
2999 #endif
3001 #ifdef HAVE_GETADDRINFO
3002 /* If we have a host, use getaddrinfo to resolve both host and service.
3003 Otherwise, use getservbyname to lookup the service. */
3004 if (!NILP (host))
3007 /* SERVICE can either be a string or int.
3008 Convert to a C string for later use by getaddrinfo. */
3009 if (EQ (service, Qt))
3010 portstring = "0";
3011 else if (INTEGERP (service))
3013 sprintf (portbuf, "%"pI"d", XINT (service));
3014 portstring = portbuf;
3016 else
3018 CHECK_STRING (service);
3019 portstring = SSDATA (service);
3022 immediate_quit = 1;
3023 QUIT;
3024 memset (&hints, 0, sizeof (hints));
3025 hints.ai_flags = 0;
3026 hints.ai_family = family;
3027 hints.ai_socktype = socktype;
3028 hints.ai_protocol = 0;
3030 #ifdef HAVE_RES_INIT
3031 res_init ();
3032 #endif
3034 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3035 if (ret)
3036 #ifdef HAVE_GAI_STRERROR
3037 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3038 #else
3039 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3040 #endif
3041 immediate_quit = 0;
3043 goto open_socket;
3045 #endif /* HAVE_GETADDRINFO */
3047 /* We end up here if getaddrinfo is not defined, or in case no hostname
3048 has been specified (e.g. for a local server process). */
3050 if (EQ (service, Qt))
3051 port = 0;
3052 else if (INTEGERP (service))
3053 port = htons ((unsigned short) XINT (service));
3054 else
3056 struct servent *svc_info;
3057 CHECK_STRING (service);
3058 svc_info = getservbyname (SSDATA (service),
3059 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3060 if (svc_info == 0)
3061 error ("Unknown service: %s", SDATA (service));
3062 port = svc_info->s_port;
3065 memset (&address_in, 0, sizeof address_in);
3066 address_in.sin_family = family;
3067 address_in.sin_addr.s_addr = INADDR_ANY;
3068 address_in.sin_port = port;
3070 #ifndef HAVE_GETADDRINFO
3071 if (!NILP (host))
3073 struct hostent *host_info_ptr;
3075 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3076 as it may `hang' Emacs for a very long time. */
3077 immediate_quit = 1;
3078 QUIT;
3080 #ifdef HAVE_RES_INIT
3081 res_init ();
3082 #endif
3084 host_info_ptr = gethostbyname (SDATA (host));
3085 immediate_quit = 0;
3087 if (host_info_ptr)
3089 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3090 host_info_ptr->h_length);
3091 family = host_info_ptr->h_addrtype;
3092 address_in.sin_family = family;
3094 else
3095 /* Attempt to interpret host as numeric inet address */
3097 unsigned long numeric_addr;
3098 numeric_addr = inet_addr (SSDATA (host));
3099 if (numeric_addr == -1)
3100 error ("Unknown host \"%s\"", SDATA (host));
3102 memcpy (&address_in.sin_addr, &numeric_addr,
3103 sizeof (address_in.sin_addr));
3107 #endif /* not HAVE_GETADDRINFO */
3109 ai.ai_family = family;
3110 ai.ai_addr = (struct sockaddr *) &address_in;
3111 ai.ai_addrlen = sizeof address_in;
3113 open_socket:
3115 /* Do this in case we never enter the for-loop below. */
3116 count1 = SPECPDL_INDEX ();
3117 s = -1;
3119 for (lres = res; lres; lres = lres->ai_next)
3121 ptrdiff_t optn;
3122 int optbits;
3124 #ifdef WINDOWSNT
3125 retry_connect:
3126 #endif
3128 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3129 lres->ai_protocol);
3130 if (s < 0)
3132 xerrno = errno;
3133 continue;
3136 #ifdef DATAGRAM_SOCKETS
3137 if (!is_server && socktype == SOCK_DGRAM)
3138 break;
3139 #endif /* DATAGRAM_SOCKETS */
3141 #ifdef NON_BLOCKING_CONNECT
3142 if (is_non_blocking_client)
3144 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3145 if (ret < 0)
3147 xerrno = errno;
3148 emacs_close (s);
3149 s = -1;
3150 continue;
3153 #endif
3155 /* Make us close S if quit. */
3156 record_unwind_protect_int (close_file_unwind, s);
3158 /* Parse network options in the arg list.
3159 We simply ignore anything which isn't a known option (including other keywords).
3160 An error is signaled if setting a known option fails. */
3161 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3162 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3164 if (is_server)
3166 /* Configure as a server socket. */
3168 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3169 explicit :reuseaddr key to override this. */
3170 #ifdef HAVE_LOCAL_SOCKETS
3171 if (family != AF_LOCAL)
3172 #endif
3173 if (!(optbits & (1 << OPIX_REUSEADDR)))
3175 int optval = 1;
3176 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3177 report_file_error ("Cannot set reuse option on server socket", Qnil);
3180 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3181 report_file_error ("Cannot bind server socket", Qnil);
3183 #ifdef HAVE_GETSOCKNAME
3184 if (EQ (service, Qt))
3186 struct sockaddr_in sa1;
3187 socklen_t len1 = sizeof (sa1);
3188 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3190 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3191 service = make_number (ntohs (sa1.sin_port));
3192 contact = Fplist_put (contact, QCservice, service);
3195 #endif
3197 if (socktype != SOCK_DGRAM && listen (s, backlog))
3198 report_file_error ("Cannot listen on server socket", Qnil);
3200 break;
3203 immediate_quit = 1;
3204 QUIT;
3206 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3207 xerrno = errno;
3209 if (ret == 0 || xerrno == EISCONN)
3211 /* The unwind-protect will be discarded afterwards.
3212 Likewise for immediate_quit. */
3213 break;
3216 #ifdef NON_BLOCKING_CONNECT
3217 #ifdef EINPROGRESS
3218 if (is_non_blocking_client && xerrno == EINPROGRESS)
3219 break;
3220 #else
3221 #ifdef EWOULDBLOCK
3222 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3223 break;
3224 #endif
3225 #endif
3226 #endif
3228 #ifndef WINDOWSNT
3229 if (xerrno == EINTR)
3231 /* Unlike most other syscalls connect() cannot be called
3232 again. (That would return EALREADY.) The proper way to
3233 wait for completion is pselect(). */
3234 int sc;
3235 socklen_t len;
3236 fd_set fdset;
3237 retry_select:
3238 FD_ZERO (&fdset);
3239 FD_SET (s, &fdset);
3240 QUIT;
3241 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3242 if (sc == -1)
3244 if (errno == EINTR)
3245 goto retry_select;
3246 else
3247 report_file_error ("Failed select", Qnil);
3249 eassert (sc > 0);
3251 len = sizeof xerrno;
3252 eassert (FD_ISSET (s, &fdset));
3253 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3254 report_file_error ("Failed getsockopt", Qnil);
3255 if (xerrno)
3256 report_file_errno ("Failed connect", Qnil, xerrno);
3257 break;
3259 #endif /* !WINDOWSNT */
3261 immediate_quit = 0;
3263 /* Discard the unwind protect closing S. */
3264 specpdl_ptr = specpdl + count1;
3265 emacs_close (s);
3266 s = -1;
3268 #ifdef WINDOWSNT
3269 if (xerrno == EINTR)
3270 goto retry_connect;
3271 #endif
3274 if (s >= 0)
3276 #ifdef DATAGRAM_SOCKETS
3277 if (socktype == SOCK_DGRAM)
3279 if (datagram_address[s].sa)
3280 emacs_abort ();
3281 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3282 datagram_address[s].len = lres->ai_addrlen;
3283 if (is_server)
3285 Lisp_Object remote;
3286 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3287 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3289 int rfamily, rlen;
3290 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3291 if (rlen != 0 && rfamily == lres->ai_family
3292 && rlen == lres->ai_addrlen)
3293 conv_lisp_to_sockaddr (rfamily, remote,
3294 datagram_address[s].sa, rlen);
3297 else
3298 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3300 #endif
3301 contact = Fplist_put (contact, QCaddress,
3302 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3303 #ifdef HAVE_GETSOCKNAME
3304 if (!is_server)
3306 struct sockaddr_in sa1;
3307 socklen_t len1 = sizeof (sa1);
3308 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3309 contact = Fplist_put (contact, QClocal,
3310 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3312 #endif
3315 immediate_quit = 0;
3317 #ifdef HAVE_GETADDRINFO
3318 if (res != &ai)
3320 block_input ();
3321 freeaddrinfo (res);
3322 unblock_input ();
3324 #endif
3326 if (s < 0)
3328 /* If non-blocking got this far - and failed - assume non-blocking is
3329 not supported after all. This is probably a wrong assumption, but
3330 the normal blocking calls to open-network-stream handles this error
3331 better. */
3332 if (is_non_blocking_client)
3333 return Qnil;
3335 report_file_errno ((is_server
3336 ? "make server process failed"
3337 : "make client process failed"),
3338 contact, xerrno);
3341 inch = s;
3342 outch = s;
3344 if (!NILP (buffer))
3345 buffer = Fget_buffer_create (buffer);
3346 proc = make_process (name);
3348 chan_process[inch] = proc;
3350 fcntl (inch, F_SETFL, O_NONBLOCK);
3352 p = XPROCESS (proc);
3354 pset_childp (p, contact);
3355 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3356 pset_type (p, Qnetwork);
3358 pset_buffer (p, buffer);
3359 pset_sentinel (p, sentinel);
3360 pset_filter (p, filter);
3361 pset_log (p, Fplist_get (contact, QClog));
3362 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3363 p->kill_without_query = 1;
3364 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3365 pset_command (p, Qt);
3366 p->pid = 0;
3368 p->open_fd[SUBPROCESS_STDIN] = inch;
3369 p->infd = inch;
3370 p->outfd = outch;
3372 /* Discard the unwind protect for closing S, if any. */
3373 specpdl_ptr = specpdl + count1;
3375 /* Unwind bind_polling_period and request_sigio. */
3376 unbind_to (count, Qnil);
3378 if (is_server && socktype != SOCK_DGRAM)
3379 pset_status (p, Qlisten);
3381 /* Make the process marker point into the process buffer (if any). */
3382 if (BUFFERP (buffer))
3383 set_marker_both (p->mark, buffer,
3384 BUF_ZV (XBUFFER (buffer)),
3385 BUF_ZV_BYTE (XBUFFER (buffer)));
3387 #ifdef NON_BLOCKING_CONNECT
3388 if (is_non_blocking_client)
3390 /* We may get here if connect did succeed immediately. However,
3391 in that case, we still need to signal this like a non-blocking
3392 connection. */
3393 pset_status (p, Qconnect);
3394 if (!FD_ISSET (inch, &connect_wait_mask))
3396 FD_SET (inch, &connect_wait_mask);
3397 FD_SET (inch, &write_mask);
3398 num_pending_connects++;
3401 else
3402 #endif
3403 /* A server may have a client filter setting of Qt, but it must
3404 still listen for incoming connects unless it is stopped. */
3405 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3406 || (EQ (p->status, Qlisten) && NILP (p->command)))
3408 FD_SET (inch, &input_wait_mask);
3409 FD_SET (inch, &non_keyboard_wait_mask);
3412 if (inch > max_process_desc)
3413 max_process_desc = inch;
3415 tem = Fplist_member (contact, QCcoding);
3416 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3417 tem = Qnil; /* No error message (too late!). */
3420 /* Setup coding systems for communicating with the network stream. */
3421 struct gcpro gcpro1;
3422 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3423 Lisp_Object coding_systems = Qt;
3424 Lisp_Object fargs[5], val;
3426 if (!NILP (tem))
3428 val = XCAR (XCDR (tem));
3429 if (CONSP (val))
3430 val = XCAR (val);
3432 else if (!NILP (Vcoding_system_for_read))
3433 val = Vcoding_system_for_read;
3434 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3435 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3436 /* We dare not decode end-of-line format by setting VAL to
3437 Qraw_text, because the existing Emacs Lisp libraries
3438 assume that they receive bare code including a sequence of
3439 CR LF. */
3440 val = Qnil;
3441 else
3443 if (NILP (host) || NILP (service))
3444 coding_systems = Qnil;
3445 else
3447 fargs[0] = Qopen_network_stream, fargs[1] = name,
3448 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3449 GCPRO1 (proc);
3450 coding_systems = Ffind_operation_coding_system (5, fargs);
3451 UNGCPRO;
3453 if (CONSP (coding_systems))
3454 val = XCAR (coding_systems);
3455 else if (CONSP (Vdefault_process_coding_system))
3456 val = XCAR (Vdefault_process_coding_system);
3457 else
3458 val = Qnil;
3460 pset_decode_coding_system (p, val);
3462 if (!NILP (tem))
3464 val = XCAR (XCDR (tem));
3465 if (CONSP (val))
3466 val = XCDR (val);
3468 else if (!NILP (Vcoding_system_for_write))
3469 val = Vcoding_system_for_write;
3470 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3471 val = Qnil;
3472 else
3474 if (EQ (coding_systems, Qt))
3476 if (NILP (host) || NILP (service))
3477 coding_systems = Qnil;
3478 else
3480 fargs[0] = Qopen_network_stream, fargs[1] = name,
3481 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3482 GCPRO1 (proc);
3483 coding_systems = Ffind_operation_coding_system (5, fargs);
3484 UNGCPRO;
3487 if (CONSP (coding_systems))
3488 val = XCDR (coding_systems);
3489 else if (CONSP (Vdefault_process_coding_system))
3490 val = XCDR (Vdefault_process_coding_system);
3491 else
3492 val = Qnil;
3494 pset_encode_coding_system (p, val);
3496 setup_process_coding_systems (proc);
3498 pset_decoding_buf (p, empty_unibyte_string);
3499 p->decoding_carryover = 0;
3500 pset_encoding_buf (p, empty_unibyte_string);
3502 p->inherit_coding_system_flag
3503 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3505 UNGCPRO;
3506 return proc;
3510 #ifdef HAVE_NET_IF_H
3512 #ifdef SIOCGIFCONF
3513 static Lisp_Object
3514 network_interface_list (void)
3516 struct ifconf ifconf;
3517 struct ifreq *ifreq;
3518 void *buf = NULL;
3519 ptrdiff_t buf_size = 512;
3520 int s;
3521 Lisp_Object res;
3522 ptrdiff_t count;
3524 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3525 if (s < 0)
3526 return Qnil;
3527 count = SPECPDL_INDEX ();
3528 record_unwind_protect_int (close_file_unwind, s);
3532 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3533 ifconf.ifc_buf = buf;
3534 ifconf.ifc_len = buf_size;
3535 if (ioctl (s, SIOCGIFCONF, &ifconf))
3537 emacs_close (s);
3538 xfree (buf);
3539 return Qnil;
3542 while (ifconf.ifc_len == buf_size);
3544 res = unbind_to (count, Qnil);
3545 ifreq = ifconf.ifc_req;
3546 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3548 struct ifreq *ifq = ifreq;
3549 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3550 #define SIZEOF_IFREQ(sif) \
3551 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3552 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3554 int len = SIZEOF_IFREQ (ifq);
3555 #else
3556 int len = sizeof (*ifreq);
3557 #endif
3558 char namebuf[sizeof (ifq->ifr_name) + 1];
3559 ifreq = (struct ifreq *) ((char *) ifreq + len);
3561 if (ifq->ifr_addr.sa_family != AF_INET)
3562 continue;
3564 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3565 namebuf[sizeof (ifq->ifr_name)] = 0;
3566 res = Fcons (Fcons (build_string (namebuf),
3567 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3568 sizeof (struct sockaddr))),
3569 res);
3572 xfree (buf);
3573 return res;
3575 #endif /* SIOCGIFCONF */
3577 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3579 struct ifflag_def {
3580 int flag_bit;
3581 const char *flag_sym;
3584 static const struct ifflag_def ifflag_table[] = {
3585 #ifdef IFF_UP
3586 { IFF_UP, "up" },
3587 #endif
3588 #ifdef IFF_BROADCAST
3589 { IFF_BROADCAST, "broadcast" },
3590 #endif
3591 #ifdef IFF_DEBUG
3592 { IFF_DEBUG, "debug" },
3593 #endif
3594 #ifdef IFF_LOOPBACK
3595 { IFF_LOOPBACK, "loopback" },
3596 #endif
3597 #ifdef IFF_POINTOPOINT
3598 { IFF_POINTOPOINT, "pointopoint" },
3599 #endif
3600 #ifdef IFF_RUNNING
3601 { IFF_RUNNING, "running" },
3602 #endif
3603 #ifdef IFF_NOARP
3604 { IFF_NOARP, "noarp" },
3605 #endif
3606 #ifdef IFF_PROMISC
3607 { IFF_PROMISC, "promisc" },
3608 #endif
3609 #ifdef IFF_NOTRAILERS
3610 #ifdef NS_IMPL_COCOA
3611 /* Really means smart, notrailers is obsolete */
3612 { IFF_NOTRAILERS, "smart" },
3613 #else
3614 { IFF_NOTRAILERS, "notrailers" },
3615 #endif
3616 #endif
3617 #ifdef IFF_ALLMULTI
3618 { IFF_ALLMULTI, "allmulti" },
3619 #endif
3620 #ifdef IFF_MASTER
3621 { IFF_MASTER, "master" },
3622 #endif
3623 #ifdef IFF_SLAVE
3624 { IFF_SLAVE, "slave" },
3625 #endif
3626 #ifdef IFF_MULTICAST
3627 { IFF_MULTICAST, "multicast" },
3628 #endif
3629 #ifdef IFF_PORTSEL
3630 { IFF_PORTSEL, "portsel" },
3631 #endif
3632 #ifdef IFF_AUTOMEDIA
3633 { IFF_AUTOMEDIA, "automedia" },
3634 #endif
3635 #ifdef IFF_DYNAMIC
3636 { IFF_DYNAMIC, "dynamic" },
3637 #endif
3638 #ifdef IFF_OACTIVE
3639 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3640 #endif
3641 #ifdef IFF_SIMPLEX
3642 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3643 #endif
3644 #ifdef IFF_LINK0
3645 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3646 #endif
3647 #ifdef IFF_LINK1
3648 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3649 #endif
3650 #ifdef IFF_LINK2
3651 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3652 #endif
3653 { 0, 0 }
3656 static Lisp_Object
3657 network_interface_info (Lisp_Object ifname)
3659 struct ifreq rq;
3660 Lisp_Object res = Qnil;
3661 Lisp_Object elt;
3662 int s;
3663 bool any = 0;
3664 ptrdiff_t count;
3665 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3666 && defined HAVE_GETIFADDRS && defined LLADDR)
3667 struct ifaddrs *ifap;
3668 #endif
3670 CHECK_STRING (ifname);
3672 if (sizeof rq.ifr_name <= SBYTES (ifname))
3673 error ("interface name too long");
3674 strcpy (rq.ifr_name, SSDATA (ifname));
3676 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3677 if (s < 0)
3678 return Qnil;
3679 count = SPECPDL_INDEX ();
3680 record_unwind_protect_int (close_file_unwind, s);
3682 elt = Qnil;
3683 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3684 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3686 int flags = rq.ifr_flags;
3687 const struct ifflag_def *fp;
3688 int fnum;
3690 /* If flags is smaller than int (i.e. short) it may have the high bit set
3691 due to IFF_MULTICAST. In that case, sign extending it into
3692 an int is wrong. */
3693 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3694 flags = (unsigned short) rq.ifr_flags;
3696 any = 1;
3697 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3699 if (flags & fp->flag_bit)
3701 elt = Fcons (intern (fp->flag_sym), elt);
3702 flags -= fp->flag_bit;
3705 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3707 if (flags & 1)
3709 elt = Fcons (make_number (fnum), elt);
3713 #endif
3714 res = Fcons (elt, res);
3716 elt = Qnil;
3717 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3718 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3720 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3721 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3722 int n;
3724 any = 1;
3725 for (n = 0; n < 6; n++)
3726 p->u.contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3727 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3729 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3730 if (getifaddrs (&ifap) != -1)
3732 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3733 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3734 struct ifaddrs *it;
3736 for (it = ifap; it != NULL; it = it->ifa_next)
3738 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3739 unsigned char linkaddr[6];
3740 int n;
3742 if (it->ifa_addr->sa_family != AF_LINK
3743 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3744 || sdl->sdl_alen != 6)
3745 continue;
3747 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3748 for (n = 0; n < 6; n++)
3749 p->u.contents[n] = make_number (linkaddr[n]);
3751 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
3752 break;
3755 #ifdef HAVE_FREEIFADDRS
3756 freeifaddrs (ifap);
3757 #endif
3759 #endif /* HAVE_GETIFADDRS && LLADDR */
3761 res = Fcons (elt, res);
3763 elt = Qnil;
3764 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3765 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3767 any = 1;
3768 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3769 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3770 #else
3771 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3772 #endif
3774 #endif
3775 res = Fcons (elt, res);
3777 elt = Qnil;
3778 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3779 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3781 any = 1;
3782 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3784 #endif
3785 res = Fcons (elt, res);
3787 elt = Qnil;
3788 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3789 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3791 any = 1;
3792 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3794 #endif
3795 res = Fcons (elt, res);
3797 return unbind_to (count, any ? res : Qnil);
3799 #endif /* !SIOCGIFADDR && !SIOCGIFHWADDR && !SIOCGIFFLAGS */
3800 #endif /* defined (HAVE_NET_IF_H) */
3802 DEFUN ("network-interface-list", Fnetwork_interface_list,
3803 Snetwork_interface_list, 0, 0, 0,
3804 doc: /* Return an alist of all network interfaces and their network address.
3805 Each element is a cons, the car of which is a string containing the
3806 interface name, and the cdr is the network address in internal
3807 format; see the description of ADDRESS in `make-network-process'.
3809 If the information is not available, return nil. */)
3810 (void)
3812 #if (defined HAVE_NET_IF_H && defined SIOCGIFCONF) || defined WINDOWSNT
3813 return network_interface_list ();
3814 #else
3815 return Qnil;
3816 #endif
3819 DEFUN ("network-interface-info", Fnetwork_interface_info,
3820 Snetwork_interface_info, 1, 1, 0,
3821 doc: /* Return information about network interface named IFNAME.
3822 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3823 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3824 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3825 FLAGS is the current flags of the interface.
3827 Data that is unavailable is returned as nil. */)
3828 (Lisp_Object ifname)
3830 #if ((defined HAVE_NET_IF_H \
3831 && (defined SIOCGIFADDR || defined SIOCGIFHWADDR \
3832 || defined SIOCGIFFLAGS)) \
3833 || defined WINDOWSNT)
3834 return network_interface_info (ifname);
3835 #else
3836 return Qnil;
3837 #endif
3841 /* Turn off input and output for process PROC. */
3843 static void
3844 deactivate_process (Lisp_Object proc)
3846 int inchannel;
3847 struct Lisp_Process *p = XPROCESS (proc);
3848 int i;
3850 #ifdef HAVE_GNUTLS
3851 /* Delete GnuTLS structures in PROC, if any. */
3852 emacs_gnutls_deinit (proc);
3853 #endif /* HAVE_GNUTLS */
3855 #ifdef ADAPTIVE_READ_BUFFERING
3856 if (p->read_output_delay > 0)
3858 if (--process_output_delay_count < 0)
3859 process_output_delay_count = 0;
3860 p->read_output_delay = 0;
3861 p->read_output_skip = 0;
3863 #endif
3865 /* Beware SIGCHLD hereabouts. */
3867 for (i = 0; i < PROCESS_OPEN_FDS; i++)
3868 close_process_fd (&p->open_fd[i]);
3870 inchannel = p->infd;
3871 if (inchannel >= 0)
3873 p->infd = -1;
3874 p->outfd = -1;
3875 #ifdef DATAGRAM_SOCKETS
3876 if (DATAGRAM_CHAN_P (inchannel))
3878 xfree (datagram_address[inchannel].sa);
3879 datagram_address[inchannel].sa = 0;
3880 datagram_address[inchannel].len = 0;
3882 #endif
3883 chan_process[inchannel] = Qnil;
3884 FD_CLR (inchannel, &input_wait_mask);
3885 FD_CLR (inchannel, &non_keyboard_wait_mask);
3886 #ifdef NON_BLOCKING_CONNECT
3887 if (FD_ISSET (inchannel, &connect_wait_mask))
3889 FD_CLR (inchannel, &connect_wait_mask);
3890 FD_CLR (inchannel, &write_mask);
3891 if (--num_pending_connects < 0)
3892 emacs_abort ();
3894 #endif
3895 if (inchannel == max_process_desc)
3897 /* We just closed the highest-numbered process input descriptor,
3898 so recompute the highest-numbered one now. */
3899 int i = inchannel;
3901 i--;
3902 while (0 <= i && NILP (chan_process[i]));
3904 max_process_desc = i;
3910 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3911 0, 4, 0,
3912 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3913 It is read into the process' buffers or given to their filter functions.
3914 Non-nil arg PROCESS means do not return until some output has been received
3915 from PROCESS.
3917 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
3918 and milliseconds to wait; return after that much time whether or not
3919 there is any subprocess output. If SECONDS is a floating point number,
3920 it specifies a fractional number of seconds to wait.
3921 The MILLISEC argument is obsolete and should be avoided.
3923 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
3924 from PROCESS, suspending reading output from other processes.
3925 If JUST-THIS-ONE is an integer, don't run any timers either.
3926 Return non-nil if we received any output before the timeout expired. */)
3927 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
3929 intmax_t secs;
3930 int nsecs;
3932 if (! NILP (process))
3933 CHECK_PROCESS (process);
3934 else
3935 just_this_one = Qnil;
3937 if (!NILP (millisec))
3938 { /* Obsolete calling convention using integers rather than floats. */
3939 CHECK_NUMBER (millisec);
3940 if (NILP (seconds))
3941 seconds = make_float (XINT (millisec) / 1000.0);
3942 else
3944 CHECK_NUMBER (seconds);
3945 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
3949 secs = 0;
3950 nsecs = -1;
3952 if (!NILP (seconds))
3954 if (INTEGERP (seconds))
3956 if (XINT (seconds) > 0)
3958 secs = XINT (seconds);
3959 nsecs = 0;
3962 else if (FLOATP (seconds))
3964 if (XFLOAT_DATA (seconds) > 0)
3966 struct timespec t = dtotimespec (XFLOAT_DATA (seconds));
3967 secs = min (t.tv_sec, WAIT_READING_MAX);
3968 nsecs = t.tv_nsec;
3971 else
3972 wrong_type_argument (Qnumberp, seconds);
3974 else if (! NILP (process))
3975 nsecs = 0;
3977 return
3978 (wait_reading_process_output (secs, nsecs, 0, 0,
3979 Qnil,
3980 !NILP (process) ? XPROCESS (process) : NULL,
3981 NILP (just_this_one) ? 0 :
3982 !INTEGERP (just_this_one) ? 1 : -1)
3983 ? Qt : Qnil);
3986 /* Accept a connection for server process SERVER on CHANNEL. */
3988 static EMACS_INT connect_counter = 0;
3990 static void
3991 server_accept_connection (Lisp_Object server, int channel)
3993 Lisp_Object proc, caller, name, buffer;
3994 Lisp_Object contact, host, service;
3995 struct Lisp_Process *ps= XPROCESS (server);
3996 struct Lisp_Process *p;
3997 int s;
3998 union u_sockaddr {
3999 struct sockaddr sa;
4000 struct sockaddr_in in;
4001 #ifdef AF_INET6
4002 struct sockaddr_in6 in6;
4003 #endif
4004 #ifdef HAVE_LOCAL_SOCKETS
4005 struct sockaddr_un un;
4006 #endif
4007 } saddr;
4008 socklen_t len = sizeof saddr;
4009 ptrdiff_t count;
4011 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
4013 if (s < 0)
4015 int code = errno;
4017 if (code == EAGAIN)
4018 return;
4019 #ifdef EWOULDBLOCK
4020 if (code == EWOULDBLOCK)
4021 return;
4022 #endif
4024 if (!NILP (ps->log))
4025 call3 (ps->log, server, Qnil,
4026 concat3 (build_string ("accept failed with code"),
4027 Fnumber_to_string (make_number (code)),
4028 build_string ("\n")));
4029 return;
4032 count = SPECPDL_INDEX ();
4033 record_unwind_protect_int (close_file_unwind, s);
4035 connect_counter++;
4037 /* Setup a new process to handle the connection. */
4039 /* Generate a unique identification of the caller, and build contact
4040 information for this process. */
4041 host = Qt;
4042 service = Qnil;
4043 switch (saddr.sa.sa_family)
4045 case AF_INET:
4047 Lisp_Object args[5];
4048 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4049 args[0] = build_string ("%d.%d.%d.%d");
4050 args[1] = make_number (*ip++);
4051 args[2] = make_number (*ip++);
4052 args[3] = make_number (*ip++);
4053 args[4] = make_number (*ip++);
4054 host = Fformat (5, args);
4055 service = make_number (ntohs (saddr.in.sin_port));
4057 args[0] = build_string (" <%s:%d>");
4058 args[1] = host;
4059 args[2] = service;
4060 caller = Fformat (3, args);
4062 break;
4064 #ifdef AF_INET6
4065 case AF_INET6:
4067 Lisp_Object args[9];
4068 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4069 int i;
4070 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4071 for (i = 0; i < 8; i++)
4072 args[i+1] = make_number (ntohs (ip6[i]));
4073 host = Fformat (9, args);
4074 service = make_number (ntohs (saddr.in.sin_port));
4076 args[0] = build_string (" <[%s]:%d>");
4077 args[1] = host;
4078 args[2] = service;
4079 caller = Fformat (3, args);
4081 break;
4082 #endif
4084 #ifdef HAVE_LOCAL_SOCKETS
4085 case AF_LOCAL:
4086 #endif
4087 default:
4088 caller = Fnumber_to_string (make_number (connect_counter));
4089 caller = concat3 (build_string (" <"), caller, build_string (">"));
4090 break;
4093 /* Create a new buffer name for this process if it doesn't have a
4094 filter. The new buffer name is based on the buffer name or
4095 process name of the server process concatenated with the caller
4096 identification. */
4098 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4099 || EQ (ps->filter, Qt)))
4100 buffer = Qnil;
4101 else
4103 buffer = ps->buffer;
4104 if (!NILP (buffer))
4105 buffer = Fbuffer_name (buffer);
4106 else
4107 buffer = ps->name;
4108 if (!NILP (buffer))
4110 buffer = concat2 (buffer, caller);
4111 buffer = Fget_buffer_create (buffer);
4115 /* Generate a unique name for the new server process. Combine the
4116 server process name with the caller identification. */
4118 name = concat2 (ps->name, caller);
4119 proc = make_process (name);
4121 chan_process[s] = proc;
4123 fcntl (s, F_SETFL, O_NONBLOCK);
4125 p = XPROCESS (proc);
4127 /* Build new contact information for this setup. */
4128 contact = Fcopy_sequence (ps->childp);
4129 contact = Fplist_put (contact, QCserver, Qnil);
4130 contact = Fplist_put (contact, QChost, host);
4131 if (!NILP (service))
4132 contact = Fplist_put (contact, QCservice, service);
4133 contact = Fplist_put (contact, QCremote,
4134 conv_sockaddr_to_lisp (&saddr.sa, len));
4135 #ifdef HAVE_GETSOCKNAME
4136 len = sizeof saddr;
4137 if (getsockname (s, &saddr.sa, &len) == 0)
4138 contact = Fplist_put (contact, QClocal,
4139 conv_sockaddr_to_lisp (&saddr.sa, len));
4140 #endif
4142 pset_childp (p, contact);
4143 pset_plist (p, Fcopy_sequence (ps->plist));
4144 pset_type (p, Qnetwork);
4146 pset_buffer (p, buffer);
4147 pset_sentinel (p, ps->sentinel);
4148 pset_filter (p, ps->filter);
4149 pset_command (p, Qnil);
4150 p->pid = 0;
4152 /* Discard the unwind protect for closing S. */
4153 specpdl_ptr = specpdl + count;
4155 p->open_fd[SUBPROCESS_STDIN] = s;
4156 p->infd = s;
4157 p->outfd = s;
4158 pset_status (p, Qrun);
4160 /* Client processes for accepted connections are not stopped initially. */
4161 if (!EQ (p->filter, Qt))
4163 FD_SET (s, &input_wait_mask);
4164 FD_SET (s, &non_keyboard_wait_mask);
4167 if (s > max_process_desc)
4168 max_process_desc = s;
4170 /* Setup coding system for new process based on server process.
4171 This seems to be the proper thing to do, as the coding system
4172 of the new process should reflect the settings at the time the
4173 server socket was opened; not the current settings. */
4175 pset_decode_coding_system (p, ps->decode_coding_system);
4176 pset_encode_coding_system (p, ps->encode_coding_system);
4177 setup_process_coding_systems (proc);
4179 pset_decoding_buf (p, empty_unibyte_string);
4180 p->decoding_carryover = 0;
4181 pset_encoding_buf (p, empty_unibyte_string);
4183 p->inherit_coding_system_flag
4184 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4186 if (!NILP (ps->log))
4187 call3 (ps->log, server, proc,
4188 concat3 (build_string ("accept from "),
4189 (STRINGP (host) ? host : build_string ("-")),
4190 build_string ("\n")));
4192 exec_sentinel (proc,
4193 concat3 (build_string ("open from "),
4194 (STRINGP (host) ? host : build_string ("-")),
4195 build_string ("\n")));
4198 /* This variable is different from waiting_for_input in keyboard.c.
4199 It is used to communicate to a lisp process-filter/sentinel (via the
4200 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4201 for user-input when that process-filter was called.
4202 waiting_for_input cannot be used as that is by definition 0 when
4203 lisp code is being evalled.
4204 This is also used in record_asynch_buffer_change.
4205 For that purpose, this must be 0
4206 when not inside wait_reading_process_output. */
4207 static int waiting_for_user_input_p;
4209 static void
4210 wait_reading_process_output_unwind (int data)
4212 waiting_for_user_input_p = data;
4215 /* This is here so breakpoints can be put on it. */
4216 static void
4217 wait_reading_process_output_1 (void)
4221 /* Read and dispose of subprocess output while waiting for timeout to
4222 elapse and/or keyboard input to be available.
4224 TIME_LIMIT is:
4225 timeout in seconds
4226 If negative, gobble data immediately available but don't wait for any.
4228 NSECS is:
4229 an additional duration to wait, measured in nanoseconds
4230 If TIME_LIMIT is zero, then:
4231 If NSECS == 0, there is no limit.
4232 If NSECS > 0, the timeout consists of NSECS only.
4233 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4235 READ_KBD is:
4236 0 to ignore keyboard input, or
4237 1 to return when input is available, or
4238 -1 meaning caller will actually read the input, so don't throw to
4239 the quit handler, or
4241 DO_DISPLAY means redisplay should be done to show subprocess
4242 output that arrives.
4244 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4245 (and gobble terminal input into the buffer if any arrives).
4247 If WAIT_PROC is specified, wait until something arrives from that
4248 process. The return value is true if we read some input from
4249 that process.
4251 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4252 (suspending output from other processes). A negative value
4253 means don't run any timers either.
4255 If WAIT_PROC is specified, then the function returns true if we
4256 received input from that process before the timeout elapsed.
4257 Otherwise, return true if we received input from any process. */
4259 bool
4260 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4261 bool do_display,
4262 Lisp_Object wait_for_cell,
4263 struct Lisp_Process *wait_proc, int just_wait_proc)
4265 int channel, nfds;
4266 fd_set Available;
4267 fd_set Writeok;
4268 bool check_write;
4269 int check_delay;
4270 bool no_avail;
4271 int xerrno;
4272 Lisp_Object proc;
4273 struct timespec timeout, end_time;
4274 int wait_channel = -1;
4275 bool got_some_input = 0;
4276 ptrdiff_t count = SPECPDL_INDEX ();
4278 FD_ZERO (&Available);
4279 FD_ZERO (&Writeok);
4281 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4282 && !(CONSP (wait_proc->status)
4283 && EQ (XCAR (wait_proc->status), Qexit)))
4284 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4286 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4287 if (wait_proc != NULL)
4288 wait_channel = wait_proc->infd;
4290 record_unwind_protect_int (wait_reading_process_output_unwind,
4291 waiting_for_user_input_p);
4292 waiting_for_user_input_p = read_kbd;
4294 if (time_limit < 0)
4296 time_limit = 0;
4297 nsecs = -1;
4299 else if (TYPE_MAXIMUM (time_t) < time_limit)
4300 time_limit = TYPE_MAXIMUM (time_t);
4302 /* Since we may need to wait several times,
4303 compute the absolute time to return at. */
4304 if (time_limit || nsecs > 0)
4306 timeout = make_timespec (time_limit, nsecs);
4307 end_time = timespec_add (current_timespec (), timeout);
4310 while (1)
4312 bool timeout_reduced_for_timers = 0;
4314 /* If calling from keyboard input, do not quit
4315 since we want to return C-g as an input character.
4316 Otherwise, do pending quit if requested. */
4317 if (read_kbd >= 0)
4318 QUIT;
4319 else if (pending_signals)
4320 process_pending_signals ();
4322 /* Exit now if the cell we're waiting for became non-nil. */
4323 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4324 break;
4326 /* Compute time from now till when time limit is up. */
4327 /* Exit if already run out. */
4328 if (nsecs < 0)
4330 /* A negative timeout means
4331 gobble output available now
4332 but don't wait at all. */
4334 timeout = make_timespec (0, 0);
4336 else if (time_limit || nsecs > 0)
4338 struct timespec now = current_timespec ();
4339 if (timespec_cmp (end_time, now) <= 0)
4340 break;
4341 timeout = timespec_sub (end_time, now);
4343 else
4345 timeout = make_timespec (100000, 0);
4348 /* Normally we run timers here.
4349 But not if wait_for_cell; in those cases,
4350 the wait is supposed to be short,
4351 and those callers cannot handle running arbitrary Lisp code here. */
4352 if (NILP (wait_for_cell)
4353 && just_wait_proc >= 0)
4355 struct timespec timer_delay;
4359 unsigned old_timers_run = timers_run;
4360 struct buffer *old_buffer = current_buffer;
4361 Lisp_Object old_window = selected_window;
4363 timer_delay = timer_check ();
4365 /* If a timer has run, this might have changed buffers
4366 an alike. Make read_key_sequence aware of that. */
4367 if (timers_run != old_timers_run
4368 && (old_buffer != current_buffer
4369 || !EQ (old_window, selected_window))
4370 && waiting_for_user_input_p == -1)
4371 record_asynch_buffer_change ();
4373 if (timers_run != old_timers_run && do_display)
4374 /* We must retry, since a timer may have requeued itself
4375 and that could alter the time_delay. */
4376 redisplay_preserve_echo_area (9);
4377 else
4378 break;
4380 while (!detect_input_pending ());
4382 /* If there is unread keyboard input, also return. */
4383 if (read_kbd != 0
4384 && requeued_events_pending_p ())
4385 break;
4387 /* A negative timeout means do not wait at all. */
4388 if (nsecs >= 0)
4390 if (timespec_valid_p (timer_delay))
4392 if (timespec_cmp (timer_delay, timeout) < 0)
4394 timeout = timer_delay;
4395 timeout_reduced_for_timers = 1;
4398 else
4400 /* This is so a breakpoint can be put here. */
4401 wait_reading_process_output_1 ();
4406 /* Cause C-g and alarm signals to take immediate action,
4407 and cause input available signals to zero out timeout.
4409 It is important that we do this before checking for process
4410 activity. If we get a SIGCHLD after the explicit checks for
4411 process activity, timeout is the only way we will know. */
4412 if (read_kbd < 0)
4413 set_waiting_for_input (&timeout);
4415 /* If status of something has changed, and no input is
4416 available, notify the user of the change right away. After
4417 this explicit check, we'll let the SIGCHLD handler zap
4418 timeout to get our attention. */
4419 if (update_tick != process_tick)
4421 fd_set Atemp;
4422 fd_set Ctemp;
4424 if (kbd_on_hold_p ())
4425 FD_ZERO (&Atemp);
4426 else
4427 Atemp = input_wait_mask;
4428 Ctemp = write_mask;
4430 timeout = make_timespec (0, 0);
4431 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4432 &Atemp,
4433 #ifdef NON_BLOCKING_CONNECT
4434 (num_pending_connects > 0 ? &Ctemp : NULL),
4435 #else
4436 NULL,
4437 #endif
4438 NULL, &timeout, NULL)
4439 <= 0))
4441 /* It's okay for us to do this and then continue with
4442 the loop, since timeout has already been zeroed out. */
4443 clear_waiting_for_input ();
4444 status_notify (NULL);
4445 if (do_display) redisplay_preserve_echo_area (13);
4449 /* Don't wait for output from a non-running process. Just
4450 read whatever data has already been received. */
4451 if (wait_proc && wait_proc->raw_status_new)
4452 update_status (wait_proc);
4453 if (wait_proc
4454 && ! EQ (wait_proc->status, Qrun)
4455 && ! EQ (wait_proc->status, Qconnect))
4457 bool read_some_bytes = 0;
4459 clear_waiting_for_input ();
4460 XSETPROCESS (proc, wait_proc);
4462 /* Read data from the process, until we exhaust it. */
4463 while (wait_proc->infd >= 0)
4465 int nread = read_process_output (proc, wait_proc->infd);
4467 if (nread == 0)
4468 break;
4470 if (nread > 0)
4471 got_some_input = read_some_bytes = 1;
4472 else if (nread == -1 && (errno == EIO || errno == EAGAIN))
4473 break;
4474 #ifdef EWOULDBLOCK
4475 else if (nread == -1 && EWOULDBLOCK == errno)
4476 break;
4477 #endif
4479 if (read_some_bytes && do_display)
4480 redisplay_preserve_echo_area (10);
4482 break;
4485 /* Wait till there is something to do */
4487 if (wait_proc && just_wait_proc)
4489 if (wait_proc->infd < 0) /* Terminated */
4490 break;
4491 FD_SET (wait_proc->infd, &Available);
4492 check_delay = 0;
4493 check_write = 0;
4495 else if (!NILP (wait_for_cell))
4497 Available = non_process_wait_mask;
4498 check_delay = 0;
4499 check_write = 0;
4501 else
4503 if (! read_kbd)
4504 Available = non_keyboard_wait_mask;
4505 else
4506 Available = input_wait_mask;
4507 Writeok = write_mask;
4508 #ifdef SELECT_CANT_DO_WRITE_MASK
4509 check_write = 0;
4510 #else
4511 check_write = 1;
4512 #endif
4513 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4516 /* If frame size has changed or the window is newly mapped,
4517 redisplay now, before we start to wait. There is a race
4518 condition here; if a SIGIO arrives between now and the select
4519 and indicates that a frame is trashed, the select may block
4520 displaying a trashed screen. */
4521 if (frame_garbaged && do_display)
4523 clear_waiting_for_input ();
4524 redisplay_preserve_echo_area (11);
4525 if (read_kbd < 0)
4526 set_waiting_for_input (&timeout);
4529 /* Skip the `select' call if input is available and we're
4530 waiting for keyboard input or a cell change (which can be
4531 triggered by processing X events). In the latter case, set
4532 nfds to 1 to avoid breaking the loop. */
4533 no_avail = 0;
4534 if ((read_kbd || !NILP (wait_for_cell))
4535 && detect_input_pending ())
4537 nfds = read_kbd ? 0 : 1;
4538 no_avail = 1;
4541 if (!no_avail)
4544 #ifdef ADAPTIVE_READ_BUFFERING
4545 /* Set the timeout for adaptive read buffering if any
4546 process has non-zero read_output_skip and non-zero
4547 read_output_delay, and we are not reading output for a
4548 specific wait_channel. It is not executed if
4549 Vprocess_adaptive_read_buffering is nil. */
4550 if (process_output_skip && check_delay > 0)
4552 int nsecs = timeout.tv_nsec;
4553 if (timeout.tv_sec > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4554 nsecs = READ_OUTPUT_DELAY_MAX;
4555 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4557 proc = chan_process[channel];
4558 if (NILP (proc))
4559 continue;
4560 /* Find minimum non-zero read_output_delay among the
4561 processes with non-zero read_output_skip. */
4562 if (XPROCESS (proc)->read_output_delay > 0)
4564 check_delay--;
4565 if (!XPROCESS (proc)->read_output_skip)
4566 continue;
4567 FD_CLR (channel, &Available);
4568 XPROCESS (proc)->read_output_skip = 0;
4569 if (XPROCESS (proc)->read_output_delay < nsecs)
4570 nsecs = XPROCESS (proc)->read_output_delay;
4573 timeout = make_timespec (0, nsecs);
4574 process_output_skip = 0;
4576 #endif
4578 #if defined (HAVE_NS)
4579 nfds = ns_select
4580 #elif defined (HAVE_GLIB)
4581 nfds = xg_select
4582 #else
4583 nfds = pselect
4584 #endif
4585 (max (max_process_desc, max_input_desc) + 1,
4586 &Available,
4587 (check_write ? &Writeok : 0),
4588 NULL, &timeout, NULL);
4590 #ifdef HAVE_GNUTLS
4591 /* GnuTLS buffers data internally. In lowat mode it leaves
4592 some data in the TCP buffers so that select works, but
4593 with custom pull/push functions we need to check if some
4594 data is available in the buffers manually. */
4595 if (nfds == 0)
4597 if (! wait_proc)
4599 /* We're not waiting on a specific process, so loop
4600 through all the channels and check for data.
4601 This is a workaround needed for some versions of
4602 the gnutls library -- 2.12.14 has been confirmed
4603 to need it. See
4604 http://comments.gmane.org/gmane.emacs.devel/145074 */
4605 for (channel = 0; channel < FD_SETSIZE; ++channel)
4606 if (! NILP (chan_process[channel]))
4608 struct Lisp_Process *p =
4609 XPROCESS (chan_process[channel]);
4610 if (p && p->gnutls_p && p->infd
4611 && ((emacs_gnutls_record_check_pending
4612 (p->gnutls_state))
4613 > 0))
4615 nfds++;
4616 FD_SET (p->infd, &Available);
4620 else
4622 /* Check this specific channel. */
4623 if (wait_proc->gnutls_p /* Check for valid process. */
4624 /* Do we have pending data? */
4625 && ((emacs_gnutls_record_check_pending
4626 (wait_proc->gnutls_state))
4627 > 0))
4629 nfds = 1;
4630 /* Set to Available. */
4631 FD_SET (wait_proc->infd, &Available);
4635 #endif
4638 xerrno = errno;
4640 /* Make C-g and alarm signals set flags again */
4641 clear_waiting_for_input ();
4643 /* If we woke up due to SIGWINCH, actually change size now. */
4644 do_pending_window_change (0);
4646 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4647 /* We waited the full specified time, so return now. */
4648 break;
4649 if (nfds < 0)
4651 if (xerrno == EINTR)
4652 no_avail = 1;
4653 else if (xerrno == EBADF)
4654 emacs_abort ();
4655 else
4656 report_file_errno ("Failed select", Qnil, xerrno);
4659 if (no_avail)
4661 FD_ZERO (&Available);
4662 check_write = 0;
4665 /* Check for keyboard input */
4666 /* If there is any, return immediately
4667 to give it higher priority than subprocesses */
4669 if (read_kbd != 0)
4671 unsigned old_timers_run = timers_run;
4672 struct buffer *old_buffer = current_buffer;
4673 Lisp_Object old_window = selected_window;
4674 bool leave = 0;
4676 if (detect_input_pending_run_timers (do_display))
4678 swallow_events (do_display);
4679 if (detect_input_pending_run_timers (do_display))
4680 leave = 1;
4683 /* If a timer has run, this might have changed buffers
4684 an alike. Make read_key_sequence aware of that. */
4685 if (timers_run != old_timers_run
4686 && waiting_for_user_input_p == -1
4687 && (old_buffer != current_buffer
4688 || !EQ (old_window, selected_window)))
4689 record_asynch_buffer_change ();
4691 if (leave)
4692 break;
4695 /* If there is unread keyboard input, also return. */
4696 if (read_kbd != 0
4697 && requeued_events_pending_p ())
4698 break;
4700 /* If we are not checking for keyboard input now,
4701 do process events (but don't run any timers).
4702 This is so that X events will be processed.
4703 Otherwise they may have to wait until polling takes place.
4704 That would causes delays in pasting selections, for example.
4706 (We used to do this only if wait_for_cell.) */
4707 if (read_kbd == 0 && detect_input_pending ())
4709 swallow_events (do_display);
4710 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4711 if (detect_input_pending ())
4712 break;
4713 #endif
4716 /* Exit now if the cell we're waiting for became non-nil. */
4717 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4718 break;
4720 #ifdef USABLE_SIGIO
4721 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4722 go read it. This can happen with X on BSD after logging out.
4723 In that case, there really is no input and no SIGIO,
4724 but select says there is input. */
4726 if (read_kbd && interrupt_input
4727 && keyboard_bit_set (&Available) && ! noninteractive)
4728 handle_input_available_signal (SIGIO);
4729 #endif
4731 if (! wait_proc)
4732 got_some_input |= nfds > 0;
4734 /* If checking input just got us a size-change event from X,
4735 obey it now if we should. */
4736 if (read_kbd || ! NILP (wait_for_cell))
4737 do_pending_window_change (0);
4739 /* Check for data from a process. */
4740 if (no_avail || nfds == 0)
4741 continue;
4743 for (channel = 0; channel <= max_input_desc; ++channel)
4745 struct fd_callback_data *d = &fd_callback_info[channel];
4746 if (d->func
4747 && ((d->condition & FOR_READ
4748 && FD_ISSET (channel, &Available))
4749 || (d->condition & FOR_WRITE
4750 && FD_ISSET (channel, &write_mask))))
4751 d->func (channel, d->data);
4754 for (channel = 0; channel <= max_process_desc; channel++)
4756 if (FD_ISSET (channel, &Available)
4757 && FD_ISSET (channel, &non_keyboard_wait_mask)
4758 && !FD_ISSET (channel, &non_process_wait_mask))
4760 int nread;
4762 /* If waiting for this channel, arrange to return as
4763 soon as no more input to be processed. No more
4764 waiting. */
4765 if (wait_channel == channel)
4767 wait_channel = -1;
4768 nsecs = -1;
4769 got_some_input = 1;
4771 proc = chan_process[channel];
4772 if (NILP (proc))
4773 continue;
4775 /* If this is a server stream socket, accept connection. */
4776 if (EQ (XPROCESS (proc)->status, Qlisten))
4778 server_accept_connection (proc, channel);
4779 continue;
4782 /* Read data from the process, starting with our
4783 buffered-ahead character if we have one. */
4785 nread = read_process_output (proc, channel);
4786 if (nread > 0)
4788 /* Since read_process_output can run a filter,
4789 which can call accept-process-output,
4790 don't try to read from any other processes
4791 before doing the select again. */
4792 FD_ZERO (&Available);
4794 if (do_display)
4795 redisplay_preserve_echo_area (12);
4797 #ifdef EWOULDBLOCK
4798 else if (nread == -1 && errno == EWOULDBLOCK)
4800 #endif
4801 else if (nread == -1 && errno == EAGAIN)
4803 #ifdef WINDOWSNT
4804 /* FIXME: Is this special case still needed? */
4805 /* Note that we cannot distinguish between no input
4806 available now and a closed pipe.
4807 With luck, a closed pipe will be accompanied by
4808 subprocess termination and SIGCHLD. */
4809 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4811 #endif
4812 #ifdef HAVE_PTYS
4813 /* On some OSs with ptys, when the process on one end of
4814 a pty exits, the other end gets an error reading with
4815 errno = EIO instead of getting an EOF (0 bytes read).
4816 Therefore, if we get an error reading and errno =
4817 EIO, just continue, because the child process has
4818 exited and should clean itself up soon (e.g. when we
4819 get a SIGCHLD). */
4820 else if (nread == -1 && errno == EIO)
4822 struct Lisp_Process *p = XPROCESS (proc);
4824 /* Clear the descriptor now, so we only raise the
4825 signal once. */
4826 FD_CLR (channel, &input_wait_mask);
4827 FD_CLR (channel, &non_keyboard_wait_mask);
4829 if (p->pid == -2)
4831 /* If the EIO occurs on a pty, the SIGCHLD handler's
4832 waitpid call will not find the process object to
4833 delete. Do it here. */
4834 p->tick = ++process_tick;
4835 pset_status (p, Qfailed);
4838 #endif /* HAVE_PTYS */
4839 /* If we can detect process termination, don't consider the
4840 process gone just because its pipe is closed. */
4841 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4843 else
4845 /* Preserve status of processes already terminated. */
4846 XPROCESS (proc)->tick = ++process_tick;
4847 deactivate_process (proc);
4848 if (XPROCESS (proc)->raw_status_new)
4849 update_status (XPROCESS (proc));
4850 if (EQ (XPROCESS (proc)->status, Qrun))
4851 pset_status (XPROCESS (proc),
4852 list2 (Qexit, make_number (256)));
4855 #ifdef NON_BLOCKING_CONNECT
4856 if (FD_ISSET (channel, &Writeok)
4857 && FD_ISSET (channel, &connect_wait_mask))
4859 struct Lisp_Process *p;
4861 FD_CLR (channel, &connect_wait_mask);
4862 FD_CLR (channel, &write_mask);
4863 if (--num_pending_connects < 0)
4864 emacs_abort ();
4866 proc = chan_process[channel];
4867 if (NILP (proc))
4868 continue;
4870 p = XPROCESS (proc);
4872 #ifdef GNU_LINUX
4873 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4874 So only use it on systems where it is known to work. */
4876 socklen_t xlen = sizeof (xerrno);
4877 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4878 xerrno = errno;
4880 #else
4882 struct sockaddr pname;
4883 socklen_t pnamelen = sizeof (pname);
4885 /* If connection failed, getpeername will fail. */
4886 xerrno = 0;
4887 if (getpeername (channel, &pname, &pnamelen) < 0)
4889 /* Obtain connect failure code through error slippage. */
4890 char dummy;
4891 xerrno = errno;
4892 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
4893 xerrno = errno;
4896 #endif
4897 if (xerrno)
4899 p->tick = ++process_tick;
4900 pset_status (p, list2 (Qfailed, make_number (xerrno)));
4901 deactivate_process (proc);
4903 else
4905 pset_status (p, Qrun);
4906 /* Execute the sentinel here. If we had relied on
4907 status_notify to do it later, it will read input
4908 from the process before calling the sentinel. */
4909 exec_sentinel (proc, build_string ("open\n"));
4910 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
4912 FD_SET (p->infd, &input_wait_mask);
4913 FD_SET (p->infd, &non_keyboard_wait_mask);
4917 #endif /* NON_BLOCKING_CONNECT */
4918 } /* End for each file descriptor. */
4919 } /* End while exit conditions not met. */
4921 unbind_to (count, Qnil);
4923 /* If calling from keyboard input, do not quit
4924 since we want to return C-g as an input character.
4925 Otherwise, do pending quit if requested. */
4926 if (read_kbd >= 0)
4928 /* Prevent input_pending from remaining set if we quit. */
4929 clear_input_pending ();
4930 QUIT;
4933 return got_some_input;
4936 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4938 static Lisp_Object
4939 read_process_output_call (Lisp_Object fun_and_args)
4941 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4944 static Lisp_Object
4945 read_process_output_error_handler (Lisp_Object error_val)
4947 cmd_error_internal (error_val, "error in process filter: ");
4948 Vinhibit_quit = Qt;
4949 update_echo_area ();
4950 Fsleep_for (make_number (2), Qnil);
4951 return Qt;
4954 static void
4955 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
4956 ssize_t nbytes,
4957 struct coding_system *coding);
4959 /* Read pending output from the process channel,
4960 starting with our buffered-ahead character if we have one.
4961 Yield number of decoded characters read.
4963 This function reads at most 4096 characters.
4964 If you want to read all available subprocess output,
4965 you must call it repeatedly until it returns zero.
4967 The characters read are decoded according to PROC's coding-system
4968 for decoding. */
4970 static int
4971 read_process_output (Lisp_Object proc, register int channel)
4973 register ssize_t nbytes;
4974 char *chars;
4975 register struct Lisp_Process *p = XPROCESS (proc);
4976 struct coding_system *coding = proc_decode_coding_system[channel];
4977 int carryover = p->decoding_carryover;
4978 int readmax = 4096;
4979 ptrdiff_t count = SPECPDL_INDEX ();
4980 Lisp_Object odeactivate;
4982 chars = alloca (carryover + readmax);
4983 if (carryover)
4984 /* See the comment above. */
4985 memcpy (chars, SDATA (p->decoding_buf), carryover);
4987 #ifdef DATAGRAM_SOCKETS
4988 /* We have a working select, so proc_buffered_char is always -1. */
4989 if (DATAGRAM_CHAN_P (channel))
4991 socklen_t len = datagram_address[channel].len;
4992 nbytes = recvfrom (channel, chars + carryover, readmax,
4993 0, datagram_address[channel].sa, &len);
4995 else
4996 #endif
4998 bool buffered = proc_buffered_char[channel] >= 0;
4999 if (buffered)
5001 chars[carryover] = proc_buffered_char[channel];
5002 proc_buffered_char[channel] = -1;
5004 #ifdef HAVE_GNUTLS
5005 if (p->gnutls_p)
5006 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5007 readmax - buffered);
5008 else
5009 #endif
5010 nbytes = emacs_read (channel, chars + carryover + buffered,
5011 readmax - buffered);
5012 #ifdef ADAPTIVE_READ_BUFFERING
5013 if (nbytes > 0 && p->adaptive_read_buffering)
5015 int delay = p->read_output_delay;
5016 if (nbytes < 256)
5018 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5020 if (delay == 0)
5021 process_output_delay_count++;
5022 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5025 else if (delay > 0 && nbytes == readmax - buffered)
5027 delay -= READ_OUTPUT_DELAY_INCREMENT;
5028 if (delay == 0)
5029 process_output_delay_count--;
5031 p->read_output_delay = delay;
5032 if (delay)
5034 p->read_output_skip = 1;
5035 process_output_skip = 1;
5038 #endif
5039 nbytes += buffered;
5040 nbytes += buffered && nbytes <= 0;
5043 p->decoding_carryover = 0;
5045 /* At this point, NBYTES holds number of bytes just received
5046 (including the one in proc_buffered_char[channel]). */
5047 if (nbytes <= 0)
5049 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5050 return nbytes;
5051 coding->mode |= CODING_MODE_LAST_BLOCK;
5054 /* Now set NBYTES how many bytes we must decode. */
5055 nbytes += carryover;
5057 odeactivate = Vdeactivate_mark;
5058 /* There's no good reason to let process filters change the current
5059 buffer, and many callers of accept-process-output, sit-for, and
5060 friends don't expect current-buffer to be changed from under them. */
5061 record_unwind_current_buffer ();
5063 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5065 /* Handling the process output should not deactivate the mark. */
5066 Vdeactivate_mark = odeactivate;
5068 unbind_to (count, Qnil);
5069 return nbytes;
5072 static void
5073 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5074 ssize_t nbytes,
5075 struct coding_system *coding)
5077 Lisp_Object outstream = p->filter;
5078 Lisp_Object text;
5079 bool outer_running_asynch_code = running_asynch_code;
5080 int waiting = waiting_for_user_input_p;
5082 /* No need to gcpro these, because all we do with them later
5083 is test them for EQness, and none of them should be a string. */
5084 #if 0
5085 Lisp_Object obuffer, okeymap;
5086 XSETBUFFER (obuffer, current_buffer);
5087 okeymap = BVAR (current_buffer, keymap);
5088 #endif
5090 /* We inhibit quit here instead of just catching it so that
5091 hitting ^G when a filter happens to be running won't screw
5092 it up. */
5093 specbind (Qinhibit_quit, Qt);
5094 specbind (Qlast_nonmenu_event, Qt);
5096 /* In case we get recursively called,
5097 and we already saved the match data nonrecursively,
5098 save the same match data in safely recursive fashion. */
5099 if (outer_running_asynch_code)
5101 Lisp_Object tem;
5102 /* Don't clobber the CURRENT match data, either! */
5103 tem = Fmatch_data (Qnil, Qnil, Qnil);
5104 restore_search_regs ();
5105 record_unwind_save_match_data ();
5106 Fset_match_data (tem, Qt);
5109 /* For speed, if a search happens within this code,
5110 save the match data in a special nonrecursive fashion. */
5111 running_asynch_code = 1;
5113 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5114 text = coding->dst_object;
5115 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5116 /* A new coding system might be found. */
5117 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5119 pset_decode_coding_system (p, Vlast_coding_system_used);
5121 /* Don't call setup_coding_system for
5122 proc_decode_coding_system[channel] here. It is done in
5123 detect_coding called via decode_coding above. */
5125 /* If a coding system for encoding is not yet decided, we set
5126 it as the same as coding-system for decoding.
5128 But, before doing that we must check if
5129 proc_encode_coding_system[p->outfd] surely points to a
5130 valid memory because p->outfd will be changed once EOF is
5131 sent to the process. */
5132 if (NILP (p->encode_coding_system)
5133 && proc_encode_coding_system[p->outfd])
5135 pset_encode_coding_system
5136 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5137 setup_coding_system (p->encode_coding_system,
5138 proc_encode_coding_system[p->outfd]);
5142 if (coding->carryover_bytes > 0)
5144 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5145 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5146 memcpy (SDATA (p->decoding_buf), coding->carryover,
5147 coding->carryover_bytes);
5148 p->decoding_carryover = coding->carryover_bytes;
5150 if (SBYTES (text) > 0)
5151 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5152 sometimes it's simply wrong to wrap (e.g. when called from
5153 accept-process-output). */
5154 internal_condition_case_1 (read_process_output_call,
5155 list3 (outstream, make_lisp_proc (p), text),
5156 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5157 read_process_output_error_handler);
5159 /* If we saved the match data nonrecursively, restore it now. */
5160 restore_search_regs ();
5161 running_asynch_code = outer_running_asynch_code;
5163 /* Restore waiting_for_user_input_p as it was
5164 when we were called, in case the filter clobbered it. */
5165 waiting_for_user_input_p = waiting;
5167 #if 0 /* Call record_asynch_buffer_change unconditionally,
5168 because we might have changed minor modes or other things
5169 that affect key bindings. */
5170 if (! EQ (Fcurrent_buffer (), obuffer)
5171 || ! EQ (current_buffer->keymap, okeymap))
5172 #endif
5173 /* But do it only if the caller is actually going to read events.
5174 Otherwise there's no need to make him wake up, and it could
5175 cause trouble (for example it would make sit_for return). */
5176 if (waiting_for_user_input_p == -1)
5177 record_asynch_buffer_change ();
5180 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5181 Sinternal_default_process_filter, 2, 2, 0,
5182 doc: /* Function used as default process filter. */)
5183 (Lisp_Object proc, Lisp_Object text)
5185 struct Lisp_Process *p;
5186 ptrdiff_t opoint;
5188 CHECK_PROCESS (proc);
5189 p = XPROCESS (proc);
5190 CHECK_STRING (text);
5192 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5194 Lisp_Object old_read_only;
5195 ptrdiff_t old_begv, old_zv;
5196 ptrdiff_t old_begv_byte, old_zv_byte;
5197 ptrdiff_t before, before_byte;
5198 ptrdiff_t opoint_byte;
5199 struct buffer *b;
5201 Fset_buffer (p->buffer);
5202 opoint = PT;
5203 opoint_byte = PT_BYTE;
5204 old_read_only = BVAR (current_buffer, read_only);
5205 old_begv = BEGV;
5206 old_zv = ZV;
5207 old_begv_byte = BEGV_BYTE;
5208 old_zv_byte = ZV_BYTE;
5210 bset_read_only (current_buffer, Qnil);
5212 /* Insert new output into buffer at the current end-of-output
5213 marker, thus preserving logical ordering of input and output. */
5214 if (XMARKER (p->mark)->buffer)
5215 set_point_from_marker (p->mark);
5216 else
5217 SET_PT_BOTH (ZV, ZV_BYTE);
5218 before = PT;
5219 before_byte = PT_BYTE;
5221 /* If the output marker is outside of the visible region, save
5222 the restriction and widen. */
5223 if (! (BEGV <= PT && PT <= ZV))
5224 Fwiden ();
5226 /* Adjust the multibyteness of TEXT to that of the buffer. */
5227 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5228 != ! STRING_MULTIBYTE (text))
5229 text = (STRING_MULTIBYTE (text)
5230 ? Fstring_as_unibyte (text)
5231 : Fstring_to_multibyte (text));
5232 /* Insert before markers in case we are inserting where
5233 the buffer's mark is, and the user's next command is Meta-y. */
5234 insert_from_string_before_markers (text, 0, 0,
5235 SCHARS (text), SBYTES (text), 0);
5237 /* Make sure the process marker's position is valid when the
5238 process buffer is changed in the signal_after_change above.
5239 W3 is known to do that. */
5240 if (BUFFERP (p->buffer)
5241 && (b = XBUFFER (p->buffer), b != current_buffer))
5242 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5243 else
5244 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5246 update_mode_lines++;
5248 /* Make sure opoint and the old restrictions
5249 float ahead of any new text just as point would. */
5250 if (opoint >= before)
5252 opoint += PT - before;
5253 opoint_byte += PT_BYTE - before_byte;
5255 if (old_begv > before)
5257 old_begv += PT - before;
5258 old_begv_byte += PT_BYTE - before_byte;
5260 if (old_zv >= before)
5262 old_zv += PT - before;
5263 old_zv_byte += PT_BYTE - before_byte;
5266 /* If the restriction isn't what it should be, set it. */
5267 if (old_begv != BEGV || old_zv != ZV)
5268 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5270 bset_read_only (current_buffer, old_read_only);
5271 SET_PT_BOTH (opoint, opoint_byte);
5273 return Qnil;
5276 /* Sending data to subprocess. */
5278 /* In send_process, when a write fails temporarily,
5279 wait_reading_process_output is called. It may execute user code,
5280 e.g. timers, that attempts to write new data to the same process.
5281 We must ensure that data is sent in the right order, and not
5282 interspersed half-completed with other writes (Bug#10815). This is
5283 handled by the write_queue element of struct process. It is a list
5284 with each entry having the form
5286 (string . (offset . length))
5288 where STRING is a lisp string, OFFSET is the offset into the
5289 string's byte sequence from which we should begin to send, and
5290 LENGTH is the number of bytes left to send. */
5292 /* Create a new entry in write_queue.
5293 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5294 BUF is a pointer to the string sequence of the input_obj or a C
5295 string in case of Qt or Qnil. */
5297 static void
5298 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5299 const char *buf, ptrdiff_t len, bool front)
5301 ptrdiff_t offset;
5302 Lisp_Object entry, obj;
5304 if (STRINGP (input_obj))
5306 offset = buf - SSDATA (input_obj);
5307 obj = input_obj;
5309 else
5311 offset = 0;
5312 obj = make_unibyte_string (buf, len);
5315 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5317 if (front)
5318 pset_write_queue (p, Fcons (entry, p->write_queue));
5319 else
5320 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5323 /* Remove the first element in the write_queue of process P, put its
5324 contents in OBJ, BUF and LEN, and return true. If the
5325 write_queue is empty, return false. */
5327 static bool
5328 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5329 const char **buf, ptrdiff_t *len)
5331 Lisp_Object entry, offset_length;
5332 ptrdiff_t offset;
5334 if (NILP (p->write_queue))
5335 return 0;
5337 entry = XCAR (p->write_queue);
5338 pset_write_queue (p, XCDR (p->write_queue));
5340 *obj = XCAR (entry);
5341 offset_length = XCDR (entry);
5343 *len = XINT (XCDR (offset_length));
5344 offset = XINT (XCAR (offset_length));
5345 *buf = SSDATA (*obj) + offset;
5347 return 1;
5350 /* Send some data to process PROC.
5351 BUF is the beginning of the data; LEN is the number of characters.
5352 OBJECT is the Lisp object that the data comes from. If OBJECT is
5353 nil or t, it means that the data comes from C string.
5355 If OBJECT is not nil, the data is encoded by PROC's coding-system
5356 for encoding before it is sent.
5358 This function can evaluate Lisp code and can garbage collect. */
5360 static void
5361 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5362 Lisp_Object object)
5364 struct Lisp_Process *p = XPROCESS (proc);
5365 ssize_t rv;
5366 struct coding_system *coding;
5368 if (p->raw_status_new)
5369 update_status (p);
5370 if (! EQ (p->status, Qrun))
5371 error ("Process %s not running", SDATA (p->name));
5372 if (p->outfd < 0)
5373 error ("Output file descriptor of %s is closed", SDATA (p->name));
5375 coding = proc_encode_coding_system[p->outfd];
5376 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5378 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5379 || (BUFFERP (object)
5380 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5381 || EQ (object, Qt))
5383 pset_encode_coding_system
5384 (p, complement_process_encoding_system (p->encode_coding_system));
5385 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5387 /* The coding system for encoding was changed to raw-text
5388 because we sent a unibyte text previously. Now we are
5389 sending a multibyte text, thus we must encode it by the
5390 original coding system specified for the current process.
5392 Another reason we come here is that the coding system
5393 was just complemented and a new one was returned by
5394 complement_process_encoding_system. */
5395 setup_coding_system (p->encode_coding_system, coding);
5396 Vlast_coding_system_used = p->encode_coding_system;
5398 coding->src_multibyte = 1;
5400 else
5402 coding->src_multibyte = 0;
5403 /* For sending a unibyte text, character code conversion should
5404 not take place but EOL conversion should. So, setup raw-text
5405 or one of the subsidiary if we have not yet done it. */
5406 if (CODING_REQUIRE_ENCODING (coding))
5408 if (CODING_REQUIRE_FLUSHING (coding))
5410 /* But, before changing the coding, we must flush out data. */
5411 coding->mode |= CODING_MODE_LAST_BLOCK;
5412 send_process (proc, "", 0, Qt);
5413 coding->mode &= CODING_MODE_LAST_BLOCK;
5415 setup_coding_system (raw_text_coding_system
5416 (Vlast_coding_system_used),
5417 coding);
5418 coding->src_multibyte = 0;
5421 coding->dst_multibyte = 0;
5423 if (CODING_REQUIRE_ENCODING (coding))
5425 coding->dst_object = Qt;
5426 if (BUFFERP (object))
5428 ptrdiff_t from_byte, from, to;
5429 ptrdiff_t save_pt, save_pt_byte;
5430 struct buffer *cur = current_buffer;
5432 set_buffer_internal (XBUFFER (object));
5433 save_pt = PT, save_pt_byte = PT_BYTE;
5435 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5436 from = BYTE_TO_CHAR (from_byte);
5437 to = BYTE_TO_CHAR (from_byte + len);
5438 TEMP_SET_PT_BOTH (from, from_byte);
5439 encode_coding_object (coding, object, from, from_byte,
5440 to, from_byte + len, Qt);
5441 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5442 set_buffer_internal (cur);
5444 else if (STRINGP (object))
5446 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5447 SBYTES (object), Qt);
5449 else
5451 coding->dst_object = make_unibyte_string (buf, len);
5452 coding->produced = len;
5455 len = coding->produced;
5456 object = coding->dst_object;
5457 buf = SSDATA (object);
5460 /* If there is already data in the write_queue, put the new data
5461 in the back of queue. Otherwise, ignore it. */
5462 if (!NILP (p->write_queue))
5463 write_queue_push (p, object, buf, len, 0);
5465 do /* while !NILP (p->write_queue) */
5467 ptrdiff_t cur_len = -1;
5468 const char *cur_buf;
5469 Lisp_Object cur_object;
5471 /* If write_queue is empty, ignore it. */
5472 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5474 cur_len = len;
5475 cur_buf = buf;
5476 cur_object = object;
5479 while (cur_len > 0)
5481 /* Send this batch, using one or more write calls. */
5482 ptrdiff_t written = 0;
5483 int outfd = p->outfd;
5484 #ifdef DATAGRAM_SOCKETS
5485 if (DATAGRAM_CHAN_P (outfd))
5487 rv = sendto (outfd, cur_buf, cur_len,
5488 0, datagram_address[outfd].sa,
5489 datagram_address[outfd].len);
5490 if (rv >= 0)
5491 written = rv;
5492 else if (errno == EMSGSIZE)
5493 report_file_error ("Sending datagram", proc);
5495 else
5496 #endif
5498 #ifdef HAVE_GNUTLS
5499 if (p->gnutls_p)
5500 written = emacs_gnutls_write (p, cur_buf, cur_len);
5501 else
5502 #endif
5503 written = emacs_write_sig (outfd, cur_buf, cur_len);
5504 rv = (written ? 0 : -1);
5505 #ifdef ADAPTIVE_READ_BUFFERING
5506 if (p->read_output_delay > 0
5507 && p->adaptive_read_buffering == 1)
5509 p->read_output_delay = 0;
5510 process_output_delay_count--;
5511 p->read_output_skip = 0;
5513 #endif
5516 if (rv < 0)
5518 if (errno == EAGAIN
5519 #ifdef EWOULDBLOCK
5520 || errno == EWOULDBLOCK
5521 #endif
5523 /* Buffer is full. Wait, accepting input;
5524 that may allow the program
5525 to finish doing output and read more. */
5527 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5528 /* A gross hack to work around a bug in FreeBSD.
5529 In the following sequence, read(2) returns
5530 bogus data:
5532 write(2) 1022 bytes
5533 write(2) 954 bytes, get EAGAIN
5534 read(2) 1024 bytes in process_read_output
5535 read(2) 11 bytes in process_read_output
5537 That is, read(2) returns more bytes than have
5538 ever been written successfully. The 1033 bytes
5539 read are the 1022 bytes written successfully
5540 after processing (for example with CRs added if
5541 the terminal is set up that way which it is
5542 here). The same bytes will be seen again in a
5543 later read(2), without the CRs. */
5545 if (errno == EAGAIN)
5547 int flags = FWRITE;
5548 ioctl (p->outfd, TIOCFLUSH, &flags);
5550 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5552 /* Put what we should have written in wait_queue. */
5553 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5554 wait_reading_process_output (0, 20 * 1000 * 1000,
5555 0, 0, Qnil, NULL, 0);
5556 /* Reread queue, to see what is left. */
5557 break;
5559 else if (errno == EPIPE)
5561 p->raw_status_new = 0;
5562 pset_status (p, list2 (Qexit, make_number (256)));
5563 p->tick = ++process_tick;
5564 deactivate_process (proc);
5565 error ("process %s no longer connected to pipe; closed it",
5566 SDATA (p->name));
5568 else
5569 /* This is a real error. */
5570 report_file_error ("Writing to process", proc);
5572 cur_buf += written;
5573 cur_len -= written;
5576 while (!NILP (p->write_queue));
5579 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5580 3, 3, 0,
5581 doc: /* Send current contents of region as input to PROCESS.
5582 PROCESS may be a process, a buffer, the name of a process or buffer, or
5583 nil, indicating the current buffer's process.
5584 Called from program, takes three arguments, PROCESS, START and END.
5585 If the region is more than 500 characters long,
5586 it is sent in several bunches. This may happen even for shorter regions.
5587 Output from processes can arrive in between bunches. */)
5588 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5590 Lisp_Object proc = get_process (process);
5591 ptrdiff_t start_byte, end_byte;
5593 validate_region (&start, &end);
5595 start_byte = CHAR_TO_BYTE (XINT (start));
5596 end_byte = CHAR_TO_BYTE (XINT (end));
5598 if (XINT (start) < GPT && XINT (end) > GPT)
5599 move_gap_both (XINT (start), start_byte);
5601 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5602 end_byte - start_byte, Fcurrent_buffer ());
5604 return Qnil;
5607 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5608 2, 2, 0,
5609 doc: /* Send PROCESS the contents of STRING as input.
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 If STRING is more than 500 characters long,
5613 it is sent in several bunches. This may happen even for shorter strings.
5614 Output from processes can arrive in between bunches. */)
5615 (Lisp_Object process, Lisp_Object string)
5617 Lisp_Object proc;
5618 CHECK_STRING (string);
5619 proc = get_process (process);
5620 send_process (proc, SSDATA (string),
5621 SBYTES (string), string);
5622 return Qnil;
5625 /* Return the foreground process group for the tty/pty that
5626 the process P uses. */
5627 static pid_t
5628 emacs_get_tty_pgrp (struct Lisp_Process *p)
5630 pid_t gid = -1;
5632 #ifdef TIOCGPGRP
5633 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5635 int fd;
5636 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5637 master side. Try the slave side. */
5638 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5640 if (fd != -1)
5642 ioctl (fd, TIOCGPGRP, &gid);
5643 emacs_close (fd);
5646 #endif /* defined (TIOCGPGRP ) */
5648 return gid;
5651 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5652 Sprocess_running_child_p, 0, 1, 0,
5653 doc: /* Return t if PROCESS has given the terminal to a child.
5654 If the operating system does not make it possible to find out,
5655 return t unconditionally. */)
5656 (Lisp_Object process)
5658 /* Initialize in case ioctl doesn't exist or gives an error,
5659 in a way that will cause returning t. */
5660 pid_t gid;
5661 Lisp_Object proc;
5662 struct Lisp_Process *p;
5664 proc = get_process (process);
5665 p = XPROCESS (proc);
5667 if (!EQ (p->type, Qreal))
5668 error ("Process %s is not a subprocess",
5669 SDATA (p->name));
5670 if (p->infd < 0)
5671 error ("Process %s is not active",
5672 SDATA (p->name));
5674 gid = emacs_get_tty_pgrp (p);
5676 if (gid == p->pid)
5677 return Qnil;
5678 return Qt;
5681 /* send a signal number SIGNO to PROCESS.
5682 If CURRENT_GROUP is t, that means send to the process group
5683 that currently owns the terminal being used to communicate with PROCESS.
5684 This is used for various commands in shell mode.
5685 If CURRENT_GROUP is lambda, that means send to the process group
5686 that currently owns the terminal, but only if it is NOT the shell itself.
5688 If NOMSG is false, insert signal-announcements into process's buffers
5689 right away.
5691 If we can, we try to signal PROCESS by sending control characters
5692 down the pty. This allows us to signal inferiors who have changed
5693 their uid, for which kill would return an EPERM error. */
5695 static void
5696 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5697 bool nomsg)
5699 Lisp_Object proc;
5700 struct Lisp_Process *p;
5701 pid_t gid;
5702 bool no_pgrp = 0;
5704 proc = get_process (process);
5705 p = XPROCESS (proc);
5707 if (!EQ (p->type, Qreal))
5708 error ("Process %s is not a subprocess",
5709 SDATA (p->name));
5710 if (p->infd < 0)
5711 error ("Process %s is not active",
5712 SDATA (p->name));
5714 if (!p->pty_flag)
5715 current_group = Qnil;
5717 /* If we are using pgrps, get a pgrp number and make it negative. */
5718 if (NILP (current_group))
5719 /* Send the signal to the shell's process group. */
5720 gid = p->pid;
5721 else
5723 #ifdef SIGNALS_VIA_CHARACTERS
5724 /* If possible, send signals to the entire pgrp
5725 by sending an input character to it. */
5727 struct termios t;
5728 cc_t *sig_char = NULL;
5730 tcgetattr (p->infd, &t);
5732 switch (signo)
5734 case SIGINT:
5735 sig_char = &t.c_cc[VINTR];
5736 break;
5738 case SIGQUIT:
5739 sig_char = &t.c_cc[VQUIT];
5740 break;
5742 case SIGTSTP:
5743 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5744 sig_char = &t.c_cc[VSWTCH];
5745 #else
5746 sig_char = &t.c_cc[VSUSP];
5747 #endif
5748 break;
5751 if (sig_char && *sig_char != CDISABLE)
5753 send_process (proc, (char *) sig_char, 1, Qnil);
5754 return;
5756 /* If we can't send the signal with a character,
5757 fall through and send it another way. */
5759 /* The code above may fall through if it can't
5760 handle the signal. */
5761 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5763 #ifdef TIOCGPGRP
5764 /* Get the current pgrp using the tty itself, if we have that.
5765 Otherwise, use the pty to get the pgrp.
5766 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5767 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5768 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5769 His patch indicates that if TIOCGPGRP returns an error, then
5770 we should just assume that p->pid is also the process group id. */
5772 gid = emacs_get_tty_pgrp (p);
5774 if (gid == -1)
5775 /* If we can't get the information, assume
5776 the shell owns the tty. */
5777 gid = p->pid;
5779 /* It is not clear whether anything really can set GID to -1.
5780 Perhaps on some system one of those ioctls can or could do so.
5781 Or perhaps this is vestigial. */
5782 if (gid == -1)
5783 no_pgrp = 1;
5784 #else /* ! defined (TIOCGPGRP ) */
5785 /* Can't select pgrps on this system, so we know that
5786 the child itself heads the pgrp. */
5787 gid = p->pid;
5788 #endif /* ! defined (TIOCGPGRP ) */
5790 /* If current_group is lambda, and the shell owns the terminal,
5791 don't send any signal. */
5792 if (EQ (current_group, Qlambda) && gid == p->pid)
5793 return;
5796 #ifdef SIGCONT
5797 if (signo == SIGCONT)
5799 p->raw_status_new = 0;
5800 pset_status (p, Qrun);
5801 p->tick = ++process_tick;
5802 if (!nomsg)
5804 status_notify (NULL);
5805 redisplay_preserve_echo_area (13);
5808 #endif
5810 /* If we don't have process groups, send the signal to the immediate
5811 subprocess. That isn't really right, but it's better than any
5812 obvious alternative. */
5813 if (no_pgrp)
5815 kill (p->pid, signo);
5816 return;
5819 /* gid may be a pid, or minus a pgrp's number */
5820 #ifdef TIOCSIGSEND
5821 if (!NILP (current_group))
5823 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
5824 kill (-gid, signo);
5826 else
5828 gid = - p->pid;
5829 kill (gid, signo);
5831 #else /* ! defined (TIOCSIGSEND) */
5832 kill (-gid, signo);
5833 #endif /* ! defined (TIOCSIGSEND) */
5836 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5837 doc: /* Interrupt process PROCESS.
5838 PROCESS may be a process, a buffer, or the name of a process or buffer.
5839 No arg or nil means current buffer's process.
5840 Second arg CURRENT-GROUP non-nil means send signal to
5841 the current process-group of the process's controlling terminal
5842 rather than to the process's own process group.
5843 If the process is a shell, this means interrupt current subjob
5844 rather than the shell.
5846 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5847 don't send the signal. */)
5848 (Lisp_Object process, Lisp_Object current_group)
5850 process_send_signal (process, SIGINT, current_group, 0);
5851 return process;
5854 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5855 doc: /* Kill process PROCESS. May be process or name of one.
5856 See function `interrupt-process' for more details on usage. */)
5857 (Lisp_Object process, Lisp_Object current_group)
5859 process_send_signal (process, SIGKILL, current_group, 0);
5860 return process;
5863 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5864 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5865 See function `interrupt-process' for more details on usage. */)
5866 (Lisp_Object process, Lisp_Object current_group)
5868 process_send_signal (process, SIGQUIT, current_group, 0);
5869 return process;
5872 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
5873 doc: /* Stop process PROCESS. May be process or name of one.
5874 See function `interrupt-process' for more details on usage.
5875 If PROCESS is a network or serial process, inhibit handling of incoming
5876 traffic. */)
5877 (Lisp_Object process, Lisp_Object current_group)
5879 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5881 struct Lisp_Process *p;
5883 p = XPROCESS (process);
5884 if (NILP (p->command)
5885 && p->infd >= 0)
5887 FD_CLR (p->infd, &input_wait_mask);
5888 FD_CLR (p->infd, &non_keyboard_wait_mask);
5890 pset_command (p, Qt);
5891 return process;
5893 #ifndef SIGTSTP
5894 error ("No SIGTSTP support");
5895 #else
5896 process_send_signal (process, SIGTSTP, current_group, 0);
5897 #endif
5898 return process;
5901 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
5902 doc: /* Continue process PROCESS. May be process or name of one.
5903 See function `interrupt-process' for more details on usage.
5904 If PROCESS is a network or serial process, resume handling of incoming
5905 traffic. */)
5906 (Lisp_Object process, Lisp_Object current_group)
5908 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5910 struct Lisp_Process *p;
5912 p = XPROCESS (process);
5913 if (EQ (p->command, Qt)
5914 && p->infd >= 0
5915 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
5917 FD_SET (p->infd, &input_wait_mask);
5918 FD_SET (p->infd, &non_keyboard_wait_mask);
5919 #ifdef WINDOWSNT
5920 if (fd_info[ p->infd ].flags & FILE_SERIAL)
5921 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
5922 #else /* not WINDOWSNT */
5923 tcflush (p->infd, TCIFLUSH);
5924 #endif /* not WINDOWSNT */
5926 pset_command (p, Qnil);
5927 return process;
5929 #ifdef SIGCONT
5930 process_send_signal (process, SIGCONT, current_group, 0);
5931 #else
5932 error ("No SIGCONT support");
5933 #endif
5934 return process;
5937 /* Return the integer value of the signal whose abbreviation is ABBR,
5938 or a negative number if there is no such signal. */
5939 static int
5940 abbr_to_signal (char const *name)
5942 int i, signo;
5943 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
5945 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
5946 name += 3;
5948 for (i = 0; i < sizeof sigbuf; i++)
5950 sigbuf[i] = c_toupper (name[i]);
5951 if (! sigbuf[i])
5952 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
5955 return -1;
5958 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
5959 2, 2, "sProcess (name or number): \nnSignal code: ",
5960 doc: /* Send PROCESS the signal with code SIGCODE.
5961 PROCESS may also be a number specifying the process id of the
5962 process to signal; in this case, the process need not be a child of
5963 this Emacs.
5964 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5965 (Lisp_Object process, Lisp_Object sigcode)
5967 pid_t pid;
5968 int signo;
5970 if (STRINGP (process))
5972 Lisp_Object tem = Fget_process (process);
5973 if (NILP (tem))
5975 Lisp_Object process_number =
5976 string_to_number (SSDATA (process), 10, 1);
5977 if (INTEGERP (process_number) || FLOATP (process_number))
5978 tem = process_number;
5980 process = tem;
5982 else if (!NUMBERP (process))
5983 process = get_process (process);
5985 if (NILP (process))
5986 return process;
5988 if (NUMBERP (process))
5989 CONS_TO_INTEGER (process, pid_t, pid);
5990 else
5992 CHECK_PROCESS (process);
5993 pid = XPROCESS (process)->pid;
5994 if (pid <= 0)
5995 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
5998 if (INTEGERP (sigcode))
6000 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6001 signo = XINT (sigcode);
6003 else
6005 char *name;
6007 CHECK_SYMBOL (sigcode);
6008 name = SSDATA (SYMBOL_NAME (sigcode));
6010 signo = abbr_to_signal (name);
6011 if (signo < 0)
6012 error ("Undefined signal name %s", name);
6015 return make_number (kill (pid, signo));
6018 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6019 doc: /* Make PROCESS see end-of-file in its input.
6020 EOF comes after any text already sent to it.
6021 PROCESS may be a process, a buffer, the name of a process or buffer, or
6022 nil, indicating the current buffer's process.
6023 If PROCESS is a network connection, or is a process communicating
6024 through a pipe (as opposed to a pty), then you cannot send any more
6025 text to PROCESS after you call this function.
6026 If PROCESS is a serial process, wait until all output written to the
6027 process has been transmitted to the serial port. */)
6028 (Lisp_Object process)
6030 Lisp_Object proc;
6031 struct coding_system *coding;
6033 if (DATAGRAM_CONN_P (process))
6034 return process;
6036 proc = get_process (process);
6037 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6039 /* Make sure the process is really alive. */
6040 if (XPROCESS (proc)->raw_status_new)
6041 update_status (XPROCESS (proc));
6042 if (! EQ (XPROCESS (proc)->status, Qrun))
6043 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6045 if (CODING_REQUIRE_FLUSHING (coding))
6047 coding->mode |= CODING_MODE_LAST_BLOCK;
6048 send_process (proc, "", 0, Qnil);
6051 if (XPROCESS (proc)->pty_flag)
6052 send_process (proc, "\004", 1, Qnil);
6053 else if (EQ (XPROCESS (proc)->type, Qserial))
6055 #ifndef WINDOWSNT
6056 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6057 report_file_error ("Failed tcdrain", Qnil);
6058 #endif /* not WINDOWSNT */
6059 /* Do nothing on Windows because writes are blocking. */
6061 else
6063 int old_outfd = XPROCESS (proc)->outfd;
6064 int new_outfd;
6066 #ifdef HAVE_SHUTDOWN
6067 /* If this is a network connection, or socketpair is used
6068 for communication with the subprocess, call shutdown to cause EOF.
6069 (In some old system, shutdown to socketpair doesn't work.
6070 Then we just can't win.) */
6071 if (EQ (XPROCESS (proc)->type, Qnetwork)
6072 || XPROCESS (proc)->infd == old_outfd)
6073 shutdown (old_outfd, 1);
6074 #endif
6075 close_process_fd (&XPROCESS (proc)->open_fd[WRITE_TO_SUBPROCESS]);
6076 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6077 if (new_outfd < 0)
6078 report_file_error ("Opening null device", Qnil);
6079 XPROCESS (proc)->open_fd[WRITE_TO_SUBPROCESS] = new_outfd;
6080 XPROCESS (proc)->outfd = new_outfd;
6082 if (!proc_encode_coding_system[new_outfd])
6083 proc_encode_coding_system[new_outfd]
6084 = xmalloc (sizeof (struct coding_system));
6085 *proc_encode_coding_system[new_outfd]
6086 = *proc_encode_coding_system[old_outfd];
6087 memset (proc_encode_coding_system[old_outfd], 0,
6088 sizeof (struct coding_system));
6090 return process;
6093 /* The main Emacs thread records child processes in three places:
6095 - Vprocess_alist, for asynchronous subprocesses, which are child
6096 processes visible to Lisp.
6098 - deleted_pid_list, for child processes invisible to Lisp,
6099 typically because of delete-process. These are recorded so that
6100 the processes can be reaped when they exit, so that the operating
6101 system's process table is not cluttered by zombies.
6103 - the local variable PID in Fcall_process, call_process_cleanup and
6104 call_process_kill, for synchronous subprocesses.
6105 record_unwind_protect is used to make sure this process is not
6106 forgotten: if the user interrupts call-process and the child
6107 process refuses to exit immediately even with two C-g's,
6108 call_process_kill adds PID's contents to deleted_pid_list before
6109 returning.
6111 The main Emacs thread invokes waitpid only on child processes that
6112 it creates and that have not been reaped. This avoid races on
6113 platforms such as GTK, where other threads create their own
6114 subprocesses which the main thread should not reap. For example,
6115 if the main thread attempted to reap an already-reaped child, it
6116 might inadvertently reap a GTK-created process that happened to
6117 have the same process ID. */
6119 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6120 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6121 keep track of its own children. GNUstep is similar. */
6123 static void dummy_handler (int sig) {}
6124 static signal_handler_t volatile lib_child_handler;
6126 /* Handle a SIGCHLD signal by looking for known child processes of
6127 Emacs whose status have changed. For each one found, record its
6128 new status.
6130 All we do is change the status; we do not run sentinels or print
6131 notifications. That is saved for the next time keyboard input is
6132 done, in order to avoid timing errors.
6134 ** WARNING: this can be called during garbage collection.
6135 Therefore, it must not be fooled by the presence of mark bits in
6136 Lisp objects.
6138 ** USG WARNING: Although it is not obvious from the documentation
6139 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6140 signal() before executing at least one wait(), otherwise the
6141 handler will be called again, resulting in an infinite loop. The
6142 relevant portion of the documentation reads "SIGCLD signals will be
6143 queued and the signal-catching function will be continually
6144 reentered until the queue is empty". Invoking signal() causes the
6145 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6146 Inc.
6148 ** Malloc WARNING: This should never call malloc either directly or
6149 indirectly; if it does, that is a bug */
6151 static void
6152 handle_child_signal (int sig)
6154 Lisp_Object tail, proc;
6156 /* Find the process that signaled us, and record its status. */
6158 /* The process can have been deleted by Fdelete_process, or have
6159 been started asynchronously by Fcall_process. */
6160 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6162 bool all_pids_are_fixnums
6163 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6164 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6165 Lisp_Object head = XCAR (tail);
6166 Lisp_Object xpid;
6167 if (! CONSP (head))
6168 continue;
6169 xpid = XCAR (head);
6170 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6172 pid_t deleted_pid;
6173 if (INTEGERP (xpid))
6174 deleted_pid = XINT (xpid);
6175 else
6176 deleted_pid = XFLOAT_DATA (xpid);
6177 if (child_status_changed (deleted_pid, 0, 0))
6179 if (STRINGP (XCDR (head)))
6180 unlink (SSDATA (XCDR (head)));
6181 XSETCAR (tail, Qnil);
6186 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6187 FOR_EACH_PROCESS (tail, proc)
6189 struct Lisp_Process *p = XPROCESS (proc);
6190 int status;
6192 if (p->alive
6193 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6195 /* Change the status of the process that was found. */
6196 p->tick = ++process_tick;
6197 p->raw_status = status;
6198 p->raw_status_new = 1;
6200 /* If process has terminated, stop waiting for its output. */
6201 if (WIFSIGNALED (status) || WIFEXITED (status))
6203 bool clear_desc_flag = 0;
6204 p->alive = 0;
6205 if (p->infd >= 0)
6206 clear_desc_flag = 1;
6208 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6209 if (clear_desc_flag)
6211 FD_CLR (p->infd, &input_wait_mask);
6212 FD_CLR (p->infd, &non_keyboard_wait_mask);
6218 lib_child_handler (sig);
6219 #ifdef NS_IMPL_GNUSTEP
6220 /* NSTask in GNUStep sets its child handler each time it is called.
6221 So we must re-set ours. */
6222 catch_child_signal();
6223 #endif
6226 static void
6227 deliver_child_signal (int sig)
6229 deliver_process_signal (sig, handle_child_signal);
6233 static Lisp_Object
6234 exec_sentinel_error_handler (Lisp_Object error_val)
6236 cmd_error_internal (error_val, "error in process sentinel: ");
6237 Vinhibit_quit = Qt;
6238 update_echo_area ();
6239 Fsleep_for (make_number (2), Qnil);
6240 return Qt;
6243 static void
6244 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6246 Lisp_Object sentinel, odeactivate;
6247 struct Lisp_Process *p = XPROCESS (proc);
6248 ptrdiff_t count = SPECPDL_INDEX ();
6249 bool outer_running_asynch_code = running_asynch_code;
6250 int waiting = waiting_for_user_input_p;
6252 if (inhibit_sentinels)
6253 return;
6255 /* No need to gcpro these, because all we do with them later
6256 is test them for EQness, and none of them should be a string. */
6257 odeactivate = Vdeactivate_mark;
6258 #if 0
6259 Lisp_Object obuffer, okeymap;
6260 XSETBUFFER (obuffer, current_buffer);
6261 okeymap = BVAR (current_buffer, keymap);
6262 #endif
6264 /* There's no good reason to let sentinels change the current
6265 buffer, and many callers of accept-process-output, sit-for, and
6266 friends don't expect current-buffer to be changed from under them. */
6267 record_unwind_current_buffer ();
6269 sentinel = p->sentinel;
6271 /* Inhibit quit so that random quits don't screw up a running filter. */
6272 specbind (Qinhibit_quit, Qt);
6273 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6275 /* In case we get recursively called,
6276 and we already saved the match data nonrecursively,
6277 save the same match data in safely recursive fashion. */
6278 if (outer_running_asynch_code)
6280 Lisp_Object tem;
6281 tem = Fmatch_data (Qnil, Qnil, Qnil);
6282 restore_search_regs ();
6283 record_unwind_save_match_data ();
6284 Fset_match_data (tem, Qt);
6287 /* For speed, if a search happens within this code,
6288 save the match data in a special nonrecursive fashion. */
6289 running_asynch_code = 1;
6291 internal_condition_case_1 (read_process_output_call,
6292 list3 (sentinel, proc, reason),
6293 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6294 exec_sentinel_error_handler);
6296 /* If we saved the match data nonrecursively, restore it now. */
6297 restore_search_regs ();
6298 running_asynch_code = outer_running_asynch_code;
6300 Vdeactivate_mark = odeactivate;
6302 /* Restore waiting_for_user_input_p as it was
6303 when we were called, in case the filter clobbered it. */
6304 waiting_for_user_input_p = waiting;
6306 #if 0
6307 if (! EQ (Fcurrent_buffer (), obuffer)
6308 || ! EQ (current_buffer->keymap, okeymap))
6309 #endif
6310 /* But do it only if the caller is actually going to read events.
6311 Otherwise there's no need to make him wake up, and it could
6312 cause trouble (for example it would make sit_for return). */
6313 if (waiting_for_user_input_p == -1)
6314 record_asynch_buffer_change ();
6316 unbind_to (count, Qnil);
6319 /* Report all recent events of a change in process status
6320 (either run the sentinel or output a message).
6321 This is usually done while Emacs is waiting for keyboard input
6322 but can be done at other times. */
6324 static void
6325 status_notify (struct Lisp_Process *deleting_process)
6327 register Lisp_Object proc;
6328 Lisp_Object tail, msg;
6329 struct gcpro gcpro1, gcpro2;
6331 tail = Qnil;
6332 msg = Qnil;
6333 /* We need to gcpro tail; if read_process_output calls a filter
6334 which deletes a process and removes the cons to which tail points
6335 from Vprocess_alist, and then causes a GC, tail is an unprotected
6336 reference. */
6337 GCPRO2 (tail, msg);
6339 /* Set this now, so that if new processes are created by sentinels
6340 that we run, we get called again to handle their status changes. */
6341 update_tick = process_tick;
6343 FOR_EACH_PROCESS (tail, proc)
6345 Lisp_Object symbol;
6346 register struct Lisp_Process *p = XPROCESS (proc);
6348 if (p->tick != p->update_tick)
6350 p->update_tick = p->tick;
6352 /* If process is still active, read any output that remains. */
6353 while (! EQ (p->filter, Qt)
6354 && ! EQ (p->status, Qconnect)
6355 && ! EQ (p->status, Qlisten)
6356 /* Network or serial process not stopped: */
6357 && ! EQ (p->command, Qt)
6358 && p->infd >= 0
6359 && p != deleting_process
6360 && read_process_output (proc, p->infd) > 0);
6362 /* Get the text to use for the message. */
6363 if (p->raw_status_new)
6364 update_status (p);
6365 msg = status_message (p);
6367 /* If process is terminated, deactivate it or delete it. */
6368 symbol = p->status;
6369 if (CONSP (p->status))
6370 symbol = XCAR (p->status);
6372 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6373 || EQ (symbol, Qclosed))
6375 if (delete_exited_processes)
6376 remove_process (proc);
6377 else
6378 deactivate_process (proc);
6381 /* The actions above may have further incremented p->tick.
6382 So set p->update_tick again so that an error in the sentinel will
6383 not cause this code to be run again. */
6384 p->update_tick = p->tick;
6385 /* Now output the message suitably. */
6386 exec_sentinel (proc, msg);
6388 } /* end for */
6390 update_mode_lines++; /* In case buffers use %s in mode-line-format. */
6391 UNGCPRO;
6394 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6395 Sinternal_default_process_sentinel, 2, 2, 0,
6396 doc: /* Function used as default sentinel for processes. */)
6397 (Lisp_Object proc, Lisp_Object msg)
6399 Lisp_Object buffer, symbol;
6400 struct Lisp_Process *p;
6401 CHECK_PROCESS (proc);
6402 p = XPROCESS (proc);
6403 buffer = p->buffer;
6404 symbol = p->status;
6405 if (CONSP (symbol))
6406 symbol = XCAR (symbol);
6408 if (!EQ (symbol, Qrun) && !NILP (buffer))
6410 Lisp_Object tem;
6411 struct buffer *old = current_buffer;
6412 ptrdiff_t opoint, opoint_byte;
6413 ptrdiff_t before, before_byte;
6415 /* Avoid error if buffer is deleted
6416 (probably that's why the process is dead, too). */
6417 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6418 return Qnil;
6419 Fset_buffer (buffer);
6421 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6422 msg = (code_convert_string_norecord
6423 (msg, Vlocale_coding_system, 1));
6425 opoint = PT;
6426 opoint_byte = PT_BYTE;
6427 /* Insert new output into buffer
6428 at the current end-of-output marker,
6429 thus preserving logical ordering of input and output. */
6430 if (XMARKER (p->mark)->buffer)
6431 Fgoto_char (p->mark);
6432 else
6433 SET_PT_BOTH (ZV, ZV_BYTE);
6435 before = PT;
6436 before_byte = PT_BYTE;
6438 tem = BVAR (current_buffer, read_only);
6439 bset_read_only (current_buffer, Qnil);
6440 insert_string ("\nProcess ");
6441 { /* FIXME: temporary kludge. */
6442 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6443 insert_string (" ");
6444 Finsert (1, &msg);
6445 bset_read_only (current_buffer, tem);
6446 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6448 if (opoint >= before)
6449 SET_PT_BOTH (opoint + (PT - before),
6450 opoint_byte + (PT_BYTE - before_byte));
6451 else
6452 SET_PT_BOTH (opoint, opoint_byte);
6454 set_buffer_internal (old);
6456 return Qnil;
6460 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6461 Sset_process_coding_system, 1, 3, 0,
6462 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6463 DECODING will be used to decode subprocess output and ENCODING to
6464 encode subprocess input. */)
6465 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6467 register struct Lisp_Process *p;
6469 CHECK_PROCESS (process);
6470 p = XPROCESS (process);
6471 if (p->infd < 0)
6472 error ("Input file descriptor of %s closed", SDATA (p->name));
6473 if (p->outfd < 0)
6474 error ("Output file descriptor of %s closed", SDATA (p->name));
6475 Fcheck_coding_system (decoding);
6476 Fcheck_coding_system (encoding);
6477 encoding = coding_inherit_eol_type (encoding, Qnil);
6478 pset_decode_coding_system (p, decoding);
6479 pset_encode_coding_system (p, encoding);
6480 setup_process_coding_systems (process);
6482 return Qnil;
6485 DEFUN ("process-coding-system",
6486 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6487 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6488 (register Lisp_Object process)
6490 CHECK_PROCESS (process);
6491 return Fcons (XPROCESS (process)->decode_coding_system,
6492 XPROCESS (process)->encode_coding_system);
6495 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6496 Sset_process_filter_multibyte, 2, 2, 0,
6497 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6498 If FLAG is non-nil, the filter is given multibyte strings.
6499 If FLAG is nil, the filter is given unibyte strings. In this case,
6500 all character code conversion except for end-of-line conversion is
6501 suppressed. */)
6502 (Lisp_Object process, Lisp_Object flag)
6504 register struct Lisp_Process *p;
6506 CHECK_PROCESS (process);
6507 p = XPROCESS (process);
6508 if (NILP (flag))
6509 pset_decode_coding_system
6510 (p, raw_text_coding_system (p->decode_coding_system));
6511 setup_process_coding_systems (process);
6513 return Qnil;
6516 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6517 Sprocess_filter_multibyte_p, 1, 1, 0,
6518 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6519 (Lisp_Object process)
6521 register struct Lisp_Process *p;
6522 struct coding_system *coding;
6524 CHECK_PROCESS (process);
6525 p = XPROCESS (process);
6526 coding = proc_decode_coding_system[p->infd];
6527 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6533 # ifdef HAVE_GPM
6535 void
6536 add_gpm_wait_descriptor (int desc)
6538 add_keyboard_wait_descriptor (desc);
6541 void
6542 delete_gpm_wait_descriptor (int desc)
6544 delete_keyboard_wait_descriptor (desc);
6547 # endif
6549 # ifdef USABLE_SIGIO
6551 /* Return true if *MASK has a bit set
6552 that corresponds to one of the keyboard input descriptors. */
6554 static bool
6555 keyboard_bit_set (fd_set *mask)
6557 int fd;
6559 for (fd = 0; fd <= max_input_desc; fd++)
6560 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6561 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6562 return 1;
6564 return 0;
6566 # endif
6568 #else /* not subprocesses */
6570 /* Defined on msdos.c. */
6571 extern int sys_select (int, fd_set *, fd_set *, fd_set *,
6572 struct timespec *, void *);
6574 /* Implementation of wait_reading_process_output, assuming that there
6575 are no subprocesses. Used only by the MS-DOS build.
6577 Wait for timeout to elapse and/or keyboard input to be available.
6579 TIME_LIMIT is:
6580 timeout in seconds
6581 If negative, gobble data immediately available but don't wait for any.
6583 NSECS is:
6584 an additional duration to wait, measured in nanoseconds
6585 If TIME_LIMIT is zero, then:
6586 If NSECS == 0, there is no limit.
6587 If NSECS > 0, the timeout consists of NSECS only.
6588 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6590 READ_KBD is:
6591 0 to ignore keyboard input, or
6592 1 to return when input is available, or
6593 -1 means caller will actually read the input, so don't throw to
6594 the quit handler.
6596 see full version for other parameters. We know that wait_proc will
6597 always be NULL, since `subprocesses' isn't defined.
6599 DO_DISPLAY means redisplay should be done to show subprocess
6600 output that arrives.
6602 Return true if we received input from any process. */
6604 bool
6605 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6606 bool do_display,
6607 Lisp_Object wait_for_cell,
6608 struct Lisp_Process *wait_proc, int just_wait_proc)
6610 register int nfds;
6611 struct timespec end_time, timeout;
6613 if (time_limit < 0)
6615 time_limit = 0;
6616 nsecs = -1;
6618 else if (TYPE_MAXIMUM (time_t) < time_limit)
6619 time_limit = TYPE_MAXIMUM (time_t);
6621 /* What does time_limit really mean? */
6622 if (time_limit || nsecs > 0)
6624 timeout = make_timespec (time_limit, nsecs);
6625 end_time = timespec_add (current_timespec (), timeout);
6628 /* Turn off periodic alarms (in case they are in use)
6629 and then turn off any other atimers,
6630 because the select emulator uses alarms. */
6631 stop_polling ();
6632 turn_on_atimers (0);
6634 while (1)
6636 bool timeout_reduced_for_timers = 0;
6637 fd_set waitchannels;
6638 int xerrno;
6640 /* If calling from keyboard input, do not quit
6641 since we want to return C-g as an input character.
6642 Otherwise, do pending quit if requested. */
6643 if (read_kbd >= 0)
6644 QUIT;
6646 /* Exit now if the cell we're waiting for became non-nil. */
6647 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6648 break;
6650 /* Compute time from now till when time limit is up. */
6651 /* Exit if already run out. */
6652 if (nsecs < 0)
6654 /* A negative timeout means
6655 gobble output available now
6656 but don't wait at all. */
6658 timeout = make_timespec (0, 0);
6660 else if (time_limit || nsecs > 0)
6662 struct timespec now = current_timespec ();
6663 if (timespec_cmp (end_time, now) <= 0)
6664 break;
6665 timeout = timespec_sub (end_time, now);
6667 else
6669 timeout = make_timespec (100000, 0);
6672 /* If our caller will not immediately handle keyboard events,
6673 run timer events directly.
6674 (Callers that will immediately read keyboard events
6675 call timer_delay on their own.) */
6676 if (NILP (wait_for_cell))
6678 struct timespec timer_delay;
6682 unsigned old_timers_run = timers_run;
6683 timer_delay = timer_check ();
6684 if (timers_run != old_timers_run && do_display)
6685 /* We must retry, since a timer may have requeued itself
6686 and that could alter the time delay. */
6687 redisplay_preserve_echo_area (14);
6688 else
6689 break;
6691 while (!detect_input_pending ());
6693 /* If there is unread keyboard input, also return. */
6694 if (read_kbd != 0
6695 && requeued_events_pending_p ())
6696 break;
6698 if (timespec_valid_p (timer_delay) && nsecs >= 0)
6700 if (timespec_cmp (timer_delay, timeout) < 0)
6702 timeout = timer_delay;
6703 timeout_reduced_for_timers = 1;
6708 /* Cause C-g and alarm signals to take immediate action,
6709 and cause input available signals to zero out timeout. */
6710 if (read_kbd < 0)
6711 set_waiting_for_input (&timeout);
6713 /* If a frame has been newly mapped and needs updating,
6714 reprocess its display stuff. */
6715 if (frame_garbaged && do_display)
6717 clear_waiting_for_input ();
6718 redisplay_preserve_echo_area (15);
6719 if (read_kbd < 0)
6720 set_waiting_for_input (&timeout);
6723 /* Wait till there is something to do. */
6724 FD_ZERO (&waitchannels);
6725 if (read_kbd && detect_input_pending ())
6726 nfds = 0;
6727 else
6729 if (read_kbd || !NILP (wait_for_cell))
6730 FD_SET (0, &waitchannels);
6731 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
6734 xerrno = errno;
6736 /* Make C-g and alarm signals set flags again */
6737 clear_waiting_for_input ();
6739 /* If we woke up due to SIGWINCH, actually change size now. */
6740 do_pending_window_change (0);
6742 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
6743 /* We waited the full specified time, so return now. */
6744 break;
6746 if (nfds == -1)
6748 /* If the system call was interrupted, then go around the
6749 loop again. */
6750 if (xerrno == EINTR)
6751 FD_ZERO (&waitchannels);
6752 else
6753 report_file_errno ("Failed select", Qnil, xerrno);
6756 /* Check for keyboard input */
6758 if (read_kbd
6759 && detect_input_pending_run_timers (do_display))
6761 swallow_events (do_display);
6762 if (detect_input_pending_run_timers (do_display))
6763 break;
6766 /* If there is unread keyboard input, also return. */
6767 if (read_kbd
6768 && requeued_events_pending_p ())
6769 break;
6771 /* If wait_for_cell. check for keyboard input
6772 but don't run any timers.
6773 ??? (It seems wrong to me to check for keyboard
6774 input at all when wait_for_cell, but the code
6775 has been this way since July 1994.
6776 Try changing this after version 19.31.) */
6777 if (! NILP (wait_for_cell)
6778 && detect_input_pending ())
6780 swallow_events (do_display);
6781 if (detect_input_pending ())
6782 break;
6785 /* Exit now if the cell we're waiting for became non-nil. */
6786 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6787 break;
6790 start_polling ();
6792 return 0;
6795 #endif /* not subprocesses */
6797 /* The following functions are needed even if async subprocesses are
6798 not supported. Some of them are no-op stubs in that case. */
6800 /* Add DESC to the set of keyboard input descriptors. */
6802 void
6803 add_keyboard_wait_descriptor (int desc)
6805 #ifdef subprocesses /* actually means "not MSDOS" */
6806 FD_SET (desc, &input_wait_mask);
6807 FD_SET (desc, &non_process_wait_mask);
6808 if (desc > max_input_desc)
6809 max_input_desc = desc;
6810 #endif
6813 /* From now on, do not expect DESC to give keyboard input. */
6815 void
6816 delete_keyboard_wait_descriptor (int desc)
6818 #ifdef subprocesses
6819 FD_CLR (desc, &input_wait_mask);
6820 FD_CLR (desc, &non_process_wait_mask);
6821 delete_input_desc (desc);
6822 #endif
6825 /* Setup coding systems of PROCESS. */
6827 void
6828 setup_process_coding_systems (Lisp_Object process)
6830 #ifdef subprocesses
6831 struct Lisp_Process *p = XPROCESS (process);
6832 int inch = p->infd;
6833 int outch = p->outfd;
6834 Lisp_Object coding_system;
6836 if (inch < 0 || outch < 0)
6837 return;
6839 if (!proc_decode_coding_system[inch])
6840 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
6841 coding_system = p->decode_coding_system;
6842 if (EQ (p->filter, Qinternal_default_process_filter)
6843 && BUFFERP (p->buffer))
6845 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
6846 coding_system = raw_text_coding_system (coding_system);
6848 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
6850 if (!proc_encode_coding_system[outch])
6851 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
6852 setup_coding_system (p->encode_coding_system,
6853 proc_encode_coding_system[outch]);
6854 #endif
6857 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
6858 doc: /* Return the (or a) process associated with BUFFER.
6859 BUFFER may be a buffer or the name of one. */)
6860 (register Lisp_Object buffer)
6862 #ifdef subprocesses
6863 register Lisp_Object buf, tail, proc;
6865 if (NILP (buffer)) return Qnil;
6866 buf = Fget_buffer (buffer);
6867 if (NILP (buf)) return Qnil;
6869 FOR_EACH_PROCESS (tail, proc)
6870 if (EQ (XPROCESS (proc)->buffer, buf))
6871 return proc;
6872 #endif /* subprocesses */
6873 return Qnil;
6876 DEFUN ("process-inherit-coding-system-flag",
6877 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
6878 1, 1, 0,
6879 doc: /* Return the value of inherit-coding-system flag for PROCESS.
6880 If this flag is t, `buffer-file-coding-system' of the buffer
6881 associated with PROCESS will inherit the coding system used to decode
6882 the process output. */)
6883 (register Lisp_Object process)
6885 #ifdef subprocesses
6886 CHECK_PROCESS (process);
6887 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
6888 #else
6889 /* Ignore the argument and return the value of
6890 inherit-process-coding-system. */
6891 return inherit_process_coding_system ? Qt : Qnil;
6892 #endif
6895 /* Kill all processes associated with `buffer'.
6896 If `buffer' is nil, kill all processes */
6898 void
6899 kill_buffer_processes (Lisp_Object buffer)
6901 #ifdef subprocesses
6902 Lisp_Object tail, proc;
6904 FOR_EACH_PROCESS (tail, proc)
6905 if (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer))
6907 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6908 Fdelete_process (proc);
6909 else if (XPROCESS (proc)->infd >= 0)
6910 process_send_signal (proc, SIGHUP, Qnil, 1);
6912 #else /* subprocesses */
6913 /* Since we have no subprocesses, this does nothing. */
6914 #endif /* subprocesses */
6917 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
6918 Swaiting_for_user_input_p, 0, 0, 0,
6919 doc: /* Return non-nil if Emacs is waiting for input from the user.
6920 This is intended for use by asynchronous process output filters and sentinels. */)
6921 (void)
6923 #ifdef subprocesses
6924 return (waiting_for_user_input_p ? Qt : Qnil);
6925 #else
6926 return Qnil;
6927 #endif
6930 /* Stop reading input from keyboard sources. */
6932 void
6933 hold_keyboard_input (void)
6935 kbd_is_on_hold = 1;
6938 /* Resume reading input from keyboard sources. */
6940 void
6941 unhold_keyboard_input (void)
6943 kbd_is_on_hold = 0;
6946 /* Return true if keyboard input is on hold, zero otherwise. */
6948 bool
6949 kbd_on_hold_p (void)
6951 return kbd_is_on_hold;
6955 /* Enumeration of and access to system processes a-la ps(1). */
6957 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
6958 0, 0, 0,
6959 doc: /* Return a list of numerical process IDs of all running processes.
6960 If this functionality is unsupported, return nil.
6962 See `process-attributes' for getting attributes of a process given its ID. */)
6963 (void)
6965 return list_system_processes ();
6968 DEFUN ("process-attributes", Fprocess_attributes,
6969 Sprocess_attributes, 1, 1, 0,
6970 doc: /* Return attributes of the process given by its PID, a number.
6972 Value is an alist where each element is a cons cell of the form
6974 \(KEY . VALUE)
6976 If this functionality is unsupported, the value is nil.
6978 See `list-system-processes' for getting a list of all process IDs.
6980 The KEYs of the attributes that this function may return are listed
6981 below, together with the type of the associated VALUE (in parentheses).
6982 Not all platforms support all of these attributes; unsupported
6983 attributes will not appear in the returned alist.
6984 Unless explicitly indicated otherwise, numbers can have either
6985 integer or floating point values.
6987 euid -- Effective user User ID of the process (number)
6988 user -- User name corresponding to euid (string)
6989 egid -- Effective user Group ID of the process (number)
6990 group -- Group name corresponding to egid (string)
6991 comm -- Command name (executable name only) (string)
6992 state -- Process state code, such as "S", "R", or "T" (string)
6993 ppid -- Parent process ID (number)
6994 pgrp -- Process group ID (number)
6995 sess -- Session ID, i.e. process ID of session leader (number)
6996 ttname -- Controlling tty name (string)
6997 tpgid -- ID of foreground process group on the process's tty (number)
6998 minflt -- number of minor page faults (number)
6999 majflt -- number of major page faults (number)
7000 cminflt -- cumulative number of minor page faults (number)
7001 cmajflt -- cumulative number of major page faults (number)
7002 utime -- user time used by the process, in (current-time) format,
7003 which is a list of integers (HIGH LOW USEC PSEC)
7004 stime -- system time used by the process (current-time)
7005 time -- sum of utime and stime (current-time)
7006 cutime -- user time used by the process and its children (current-time)
7007 cstime -- system time used by the process and its children (current-time)
7008 ctime -- sum of cutime and cstime (current-time)
7009 pri -- priority of the process (number)
7010 nice -- nice value of the process (number)
7011 thcount -- process thread count (number)
7012 start -- time the process started (current-time)
7013 vsize -- virtual memory size of the process in KB's (number)
7014 rss -- resident set size of the process in KB's (number)
7015 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7016 pcpu -- percents of CPU time used by the process (floating-point number)
7017 pmem -- percents of total physical memory used by process's resident set
7018 (floating-point number)
7019 args -- command line which invoked the process (string). */)
7020 ( Lisp_Object pid)
7022 return system_process_attributes (pid);
7025 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7026 Invoke this after init_process_emacs, and after glib and/or GNUstep
7027 futz with the SIGCHLD handler, but before Emacs forks any children.
7028 This function's caller should block SIGCHLD. */
7030 #ifndef NS_IMPL_GNUSTEP
7031 static
7032 #endif
7033 void
7034 catch_child_signal (void)
7036 struct sigaction action, old_action;
7037 emacs_sigaction_init (&action, deliver_child_signal);
7038 block_child_signal ();
7039 sigaction (SIGCHLD, &action, &old_action);
7040 eassert (! (old_action.sa_flags & SA_SIGINFO));
7042 if (old_action.sa_handler != deliver_child_signal)
7043 lib_child_handler
7044 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7045 ? dummy_handler
7046 : old_action.sa_handler);
7047 unblock_child_signal ();
7051 /* This is not called "init_process" because that is the name of a
7052 Mach system call, so it would cause problems on Darwin systems. */
7053 void
7054 init_process_emacs (void)
7056 #ifdef subprocesses
7057 register int i;
7059 inhibit_sentinels = 0;
7061 #ifndef CANNOT_DUMP
7062 if (! noninteractive || initialized)
7063 #endif
7065 #if defined HAVE_GLIB && !defined WINDOWSNT
7066 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7067 this should always fail, but is enough to initialize glib's
7068 private SIGCHLD handler, allowing catch_child_signal to copy
7069 it into lib_child_handler. */
7070 g_source_unref (g_child_watch_source_new (getpid ()));
7071 #endif
7072 catch_child_signal ();
7075 FD_ZERO (&input_wait_mask);
7076 FD_ZERO (&non_keyboard_wait_mask);
7077 FD_ZERO (&non_process_wait_mask);
7078 FD_ZERO (&write_mask);
7079 max_process_desc = max_input_desc = -1;
7080 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7082 #ifdef NON_BLOCKING_CONNECT
7083 FD_ZERO (&connect_wait_mask);
7084 num_pending_connects = 0;
7085 #endif
7087 #ifdef ADAPTIVE_READ_BUFFERING
7088 process_output_delay_count = 0;
7089 process_output_skip = 0;
7090 #endif
7092 /* Don't do this, it caused infinite select loops. The display
7093 method should call add_keyboard_wait_descriptor on stdin if it
7094 needs that. */
7095 #if 0
7096 FD_SET (0, &input_wait_mask);
7097 #endif
7099 Vprocess_alist = Qnil;
7100 deleted_pid_list = Qnil;
7101 for (i = 0; i < FD_SETSIZE; i++)
7103 chan_process[i] = Qnil;
7104 proc_buffered_char[i] = -1;
7106 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7107 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7108 #ifdef DATAGRAM_SOCKETS
7109 memset (datagram_address, 0, sizeof datagram_address);
7110 #endif
7113 Lisp_Object subfeatures = Qnil;
7114 const struct socket_options *sopt;
7116 #define ADD_SUBFEATURE(key, val) \
7117 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7119 #ifdef NON_BLOCKING_CONNECT
7120 ADD_SUBFEATURE (QCnowait, Qt);
7121 #endif
7122 #ifdef DATAGRAM_SOCKETS
7123 ADD_SUBFEATURE (QCtype, Qdatagram);
7124 #endif
7125 #ifdef HAVE_SEQPACKET
7126 ADD_SUBFEATURE (QCtype, Qseqpacket);
7127 #endif
7128 #ifdef HAVE_LOCAL_SOCKETS
7129 ADD_SUBFEATURE (QCfamily, Qlocal);
7130 #endif
7131 ADD_SUBFEATURE (QCfamily, Qipv4);
7132 #ifdef AF_INET6
7133 ADD_SUBFEATURE (QCfamily, Qipv6);
7134 #endif
7135 #ifdef HAVE_GETSOCKNAME
7136 ADD_SUBFEATURE (QCservice, Qt);
7137 #endif
7138 ADD_SUBFEATURE (QCserver, Qt);
7140 for (sopt = socket_options; sopt->name; sopt++)
7141 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7143 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7146 #if defined (DARWIN_OS)
7147 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7148 processes. As such, we only change the default value. */
7149 if (initialized)
7151 char const *release = (STRINGP (Voperating_system_release)
7152 ? SSDATA (Voperating_system_release)
7153 : 0);
7154 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7155 Vprocess_connection_type = Qnil;
7158 #endif
7159 #endif /* subprocesses */
7160 kbd_is_on_hold = 0;
7163 void
7164 syms_of_process (void)
7166 #ifdef subprocesses
7168 DEFSYM (Qprocessp, "processp");
7169 DEFSYM (Qrun, "run");
7170 DEFSYM (Qstop, "stop");
7171 DEFSYM (Qsignal, "signal");
7173 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7174 here again.
7176 Qexit = intern_c_string ("exit");
7177 staticpro (&Qexit); */
7179 DEFSYM (Qopen, "open");
7180 DEFSYM (Qclosed, "closed");
7181 DEFSYM (Qconnect, "connect");
7182 DEFSYM (Qfailed, "failed");
7183 DEFSYM (Qlisten, "listen");
7184 DEFSYM (Qlocal, "local");
7185 DEFSYM (Qipv4, "ipv4");
7186 #ifdef AF_INET6
7187 DEFSYM (Qipv6, "ipv6");
7188 #endif
7189 DEFSYM (Qdatagram, "datagram");
7190 DEFSYM (Qseqpacket, "seqpacket");
7192 DEFSYM (QCport, ":port");
7193 DEFSYM (QCspeed, ":speed");
7194 DEFSYM (QCprocess, ":process");
7196 DEFSYM (QCbytesize, ":bytesize");
7197 DEFSYM (QCstopbits, ":stopbits");
7198 DEFSYM (QCparity, ":parity");
7199 DEFSYM (Qodd, "odd");
7200 DEFSYM (Qeven, "even");
7201 DEFSYM (QCflowcontrol, ":flowcontrol");
7202 DEFSYM (Qhw, "hw");
7203 DEFSYM (Qsw, "sw");
7204 DEFSYM (QCsummary, ":summary");
7206 DEFSYM (Qreal, "real");
7207 DEFSYM (Qnetwork, "network");
7208 DEFSYM (Qserial, "serial");
7209 DEFSYM (QCbuffer, ":buffer");
7210 DEFSYM (QChost, ":host");
7211 DEFSYM (QCservice, ":service");
7212 DEFSYM (QClocal, ":local");
7213 DEFSYM (QCremote, ":remote");
7214 DEFSYM (QCcoding, ":coding");
7215 DEFSYM (QCserver, ":server");
7216 DEFSYM (QCnowait, ":nowait");
7217 DEFSYM (QCsentinel, ":sentinel");
7218 DEFSYM (QClog, ":log");
7219 DEFSYM (QCnoquery, ":noquery");
7220 DEFSYM (QCstop, ":stop");
7221 DEFSYM (QCoptions, ":options");
7222 DEFSYM (QCplist, ":plist");
7224 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7226 staticpro (&Vprocess_alist);
7227 staticpro (&deleted_pid_list);
7229 #endif /* subprocesses */
7231 DEFSYM (QCname, ":name");
7232 DEFSYM (QCtype, ":type");
7234 DEFSYM (Qeuid, "euid");
7235 DEFSYM (Qegid, "egid");
7236 DEFSYM (Quser, "user");
7237 DEFSYM (Qgroup, "group");
7238 DEFSYM (Qcomm, "comm");
7239 DEFSYM (Qstate, "state");
7240 DEFSYM (Qppid, "ppid");
7241 DEFSYM (Qpgrp, "pgrp");
7242 DEFSYM (Qsess, "sess");
7243 DEFSYM (Qttname, "ttname");
7244 DEFSYM (Qtpgid, "tpgid");
7245 DEFSYM (Qminflt, "minflt");
7246 DEFSYM (Qmajflt, "majflt");
7247 DEFSYM (Qcminflt, "cminflt");
7248 DEFSYM (Qcmajflt, "cmajflt");
7249 DEFSYM (Qutime, "utime");
7250 DEFSYM (Qstime, "stime");
7251 DEFSYM (Qtime, "time");
7252 DEFSYM (Qcutime, "cutime");
7253 DEFSYM (Qcstime, "cstime");
7254 DEFSYM (Qctime, "ctime");
7255 DEFSYM (Qinternal_default_process_sentinel,
7256 "internal-default-process-sentinel");
7257 DEFSYM (Qinternal_default_process_filter,
7258 "internal-default-process-filter");
7259 DEFSYM (Qpri, "pri");
7260 DEFSYM (Qnice, "nice");
7261 DEFSYM (Qthcount, "thcount");
7262 DEFSYM (Qstart, "start");
7263 DEFSYM (Qvsize, "vsize");
7264 DEFSYM (Qrss, "rss");
7265 DEFSYM (Qetime, "etime");
7266 DEFSYM (Qpcpu, "pcpu");
7267 DEFSYM (Qpmem, "pmem");
7268 DEFSYM (Qargs, "args");
7270 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7271 doc: /* Non-nil means delete processes immediately when they exit.
7272 A value of nil means don't delete them until `list-processes' is run. */);
7274 delete_exited_processes = 1;
7276 #ifdef subprocesses
7277 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7278 doc: /* Control type of device used to communicate with subprocesses.
7279 Values are nil to use a pipe, or t or `pty' to use a pty.
7280 The value has no effect if the system has no ptys or if all ptys are busy:
7281 then a pipe is used in any case.
7282 The value takes effect when `start-process' is called. */);
7283 Vprocess_connection_type = Qt;
7285 #ifdef ADAPTIVE_READ_BUFFERING
7286 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7287 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7288 On some systems, when Emacs reads the output from a subprocess, the output data
7289 is read in very small blocks, potentially resulting in very poor performance.
7290 This behavior can be remedied to some extent by setting this variable to a
7291 non-nil value, as it will automatically delay reading from such processes, to
7292 allow them to produce more output before Emacs tries to read it.
7293 If the value is t, the delay is reset after each write to the process; any other
7294 non-nil value means that the delay is not reset on write.
7295 The variable takes effect when `start-process' is called. */);
7296 Vprocess_adaptive_read_buffering = Qt;
7297 #endif
7299 defsubr (&Sprocessp);
7300 defsubr (&Sget_process);
7301 defsubr (&Sdelete_process);
7302 defsubr (&Sprocess_status);
7303 defsubr (&Sprocess_exit_status);
7304 defsubr (&Sprocess_id);
7305 defsubr (&Sprocess_name);
7306 defsubr (&Sprocess_tty_name);
7307 defsubr (&Sprocess_command);
7308 defsubr (&Sset_process_buffer);
7309 defsubr (&Sprocess_buffer);
7310 defsubr (&Sprocess_mark);
7311 defsubr (&Sset_process_filter);
7312 defsubr (&Sprocess_filter);
7313 defsubr (&Sset_process_sentinel);
7314 defsubr (&Sprocess_sentinel);
7315 defsubr (&Sset_process_window_size);
7316 defsubr (&Sset_process_inherit_coding_system_flag);
7317 defsubr (&Sset_process_query_on_exit_flag);
7318 defsubr (&Sprocess_query_on_exit_flag);
7319 defsubr (&Sprocess_contact);
7320 defsubr (&Sprocess_plist);
7321 defsubr (&Sset_process_plist);
7322 defsubr (&Sprocess_list);
7323 defsubr (&Sstart_process);
7324 defsubr (&Sserial_process_configure);
7325 defsubr (&Smake_serial_process);
7326 defsubr (&Sset_network_process_option);
7327 defsubr (&Smake_network_process);
7328 defsubr (&Sformat_network_address);
7329 defsubr (&Snetwork_interface_list);
7330 defsubr (&Snetwork_interface_info);
7331 #ifdef DATAGRAM_SOCKETS
7332 defsubr (&Sprocess_datagram_address);
7333 defsubr (&Sset_process_datagram_address);
7334 #endif
7335 defsubr (&Saccept_process_output);
7336 defsubr (&Sprocess_send_region);
7337 defsubr (&Sprocess_send_string);
7338 defsubr (&Sinterrupt_process);
7339 defsubr (&Skill_process);
7340 defsubr (&Squit_process);
7341 defsubr (&Sstop_process);
7342 defsubr (&Scontinue_process);
7343 defsubr (&Sprocess_running_child_p);
7344 defsubr (&Sprocess_send_eof);
7345 defsubr (&Ssignal_process);
7346 defsubr (&Swaiting_for_user_input_p);
7347 defsubr (&Sprocess_type);
7348 defsubr (&Sinternal_default_process_sentinel);
7349 defsubr (&Sinternal_default_process_filter);
7350 defsubr (&Sset_process_coding_system);
7351 defsubr (&Sprocess_coding_system);
7352 defsubr (&Sset_process_filter_multibyte);
7353 defsubr (&Sprocess_filter_multibyte_p);
7355 #endif /* subprocesses */
7357 defsubr (&Sget_buffer_process);
7358 defsubr (&Sprocess_inherit_coding_system_flag);
7359 defsubr (&Slist_system_processes);
7360 defsubr (&Sprocess_attributes);