* lisp/subr.el (define-error): New function.
[emacs.git] / src / process.c
blob85d07028c598f0476593aee0c261bec7ed598358
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 #define PROCESS_INLINE EXTERN_INLINE
26 #include <stdio.h>
27 #include <errno.h>
28 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
29 #include <sys/file.h>
30 #include <sys/stat.h>
31 #include <unistd.h>
32 #include <fcntl.h>
34 #include "lisp.h"
36 /* Only MS-DOS does not define `subprocesses'. */
37 #ifdef subprocesses
39 #include <sys/socket.h>
40 #include <netdb.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
44 /* Are local (unix) sockets supported? */
45 #if defined (HAVE_SYS_UN_H)
46 #if !defined (AF_LOCAL) && defined (AF_UNIX)
47 #define AF_LOCAL AF_UNIX
48 #endif
49 #ifdef AF_LOCAL
50 #define HAVE_LOCAL_SOCKETS
51 #include <sys/un.h>
52 #endif
53 #endif
55 #include <sys/ioctl.h>
56 #if defined (HAVE_NET_IF_H)
57 #include <net/if.h>
58 #endif /* HAVE_NET_IF_H */
60 #if defined (HAVE_IFADDRS_H)
61 /* Must be after net/if.h */
62 #include <ifaddrs.h>
64 /* We only use structs from this header when we use getifaddrs. */
65 #if defined (HAVE_NET_IF_DL_H)
66 #include <net/if_dl.h>
67 #endif
69 #endif
71 #ifdef NEED_BSDTTY
72 #include <bsdtty.h>
73 #endif
75 #ifdef USG5_4
76 # include <sys/stream.h>
77 # include <sys/stropts.h>
78 #endif
80 #ifdef HAVE_RES_INIT
81 #include <arpa/nameser.h>
82 #include <resolv.h>
83 #endif
85 #ifdef HAVE_UTIL_H
86 #include <util.h>
87 #endif
89 #ifdef HAVE_PTY_H
90 #include <pty.h>
91 #endif
93 #include <c-ctype.h>
94 #include <sig2str.h>
96 #endif /* subprocesses */
98 #include "systime.h"
99 #include "systty.h"
101 #include "window.h"
102 #include "character.h"
103 #include "buffer.h"
104 #include "coding.h"
105 #include "process.h"
106 #include "frame.h"
107 #include "termhooks.h"
108 #include "termopts.h"
109 #include "commands.h"
110 #include "keyboard.h"
111 #include "blockinput.h"
112 #include "dispextern.h"
113 #include "composite.h"
114 #include "atimer.h"
115 #include "sysselect.h"
116 #include "syssignal.h"
117 #include "syswait.h"
118 #ifdef HAVE_GNUTLS
119 #include "gnutls.h"
120 #endif
122 #ifdef HAVE_WINDOW_SYSTEM
123 #include TERM_HEADER
124 #endif /* HAVE_WINDOW_SYSTEM */
126 #ifdef HAVE_GLIB
127 #include "xgselect.h"
128 #ifndef WINDOWSNT
129 #include <glib.h>
130 #endif
131 #endif
133 #ifdef WINDOWSNT
134 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
135 EMACS_TIME *, void *);
136 #endif
138 #ifndef SOCK_CLOEXEC
139 # define SOCK_CLOEXEC 0
140 #endif
142 #ifndef HAVE_ACCEPT4
144 /* Emulate GNU/Linux accept4 and socket well enough for this module. */
146 static int
147 close_on_exec (int fd)
149 if (0 <= fd)
150 fcntl (fd, F_SETFD, FD_CLOEXEC);
151 return fd;
154 static int
155 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
157 return close_on_exec (accept (sockfd, addr, addrlen));
160 static int
161 process_socket (int domain, int type, int protocol)
163 return close_on_exec (socket (domain, type, protocol));
165 # undef socket
166 # define socket(domain, type, protocol) process_socket (domain, type, protocol)
167 #endif
169 /* Work around GCC 4.7.0 bug with strict overflow checking; see
170 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
171 These lines can be removed once the GCC bug is fixed. */
172 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
173 # pragma GCC diagnostic ignored "-Wstrict-overflow"
174 #endif
176 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
177 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
178 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
179 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
180 Lisp_Object QCname, QCtype;
182 /* True if keyboard input is on hold, zero otherwise. */
184 static bool kbd_is_on_hold;
186 /* Nonzero means don't run process sentinels. This is used
187 when exiting. */
188 bool inhibit_sentinels;
190 #ifdef subprocesses
192 Lisp_Object Qprocessp;
193 static Lisp_Object Qrun, Qstop, Qsignal;
194 static Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
195 Lisp_Object Qlocal;
196 static Lisp_Object Qipv4, Qdatagram, Qseqpacket;
197 static Lisp_Object Qreal, Qnetwork, Qserial;
198 #ifdef AF_INET6
199 static Lisp_Object Qipv6;
200 #endif
201 static Lisp_Object QCport, QCprocess;
202 Lisp_Object QCspeed;
203 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
204 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
205 static Lisp_Object QCbuffer, QChost, QCservice;
206 static Lisp_Object QClocal, QCremote, QCcoding;
207 static Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
208 static Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
209 static Lisp_Object Qlast_nonmenu_event;
210 static Lisp_Object Qinternal_default_process_sentinel;
211 static Lisp_Object Qinternal_default_process_filter;
213 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
214 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
215 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
216 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
218 /* Number of events of change of status of a process. */
219 static EMACS_INT process_tick;
220 /* Number of events for which the user or sentinel has been notified. */
221 static EMACS_INT update_tick;
223 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
225 /* Only W32 has this, it really means that select can't take write mask. */
226 #ifdef BROKEN_NON_BLOCKING_CONNECT
227 #undef NON_BLOCKING_CONNECT
228 #define SELECT_CANT_DO_WRITE_MASK
229 #else
230 #ifndef NON_BLOCKING_CONNECT
231 #ifdef HAVE_SELECT
232 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
233 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
234 #define NON_BLOCKING_CONNECT
235 #endif /* EWOULDBLOCK || EINPROGRESS */
236 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
237 #endif /* HAVE_SELECT */
238 #endif /* NON_BLOCKING_CONNECT */
239 #endif /* BROKEN_NON_BLOCKING_CONNECT */
241 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
242 this system. We need to read full packets, so we need a
243 "non-destructive" select. So we require either native select,
244 or emulation of select using FIONREAD. */
246 #ifndef BROKEN_DATAGRAM_SOCKETS
247 # if defined HAVE_SELECT || defined USABLE_FIONREAD
248 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
249 # define DATAGRAM_SOCKETS
250 # endif
251 # endif
252 #endif
254 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
255 # define HAVE_SEQPACKET
256 #endif
258 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
259 #define ADAPTIVE_READ_BUFFERING
260 #endif
262 #ifdef ADAPTIVE_READ_BUFFERING
263 #define READ_OUTPUT_DELAY_INCREMENT (EMACS_TIME_RESOLUTION / 100)
264 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
265 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
267 /* Number of processes which have a non-zero read_output_delay,
268 and therefore might be delayed for adaptive read buffering. */
270 static int process_output_delay_count;
272 /* True if any process has non-nil read_output_skip. */
274 static bool process_output_skip;
276 #else
277 #define process_output_delay_count 0
278 #endif
280 static void create_process (Lisp_Object, char **, Lisp_Object);
281 #ifdef USABLE_SIGIO
282 static bool keyboard_bit_set (SELECT_TYPE *);
283 #endif
284 static void deactivate_process (Lisp_Object);
285 static void status_notify (struct Lisp_Process *);
286 static int read_process_output (Lisp_Object, int);
287 static void handle_child_signal (int);
288 static void create_pty (Lisp_Object);
290 /* If we support a window system, turn on the code to poll periodically
291 to detect C-g. It isn't actually used when doing interrupt input. */
292 #ifdef HAVE_WINDOW_SYSTEM
293 #define POLL_FOR_INPUT
294 #endif
296 static Lisp_Object get_process (register Lisp_Object name);
297 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
299 /* Mask of bits indicating the descriptors that we wait for input on. */
301 static SELECT_TYPE input_wait_mask;
303 /* Mask that excludes keyboard input descriptor(s). */
305 static SELECT_TYPE non_keyboard_wait_mask;
307 /* Mask that excludes process input descriptor(s). */
309 static SELECT_TYPE non_process_wait_mask;
311 /* Mask for selecting for write. */
313 static SELECT_TYPE write_mask;
315 #ifdef NON_BLOCKING_CONNECT
316 /* Mask of bits indicating the descriptors that we wait for connect to
317 complete on. Once they complete, they are removed from this mask
318 and added to the input_wait_mask and non_keyboard_wait_mask. */
320 static SELECT_TYPE connect_wait_mask;
322 /* Number of bits set in connect_wait_mask. */
323 static int num_pending_connects;
324 #endif /* NON_BLOCKING_CONNECT */
326 /* The largest descriptor currently in use for a process object; -1 if none. */
327 static int max_process_desc;
329 /* The largest descriptor currently in use for input; -1 if none. */
330 static int max_input_desc;
332 /* Indexed by descriptor, gives the process (if any) for that descriptor */
333 static Lisp_Object chan_process[MAXDESC];
335 /* Alist of elements (NAME . PROCESS) */
336 static Lisp_Object Vprocess_alist;
338 /* Buffered-ahead input char from process, indexed by channel.
339 -1 means empty (no char is buffered).
340 Used on sys V where the only way to tell if there is any
341 output from the process is to read at least one char.
342 Always -1 on systems that support FIONREAD. */
344 static int proc_buffered_char[MAXDESC];
346 /* Table of `struct coding-system' for each process. */
347 static struct coding_system *proc_decode_coding_system[MAXDESC];
348 static struct coding_system *proc_encode_coding_system[MAXDESC];
350 #ifdef DATAGRAM_SOCKETS
351 /* Table of `partner address' for datagram sockets. */
352 static struct sockaddr_and_len {
353 struct sockaddr *sa;
354 int len;
355 } datagram_address[MAXDESC];
356 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
357 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
358 #else
359 #define DATAGRAM_CHAN_P(chan) (0)
360 #define DATAGRAM_CONN_P(proc) (0)
361 #endif
363 /* These setters are used only in this file, so they can be private. */
364 static void
365 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
367 p->buffer = val;
369 static void
370 pset_command (struct Lisp_Process *p, Lisp_Object val)
372 p->command = val;
374 static void
375 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
377 p->decode_coding_system = val;
379 static void
380 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
382 p->decoding_buf = val;
384 static void
385 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
387 p->encode_coding_system = val;
389 static void
390 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
392 p->encoding_buf = val;
394 static void
395 pset_filter (struct Lisp_Process *p, Lisp_Object val)
397 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
399 static void
400 pset_log (struct Lisp_Process *p, Lisp_Object val)
402 p->log = val;
404 static void
405 pset_mark (struct Lisp_Process *p, Lisp_Object val)
407 p->mark = val;
409 static void
410 pset_name (struct Lisp_Process *p, Lisp_Object val)
412 p->name = val;
414 static void
415 pset_plist (struct Lisp_Process *p, Lisp_Object val)
417 p->plist = val;
419 static void
420 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
422 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
424 static void
425 pset_status (struct Lisp_Process *p, Lisp_Object val)
427 p->status = val;
429 static void
430 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
432 p->tty_name = val;
434 static void
435 pset_type (struct Lisp_Process *p, Lisp_Object val)
437 p->type = val;
439 static void
440 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
442 p->write_queue = val;
447 static struct fd_callback_data
449 fd_callback func;
450 void *data;
451 #define FOR_READ 1
452 #define FOR_WRITE 2
453 int condition; /* mask of the defines above. */
454 } fd_callback_info[MAXDESC];
457 /* Add a file descriptor FD to be monitored for when read is possible.
458 When read is possible, call FUNC with argument DATA. */
460 void
461 add_read_fd (int fd, fd_callback func, void *data)
463 eassert (fd < MAXDESC);
464 add_keyboard_wait_descriptor (fd);
466 fd_callback_info[fd].func = func;
467 fd_callback_info[fd].data = data;
468 fd_callback_info[fd].condition |= FOR_READ;
471 /* Stop monitoring file descriptor FD for when read is possible. */
473 void
474 delete_read_fd (int fd)
476 eassert (fd < MAXDESC);
477 delete_keyboard_wait_descriptor (fd);
479 fd_callback_info[fd].condition &= ~FOR_READ;
480 if (fd_callback_info[fd].condition == 0)
482 fd_callback_info[fd].func = 0;
483 fd_callback_info[fd].data = 0;
487 /* Add a file descriptor FD to be monitored for when write is possible.
488 When write is possible, call FUNC with argument DATA. */
490 void
491 add_write_fd (int fd, fd_callback func, void *data)
493 eassert (fd < MAXDESC);
494 FD_SET (fd, &write_mask);
495 if (fd > max_input_desc)
496 max_input_desc = fd;
498 fd_callback_info[fd].func = func;
499 fd_callback_info[fd].data = data;
500 fd_callback_info[fd].condition |= FOR_WRITE;
503 /* FD is no longer an input descriptor; update max_input_desc accordingly. */
505 static void
506 delete_input_desc (int fd)
508 if (fd == max_input_desc)
511 fd--;
512 while (0 <= fd && ! (FD_ISSET (fd, &input_wait_mask)
513 || FD_ISSET (fd, &write_mask)));
515 max_input_desc = fd;
519 /* Stop monitoring file descriptor FD for when write is possible. */
521 void
522 delete_write_fd (int fd)
524 eassert (fd < MAXDESC);
525 FD_CLR (fd, &write_mask);
526 fd_callback_info[fd].condition &= ~FOR_WRITE;
527 if (fd_callback_info[fd].condition == 0)
529 fd_callback_info[fd].func = 0;
530 fd_callback_info[fd].data = 0;
531 delete_input_desc (fd);
536 /* Compute the Lisp form of the process status, p->status, from
537 the numeric status that was returned by `wait'. */
539 static Lisp_Object status_convert (int);
541 static void
542 update_status (struct Lisp_Process *p)
544 eassert (p->raw_status_new);
545 pset_status (p, status_convert (p->raw_status));
546 p->raw_status_new = 0;
549 /* Convert a process status word in Unix format to
550 the list that we use internally. */
552 static Lisp_Object
553 status_convert (int w)
555 if (WIFSTOPPED (w))
556 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
557 else if (WIFEXITED (w))
558 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
559 WCOREDUMP (w) ? Qt : Qnil));
560 else if (WIFSIGNALED (w))
561 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
562 WCOREDUMP (w) ? Qt : Qnil));
563 else
564 return Qrun;
567 /* Given a status-list, extract the three pieces of information
568 and store them individually through the three pointers. */
570 static void
571 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
573 Lisp_Object tem;
575 if (SYMBOLP (l))
577 *symbol = l;
578 *code = 0;
579 *coredump = 0;
581 else
583 *symbol = XCAR (l);
584 tem = XCDR (l);
585 *code = XFASTINT (XCAR (tem));
586 tem = XCDR (tem);
587 *coredump = !NILP (tem);
591 /* Return a string describing a process status list. */
593 static Lisp_Object
594 status_message (struct Lisp_Process *p)
596 Lisp_Object status = p->status;
597 Lisp_Object symbol;
598 int code;
599 bool coredump;
600 Lisp_Object string, string2;
602 decode_status (status, &symbol, &code, &coredump);
604 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
606 char const *signame;
607 synchronize_system_messages_locale ();
608 signame = strsignal (code);
609 if (signame == 0)
610 string = build_string ("unknown");
611 else
613 int c1, c2;
615 string = build_unibyte_string (signame);
616 if (! NILP (Vlocale_coding_system))
617 string = (code_convert_string_norecord
618 (string, Vlocale_coding_system, 0));
619 c1 = STRING_CHAR (SDATA (string));
620 c2 = downcase (c1);
621 if (c1 != c2)
622 Faset (string, make_number (0), make_number (c2));
624 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
625 return concat2 (string, string2);
627 else if (EQ (symbol, Qexit))
629 if (NETCONN1_P (p))
630 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
631 if (code == 0)
632 return build_string ("finished\n");
633 string = Fnumber_to_string (make_number (code));
634 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
635 return concat3 (build_string ("exited abnormally with code "),
636 string, string2);
638 else if (EQ (symbol, Qfailed))
640 string = Fnumber_to_string (make_number (code));
641 string2 = build_string ("\n");
642 return concat3 (build_string ("failed with code "),
643 string, string2);
645 else
646 return Fcopy_sequence (Fsymbol_name (symbol));
649 enum { PTY_NAME_SIZE = 24 };
651 /* Open an available pty, returning a file descriptor.
652 Store into PTY_NAME the file name of the terminal corresponding to the pty.
653 Return -1 on failure. */
655 static int
656 allocate_pty (char pty_name[PTY_NAME_SIZE])
658 #ifdef HAVE_PTYS
659 int fd;
661 #ifdef PTY_ITERATION
662 PTY_ITERATION
663 #else
664 register int c, i;
665 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
666 for (i = 0; i < 16; i++)
667 #endif
669 #ifdef PTY_NAME_SPRINTF
670 PTY_NAME_SPRINTF
671 #else
672 sprintf (pty_name, "/dev/pty%c%x", c, i);
673 #endif /* no PTY_NAME_SPRINTF */
675 #ifdef PTY_OPEN
676 PTY_OPEN;
677 #else /* no PTY_OPEN */
678 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
679 #endif /* no PTY_OPEN */
681 if (fd >= 0)
683 /* check to make certain that both sides are available
684 this avoids a nasty yet stupid bug in rlogins */
685 #ifdef PTY_TTY_NAME_SPRINTF
686 PTY_TTY_NAME_SPRINTF
687 #else
688 sprintf (pty_name, "/dev/tty%c%x", c, i);
689 #endif /* no PTY_TTY_NAME_SPRINTF */
690 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
692 emacs_close (fd);
693 # ifndef __sgi
694 continue;
695 # else
696 return -1;
697 # endif /* __sgi */
699 setup_pty (fd);
700 return fd;
703 #endif /* HAVE_PTYS */
704 return -1;
707 static Lisp_Object
708 make_process (Lisp_Object name)
710 register Lisp_Object val, tem, name1;
711 register struct Lisp_Process *p;
712 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
713 printmax_t i;
715 p = allocate_process ();
716 /* Initialize Lisp data. Note that allocate_process initializes all
717 Lisp data to nil, so do it only for slots which should not be nil. */
718 pset_status (p, Qrun);
719 pset_mark (p, Fmake_marker ());
721 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
722 non-Lisp data, so do it only for slots which should not be zero. */
723 p->infd = -1;
724 p->outfd = -1;
726 #ifdef HAVE_GNUTLS
727 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
728 #endif
730 /* If name is already in use, modify it until it is unused. */
732 name1 = name;
733 for (i = 1; ; i++)
735 tem = Fget_process (name1);
736 if (NILP (tem)) break;
737 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
739 name = name1;
740 pset_name (p, name);
741 pset_sentinel (p, Qinternal_default_process_sentinel);
742 pset_filter (p, Qinternal_default_process_filter);
743 XSETPROCESS (val, p);
744 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
745 return val;
748 static void
749 remove_process (register Lisp_Object proc)
751 register Lisp_Object pair;
753 pair = Frassq (proc, Vprocess_alist);
754 Vprocess_alist = Fdelq (pair, Vprocess_alist);
756 deactivate_process (proc);
760 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
761 doc: /* Return t if OBJECT is a process. */)
762 (Lisp_Object object)
764 return PROCESSP (object) ? Qt : Qnil;
767 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
768 doc: /* Return the process named NAME, or nil if there is none. */)
769 (register Lisp_Object name)
771 if (PROCESSP (name))
772 return name;
773 CHECK_STRING (name);
774 return Fcdr (Fassoc (name, Vprocess_alist));
777 /* This is how commands for the user decode process arguments. It
778 accepts a process, a process name, a buffer, a buffer name, or nil.
779 Buffers denote the first process in the buffer, and nil denotes the
780 current buffer. */
782 static Lisp_Object
783 get_process (register Lisp_Object name)
785 register Lisp_Object proc, obj;
786 if (STRINGP (name))
788 obj = Fget_process (name);
789 if (NILP (obj))
790 obj = Fget_buffer (name);
791 if (NILP (obj))
792 error ("Process %s does not exist", SDATA (name));
794 else if (NILP (name))
795 obj = Fcurrent_buffer ();
796 else
797 obj = name;
799 /* Now obj should be either a buffer object or a process object.
801 if (BUFFERP (obj))
803 proc = Fget_buffer_process (obj);
804 if (NILP (proc))
805 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
807 else
809 CHECK_PROCESS (obj);
810 proc = obj;
812 return proc;
816 /* Fdelete_process promises to immediately forget about the process, but in
817 reality, Emacs needs to remember those processes until they have been
818 treated by the SIGCHLD handler and waitpid has been invoked on them;
819 otherwise they might fill up the kernel's process table.
821 Some processes created by call-process are also put onto this list. */
822 static Lisp_Object deleted_pid_list;
824 void
825 record_deleted_pid (pid_t pid)
827 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
828 /* GC treated elements set to nil. */
829 Fdelq (Qnil, deleted_pid_list));
833 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
834 doc: /* Delete PROCESS: kill it and forget about it immediately.
835 PROCESS may be a process, a buffer, the name of a process or buffer, or
836 nil, indicating the current buffer's process. */)
837 (register Lisp_Object process)
839 register struct Lisp_Process *p;
841 process = get_process (process);
842 p = XPROCESS (process);
844 p->raw_status_new = 0;
845 if (NETCONN1_P (p) || SERIALCONN1_P (p))
847 pset_status (p, list2 (Qexit, make_number (0)));
848 p->tick = ++process_tick;
849 status_notify (p);
850 redisplay_preserve_echo_area (13);
852 else
854 if (p->alive)
855 record_kill_process (p);
857 if (p->infd >= 0)
859 /* Update P's status, since record_kill_process will make the
860 SIGCHLD handler update deleted_pid_list, not *P. */
861 Lisp_Object symbol;
862 if (p->raw_status_new)
863 update_status (p);
864 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
865 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
866 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
868 p->tick = ++process_tick;
869 status_notify (p);
870 redisplay_preserve_echo_area (13);
873 remove_process (process);
874 return Qnil;
877 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
878 doc: /* Return the status of PROCESS.
879 The returned value is one of the following symbols:
880 run -- for a process that is running.
881 stop -- for a process stopped but continuable.
882 exit -- for a process that has exited.
883 signal -- for a process that has got a fatal signal.
884 open -- for a network stream connection that is open.
885 listen -- for a network stream server that is listening.
886 closed -- for a network stream connection that is closed.
887 connect -- when waiting for a non-blocking connection to complete.
888 failed -- when a non-blocking connection has failed.
889 nil -- if arg is a process name and no such process exists.
890 PROCESS may be a process, a buffer, the name of a process, or
891 nil, indicating the current buffer's process. */)
892 (register Lisp_Object process)
894 register struct Lisp_Process *p;
895 register Lisp_Object status;
897 if (STRINGP (process))
898 process = Fget_process (process);
899 else
900 process = get_process (process);
902 if (NILP (process))
903 return process;
905 p = XPROCESS (process);
906 if (p->raw_status_new)
907 update_status (p);
908 status = p->status;
909 if (CONSP (status))
910 status = XCAR (status);
911 if (NETCONN1_P (p) || SERIALCONN1_P (p))
913 if (EQ (status, Qexit))
914 status = Qclosed;
915 else if (EQ (p->command, Qt))
916 status = Qstop;
917 else if (EQ (status, Qrun))
918 status = Qopen;
920 return status;
923 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
924 1, 1, 0,
925 doc: /* Return the exit status of PROCESS or the signal number that killed it.
926 If PROCESS has not yet exited or died, return 0. */)
927 (register Lisp_Object process)
929 CHECK_PROCESS (process);
930 if (XPROCESS (process)->raw_status_new)
931 update_status (XPROCESS (process));
932 if (CONSP (XPROCESS (process)->status))
933 return XCAR (XCDR (XPROCESS (process)->status));
934 return make_number (0);
937 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
938 doc: /* Return the process id of PROCESS.
939 This is the pid of the external process which PROCESS uses or talks to.
940 For a network connection, this value is nil. */)
941 (register Lisp_Object process)
943 pid_t pid;
945 CHECK_PROCESS (process);
946 pid = XPROCESS (process)->pid;
947 return (pid ? make_fixnum_or_float (pid) : Qnil);
950 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
951 doc: /* Return the name of PROCESS, as a string.
952 This is the name of the program invoked in PROCESS,
953 possibly modified to make it unique among process names. */)
954 (register Lisp_Object process)
956 CHECK_PROCESS (process);
957 return XPROCESS (process)->name;
960 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
961 doc: /* Return the command that was executed to start PROCESS.
962 This is a list of strings, the first string being the program executed
963 and the rest of the strings being the arguments given to it.
964 For a network or serial process, this is nil (process is running) or t
965 \(process is stopped). */)
966 (register Lisp_Object process)
968 CHECK_PROCESS (process);
969 return XPROCESS (process)->command;
972 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
973 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
974 This is the terminal that the process itself reads and writes on,
975 not the name of the pty that Emacs uses to talk with that terminal. */)
976 (register Lisp_Object process)
978 CHECK_PROCESS (process);
979 return XPROCESS (process)->tty_name;
982 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
983 2, 2, 0,
984 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
985 Return BUFFER. */)
986 (register Lisp_Object process, Lisp_Object buffer)
988 struct Lisp_Process *p;
990 CHECK_PROCESS (process);
991 if (!NILP (buffer))
992 CHECK_BUFFER (buffer);
993 p = XPROCESS (process);
994 pset_buffer (p, buffer);
995 if (NETCONN1_P (p) || SERIALCONN1_P (p))
996 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
997 setup_process_coding_systems (process);
998 return buffer;
1001 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
1002 1, 1, 0,
1003 doc: /* Return the buffer PROCESS is associated with.
1004 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
1005 (register Lisp_Object process)
1007 CHECK_PROCESS (process);
1008 return XPROCESS (process)->buffer;
1011 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
1012 1, 1, 0,
1013 doc: /* Return the marker for the end of the last output from PROCESS. */)
1014 (register Lisp_Object process)
1016 CHECK_PROCESS (process);
1017 return XPROCESS (process)->mark;
1020 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
1021 2, 2, 0,
1022 doc: /* Give PROCESS the filter function FILTER; nil means default.
1023 A value of t means stop accepting output from the process.
1025 When a process has a non-default filter, its buffer is not used for output.
1026 Instead, each time it does output, the entire string of output is
1027 passed to the filter.
1029 The filter gets two arguments: the process and the string of output.
1030 The string argument is normally a multibyte string, except:
1031 - if the process' input coding system is no-conversion or raw-text,
1032 it is a unibyte string (the non-converted input), or else
1033 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1034 string (the result of converting the decoded input multibyte
1035 string to unibyte with `string-make-unibyte'). */)
1036 (register Lisp_Object process, Lisp_Object filter)
1038 struct Lisp_Process *p;
1040 CHECK_PROCESS (process);
1041 p = XPROCESS (process);
1043 /* Don't signal an error if the process' input file descriptor
1044 is closed. This could make debugging Lisp more difficult,
1045 for example when doing something like
1047 (setq process (start-process ...))
1048 (debug)
1049 (set-process-filter process ...) */
1051 if (NILP (filter))
1052 filter = Qinternal_default_process_filter;
1054 if (p->infd >= 0)
1056 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1058 FD_CLR (p->infd, &input_wait_mask);
1059 FD_CLR (p->infd, &non_keyboard_wait_mask);
1061 else if (EQ (p->filter, Qt)
1062 /* Network or serial process not stopped: */
1063 && !EQ (p->command, Qt))
1065 FD_SET (p->infd, &input_wait_mask);
1066 FD_SET (p->infd, &non_keyboard_wait_mask);
1070 pset_filter (p, filter);
1071 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1072 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1073 setup_process_coding_systems (process);
1074 return filter;
1077 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1078 1, 1, 0,
1079 doc: /* Return the filter function of PROCESS.
1080 See `set-process-filter' for more info on filter functions. */)
1081 (register Lisp_Object process)
1083 CHECK_PROCESS (process);
1084 return XPROCESS (process)->filter;
1087 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1088 2, 2, 0,
1089 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1090 The sentinel is called as a function when the process changes state.
1091 It gets two arguments: the process, and a string describing the change. */)
1092 (register Lisp_Object process, Lisp_Object sentinel)
1094 struct Lisp_Process *p;
1096 CHECK_PROCESS (process);
1097 p = XPROCESS (process);
1099 if (NILP (sentinel))
1100 sentinel = Qinternal_default_process_sentinel;
1102 pset_sentinel (p, sentinel);
1103 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1104 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1105 return sentinel;
1108 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1109 1, 1, 0,
1110 doc: /* Return the sentinel of PROCESS.
1111 See `set-process-sentinel' for more info on sentinels. */)
1112 (register Lisp_Object process)
1114 CHECK_PROCESS (process);
1115 return XPROCESS (process)->sentinel;
1118 DEFUN ("set-process-window-size", Fset_process_window_size,
1119 Sset_process_window_size, 3, 3, 0,
1120 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1121 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
1123 CHECK_PROCESS (process);
1124 CHECK_RANGED_INTEGER (height, 0, INT_MAX);
1125 CHECK_RANGED_INTEGER (width, 0, INT_MAX);
1127 if (XPROCESS (process)->infd < 0
1128 || set_window_size (XPROCESS (process)->infd,
1129 XINT (height), XINT (width)) <= 0)
1130 return Qnil;
1131 else
1132 return Qt;
1135 DEFUN ("set-process-inherit-coding-system-flag",
1136 Fset_process_inherit_coding_system_flag,
1137 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1138 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1139 If the second argument FLAG is non-nil, then the variable
1140 `buffer-file-coding-system' of the buffer associated with PROCESS
1141 will be bound to the value of the coding system used to decode
1142 the process output.
1144 This is useful when the coding system specified for the process buffer
1145 leaves either the character code conversion or the end-of-line conversion
1146 unspecified, or if the coding system used to decode the process output
1147 is more appropriate for saving the process buffer.
1149 Binding the variable `inherit-process-coding-system' to non-nil before
1150 starting the process is an alternative way of setting the inherit flag
1151 for the process which will run.
1153 This function returns FLAG. */)
1154 (register Lisp_Object process, Lisp_Object flag)
1156 CHECK_PROCESS (process);
1157 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1158 return flag;
1161 DEFUN ("set-process-query-on-exit-flag",
1162 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1163 2, 2, 0,
1164 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1165 If the second argument FLAG is non-nil, Emacs will query the user before
1166 exiting or killing a buffer if PROCESS is running. This function
1167 returns FLAG. */)
1168 (register Lisp_Object process, Lisp_Object flag)
1170 CHECK_PROCESS (process);
1171 XPROCESS (process)->kill_without_query = NILP (flag);
1172 return flag;
1175 DEFUN ("process-query-on-exit-flag",
1176 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1177 1, 1, 0,
1178 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1179 (register Lisp_Object process)
1181 CHECK_PROCESS (process);
1182 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1185 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1186 1, 2, 0,
1187 doc: /* Return the contact info of PROCESS; t for a real child.
1188 For a network or serial connection, the value depends on the optional
1189 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1190 SERVICE) for a network connection or (PORT SPEED) for a serial
1191 connection. If KEY is t, the complete contact information for the
1192 connection is returned, else the specific value for the keyword KEY is
1193 returned. See `make-network-process' or `make-serial-process' for a
1194 list of keywords. */)
1195 (register Lisp_Object process, Lisp_Object key)
1197 Lisp_Object contact;
1199 CHECK_PROCESS (process);
1200 contact = XPROCESS (process)->childp;
1202 #ifdef DATAGRAM_SOCKETS
1203 if (DATAGRAM_CONN_P (process)
1204 && (EQ (key, Qt) || EQ (key, QCremote)))
1205 contact = Fplist_put (contact, QCremote,
1206 Fprocess_datagram_address (process));
1207 #endif
1209 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1210 return contact;
1211 if (NILP (key) && NETCONN_P (process))
1212 return list2 (Fplist_get (contact, QChost),
1213 Fplist_get (contact, QCservice));
1214 if (NILP (key) && SERIALCONN_P (process))
1215 return list2 (Fplist_get (contact, QCport),
1216 Fplist_get (contact, QCspeed));
1217 return Fplist_get (contact, key);
1220 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1221 1, 1, 0,
1222 doc: /* Return the plist of PROCESS. */)
1223 (register Lisp_Object process)
1225 CHECK_PROCESS (process);
1226 return XPROCESS (process)->plist;
1229 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1230 2, 2, 0,
1231 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1232 (register Lisp_Object process, Lisp_Object plist)
1234 CHECK_PROCESS (process);
1235 CHECK_LIST (plist);
1237 pset_plist (XPROCESS (process), plist);
1238 return plist;
1241 #if 0 /* Turned off because we don't currently record this info
1242 in the process. Perhaps add it. */
1243 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1244 doc: /* Return the connection type of PROCESS.
1245 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1246 a socket connection. */)
1247 (Lisp_Object process)
1249 return XPROCESS (process)->type;
1251 #endif
1253 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1254 doc: /* Return the connection type of PROCESS.
1255 The value is either the symbol `real', `network', or `serial'.
1256 PROCESS may be a process, a buffer, the name of a process or buffer, or
1257 nil, indicating the current buffer's process. */)
1258 (Lisp_Object process)
1260 Lisp_Object proc;
1261 proc = get_process (process);
1262 return XPROCESS (proc)->type;
1265 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1266 1, 2, 0,
1267 doc: /* Convert network ADDRESS from internal format to a string.
1268 A 4 or 5 element vector represents an IPv4 address (with port number).
1269 An 8 or 9 element vector represents an IPv6 address (with port number).
1270 If optional second argument OMIT-PORT is non-nil, don't include a port
1271 number in the string, even when present in ADDRESS.
1272 Returns nil if format of ADDRESS is invalid. */)
1273 (Lisp_Object address, Lisp_Object omit_port)
1275 if (NILP (address))
1276 return Qnil;
1278 if (STRINGP (address)) /* AF_LOCAL */
1279 return address;
1281 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1283 register struct Lisp_Vector *p = XVECTOR (address);
1284 ptrdiff_t size = p->header.size;
1285 Lisp_Object args[10];
1286 int nargs, i;
1288 if (size == 4 || (size == 5 && !NILP (omit_port)))
1290 args[0] = build_string ("%d.%d.%d.%d");
1291 nargs = 4;
1293 else if (size == 5)
1295 args[0] = build_string ("%d.%d.%d.%d:%d");
1296 nargs = 5;
1298 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1300 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1301 nargs = 8;
1303 else if (size == 9)
1305 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1306 nargs = 9;
1308 else
1309 return Qnil;
1311 for (i = 0; i < nargs; i++)
1313 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1314 return Qnil;
1316 if (nargs <= 5 /* IPv4 */
1317 && i < 4 /* host, not port */
1318 && XINT (p->contents[i]) > 255)
1319 return Qnil;
1321 args[i+1] = p->contents[i];
1324 return Fformat (nargs+1, args);
1327 if (CONSP (address))
1329 Lisp_Object args[2];
1330 args[0] = build_string ("<Family %d>");
1331 args[1] = Fcar (address);
1332 return Fformat (2, args);
1335 return Qnil;
1338 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1339 doc: /* Return a list of all processes that are Emacs sub-processes. */)
1340 (void)
1342 return Fmapcar (Qcdr, Vprocess_alist);
1345 /* Starting asynchronous inferior processes. */
1347 static void start_process_unwind (Lisp_Object proc);
1349 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1350 doc: /* Start a program in a subprocess. Return the process object for it.
1351 NAME is name for process. It is modified if necessary to make it unique.
1352 BUFFER is the buffer (or buffer name) to associate with the process.
1354 Process output (both standard output and standard error streams) goes
1355 at end of BUFFER, unless you specify an output stream or filter
1356 function to handle the output. BUFFER may also be nil, meaning that
1357 this process is not associated with any buffer.
1359 PROGRAM is the program file name. It is searched for in `exec-path'
1360 (which see). If nil, just associate a pty with the buffer. Remaining
1361 arguments are strings to give program as arguments.
1363 If you want to separate standard output from standard error, invoke
1364 the command through a shell and redirect one of them using the shell
1365 syntax.
1367 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1368 (ptrdiff_t nargs, Lisp_Object *args)
1370 Lisp_Object buffer, name, program, proc, current_dir, tem;
1371 register unsigned char **new_argv;
1372 ptrdiff_t i;
1373 ptrdiff_t count = SPECPDL_INDEX ();
1375 buffer = args[1];
1376 if (!NILP (buffer))
1377 buffer = Fget_buffer_create (buffer);
1379 /* Make sure that the child will be able to chdir to the current
1380 buffer's current directory, or its unhandled equivalent. We
1381 can't just have the child check for an error when it does the
1382 chdir, since it's in a vfork.
1384 We have to GCPRO around this because Fexpand_file_name and
1385 Funhandled_file_name_directory might call a file name handling
1386 function. The argument list is protected by the caller, so all
1387 we really have to worry about is buffer. */
1389 struct gcpro gcpro1, gcpro2;
1391 current_dir = BVAR (current_buffer, directory);
1393 GCPRO2 (buffer, current_dir);
1395 current_dir = Funhandled_file_name_directory (current_dir);
1396 if (NILP (current_dir))
1397 /* If the file name handler says that current_dir is unreachable, use
1398 a sensible default. */
1399 current_dir = build_string ("~/");
1400 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1401 if (NILP (Ffile_accessible_directory_p (current_dir)))
1402 report_file_error ("Setting current directory",
1403 BVAR (current_buffer, directory));
1405 UNGCPRO;
1408 name = args[0];
1409 CHECK_STRING (name);
1411 program = args[2];
1413 if (!NILP (program))
1414 CHECK_STRING (program);
1416 proc = make_process (name);
1417 /* If an error occurs and we can't start the process, we want to
1418 remove it from the process list. This means that each error
1419 check in create_process doesn't need to call remove_process
1420 itself; it's all taken care of here. */
1421 record_unwind_protect (start_process_unwind, proc);
1423 pset_childp (XPROCESS (proc), Qt);
1424 pset_plist (XPROCESS (proc), Qnil);
1425 pset_type (XPROCESS (proc), Qreal);
1426 pset_buffer (XPROCESS (proc), buffer);
1427 pset_sentinel (XPROCESS (proc), Qinternal_default_process_sentinel);
1428 pset_filter (XPROCESS (proc), Qinternal_default_process_filter);
1429 pset_command (XPROCESS (proc), Flist (nargs - 2, args + 2));
1431 #ifdef HAVE_GNUTLS
1432 /* AKA GNUTLS_INITSTAGE(proc). */
1433 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1434 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1435 #endif
1437 #ifdef ADAPTIVE_READ_BUFFERING
1438 XPROCESS (proc)->adaptive_read_buffering
1439 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1440 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1441 #endif
1443 /* Make the process marker point into the process buffer (if any). */
1444 if (BUFFERP (buffer))
1445 set_marker_both (XPROCESS (proc)->mark, buffer,
1446 BUF_ZV (XBUFFER (buffer)),
1447 BUF_ZV_BYTE (XBUFFER (buffer)));
1450 /* Decide coding systems for communicating with the process. Here
1451 we don't setup the structure coding_system nor pay attention to
1452 unibyte mode. They are done in create_process. */
1454 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1455 Lisp_Object coding_systems = Qt;
1456 Lisp_Object val, *args2;
1457 struct gcpro gcpro1, gcpro2;
1459 val = Vcoding_system_for_read;
1460 if (NILP (val))
1462 args2 = alloca ((nargs + 1) * sizeof *args2);
1463 args2[0] = Qstart_process;
1464 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1465 GCPRO2 (proc, current_dir);
1466 if (!NILP (program))
1467 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1468 UNGCPRO;
1469 if (CONSP (coding_systems))
1470 val = XCAR (coding_systems);
1471 else if (CONSP (Vdefault_process_coding_system))
1472 val = XCAR (Vdefault_process_coding_system);
1474 pset_decode_coding_system (XPROCESS (proc), val);
1476 val = Vcoding_system_for_write;
1477 if (NILP (val))
1479 if (EQ (coding_systems, Qt))
1481 args2 = alloca ((nargs + 1) * sizeof *args2);
1482 args2[0] = Qstart_process;
1483 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1484 GCPRO2 (proc, current_dir);
1485 if (!NILP (program))
1486 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1487 UNGCPRO;
1489 if (CONSP (coding_systems))
1490 val = XCDR (coding_systems);
1491 else if (CONSP (Vdefault_process_coding_system))
1492 val = XCDR (Vdefault_process_coding_system);
1494 pset_encode_coding_system (XPROCESS (proc), val);
1495 /* Note: At this moment, the above coding system may leave
1496 text-conversion or eol-conversion unspecified. They will be
1497 decided after we read output from the process and decode it by
1498 some coding system, or just before we actually send a text to
1499 the process. */
1503 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1504 XPROCESS (proc)->decoding_carryover = 0;
1505 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1507 XPROCESS (proc)->inherit_coding_system_flag
1508 = !(NILP (buffer) || !inherit_process_coding_system);
1510 if (!NILP (program))
1512 /* If program file name is not absolute, search our path for it.
1513 Put the name we will really use in TEM. */
1514 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1515 && !(SCHARS (program) > 1
1516 && IS_DEVICE_SEP (SREF (program, 1))))
1518 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1520 tem = Qnil;
1521 GCPRO4 (name, program, buffer, current_dir);
1522 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1523 UNGCPRO;
1524 if (NILP (tem))
1525 report_file_error ("Searching for program", program);
1526 tem = Fexpand_file_name (tem, Qnil);
1528 else
1530 if (!NILP (Ffile_directory_p (program)))
1531 error ("Specified program for new process is a directory");
1532 tem = program;
1535 /* If program file name starts with /: for quoting a magic name,
1536 discard that. */
1537 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1538 && SREF (tem, 1) == ':')
1539 tem = Fsubstring (tem, make_number (2), Qnil);
1542 Lisp_Object arg_encoding = Qnil;
1543 struct gcpro gcpro1;
1544 GCPRO1 (tem);
1546 /* Encode the file name and put it in NEW_ARGV.
1547 That's where the child will use it to execute the program. */
1548 tem = list1 (ENCODE_FILE (tem));
1550 /* Here we encode arguments by the coding system used for sending
1551 data to the process. We don't support using different coding
1552 systems for encoding arguments and for encoding data sent to the
1553 process. */
1555 for (i = 3; i < nargs; i++)
1557 tem = Fcons (args[i], tem);
1558 CHECK_STRING (XCAR (tem));
1559 if (STRING_MULTIBYTE (XCAR (tem)))
1561 if (NILP (arg_encoding))
1562 arg_encoding = (complement_process_encoding_system
1563 (XPROCESS (proc)->encode_coding_system));
1564 XSETCAR (tem,
1565 code_convert_string_norecord
1566 (XCAR (tem), arg_encoding, 1));
1570 UNGCPRO;
1573 /* Now that everything is encoded we can collect the strings into
1574 NEW_ARGV. */
1575 new_argv = alloca ((nargs - 1) * sizeof *new_argv);
1576 new_argv[nargs - 2] = 0;
1578 for (i = nargs - 2; i-- != 0; )
1580 new_argv[i] = SDATA (XCAR (tem));
1581 tem = XCDR (tem);
1584 create_process (proc, (char **) new_argv, current_dir);
1586 else
1587 create_pty (proc);
1589 return unbind_to (count, proc);
1592 /* This function is the unwind_protect form for Fstart_process. If
1593 PROC doesn't have its pid set, then we know someone has signaled
1594 an error and the process wasn't started successfully, so we should
1595 remove it from the process list. */
1596 static void
1597 start_process_unwind (Lisp_Object proc)
1599 if (!PROCESSP (proc))
1600 emacs_abort ();
1602 /* Was PROC started successfully?
1603 -2 is used for a pty with no process, eg for gdb. */
1604 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1605 remove_process (proc);
1609 static void
1610 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1612 int inchannel, outchannel;
1613 pid_t pid;
1614 int vfork_errno;
1615 int sv[2];
1616 #ifndef WINDOWSNT
1617 int wait_child_setup[2];
1618 #endif
1619 int forkin, forkout;
1620 bool pty_flag = 0;
1621 char pty_name[PTY_NAME_SIZE];
1622 Lisp_Object lisp_pty_name = Qnil;
1623 Lisp_Object encoded_current_dir;
1625 inchannel = outchannel = -1;
1627 if (!NILP (Vprocess_connection_type))
1628 outchannel = inchannel = allocate_pty (pty_name);
1630 if (inchannel >= 0)
1632 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1633 /* On most USG systems it does not work to open the pty's tty here,
1634 then close it and reopen it in the child. */
1635 /* Don't let this terminal become our controlling terminal
1636 (in case we don't have one). */
1637 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1638 if (forkin < 0)
1639 report_file_error ("Opening pty", Qnil);
1640 #else
1641 forkin = forkout = -1;
1642 #endif /* not USG, or USG_SUBTTY_WORKS */
1643 pty_flag = 1;
1644 lisp_pty_name = build_string (pty_name);
1646 else
1648 if (emacs_pipe (sv) != 0)
1649 report_file_error ("Creating pipe", Qnil);
1650 inchannel = sv[0];
1651 forkout = sv[1];
1652 if (emacs_pipe (sv) != 0)
1654 int pipe_errno = errno;
1655 emacs_close (inchannel);
1656 emacs_close (forkout);
1657 report_file_errno ("Creating pipe", Qnil, pipe_errno);
1659 outchannel = sv[1];
1660 forkin = sv[0];
1663 #ifndef WINDOWSNT
1664 if (emacs_pipe (wait_child_setup) != 0)
1665 report_file_error ("Creating pipe", Qnil);
1666 #endif
1668 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1669 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1671 /* Record this as an active process, with its channels. */
1672 chan_process[inchannel] = process;
1673 XPROCESS (process)->infd = inchannel;
1674 XPROCESS (process)->outfd = outchannel;
1676 /* Previously we recorded the tty descriptor used in the subprocess.
1677 It was only used for getting the foreground tty process, so now
1678 we just reopen the device (see emacs_get_tty_pgrp) as this is
1679 more portable (see USG_SUBTTY_WORKS above). */
1681 XPROCESS (process)->pty_flag = pty_flag;
1682 pset_status (XPROCESS (process), Qrun);
1684 FD_SET (inchannel, &input_wait_mask);
1685 FD_SET (inchannel, &non_keyboard_wait_mask);
1686 if (inchannel > max_process_desc)
1687 max_process_desc = inchannel;
1689 /* This may signal an error. */
1690 setup_process_coding_systems (process);
1692 encoded_current_dir = ENCODE_FILE (current_dir);
1694 block_input ();
1695 block_child_signal ();
1697 #ifndef WINDOWSNT
1698 /* vfork, and prevent local vars from being clobbered by the vfork. */
1700 Lisp_Object volatile encoded_current_dir_volatile = encoded_current_dir;
1701 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1702 Lisp_Object volatile process_volatile = process;
1703 char **volatile new_argv_volatile = new_argv;
1704 int volatile forkin_volatile = forkin;
1705 int volatile forkout_volatile = forkout;
1706 int volatile wait_child_setup_0_volatile = wait_child_setup[0];
1707 int volatile wait_child_setup_1_volatile = wait_child_setup[1];
1709 pid = vfork ();
1711 encoded_current_dir = encoded_current_dir_volatile;
1712 lisp_pty_name = lisp_pty_name_volatile;
1713 process = process_volatile;
1714 new_argv = new_argv_volatile;
1715 forkin = forkin_volatile;
1716 forkout = forkout_volatile;
1717 wait_child_setup[0] = wait_child_setup_0_volatile;
1718 wait_child_setup[1] = wait_child_setup_1_volatile;
1720 pty_flag = XPROCESS (process)->pty_flag;
1723 if (pid == 0)
1724 #endif /* not WINDOWSNT */
1726 int xforkin = forkin;
1727 int xforkout = forkout;
1729 /* Make the pty be the controlling terminal of the process. */
1730 #ifdef HAVE_PTYS
1731 /* First, disconnect its current controlling terminal. */
1732 /* We tried doing setsid only if pty_flag, but it caused
1733 process_set_signal to fail on SGI when using a pipe. */
1734 setsid ();
1735 /* Make the pty's terminal the controlling terminal. */
1736 if (pty_flag && xforkin >= 0)
1738 #ifdef TIOCSCTTY
1739 /* We ignore the return value
1740 because faith@cs.unc.edu says that is necessary on Linux. */
1741 ioctl (xforkin, TIOCSCTTY, 0);
1742 #endif
1744 #if defined (LDISC1)
1745 if (pty_flag && xforkin >= 0)
1747 struct termios t;
1748 tcgetattr (xforkin, &t);
1749 t.c_lflag = LDISC1;
1750 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1751 emacs_perror ("create_process/tcsetattr LDISC1");
1753 #else
1754 #if defined (NTTYDISC) && defined (TIOCSETD)
1755 if (pty_flag && xforkin >= 0)
1757 /* Use new line discipline. */
1758 int ldisc = NTTYDISC;
1759 ioctl (xforkin, TIOCSETD, &ldisc);
1761 #endif
1762 #endif
1763 #ifdef TIOCNOTTY
1764 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1765 can do TIOCSPGRP only to the process's controlling tty. */
1766 if (pty_flag)
1768 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1769 I can't test it since I don't have 4.3. */
1770 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1771 if (j >= 0)
1773 ioctl (j, TIOCNOTTY, 0);
1774 emacs_close (j);
1777 #endif /* TIOCNOTTY */
1779 #if !defined (DONT_REOPEN_PTY)
1780 /*** There is a suggestion that this ought to be a
1781 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1782 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1783 that system does seem to need this code, even though
1784 both TIOCSCTTY is defined. */
1785 /* Now close the pty (if we had it open) and reopen it.
1786 This makes the pty the controlling terminal of the subprocess. */
1787 if (pty_flag)
1790 /* I wonder if emacs_close (emacs_open (SSDATA (lisp_pty_name), ...))
1791 would work? */
1792 if (xforkin >= 0)
1793 emacs_close (xforkin);
1794 xforkout = xforkin = emacs_open (SSDATA (lisp_pty_name), O_RDWR, 0);
1796 if (xforkin < 0)
1798 emacs_perror (SSDATA (lisp_pty_name));
1799 _exit (EXIT_CANCELED);
1803 #endif /* not DONT_REOPEN_PTY */
1805 #ifdef SETUP_SLAVE_PTY
1806 if (pty_flag)
1808 SETUP_SLAVE_PTY;
1810 #endif /* SETUP_SLAVE_PTY */
1811 #endif /* HAVE_PTYS */
1813 signal (SIGINT, SIG_DFL);
1814 signal (SIGQUIT, SIG_DFL);
1816 /* Emacs ignores SIGPIPE, but the child should not. */
1817 signal (SIGPIPE, SIG_DFL);
1819 /* Stop blocking SIGCHLD in the child. */
1820 unblock_child_signal ();
1822 if (pty_flag)
1823 child_setup_tty (xforkout);
1824 #ifdef WINDOWSNT
1825 pid = child_setup (xforkin, xforkout, xforkout,
1826 new_argv, 1, encoded_current_dir);
1827 #else /* not WINDOWSNT */
1828 child_setup (xforkin, xforkout, xforkout,
1829 new_argv, 1, encoded_current_dir);
1830 #endif /* not WINDOWSNT */
1833 /* Back in the parent process. */
1835 vfork_errno = errno;
1836 XPROCESS (process)->pid = pid;
1837 if (pid >= 0)
1838 XPROCESS (process)->alive = 1;
1840 /* Stop blocking in the parent. */
1841 unblock_child_signal ();
1842 unblock_input ();
1844 if (forkin >= 0)
1845 emacs_close (forkin);
1846 if (forkin != forkout && forkout >= 0)
1847 emacs_close (forkout);
1849 if (pid < 0)
1850 report_file_errno ("Doing vfork", Qnil, vfork_errno);
1851 else
1853 /* vfork succeeded. */
1855 #ifdef WINDOWSNT
1856 register_child (pid, inchannel);
1857 #endif /* WINDOWSNT */
1859 pset_tty_name (XPROCESS (process), lisp_pty_name);
1861 #ifndef WINDOWSNT
1862 /* Wait for child_setup to complete in case that vfork is
1863 actually defined as fork. The descriptor wait_child_setup[1]
1864 of a pipe is closed at the child side either by close-on-exec
1865 on successful execve or the _exit call in child_setup. */
1867 char dummy;
1869 emacs_close (wait_child_setup[1]);
1870 emacs_read (wait_child_setup[0], &dummy, 1);
1871 emacs_close (wait_child_setup[0]);
1873 #endif
1877 static void
1878 create_pty (Lisp_Object process)
1880 char pty_name[PTY_NAME_SIZE];
1881 int inchannel, outchannel;
1883 inchannel = outchannel = -1;
1885 if (!NILP (Vprocess_connection_type))
1886 outchannel = inchannel = allocate_pty (pty_name);
1888 if (inchannel >= 0)
1890 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1891 /* On most USG systems it does not work to open the pty's tty here,
1892 then close it and reopen it in the child. */
1893 /* Don't let this terminal become our controlling terminal
1894 (in case we don't have one). */
1895 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1896 if (forkout < 0)
1897 report_file_error ("Opening pty", Qnil);
1898 #if defined (DONT_REOPEN_PTY)
1899 /* In the case that vfork is defined as fork, the parent process
1900 (Emacs) may send some data before the child process completes
1901 tty options setup. So we setup tty before forking. */
1902 child_setup_tty (forkout);
1903 #endif /* DONT_REOPEN_PTY */
1904 #endif /* not USG, or USG_SUBTTY_WORKS */
1906 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1907 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1909 /* Record this as an active process, with its channels.
1910 As a result, child_setup will close Emacs's side of the pipes. */
1911 chan_process[inchannel] = process;
1912 XPROCESS (process)->infd = inchannel;
1913 XPROCESS (process)->outfd = outchannel;
1915 /* Previously we recorded the tty descriptor used in the subprocess.
1916 It was only used for getting the foreground tty process, so now
1917 we just reopen the device (see emacs_get_tty_pgrp) as this is
1918 more portable (see USG_SUBTTY_WORKS above). */
1920 XPROCESS (process)->pty_flag = 1;
1921 pset_status (XPROCESS (process), Qrun);
1922 setup_process_coding_systems (process);
1924 FD_SET (inchannel, &input_wait_mask);
1925 FD_SET (inchannel, &non_keyboard_wait_mask);
1926 if (inchannel > max_process_desc)
1927 max_process_desc = inchannel;
1929 pset_tty_name (XPROCESS (process), build_string (pty_name));
1932 XPROCESS (process)->pid = -2;
1936 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1937 The address family of sa is not included in the result. */
1939 static Lisp_Object
1940 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
1942 Lisp_Object address;
1943 int i;
1944 unsigned char *cp;
1945 register struct Lisp_Vector *p;
1947 /* Workaround for a bug in getsockname on BSD: Names bound to
1948 sockets in the UNIX domain are inaccessible; getsockname returns
1949 a zero length name. */
1950 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
1951 return empty_unibyte_string;
1953 switch (sa->sa_family)
1955 case AF_INET:
1957 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
1958 len = sizeof (sin->sin_addr) + 1;
1959 address = Fmake_vector (make_number (len), Qnil);
1960 p = XVECTOR (address);
1961 p->contents[--len] = make_number (ntohs (sin->sin_port));
1962 cp = (unsigned char *) &sin->sin_addr;
1963 break;
1965 #ifdef AF_INET6
1966 case AF_INET6:
1968 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
1969 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
1970 len = sizeof (sin6->sin6_addr)/2 + 1;
1971 address = Fmake_vector (make_number (len), Qnil);
1972 p = XVECTOR (address);
1973 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
1974 for (i = 0; i < len; i++)
1975 p->contents[i] = make_number (ntohs (ip6[i]));
1976 return address;
1978 #endif
1979 #ifdef HAVE_LOCAL_SOCKETS
1980 case AF_LOCAL:
1982 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
1983 for (i = 0; i < sizeof (sockun->sun_path); i++)
1984 if (sockun->sun_path[i] == 0)
1985 break;
1986 return make_unibyte_string (sockun->sun_path, i);
1988 #endif
1989 default:
1990 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
1991 address = Fcons (make_number (sa->sa_family),
1992 Fmake_vector (make_number (len), Qnil));
1993 p = XVECTOR (XCDR (address));
1994 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
1995 break;
1998 i = 0;
1999 while (i < len)
2000 p->contents[i++] = make_number (*cp++);
2002 return address;
2006 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2008 static int
2009 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2011 register struct Lisp_Vector *p;
2013 if (VECTORP (address))
2015 p = XVECTOR (address);
2016 if (p->header.size == 5)
2018 *familyp = AF_INET;
2019 return sizeof (struct sockaddr_in);
2021 #ifdef AF_INET6
2022 else if (p->header.size == 9)
2024 *familyp = AF_INET6;
2025 return sizeof (struct sockaddr_in6);
2027 #endif
2029 #ifdef HAVE_LOCAL_SOCKETS
2030 else if (STRINGP (address))
2032 *familyp = AF_LOCAL;
2033 return sizeof (struct sockaddr_un);
2035 #endif
2036 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2037 && VECTORP (XCDR (address)))
2039 struct sockaddr *sa;
2040 *familyp = XINT (XCAR (address));
2041 p = XVECTOR (XCDR (address));
2042 return p->header.size + sizeof (sa->sa_family);
2044 return 0;
2047 /* Convert an address object (vector or string) to an internal sockaddr.
2049 The address format has been basically validated by
2050 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2051 it could have come from user data. So if FAMILY is not valid,
2052 we return after zeroing *SA. */
2054 static void
2055 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2057 register struct Lisp_Vector *p;
2058 register unsigned char *cp = NULL;
2059 register int i;
2060 EMACS_INT hostport;
2062 memset (sa, 0, len);
2064 if (VECTORP (address))
2066 p = XVECTOR (address);
2067 if (family == AF_INET)
2069 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2070 len = sizeof (sin->sin_addr) + 1;
2071 hostport = XINT (p->contents[--len]);
2072 sin->sin_port = htons (hostport);
2073 cp = (unsigned char *)&sin->sin_addr;
2074 sa->sa_family = family;
2076 #ifdef AF_INET6
2077 else if (family == AF_INET6)
2079 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2080 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2081 len = sizeof (sin6->sin6_addr) + 1;
2082 hostport = XINT (p->contents[--len]);
2083 sin6->sin6_port = htons (hostport);
2084 for (i = 0; i < len; i++)
2085 if (INTEGERP (p->contents[i]))
2087 int j = XFASTINT (p->contents[i]) & 0xffff;
2088 ip6[i] = ntohs (j);
2090 sa->sa_family = family;
2091 return;
2093 #endif
2094 else
2095 return;
2097 else if (STRINGP (address))
2099 #ifdef HAVE_LOCAL_SOCKETS
2100 if (family == AF_LOCAL)
2102 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2103 cp = SDATA (address);
2104 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2105 sockun->sun_path[i] = *cp++;
2106 sa->sa_family = family;
2108 #endif
2109 return;
2111 else
2113 p = XVECTOR (XCDR (address));
2114 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2117 for (i = 0; i < len; i++)
2118 if (INTEGERP (p->contents[i]))
2119 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2122 #ifdef DATAGRAM_SOCKETS
2123 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2124 1, 1, 0,
2125 doc: /* Get the current datagram address associated with PROCESS. */)
2126 (Lisp_Object process)
2128 int channel;
2130 CHECK_PROCESS (process);
2132 if (!DATAGRAM_CONN_P (process))
2133 return Qnil;
2135 channel = XPROCESS (process)->infd;
2136 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2137 datagram_address[channel].len);
2140 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2141 2, 2, 0,
2142 doc: /* Set the datagram address for PROCESS to ADDRESS.
2143 Returns nil upon error setting address, ADDRESS otherwise. */)
2144 (Lisp_Object process, Lisp_Object address)
2146 int channel;
2147 int family, len;
2149 CHECK_PROCESS (process);
2151 if (!DATAGRAM_CONN_P (process))
2152 return Qnil;
2154 channel = XPROCESS (process)->infd;
2156 len = get_lisp_to_sockaddr_size (address, &family);
2157 if (len == 0 || datagram_address[channel].len != len)
2158 return Qnil;
2159 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2160 return address;
2162 #endif
2165 static const struct socket_options {
2166 /* The name of this option. Should be lowercase version of option
2167 name without SO_ prefix. */
2168 const char *name;
2169 /* Option level SOL_... */
2170 int optlevel;
2171 /* Option number SO_... */
2172 int optnum;
2173 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2174 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2175 } socket_options[] =
2177 #ifdef SO_BINDTODEVICE
2178 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2179 #endif
2180 #ifdef SO_BROADCAST
2181 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2182 #endif
2183 #ifdef SO_DONTROUTE
2184 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2185 #endif
2186 #ifdef SO_KEEPALIVE
2187 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2188 #endif
2189 #ifdef SO_LINGER
2190 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2191 #endif
2192 #ifdef SO_OOBINLINE
2193 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2194 #endif
2195 #ifdef SO_PRIORITY
2196 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2197 #endif
2198 #ifdef SO_REUSEADDR
2199 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2200 #endif
2201 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2204 /* Set option OPT to value VAL on socket S.
2206 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2207 Signals an error if setting a known option fails.
2210 static int
2211 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2213 char *name;
2214 const struct socket_options *sopt;
2215 int ret = 0;
2217 CHECK_SYMBOL (opt);
2219 name = SSDATA (SYMBOL_NAME (opt));
2220 for (sopt = socket_options; sopt->name; sopt++)
2221 if (strcmp (name, sopt->name) == 0)
2222 break;
2224 switch (sopt->opttype)
2226 case SOPT_BOOL:
2228 int optval;
2229 optval = NILP (val) ? 0 : 1;
2230 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2231 &optval, sizeof (optval));
2232 break;
2235 case SOPT_INT:
2237 int optval;
2238 if (TYPE_RANGED_INTEGERP (int, val))
2239 optval = XINT (val);
2240 else
2241 error ("Bad option value for %s", name);
2242 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2243 &optval, sizeof (optval));
2244 break;
2247 #ifdef SO_BINDTODEVICE
2248 case SOPT_IFNAME:
2250 char devname[IFNAMSIZ+1];
2252 /* This is broken, at least in the Linux 2.4 kernel.
2253 To unbind, the arg must be a zero integer, not the empty string.
2254 This should work on all systems. KFS. 2003-09-23. */
2255 memset (devname, 0, sizeof devname);
2256 if (STRINGP (val))
2258 char *arg = SSDATA (val);
2259 int len = min (strlen (arg), IFNAMSIZ);
2260 memcpy (devname, arg, len);
2262 else if (!NILP (val))
2263 error ("Bad option value for %s", name);
2264 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2265 devname, IFNAMSIZ);
2266 break;
2268 #endif
2270 #ifdef SO_LINGER
2271 case SOPT_LINGER:
2273 struct linger linger;
2275 linger.l_onoff = 1;
2276 linger.l_linger = 0;
2277 if (TYPE_RANGED_INTEGERP (int, val))
2278 linger.l_linger = XINT (val);
2279 else
2280 linger.l_onoff = NILP (val) ? 0 : 1;
2281 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2282 &linger, sizeof (linger));
2283 break;
2285 #endif
2287 default:
2288 return 0;
2291 if (ret < 0)
2293 int setsockopt_errno = errno;
2294 report_file_errno ("Cannot set network option", list2 (opt, val),
2295 setsockopt_errno);
2298 return (1 << sopt->optbit);
2302 DEFUN ("set-network-process-option",
2303 Fset_network_process_option, Sset_network_process_option,
2304 3, 4, 0,
2305 doc: /* For network process PROCESS set option OPTION to value VALUE.
2306 See `make-network-process' for a list of options and values.
2307 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2308 OPTION is not a supported option, return nil instead; otherwise return t. */)
2309 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2311 int s;
2312 struct Lisp_Process *p;
2314 CHECK_PROCESS (process);
2315 p = XPROCESS (process);
2316 if (!NETCONN1_P (p))
2317 error ("Process is not a network process");
2319 s = p->infd;
2320 if (s < 0)
2321 error ("Process is not running");
2323 if (set_socket_option (s, option, value))
2325 pset_childp (p, Fplist_put (p->childp, option, value));
2326 return Qt;
2329 if (NILP (no_error))
2330 error ("Unknown or unsupported option");
2332 return Qnil;
2336 DEFUN ("serial-process-configure",
2337 Fserial_process_configure,
2338 Sserial_process_configure,
2339 0, MANY, 0,
2340 doc: /* Configure speed, bytesize, etc. of a serial process.
2342 Arguments are specified as keyword/argument pairs. Attributes that
2343 are not given are re-initialized from the process's current
2344 configuration (available via the function `process-contact') or set to
2345 reasonable default values. The following arguments are defined:
2347 :process PROCESS
2348 :name NAME
2349 :buffer BUFFER
2350 :port PORT
2351 -- Any of these arguments can be given to identify the process that is
2352 to be configured. If none of these arguments is given, the current
2353 buffer's process is used.
2355 :speed SPEED -- SPEED is the speed of the serial port in bits per
2356 second, also called baud rate. Any value can be given for SPEED, but
2357 most serial ports work only at a few defined values between 1200 and
2358 115200, with 9600 being the most common value. If SPEED is nil, the
2359 serial port is not configured any further, i.e., all other arguments
2360 are ignored. This may be useful for special serial ports such as
2361 Bluetooth-to-serial converters which can only be configured through AT
2362 commands. A value of nil for SPEED can be used only when passed
2363 through `make-serial-process' or `serial-term'.
2365 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2366 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2368 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2369 `odd' (use odd parity), or the symbol `even' (use even parity). If
2370 PARITY is not given, no parity is used.
2372 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2373 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2374 is not given or nil, 1 stopbit is used.
2376 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2377 flowcontrol to be used, which is either nil (don't use flowcontrol),
2378 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2379 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2380 flowcontrol is used.
2382 `serial-process-configure' is called by `make-serial-process' for the
2383 initial configuration of the serial port.
2385 Examples:
2387 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2389 \(serial-process-configure
2390 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2392 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2394 usage: (serial-process-configure &rest ARGS) */)
2395 (ptrdiff_t nargs, Lisp_Object *args)
2397 struct Lisp_Process *p;
2398 Lisp_Object contact = Qnil;
2399 Lisp_Object proc = Qnil;
2400 struct gcpro gcpro1;
2402 contact = Flist (nargs, args);
2403 GCPRO1 (contact);
2405 proc = Fplist_get (contact, QCprocess);
2406 if (NILP (proc))
2407 proc = Fplist_get (contact, QCname);
2408 if (NILP (proc))
2409 proc = Fplist_get (contact, QCbuffer);
2410 if (NILP (proc))
2411 proc = Fplist_get (contact, QCport);
2412 proc = get_process (proc);
2413 p = XPROCESS (proc);
2414 if (!EQ (p->type, Qserial))
2415 error ("Not a serial process");
2417 if (NILP (Fplist_get (p->childp, QCspeed)))
2419 UNGCPRO;
2420 return Qnil;
2423 serial_configure (p, contact);
2425 UNGCPRO;
2426 return Qnil;
2429 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2430 0, MANY, 0,
2431 doc: /* Create and return a serial port process.
2433 In Emacs, serial port connections are represented by process objects,
2434 so input and output work as for subprocesses, and `delete-process'
2435 closes a serial port connection. However, a serial process has no
2436 process id, it cannot be signaled, and the status codes are different
2437 from normal processes.
2439 `make-serial-process' creates a process and a buffer, on which you
2440 probably want to use `process-send-string'. Try \\[serial-term] for
2441 an interactive terminal. See below for examples.
2443 Arguments are specified as keyword/argument pairs. The following
2444 arguments are defined:
2446 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2447 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2448 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2449 the backslashes in strings).
2451 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2452 which this function calls.
2454 :name NAME -- NAME is the name of the process. If NAME is not given,
2455 the value of PORT is used.
2457 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2458 with the process. Process output goes at the end of that buffer,
2459 unless you specify an output stream or filter function to handle the
2460 output. If BUFFER is not given, the value of NAME is used.
2462 :coding CODING -- If CODING is a symbol, it specifies the coding
2463 system used for both reading and writing for this process. If CODING
2464 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2465 ENCODING is used for writing.
2467 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2468 the process is running. If BOOL is not given, query before exiting.
2470 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2471 In the stopped state, a serial process does not accept incoming data,
2472 but you can send outgoing data. The stopped state is cleared by
2473 `continue-process' and set by `stop-process'.
2475 :filter FILTER -- Install FILTER as the process filter.
2477 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2479 :plist PLIST -- Install PLIST as the initial plist of the process.
2481 :bytesize
2482 :parity
2483 :stopbits
2484 :flowcontrol
2485 -- This function calls `serial-process-configure' to handle these
2486 arguments.
2488 The original argument list, possibly modified by later configuration,
2489 is available via the function `process-contact'.
2491 Examples:
2493 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2495 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2497 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2499 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2501 usage: (make-serial-process &rest ARGS) */)
2502 (ptrdiff_t nargs, Lisp_Object *args)
2504 int fd = -1;
2505 Lisp_Object proc, contact, port;
2506 struct Lisp_Process *p;
2507 struct gcpro gcpro1;
2508 Lisp_Object name, buffer;
2509 Lisp_Object tem, val;
2510 ptrdiff_t specpdl_count;
2512 if (nargs == 0)
2513 return Qnil;
2515 contact = Flist (nargs, args);
2516 GCPRO1 (contact);
2518 port = Fplist_get (contact, QCport);
2519 if (NILP (port))
2520 error ("No port specified");
2521 CHECK_STRING (port);
2523 if (NILP (Fplist_member (contact, QCspeed)))
2524 error (":speed not specified");
2525 if (!NILP (Fplist_get (contact, QCspeed)))
2526 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2528 name = Fplist_get (contact, QCname);
2529 if (NILP (name))
2530 name = port;
2531 CHECK_STRING (name);
2532 proc = make_process (name);
2533 specpdl_count = SPECPDL_INDEX ();
2534 record_unwind_protect (remove_process, proc);
2535 p = XPROCESS (proc);
2537 fd = serial_open (port);
2538 p->infd = fd;
2539 p->outfd = fd;
2540 if (fd > max_process_desc)
2541 max_process_desc = fd;
2542 chan_process[fd] = proc;
2544 buffer = Fplist_get (contact, QCbuffer);
2545 if (NILP (buffer))
2546 buffer = name;
2547 buffer = Fget_buffer_create (buffer);
2548 pset_buffer (p, buffer);
2550 pset_childp (p, contact);
2551 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2552 pset_type (p, Qserial);
2553 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2554 pset_filter (p, Fplist_get (contact, QCfilter));
2555 pset_log (p, Qnil);
2556 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2557 p->kill_without_query = 1;
2558 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2559 pset_command (p, Qt);
2560 eassert (! p->pty_flag);
2562 if (!EQ (p->command, Qt))
2564 FD_SET (fd, &input_wait_mask);
2565 FD_SET (fd, &non_keyboard_wait_mask);
2568 if (BUFFERP (buffer))
2570 set_marker_both (p->mark, buffer,
2571 BUF_ZV (XBUFFER (buffer)),
2572 BUF_ZV_BYTE (XBUFFER (buffer)));
2575 tem = Fplist_member (contact, QCcoding);
2576 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2577 tem = Qnil;
2579 val = Qnil;
2580 if (!NILP (tem))
2582 val = XCAR (XCDR (tem));
2583 if (CONSP (val))
2584 val = XCAR (val);
2586 else if (!NILP (Vcoding_system_for_read))
2587 val = Vcoding_system_for_read;
2588 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2589 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2590 val = Qnil;
2591 pset_decode_coding_system (p, val);
2593 val = Qnil;
2594 if (!NILP (tem))
2596 val = XCAR (XCDR (tem));
2597 if (CONSP (val))
2598 val = XCDR (val);
2600 else if (!NILP (Vcoding_system_for_write))
2601 val = Vcoding_system_for_write;
2602 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2603 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2604 val = Qnil;
2605 pset_encode_coding_system (p, val);
2607 setup_process_coding_systems (proc);
2608 pset_decoding_buf (p, empty_unibyte_string);
2609 p->decoding_carryover = 0;
2610 pset_encoding_buf (p, empty_unibyte_string);
2611 p->inherit_coding_system_flag
2612 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2614 Fserial_process_configure (nargs, args);
2616 specpdl_ptr = specpdl + specpdl_count;
2618 UNGCPRO;
2619 return proc;
2622 /* Create a network stream/datagram client/server process. Treated
2623 exactly like a normal process when reading and writing. Primary
2624 differences are in status display and process deletion. A network
2625 connection has no PID; you cannot signal it. All you can do is
2626 stop/continue it and deactivate/close it via delete-process */
2628 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2629 0, MANY, 0,
2630 doc: /* Create and return a network server or client process.
2632 In Emacs, network connections are represented by process objects, so
2633 input and output work as for subprocesses and `delete-process' closes
2634 a network connection. However, a network process has no process id,
2635 it cannot be signaled, and the status codes are different from normal
2636 processes.
2638 Arguments are specified as keyword/argument pairs. The following
2639 arguments are defined:
2641 :name NAME -- NAME is name for process. It is modified if necessary
2642 to make it unique.
2644 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2645 with the process. Process output goes at end of that buffer, unless
2646 you specify an output stream or filter function to handle the output.
2647 BUFFER may be also nil, meaning that this process is not associated
2648 with any buffer.
2650 :host HOST -- HOST is name of the host to connect to, or its IP
2651 address. The symbol `local' specifies the local host. If specified
2652 for a server process, it must be a valid name or address for the local
2653 host, and only clients connecting to that address will be accepted.
2655 :service SERVICE -- SERVICE is name of the service desired, or an
2656 integer specifying a port number to connect to. If SERVICE is t,
2657 a random port number is selected for the server. (If Emacs was
2658 compiled with getaddrinfo, a port number can also be specified as a
2659 string, e.g. "80", as well as an integer. This is not portable.)
2661 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2662 stream type connection, `datagram' creates a datagram type connection,
2663 `seqpacket' creates a reliable datagram connection.
2665 :family FAMILY -- FAMILY is the address (and protocol) family for the
2666 service specified by HOST and SERVICE. The default (nil) is to use
2667 whatever address family (IPv4 or IPv6) that is defined for the host
2668 and port number specified by HOST and SERVICE. Other address families
2669 supported are:
2670 local -- for a local (i.e. UNIX) address specified by SERVICE.
2671 ipv4 -- use IPv4 address family only.
2672 ipv6 -- use IPv6 address family only.
2674 :local ADDRESS -- ADDRESS is the local address used for the connection.
2675 This parameter is ignored when opening a client process. When specified
2676 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2678 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2679 connection. This parameter is ignored when opening a stream server
2680 process. For a datagram server process, it specifies the initial
2681 setting of the remote datagram address. When specified for a client
2682 process, the FAMILY, HOST, and SERVICE args are ignored.
2684 The format of ADDRESS depends on the address family:
2685 - An IPv4 address is represented as an vector of integers [A B C D P]
2686 corresponding to numeric IP address A.B.C.D and port number P.
2687 - A local address is represented as a string with the address in the
2688 local address space.
2689 - An "unsupported family" address is represented by a cons (F . AV)
2690 where F is the family number and AV is a vector containing the socket
2691 address data with one element per address data byte. Do not rely on
2692 this format in portable code, as it may depend on implementation
2693 defined constants, data sizes, and data structure alignment.
2695 :coding CODING -- If CODING is a symbol, it specifies the coding
2696 system used for both reading and writing for this process. If CODING
2697 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2698 ENCODING is used for writing.
2700 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2701 return without waiting for the connection to complete; instead, the
2702 sentinel function will be called with second arg matching "open" (if
2703 successful) or "failed" when the connect completes. Default is to use
2704 a blocking connect (i.e. wait) for stream type connections.
2706 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2707 running when Emacs is exited.
2709 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2710 In the stopped state, a server process does not accept new
2711 connections, and a client process does not handle incoming traffic.
2712 The stopped state is cleared by `continue-process' and set by
2713 `stop-process'.
2715 :filter FILTER -- Install FILTER as the process filter.
2717 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2718 process filter are multibyte, otherwise they are unibyte.
2719 If this keyword is not specified, the strings are multibyte if
2720 the default value of `enable-multibyte-characters' is non-nil.
2722 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2724 :log LOG -- Install LOG as the server process log function. This
2725 function is called when the server accepts a network connection from a
2726 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2727 is the server process, CLIENT is the new process for the connection,
2728 and MESSAGE is a string.
2730 :plist PLIST -- Install PLIST as the new process' initial plist.
2732 :server QLEN -- if QLEN is non-nil, create a server process for the
2733 specified FAMILY, SERVICE, and connection type (stream or datagram).
2734 If QLEN is an integer, it is used as the max. length of the server's
2735 pending connection queue (also known as the backlog); the default
2736 queue length is 5. Default is to create a client process.
2738 The following network options can be specified for this connection:
2740 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2741 :dontroute BOOL -- Only send to directly connected hosts.
2742 :keepalive BOOL -- Send keep-alive messages on network stream.
2743 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2744 :oobinline BOOL -- Place out-of-band data in receive data stream.
2745 :priority INT -- Set protocol defined priority for sent packets.
2746 :reuseaddr BOOL -- Allow reusing a recently used local address
2747 (this is allowed by default for a server process).
2748 :bindtodevice NAME -- bind to interface NAME. Using this may require
2749 special privileges on some systems.
2751 Consult the relevant system programmer's manual pages for more
2752 information on using these options.
2755 A server process will listen for and accept connections from clients.
2756 When a client connection is accepted, a new network process is created
2757 for the connection with the following parameters:
2759 - The client's process name is constructed by concatenating the server
2760 process' NAME and a client identification string.
2761 - If the FILTER argument is non-nil, the client process will not get a
2762 separate process buffer; otherwise, the client's process buffer is a newly
2763 created buffer named after the server process' BUFFER name or process
2764 NAME concatenated with the client identification string.
2765 - The connection type and the process filter and sentinel parameters are
2766 inherited from the server process' TYPE, FILTER and SENTINEL.
2767 - The client process' contact info is set according to the client's
2768 addressing information (typically an IP address and a port number).
2769 - The client process' plist is initialized from the server's plist.
2771 Notice that the FILTER and SENTINEL args are never used directly by
2772 the server process. Also, the BUFFER argument is not used directly by
2773 the server process, but via the optional :log function, accepted (and
2774 failed) connections may be logged in the server process' buffer.
2776 The original argument list, modified with the actual connection
2777 information, is available via the `process-contact' function.
2779 usage: (make-network-process &rest ARGS) */)
2780 (ptrdiff_t nargs, Lisp_Object *args)
2782 Lisp_Object proc;
2783 Lisp_Object contact;
2784 struct Lisp_Process *p;
2785 #ifdef HAVE_GETADDRINFO
2786 struct addrinfo ai, *res, *lres;
2787 struct addrinfo hints;
2788 const char *portstring;
2789 char portbuf[128];
2790 #else /* HAVE_GETADDRINFO */
2791 struct _emacs_addrinfo
2793 int ai_family;
2794 int ai_socktype;
2795 int ai_protocol;
2796 int ai_addrlen;
2797 struct sockaddr *ai_addr;
2798 struct _emacs_addrinfo *ai_next;
2799 } ai, *res, *lres;
2800 #endif /* HAVE_GETADDRINFO */
2801 struct sockaddr_in address_in;
2802 #ifdef HAVE_LOCAL_SOCKETS
2803 struct sockaddr_un address_un;
2804 #endif
2805 int port;
2806 int ret = 0;
2807 int xerrno = 0;
2808 int s = -1, outch, inch;
2809 struct gcpro gcpro1;
2810 ptrdiff_t count = SPECPDL_INDEX ();
2811 ptrdiff_t count1;
2812 Lisp_Object QCaddress; /* one of QClocal or QCremote */
2813 Lisp_Object tem;
2814 Lisp_Object name, buffer, host, service, address;
2815 Lisp_Object filter, sentinel;
2816 bool is_non_blocking_client = 0;
2817 bool is_server = 0;
2818 int backlog = 5;
2819 int socktype;
2820 int family = -1;
2822 if (nargs == 0)
2823 return Qnil;
2825 /* Save arguments for process-contact and clone-process. */
2826 contact = Flist (nargs, args);
2827 GCPRO1 (contact);
2829 #ifdef WINDOWSNT
2830 /* Ensure socket support is loaded if available. */
2831 init_winsock (TRUE);
2832 #endif
2834 /* :type TYPE (nil: stream, datagram */
2835 tem = Fplist_get (contact, QCtype);
2836 if (NILP (tem))
2837 socktype = SOCK_STREAM;
2838 #ifdef DATAGRAM_SOCKETS
2839 else if (EQ (tem, Qdatagram))
2840 socktype = SOCK_DGRAM;
2841 #endif
2842 #ifdef HAVE_SEQPACKET
2843 else if (EQ (tem, Qseqpacket))
2844 socktype = SOCK_SEQPACKET;
2845 #endif
2846 else
2847 error ("Unsupported connection type");
2849 /* :server BOOL */
2850 tem = Fplist_get (contact, QCserver);
2851 if (!NILP (tem))
2853 /* Don't support network sockets when non-blocking mode is
2854 not available, since a blocked Emacs is not useful. */
2855 is_server = 1;
2856 if (TYPE_RANGED_INTEGERP (int, tem))
2857 backlog = XINT (tem);
2860 /* Make QCaddress an alias for :local (server) or :remote (client). */
2861 QCaddress = is_server ? QClocal : QCremote;
2863 /* :nowait BOOL */
2864 if (!is_server && socktype != SOCK_DGRAM
2865 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2867 #ifndef NON_BLOCKING_CONNECT
2868 error ("Non-blocking connect not supported");
2869 #else
2870 is_non_blocking_client = 1;
2871 #endif
2874 name = Fplist_get (contact, QCname);
2875 buffer = Fplist_get (contact, QCbuffer);
2876 filter = Fplist_get (contact, QCfilter);
2877 sentinel = Fplist_get (contact, QCsentinel);
2879 CHECK_STRING (name);
2881 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2882 ai.ai_socktype = socktype;
2883 ai.ai_protocol = 0;
2884 ai.ai_next = NULL;
2885 res = &ai;
2887 /* :local ADDRESS or :remote ADDRESS */
2888 address = Fplist_get (contact, QCaddress);
2889 if (!NILP (address))
2891 host = service = Qnil;
2893 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2894 error ("Malformed :address");
2895 ai.ai_family = family;
2896 ai.ai_addr = alloca (ai.ai_addrlen);
2897 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
2898 goto open_socket;
2901 /* :family FAMILY -- nil (for Inet), local, or integer. */
2902 tem = Fplist_get (contact, QCfamily);
2903 if (NILP (tem))
2905 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
2906 family = AF_UNSPEC;
2907 #else
2908 family = AF_INET;
2909 #endif
2911 #ifdef HAVE_LOCAL_SOCKETS
2912 else if (EQ (tem, Qlocal))
2913 family = AF_LOCAL;
2914 #endif
2915 #ifdef AF_INET6
2916 else if (EQ (tem, Qipv6))
2917 family = AF_INET6;
2918 #endif
2919 else if (EQ (tem, Qipv4))
2920 family = AF_INET;
2921 else if (TYPE_RANGED_INTEGERP (int, tem))
2922 family = XINT (tem);
2923 else
2924 error ("Unknown address family");
2926 ai.ai_family = family;
2928 /* :service SERVICE -- string, integer (port number), or t (random port). */
2929 service = Fplist_get (contact, QCservice);
2931 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2932 host = Fplist_get (contact, QChost);
2933 if (!NILP (host))
2935 if (EQ (host, Qlocal))
2936 /* Depending on setup, "localhost" may map to different IPv4 and/or
2937 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
2938 host = build_string ("127.0.0.1");
2939 CHECK_STRING (host);
2942 #ifdef HAVE_LOCAL_SOCKETS
2943 if (family == AF_LOCAL)
2945 if (!NILP (host))
2947 message (":family local ignores the :host \"%s\" property",
2948 SDATA (host));
2949 contact = Fplist_put (contact, QChost, Qnil);
2950 host = Qnil;
2952 CHECK_STRING (service);
2953 memset (&address_un, 0, sizeof address_un);
2954 address_un.sun_family = AF_LOCAL;
2955 if (sizeof address_un.sun_path <= SBYTES (service))
2956 error ("Service name too long");
2957 strcpy (address_un.sun_path, SSDATA (service));
2958 ai.ai_addr = (struct sockaddr *) &address_un;
2959 ai.ai_addrlen = sizeof address_un;
2960 goto open_socket;
2962 #endif
2964 /* Slow down polling to every ten seconds.
2965 Some kernels have a bug which causes retrying connect to fail
2966 after a connect. Polling can interfere with gethostbyname too. */
2967 #ifdef POLL_FOR_INPUT
2968 if (socktype != SOCK_DGRAM)
2970 record_unwind_protect_void (run_all_atimers);
2971 bind_polling_period (10);
2973 #endif
2975 #ifdef HAVE_GETADDRINFO
2976 /* If we have a host, use getaddrinfo to resolve both host and service.
2977 Otherwise, use getservbyname to lookup the service. */
2978 if (!NILP (host))
2981 /* SERVICE can either be a string or int.
2982 Convert to a C string for later use by getaddrinfo. */
2983 if (EQ (service, Qt))
2984 portstring = "0";
2985 else if (INTEGERP (service))
2987 sprintf (portbuf, "%"pI"d", XINT (service));
2988 portstring = portbuf;
2990 else
2992 CHECK_STRING (service);
2993 portstring = SSDATA (service);
2996 immediate_quit = 1;
2997 QUIT;
2998 memset (&hints, 0, sizeof (hints));
2999 hints.ai_flags = 0;
3000 hints.ai_family = family;
3001 hints.ai_socktype = socktype;
3002 hints.ai_protocol = 0;
3004 #ifdef HAVE_RES_INIT
3005 res_init ();
3006 #endif
3008 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3009 if (ret)
3010 #ifdef HAVE_GAI_STRERROR
3011 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3012 #else
3013 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3014 #endif
3015 immediate_quit = 0;
3017 goto open_socket;
3019 #endif /* HAVE_GETADDRINFO */
3021 /* We end up here if getaddrinfo is not defined, or in case no hostname
3022 has been specified (e.g. for a local server process). */
3024 if (EQ (service, Qt))
3025 port = 0;
3026 else if (INTEGERP (service))
3027 port = htons ((unsigned short) XINT (service));
3028 else
3030 struct servent *svc_info;
3031 CHECK_STRING (service);
3032 svc_info = getservbyname (SSDATA (service),
3033 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3034 if (svc_info == 0)
3035 error ("Unknown service: %s", SDATA (service));
3036 port = svc_info->s_port;
3039 memset (&address_in, 0, sizeof address_in);
3040 address_in.sin_family = family;
3041 address_in.sin_addr.s_addr = INADDR_ANY;
3042 address_in.sin_port = port;
3044 #ifndef HAVE_GETADDRINFO
3045 if (!NILP (host))
3047 struct hostent *host_info_ptr;
3049 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3050 as it may `hang' Emacs for a very long time. */
3051 immediate_quit = 1;
3052 QUIT;
3054 #ifdef HAVE_RES_INIT
3055 res_init ();
3056 #endif
3058 host_info_ptr = gethostbyname (SDATA (host));
3059 immediate_quit = 0;
3061 if (host_info_ptr)
3063 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3064 host_info_ptr->h_length);
3065 family = host_info_ptr->h_addrtype;
3066 address_in.sin_family = family;
3068 else
3069 /* Attempt to interpret host as numeric inet address */
3071 unsigned long numeric_addr;
3072 numeric_addr = inet_addr (SSDATA (host));
3073 if (numeric_addr == -1)
3074 error ("Unknown host \"%s\"", SDATA (host));
3076 memcpy (&address_in.sin_addr, &numeric_addr,
3077 sizeof (address_in.sin_addr));
3081 #endif /* not HAVE_GETADDRINFO */
3083 ai.ai_family = family;
3084 ai.ai_addr = (struct sockaddr *) &address_in;
3085 ai.ai_addrlen = sizeof address_in;
3087 open_socket:
3089 /* Do this in case we never enter the for-loop below. */
3090 count1 = SPECPDL_INDEX ();
3091 s = -1;
3093 for (lres = res; lres; lres = lres->ai_next)
3095 ptrdiff_t optn;
3096 int optbits;
3098 #ifdef WINDOWSNT
3099 retry_connect:
3100 #endif
3102 s = socket (lres->ai_family, lres->ai_socktype | SOCK_CLOEXEC,
3103 lres->ai_protocol);
3104 if (s < 0)
3106 xerrno = errno;
3107 continue;
3110 #ifdef DATAGRAM_SOCKETS
3111 if (!is_server && socktype == SOCK_DGRAM)
3112 break;
3113 #endif /* DATAGRAM_SOCKETS */
3115 #ifdef NON_BLOCKING_CONNECT
3116 if (is_non_blocking_client)
3118 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3119 if (ret < 0)
3121 xerrno = errno;
3122 emacs_close (s);
3123 s = -1;
3124 continue;
3127 #endif
3129 /* Make us close S if quit. */
3130 record_unwind_protect_int (close_file_unwind, s);
3132 /* Parse network options in the arg list.
3133 We simply ignore anything which isn't a known option (including other keywords).
3134 An error is signaled if setting a known option fails. */
3135 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3136 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3138 if (is_server)
3140 /* Configure as a server socket. */
3142 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3143 explicit :reuseaddr key to override this. */
3144 #ifdef HAVE_LOCAL_SOCKETS
3145 if (family != AF_LOCAL)
3146 #endif
3147 if (!(optbits & (1 << OPIX_REUSEADDR)))
3149 int optval = 1;
3150 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3151 report_file_error ("Cannot set reuse option on server socket", Qnil);
3154 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3155 report_file_error ("Cannot bind server socket", Qnil);
3157 #ifdef HAVE_GETSOCKNAME
3158 if (EQ (service, Qt))
3160 struct sockaddr_in sa1;
3161 socklen_t len1 = sizeof (sa1);
3162 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3164 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3165 service = make_number (ntohs (sa1.sin_port));
3166 contact = Fplist_put (contact, QCservice, service);
3169 #endif
3171 if (socktype != SOCK_DGRAM && listen (s, backlog))
3172 report_file_error ("Cannot listen on server socket", Qnil);
3174 break;
3177 immediate_quit = 1;
3178 QUIT;
3180 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3181 xerrno = errno;
3183 if (ret == 0 || xerrno == EISCONN)
3185 /* The unwind-protect will be discarded afterwards.
3186 Likewise for immediate_quit. */
3187 break;
3190 #ifdef NON_BLOCKING_CONNECT
3191 #ifdef EINPROGRESS
3192 if (is_non_blocking_client && xerrno == EINPROGRESS)
3193 break;
3194 #else
3195 #ifdef EWOULDBLOCK
3196 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3197 break;
3198 #endif
3199 #endif
3200 #endif
3202 #ifndef WINDOWSNT
3203 if (xerrno == EINTR)
3205 /* Unlike most other syscalls connect() cannot be called
3206 again. (That would return EALREADY.) The proper way to
3207 wait for completion is pselect(). */
3208 int sc;
3209 socklen_t len;
3210 SELECT_TYPE fdset;
3211 retry_select:
3212 FD_ZERO (&fdset);
3213 FD_SET (s, &fdset);
3214 QUIT;
3215 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3216 if (sc == -1)
3218 if (errno == EINTR)
3219 goto retry_select;
3220 else
3221 report_file_error ("Failed select", Qnil);
3223 eassert (sc > 0);
3225 len = sizeof xerrno;
3226 eassert (FD_ISSET (s, &fdset));
3227 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) < 0)
3228 report_file_error ("Failed getsockopt", Qnil);
3229 if (xerrno)
3230 report_file_errno ("Failed connect", Qnil, xerrno);
3231 break;
3233 #endif /* !WINDOWSNT */
3235 immediate_quit = 0;
3237 /* Discard the unwind protect closing S. */
3238 specpdl_ptr = specpdl + count1;
3239 emacs_close (s);
3240 s = -1;
3242 #ifdef WINDOWSNT
3243 if (xerrno == EINTR)
3244 goto retry_connect;
3245 #endif
3248 if (s >= 0)
3250 #ifdef DATAGRAM_SOCKETS
3251 if (socktype == SOCK_DGRAM)
3253 if (datagram_address[s].sa)
3254 emacs_abort ();
3255 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3256 datagram_address[s].len = lres->ai_addrlen;
3257 if (is_server)
3259 Lisp_Object remote;
3260 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3261 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3263 int rfamily, rlen;
3264 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3265 if (rlen != 0 && rfamily == lres->ai_family
3266 && rlen == lres->ai_addrlen)
3267 conv_lisp_to_sockaddr (rfamily, remote,
3268 datagram_address[s].sa, rlen);
3271 else
3272 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3274 #endif
3275 contact = Fplist_put (contact, QCaddress,
3276 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3277 #ifdef HAVE_GETSOCKNAME
3278 if (!is_server)
3280 struct sockaddr_in sa1;
3281 socklen_t len1 = sizeof (sa1);
3282 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3283 contact = Fplist_put (contact, QClocal,
3284 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3286 #endif
3289 immediate_quit = 0;
3291 #ifdef HAVE_GETADDRINFO
3292 if (res != &ai)
3294 block_input ();
3295 freeaddrinfo (res);
3296 unblock_input ();
3298 #endif
3300 /* Discard the unwind protect for closing S, if any. */
3301 specpdl_ptr = specpdl + count1;
3303 /* Unwind bind_polling_period and request_sigio. */
3304 unbind_to (count, Qnil);
3306 if (s < 0)
3308 /* If non-blocking got this far - and failed - assume non-blocking is
3309 not supported after all. This is probably a wrong assumption, but
3310 the normal blocking calls to open-network-stream handles this error
3311 better. */
3312 if (is_non_blocking_client)
3313 return Qnil;
3315 report_file_errno ((is_server
3316 ? "make server process failed"
3317 : "make client process failed"),
3318 contact, xerrno);
3321 inch = s;
3322 outch = s;
3324 if (!NILP (buffer))
3325 buffer = Fget_buffer_create (buffer);
3326 proc = make_process (name);
3328 chan_process[inch] = proc;
3330 fcntl (inch, F_SETFL, O_NONBLOCK);
3332 p = XPROCESS (proc);
3334 pset_childp (p, contact);
3335 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3336 pset_type (p, Qnetwork);
3338 pset_buffer (p, buffer);
3339 pset_sentinel (p, sentinel);
3340 pset_filter (p, filter);
3341 pset_log (p, Fplist_get (contact, QClog));
3342 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3343 p->kill_without_query = 1;
3344 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3345 pset_command (p, Qt);
3346 p->pid = 0;
3347 p->infd = inch;
3348 p->outfd = outch;
3349 if (is_server && socktype != SOCK_DGRAM)
3350 pset_status (p, Qlisten);
3352 /* Make the process marker point into the process buffer (if any). */
3353 if (BUFFERP (buffer))
3354 set_marker_both (p->mark, buffer,
3355 BUF_ZV (XBUFFER (buffer)),
3356 BUF_ZV_BYTE (XBUFFER (buffer)));
3358 #ifdef NON_BLOCKING_CONNECT
3359 if (is_non_blocking_client)
3361 /* We may get here if connect did succeed immediately. However,
3362 in that case, we still need to signal this like a non-blocking
3363 connection. */
3364 pset_status (p, Qconnect);
3365 if (!FD_ISSET (inch, &connect_wait_mask))
3367 FD_SET (inch, &connect_wait_mask);
3368 FD_SET (inch, &write_mask);
3369 num_pending_connects++;
3372 else
3373 #endif
3374 /* A server may have a client filter setting of Qt, but it must
3375 still listen for incoming connects unless it is stopped. */
3376 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3377 || (EQ (p->status, Qlisten) && NILP (p->command)))
3379 FD_SET (inch, &input_wait_mask);
3380 FD_SET (inch, &non_keyboard_wait_mask);
3383 if (inch > max_process_desc)
3384 max_process_desc = inch;
3386 tem = Fplist_member (contact, QCcoding);
3387 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3388 tem = Qnil; /* No error message (too late!). */
3391 /* Setup coding systems for communicating with the network stream. */
3392 struct gcpro gcpro1;
3393 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3394 Lisp_Object coding_systems = Qt;
3395 Lisp_Object fargs[5], val;
3397 if (!NILP (tem))
3399 val = XCAR (XCDR (tem));
3400 if (CONSP (val))
3401 val = XCAR (val);
3403 else if (!NILP (Vcoding_system_for_read))
3404 val = Vcoding_system_for_read;
3405 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3406 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3407 /* We dare not decode end-of-line format by setting VAL to
3408 Qraw_text, because the existing Emacs Lisp libraries
3409 assume that they receive bare code including a sequence of
3410 CR LF. */
3411 val = Qnil;
3412 else
3414 if (NILP (host) || NILP (service))
3415 coding_systems = Qnil;
3416 else
3418 fargs[0] = Qopen_network_stream, fargs[1] = name,
3419 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3420 GCPRO1 (proc);
3421 coding_systems = Ffind_operation_coding_system (5, fargs);
3422 UNGCPRO;
3424 if (CONSP (coding_systems))
3425 val = XCAR (coding_systems);
3426 else if (CONSP (Vdefault_process_coding_system))
3427 val = XCAR (Vdefault_process_coding_system);
3428 else
3429 val = Qnil;
3431 pset_decode_coding_system (p, val);
3433 if (!NILP (tem))
3435 val = XCAR (XCDR (tem));
3436 if (CONSP (val))
3437 val = XCDR (val);
3439 else if (!NILP (Vcoding_system_for_write))
3440 val = Vcoding_system_for_write;
3441 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3442 val = Qnil;
3443 else
3445 if (EQ (coding_systems, Qt))
3447 if (NILP (host) || NILP (service))
3448 coding_systems = Qnil;
3449 else
3451 fargs[0] = Qopen_network_stream, fargs[1] = name,
3452 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3453 GCPRO1 (proc);
3454 coding_systems = Ffind_operation_coding_system (5, fargs);
3455 UNGCPRO;
3458 if (CONSP (coding_systems))
3459 val = XCDR (coding_systems);
3460 else if (CONSP (Vdefault_process_coding_system))
3461 val = XCDR (Vdefault_process_coding_system);
3462 else
3463 val = Qnil;
3465 pset_encode_coding_system (p, val);
3467 setup_process_coding_systems (proc);
3469 pset_decoding_buf (p, empty_unibyte_string);
3470 p->decoding_carryover = 0;
3471 pset_encoding_buf (p, empty_unibyte_string);
3473 p->inherit_coding_system_flag
3474 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3476 UNGCPRO;
3477 return proc;
3481 #if defined (HAVE_NET_IF_H)
3483 #ifdef SIOCGIFCONF
3484 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3485 doc: /* Return an alist of all network interfaces and their network address.
3486 Each element is a cons, the car of which is a string containing the
3487 interface name, and the cdr is the network address in internal
3488 format; see the description of ADDRESS in `make-network-process'. */)
3489 (void)
3491 struct ifconf ifconf;
3492 struct ifreq *ifreq;
3493 void *buf = NULL;
3494 ptrdiff_t buf_size = 512;
3495 int s;
3496 Lisp_Object res;
3497 ptrdiff_t count;
3499 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3500 if (s < 0)
3501 return Qnil;
3502 count = SPECPDL_INDEX ();
3503 record_unwind_protect_int (close_file_unwind, s);
3507 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3508 ifconf.ifc_buf = buf;
3509 ifconf.ifc_len = buf_size;
3510 if (ioctl (s, SIOCGIFCONF, &ifconf))
3512 emacs_close (s);
3513 xfree (buf);
3514 return Qnil;
3517 while (ifconf.ifc_len == buf_size);
3519 res = unbind_to (count, Qnil);
3520 ifreq = ifconf.ifc_req;
3521 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3523 struct ifreq *ifq = ifreq;
3524 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3525 #define SIZEOF_IFREQ(sif) \
3526 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3527 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3529 int len = SIZEOF_IFREQ (ifq);
3530 #else
3531 int len = sizeof (*ifreq);
3532 #endif
3533 char namebuf[sizeof (ifq->ifr_name) + 1];
3534 ifreq = (struct ifreq *) ((char *) ifreq + len);
3536 if (ifq->ifr_addr.sa_family != AF_INET)
3537 continue;
3539 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3540 namebuf[sizeof (ifq->ifr_name)] = 0;
3541 res = Fcons (Fcons (build_string (namebuf),
3542 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3543 sizeof (struct sockaddr))),
3544 res);
3547 xfree (buf);
3548 return res;
3550 #endif /* SIOCGIFCONF */
3552 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3554 struct ifflag_def {
3555 int flag_bit;
3556 const char *flag_sym;
3559 static const struct ifflag_def ifflag_table[] = {
3560 #ifdef IFF_UP
3561 { IFF_UP, "up" },
3562 #endif
3563 #ifdef IFF_BROADCAST
3564 { IFF_BROADCAST, "broadcast" },
3565 #endif
3566 #ifdef IFF_DEBUG
3567 { IFF_DEBUG, "debug" },
3568 #endif
3569 #ifdef IFF_LOOPBACK
3570 { IFF_LOOPBACK, "loopback" },
3571 #endif
3572 #ifdef IFF_POINTOPOINT
3573 { IFF_POINTOPOINT, "pointopoint" },
3574 #endif
3575 #ifdef IFF_RUNNING
3576 { IFF_RUNNING, "running" },
3577 #endif
3578 #ifdef IFF_NOARP
3579 { IFF_NOARP, "noarp" },
3580 #endif
3581 #ifdef IFF_PROMISC
3582 { IFF_PROMISC, "promisc" },
3583 #endif
3584 #ifdef IFF_NOTRAILERS
3585 #ifdef NS_IMPL_COCOA
3586 /* Really means smart, notrailers is obsolete */
3587 { IFF_NOTRAILERS, "smart" },
3588 #else
3589 { IFF_NOTRAILERS, "notrailers" },
3590 #endif
3591 #endif
3592 #ifdef IFF_ALLMULTI
3593 { IFF_ALLMULTI, "allmulti" },
3594 #endif
3595 #ifdef IFF_MASTER
3596 { IFF_MASTER, "master" },
3597 #endif
3598 #ifdef IFF_SLAVE
3599 { IFF_SLAVE, "slave" },
3600 #endif
3601 #ifdef IFF_MULTICAST
3602 { IFF_MULTICAST, "multicast" },
3603 #endif
3604 #ifdef IFF_PORTSEL
3605 { IFF_PORTSEL, "portsel" },
3606 #endif
3607 #ifdef IFF_AUTOMEDIA
3608 { IFF_AUTOMEDIA, "automedia" },
3609 #endif
3610 #ifdef IFF_DYNAMIC
3611 { IFF_DYNAMIC, "dynamic" },
3612 #endif
3613 #ifdef IFF_OACTIVE
3614 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3615 #endif
3616 #ifdef IFF_SIMPLEX
3617 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3618 #endif
3619 #ifdef IFF_LINK0
3620 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3621 #endif
3622 #ifdef IFF_LINK1
3623 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3624 #endif
3625 #ifdef IFF_LINK2
3626 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3627 #endif
3628 { 0, 0 }
3631 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3632 doc: /* Return information about network interface named IFNAME.
3633 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3634 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3635 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3636 FLAGS is the current flags of the interface. */)
3637 (Lisp_Object ifname)
3639 struct ifreq rq;
3640 Lisp_Object res = Qnil;
3641 Lisp_Object elt;
3642 int s;
3643 bool any = 0;
3644 ptrdiff_t count;
3645 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3646 && defined HAVE_GETIFADDRS && defined LLADDR)
3647 struct ifaddrs *ifap;
3648 #endif
3650 CHECK_STRING (ifname);
3652 if (sizeof rq.ifr_name <= SBYTES (ifname))
3653 error ("interface name too long");
3654 strcpy (rq.ifr_name, SSDATA (ifname));
3656 s = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
3657 if (s < 0)
3658 return Qnil;
3659 count = SPECPDL_INDEX ();
3660 record_unwind_protect_int (close_file_unwind, s);
3662 elt = Qnil;
3663 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3664 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3666 int flags = rq.ifr_flags;
3667 const struct ifflag_def *fp;
3668 int fnum;
3670 /* If flags is smaller than int (i.e. short) it may have the high bit set
3671 due to IFF_MULTICAST. In that case, sign extending it into
3672 an int is wrong. */
3673 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3674 flags = (unsigned short) rq.ifr_flags;
3676 any = 1;
3677 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3679 if (flags & fp->flag_bit)
3681 elt = Fcons (intern (fp->flag_sym), elt);
3682 flags -= fp->flag_bit;
3685 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3687 if (flags & 1)
3689 elt = Fcons (make_number (fnum), elt);
3693 #endif
3694 res = Fcons (elt, res);
3696 elt = Qnil;
3697 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3698 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3700 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3701 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3702 int n;
3704 any = 1;
3705 for (n = 0; n < 6; n++)
3706 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3707 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3709 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3710 if (getifaddrs (&ifap) != -1)
3712 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3713 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3714 struct ifaddrs *it;
3716 for (it = ifap; it != NULL; it = it->ifa_next)
3718 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3719 unsigned char linkaddr[6];
3720 int n;
3722 if (it->ifa_addr->sa_family != AF_LINK
3723 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3724 || sdl->sdl_alen != 6)
3725 continue;
3727 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3728 for (n = 0; n < 6; n++)
3729 p->contents[n] = make_number (linkaddr[n]);
3731 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
3732 break;
3735 #ifdef HAVE_FREEIFADDRS
3736 freeifaddrs (ifap);
3737 #endif
3739 #endif /* HAVE_GETIFADDRS && LLADDR */
3741 res = Fcons (elt, res);
3743 elt = Qnil;
3744 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3745 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3747 any = 1;
3748 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3749 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3750 #else
3751 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3752 #endif
3754 #endif
3755 res = Fcons (elt, res);
3757 elt = Qnil;
3758 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3759 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3761 any = 1;
3762 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3764 #endif
3765 res = Fcons (elt, res);
3767 elt = Qnil;
3768 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3769 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3771 any = 1;
3772 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3774 #endif
3775 res = Fcons (elt, res);
3777 return unbind_to (count, any ? res : Qnil);
3779 #endif
3780 #endif /* defined (HAVE_NET_IF_H) */
3782 /* Turn off input and output for process PROC. */
3784 static void
3785 deactivate_process (Lisp_Object proc)
3787 register int inchannel, outchannel;
3788 register struct Lisp_Process *p = XPROCESS (proc);
3790 #ifdef HAVE_GNUTLS
3791 /* Delete GnuTLS structures in PROC, if any. */
3792 emacs_gnutls_deinit (proc);
3793 #endif /* HAVE_GNUTLS */
3795 inchannel = p->infd;
3796 outchannel = p->outfd;
3798 #ifdef ADAPTIVE_READ_BUFFERING
3799 if (p->read_output_delay > 0)
3801 if (--process_output_delay_count < 0)
3802 process_output_delay_count = 0;
3803 p->read_output_delay = 0;
3804 p->read_output_skip = 0;
3806 #endif
3808 if (inchannel >= 0)
3810 /* Beware SIGCHLD hereabouts. */
3811 flush_pending_output (inchannel);
3812 emacs_close (inchannel);
3813 if (outchannel >= 0 && outchannel != inchannel)
3814 emacs_close (outchannel);
3816 p->infd = -1;
3817 p->outfd = -1;
3818 #ifdef DATAGRAM_SOCKETS
3819 if (DATAGRAM_CHAN_P (inchannel))
3821 xfree (datagram_address[inchannel].sa);
3822 datagram_address[inchannel].sa = 0;
3823 datagram_address[inchannel].len = 0;
3825 #endif
3826 chan_process[inchannel] = Qnil;
3827 FD_CLR (inchannel, &input_wait_mask);
3828 FD_CLR (inchannel, &non_keyboard_wait_mask);
3829 #ifdef NON_BLOCKING_CONNECT
3830 if (FD_ISSET (inchannel, &connect_wait_mask))
3832 FD_CLR (inchannel, &connect_wait_mask);
3833 FD_CLR (inchannel, &write_mask);
3834 if (--num_pending_connects < 0)
3835 emacs_abort ();
3837 #endif
3838 if (inchannel == max_process_desc)
3840 /* We just closed the highest-numbered process input descriptor,
3841 so recompute the highest-numbered one now. */
3842 int i = inchannel;
3844 i--;
3845 while (0 <= i && NILP (chan_process[i]));
3847 max_process_desc = i;
3853 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3854 0, 4, 0,
3855 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3856 It is read into the process' buffers or given to their filter functions.
3857 Non-nil arg PROCESS means do not return until some output has been received
3858 from PROCESS.
3860 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
3861 and milliseconds to wait; return after that much time whether or not
3862 there is any subprocess output. If SECONDS is a floating point number,
3863 it specifies a fractional number of seconds to wait.
3864 The MILLISEC argument is obsolete and should be avoided.
3866 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
3867 from PROCESS, suspending reading output from other processes.
3868 If JUST-THIS-ONE is an integer, don't run any timers either.
3869 Return non-nil if we received any output before the timeout expired. */)
3870 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
3872 intmax_t secs;
3873 int nsecs;
3875 if (! NILP (process))
3876 CHECK_PROCESS (process);
3877 else
3878 just_this_one = Qnil;
3880 if (!NILP (millisec))
3881 { /* Obsolete calling convention using integers rather than floats. */
3882 CHECK_NUMBER (millisec);
3883 if (NILP (seconds))
3884 seconds = make_float (XINT (millisec) / 1000.0);
3885 else
3887 CHECK_NUMBER (seconds);
3888 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
3892 secs = 0;
3893 nsecs = -1;
3895 if (!NILP (seconds))
3897 if (INTEGERP (seconds))
3899 if (XINT (seconds) > 0)
3901 secs = XINT (seconds);
3902 nsecs = 0;
3905 else if (FLOATP (seconds))
3907 if (XFLOAT_DATA (seconds) > 0)
3909 EMACS_TIME t = EMACS_TIME_FROM_DOUBLE (XFLOAT_DATA (seconds));
3910 secs = min (EMACS_SECS (t), WAIT_READING_MAX);
3911 nsecs = EMACS_NSECS (t);
3914 else
3915 wrong_type_argument (Qnumberp, seconds);
3917 else if (! NILP (process))
3918 nsecs = 0;
3920 return
3921 (wait_reading_process_output (secs, nsecs, 0, 0,
3922 Qnil,
3923 !NILP (process) ? XPROCESS (process) : NULL,
3924 NILP (just_this_one) ? 0 :
3925 !INTEGERP (just_this_one) ? 1 : -1)
3926 ? Qt : Qnil);
3929 /* Accept a connection for server process SERVER on CHANNEL. */
3931 static EMACS_INT connect_counter = 0;
3933 static void
3934 server_accept_connection (Lisp_Object server, int channel)
3936 Lisp_Object proc, caller, name, buffer;
3937 Lisp_Object contact, host, service;
3938 struct Lisp_Process *ps= XPROCESS (server);
3939 struct Lisp_Process *p;
3940 int s;
3941 union u_sockaddr {
3942 struct sockaddr sa;
3943 struct sockaddr_in in;
3944 #ifdef AF_INET6
3945 struct sockaddr_in6 in6;
3946 #endif
3947 #ifdef HAVE_LOCAL_SOCKETS
3948 struct sockaddr_un un;
3949 #endif
3950 } saddr;
3951 socklen_t len = sizeof saddr;
3952 ptrdiff_t count;
3954 s = accept4 (channel, &saddr.sa, &len, SOCK_CLOEXEC);
3956 if (s < 0)
3958 int code = errno;
3960 if (code == EAGAIN)
3961 return;
3962 #ifdef EWOULDBLOCK
3963 if (code == EWOULDBLOCK)
3964 return;
3965 #endif
3967 if (!NILP (ps->log))
3968 call3 (ps->log, server, Qnil,
3969 concat3 (build_string ("accept failed with code"),
3970 Fnumber_to_string (make_number (code)),
3971 build_string ("\n")));
3972 return;
3975 count = SPECPDL_INDEX ();
3976 record_unwind_protect_int (close_file_unwind, s);
3978 connect_counter++;
3980 /* Setup a new process to handle the connection. */
3982 /* Generate a unique identification of the caller, and build contact
3983 information for this process. */
3984 host = Qt;
3985 service = Qnil;
3986 switch (saddr.sa.sa_family)
3988 case AF_INET:
3990 Lisp_Object args[5];
3991 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
3992 args[0] = build_string ("%d.%d.%d.%d");
3993 args[1] = make_number (*ip++);
3994 args[2] = make_number (*ip++);
3995 args[3] = make_number (*ip++);
3996 args[4] = make_number (*ip++);
3997 host = Fformat (5, args);
3998 service = make_number (ntohs (saddr.in.sin_port));
4000 args[0] = build_string (" <%s:%d>");
4001 args[1] = host;
4002 args[2] = service;
4003 caller = Fformat (3, args);
4005 break;
4007 #ifdef AF_INET6
4008 case AF_INET6:
4010 Lisp_Object args[9];
4011 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4012 int i;
4013 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4014 for (i = 0; i < 8; i++)
4015 args[i+1] = make_number (ntohs (ip6[i]));
4016 host = Fformat (9, args);
4017 service = make_number (ntohs (saddr.in.sin_port));
4019 args[0] = build_string (" <[%s]:%d>");
4020 args[1] = host;
4021 args[2] = service;
4022 caller = Fformat (3, args);
4024 break;
4025 #endif
4027 #ifdef HAVE_LOCAL_SOCKETS
4028 case AF_LOCAL:
4029 #endif
4030 default:
4031 caller = Fnumber_to_string (make_number (connect_counter));
4032 caller = concat3 (build_string (" <"), caller, build_string (">"));
4033 break;
4036 /* Create a new buffer name for this process if it doesn't have a
4037 filter. The new buffer name is based on the buffer name or
4038 process name of the server process concatenated with the caller
4039 identification. */
4041 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4042 || EQ (ps->filter, Qt)))
4043 buffer = Qnil;
4044 else
4046 buffer = ps->buffer;
4047 if (!NILP (buffer))
4048 buffer = Fbuffer_name (buffer);
4049 else
4050 buffer = ps->name;
4051 if (!NILP (buffer))
4053 buffer = concat2 (buffer, caller);
4054 buffer = Fget_buffer_create (buffer);
4058 /* Generate a unique name for the new server process. Combine the
4059 server process name with the caller identification. */
4061 name = concat2 (ps->name, caller);
4062 proc = make_process (name);
4064 chan_process[s] = proc;
4066 fcntl (s, F_SETFL, O_NONBLOCK);
4068 p = XPROCESS (proc);
4070 /* Build new contact information for this setup. */
4071 contact = Fcopy_sequence (ps->childp);
4072 contact = Fplist_put (contact, QCserver, Qnil);
4073 contact = Fplist_put (contact, QChost, host);
4074 if (!NILP (service))
4075 contact = Fplist_put (contact, QCservice, service);
4076 contact = Fplist_put (contact, QCremote,
4077 conv_sockaddr_to_lisp (&saddr.sa, len));
4078 #ifdef HAVE_GETSOCKNAME
4079 len = sizeof saddr;
4080 if (getsockname (s, &saddr.sa, &len) == 0)
4081 contact = Fplist_put (contact, QClocal,
4082 conv_sockaddr_to_lisp (&saddr.sa, len));
4083 #endif
4085 pset_childp (p, contact);
4086 pset_plist (p, Fcopy_sequence (ps->plist));
4087 pset_type (p, Qnetwork);
4089 pset_buffer (p, buffer);
4090 pset_sentinel (p, ps->sentinel);
4091 pset_filter (p, ps->filter);
4092 pset_command (p, Qnil);
4093 p->pid = 0;
4095 /* Discard the unwind protect for closing S. */
4096 specpdl_ptr = specpdl + count;
4098 p->infd = s;
4099 p->outfd = s;
4100 pset_status (p, Qrun);
4102 /* Client processes for accepted connections are not stopped initially. */
4103 if (!EQ (p->filter, Qt))
4105 FD_SET (s, &input_wait_mask);
4106 FD_SET (s, &non_keyboard_wait_mask);
4109 if (s > max_process_desc)
4110 max_process_desc = s;
4112 /* Setup coding system for new process based on server process.
4113 This seems to be the proper thing to do, as the coding system
4114 of the new process should reflect the settings at the time the
4115 server socket was opened; not the current settings. */
4117 pset_decode_coding_system (p, ps->decode_coding_system);
4118 pset_encode_coding_system (p, ps->encode_coding_system);
4119 setup_process_coding_systems (proc);
4121 pset_decoding_buf (p, empty_unibyte_string);
4122 p->decoding_carryover = 0;
4123 pset_encoding_buf (p, empty_unibyte_string);
4125 p->inherit_coding_system_flag
4126 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4128 if (!NILP (ps->log))
4129 call3 (ps->log, server, proc,
4130 concat3 (build_string ("accept from "),
4131 (STRINGP (host) ? host : build_string ("-")),
4132 build_string ("\n")));
4134 exec_sentinel (proc,
4135 concat3 (build_string ("open from "),
4136 (STRINGP (host) ? host : build_string ("-")),
4137 build_string ("\n")));
4140 /* This variable is different from waiting_for_input in keyboard.c.
4141 It is used to communicate to a lisp process-filter/sentinel (via the
4142 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4143 for user-input when that process-filter was called.
4144 waiting_for_input cannot be used as that is by definition 0 when
4145 lisp code is being evalled.
4146 This is also used in record_asynch_buffer_change.
4147 For that purpose, this must be 0
4148 when not inside wait_reading_process_output. */
4149 static int waiting_for_user_input_p;
4151 static void
4152 wait_reading_process_output_unwind (int data)
4154 waiting_for_user_input_p = data;
4157 /* This is here so breakpoints can be put on it. */
4158 static void
4159 wait_reading_process_output_1 (void)
4163 /* Read and dispose of subprocess output while waiting for timeout to
4164 elapse and/or keyboard input to be available.
4166 TIME_LIMIT is:
4167 timeout in seconds
4168 If negative, gobble data immediately available but don't wait for any.
4170 NSECS is:
4171 an additional duration to wait, measured in nanoseconds
4172 If TIME_LIMIT is zero, then:
4173 If NSECS == 0, there is no limit.
4174 If NSECS > 0, the timeout consists of NSECS only.
4175 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4177 READ_KBD is:
4178 0 to ignore keyboard input, or
4179 1 to return when input is available, or
4180 -1 meaning caller will actually read the input, so don't throw to
4181 the quit handler, or
4183 DO_DISPLAY means redisplay should be done to show subprocess
4184 output that arrives.
4186 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4187 (and gobble terminal input into the buffer if any arrives).
4189 If WAIT_PROC is specified, wait until something arrives from that
4190 process. The return value is true if we read some input from
4191 that process.
4193 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4194 (suspending output from other processes). A negative value
4195 means don't run any timers either.
4197 If WAIT_PROC is specified, then the function returns true if we
4198 received input from that process before the timeout elapsed.
4199 Otherwise, return true if we received input from any process. */
4201 bool
4202 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4203 bool do_display,
4204 Lisp_Object wait_for_cell,
4205 struct Lisp_Process *wait_proc, int just_wait_proc)
4207 int channel, nfds;
4208 SELECT_TYPE Available;
4209 SELECT_TYPE Writeok;
4210 bool check_write;
4211 int check_delay;
4212 bool no_avail;
4213 int xerrno;
4214 Lisp_Object proc;
4215 EMACS_TIME timeout, end_time;
4216 int wait_channel = -1;
4217 bool got_some_input = 0;
4218 ptrdiff_t count = SPECPDL_INDEX ();
4220 FD_ZERO (&Available);
4221 FD_ZERO (&Writeok);
4223 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4224 && !(CONSP (wait_proc->status)
4225 && EQ (XCAR (wait_proc->status), Qexit)))
4226 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4228 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4229 if (wait_proc != NULL)
4230 wait_channel = wait_proc->infd;
4232 record_unwind_protect_int (wait_reading_process_output_unwind,
4233 waiting_for_user_input_p);
4234 waiting_for_user_input_p = read_kbd;
4236 if (time_limit < 0)
4238 time_limit = 0;
4239 nsecs = -1;
4241 else if (TYPE_MAXIMUM (time_t) < time_limit)
4242 time_limit = TYPE_MAXIMUM (time_t);
4244 /* Since we may need to wait several times,
4245 compute the absolute time to return at. */
4246 if (time_limit || nsecs > 0)
4248 timeout = make_emacs_time (time_limit, nsecs);
4249 end_time = add_emacs_time (current_emacs_time (), timeout);
4252 while (1)
4254 bool timeout_reduced_for_timers = 0;
4256 /* If calling from keyboard input, do not quit
4257 since we want to return C-g as an input character.
4258 Otherwise, do pending quit if requested. */
4259 if (read_kbd >= 0)
4260 QUIT;
4261 else if (pending_signals)
4262 process_pending_signals ();
4264 /* Exit now if the cell we're waiting for became non-nil. */
4265 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4266 break;
4268 /* Compute time from now till when time limit is up. */
4269 /* Exit if already run out. */
4270 if (nsecs < 0)
4272 /* A negative timeout means
4273 gobble output available now
4274 but don't wait at all. */
4276 timeout = make_emacs_time (0, 0);
4278 else if (time_limit || nsecs > 0)
4280 EMACS_TIME now = current_emacs_time ();
4281 if (EMACS_TIME_LE (end_time, now))
4282 break;
4283 timeout = sub_emacs_time (end_time, now);
4285 else
4287 timeout = make_emacs_time (100000, 0);
4290 /* Normally we run timers here.
4291 But not if wait_for_cell; in those cases,
4292 the wait is supposed to be short,
4293 and those callers cannot handle running arbitrary Lisp code here. */
4294 if (NILP (wait_for_cell)
4295 && just_wait_proc >= 0)
4297 EMACS_TIME timer_delay;
4301 unsigned old_timers_run = timers_run;
4302 struct buffer *old_buffer = current_buffer;
4303 Lisp_Object old_window = selected_window;
4305 timer_delay = timer_check ();
4307 /* If a timer has run, this might have changed buffers
4308 an alike. Make read_key_sequence aware of that. */
4309 if (timers_run != old_timers_run
4310 && (old_buffer != current_buffer
4311 || !EQ (old_window, selected_window))
4312 && waiting_for_user_input_p == -1)
4313 record_asynch_buffer_change ();
4315 if (timers_run != old_timers_run && do_display)
4316 /* We must retry, since a timer may have requeued itself
4317 and that could alter the time_delay. */
4318 redisplay_preserve_echo_area (9);
4319 else
4320 break;
4322 while (!detect_input_pending ());
4324 /* If there is unread keyboard input, also return. */
4325 if (read_kbd != 0
4326 && requeued_events_pending_p ())
4327 break;
4329 /* A negative timeout means do not wait at all. */
4330 if (nsecs >= 0)
4332 if (EMACS_TIME_VALID_P (timer_delay))
4334 if (EMACS_TIME_LT (timer_delay, timeout))
4336 timeout = timer_delay;
4337 timeout_reduced_for_timers = 1;
4340 else
4342 /* This is so a breakpoint can be put here. */
4343 wait_reading_process_output_1 ();
4348 /* Cause C-g and alarm signals to take immediate action,
4349 and cause input available signals to zero out timeout.
4351 It is important that we do this before checking for process
4352 activity. If we get a SIGCHLD after the explicit checks for
4353 process activity, timeout is the only way we will know. */
4354 if (read_kbd < 0)
4355 set_waiting_for_input (&timeout);
4357 /* If status of something has changed, and no input is
4358 available, notify the user of the change right away. After
4359 this explicit check, we'll let the SIGCHLD handler zap
4360 timeout to get our attention. */
4361 if (update_tick != process_tick)
4363 SELECT_TYPE Atemp;
4364 SELECT_TYPE Ctemp;
4366 if (kbd_on_hold_p ())
4367 FD_ZERO (&Atemp);
4368 else
4369 Atemp = input_wait_mask;
4370 Ctemp = write_mask;
4372 timeout = make_emacs_time (0, 0);
4373 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4374 &Atemp,
4375 #ifdef NON_BLOCKING_CONNECT
4376 (num_pending_connects > 0 ? &Ctemp : NULL),
4377 #else
4378 NULL,
4379 #endif
4380 NULL, &timeout, NULL)
4381 <= 0))
4383 /* It's okay for us to do this and then continue with
4384 the loop, since timeout has already been zeroed out. */
4385 clear_waiting_for_input ();
4386 status_notify (NULL);
4387 if (do_display) redisplay_preserve_echo_area (13);
4391 /* Don't wait for output from a non-running process. Just
4392 read whatever data has already been received. */
4393 if (wait_proc && wait_proc->raw_status_new)
4394 update_status (wait_proc);
4395 if (wait_proc
4396 && ! EQ (wait_proc->status, Qrun)
4397 && ! EQ (wait_proc->status, Qconnect))
4399 bool read_some_bytes = 0;
4401 clear_waiting_for_input ();
4402 XSETPROCESS (proc, wait_proc);
4404 /* Read data from the process, until we exhaust it. */
4405 while (wait_proc->infd >= 0)
4407 int nread = read_process_output (proc, wait_proc->infd);
4409 if (nread == 0)
4410 break;
4412 if (nread > 0)
4413 got_some_input = read_some_bytes = 1;
4414 else if (nread == -1 && (errno == EIO || errno == EAGAIN))
4415 break;
4416 #ifdef EWOULDBLOCK
4417 else if (nread == -1 && EWOULDBLOCK == errno)
4418 break;
4419 #endif
4421 if (read_some_bytes && do_display)
4422 redisplay_preserve_echo_area (10);
4424 break;
4427 /* Wait till there is something to do */
4429 if (wait_proc && just_wait_proc)
4431 if (wait_proc->infd < 0) /* Terminated */
4432 break;
4433 FD_SET (wait_proc->infd, &Available);
4434 check_delay = 0;
4435 check_write = 0;
4437 else if (!NILP (wait_for_cell))
4439 Available = non_process_wait_mask;
4440 check_delay = 0;
4441 check_write = 0;
4443 else
4445 if (! read_kbd)
4446 Available = non_keyboard_wait_mask;
4447 else
4448 Available = input_wait_mask;
4449 Writeok = write_mask;
4450 #ifdef SELECT_CANT_DO_WRITE_MASK
4451 check_write = 0;
4452 #else
4453 check_write = 1;
4454 #endif
4455 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4458 /* If frame size has changed or the window is newly mapped,
4459 redisplay now, before we start to wait. There is a race
4460 condition here; if a SIGIO arrives between now and the select
4461 and indicates that a frame is trashed, the select may block
4462 displaying a trashed screen. */
4463 if (frame_garbaged && do_display)
4465 clear_waiting_for_input ();
4466 redisplay_preserve_echo_area (11);
4467 if (read_kbd < 0)
4468 set_waiting_for_input (&timeout);
4471 /* Skip the `select' call if input is available and we're
4472 waiting for keyboard input or a cell change (which can be
4473 triggered by processing X events). In the latter case, set
4474 nfds to 1 to avoid breaking the loop. */
4475 no_avail = 0;
4476 if ((read_kbd || !NILP (wait_for_cell))
4477 && detect_input_pending ())
4479 nfds = read_kbd ? 0 : 1;
4480 no_avail = 1;
4483 if (!no_avail)
4486 #ifdef ADAPTIVE_READ_BUFFERING
4487 /* Set the timeout for adaptive read buffering if any
4488 process has non-zero read_output_skip and non-zero
4489 read_output_delay, and we are not reading output for a
4490 specific wait_channel. It is not executed if
4491 Vprocess_adaptive_read_buffering is nil. */
4492 if (process_output_skip && check_delay > 0)
4494 int nsecs = EMACS_NSECS (timeout);
4495 if (EMACS_SECS (timeout) > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4496 nsecs = READ_OUTPUT_DELAY_MAX;
4497 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4499 proc = chan_process[channel];
4500 if (NILP (proc))
4501 continue;
4502 /* Find minimum non-zero read_output_delay among the
4503 processes with non-zero read_output_skip. */
4504 if (XPROCESS (proc)->read_output_delay > 0)
4506 check_delay--;
4507 if (!XPROCESS (proc)->read_output_skip)
4508 continue;
4509 FD_CLR (channel, &Available);
4510 XPROCESS (proc)->read_output_skip = 0;
4511 if (XPROCESS (proc)->read_output_delay < nsecs)
4512 nsecs = XPROCESS (proc)->read_output_delay;
4515 timeout = make_emacs_time (0, nsecs);
4516 process_output_skip = 0;
4518 #endif
4520 #if defined (HAVE_NS)
4521 nfds = ns_select
4522 #elif defined (HAVE_GLIB)
4523 nfds = xg_select
4524 #else
4525 nfds = pselect
4526 #endif
4527 (max (max_process_desc, max_input_desc) + 1,
4528 &Available,
4529 (check_write ? &Writeok : (SELECT_TYPE *)0),
4530 NULL, &timeout, NULL);
4532 #ifdef HAVE_GNUTLS
4533 /* GnuTLS buffers data internally. In lowat mode it leaves
4534 some data in the TCP buffers so that select works, but
4535 with custom pull/push functions we need to check if some
4536 data is available in the buffers manually. */
4537 if (nfds == 0)
4539 if (! wait_proc)
4541 /* We're not waiting on a specific process, so loop
4542 through all the channels and check for data.
4543 This is a workaround needed for some versions of
4544 the gnutls library -- 2.12.14 has been confirmed
4545 to need it. See
4546 http://comments.gmane.org/gmane.emacs.devel/145074 */
4547 for (channel = 0; channel < MAXDESC; ++channel)
4548 if (! NILP (chan_process[channel]))
4550 struct Lisp_Process *p =
4551 XPROCESS (chan_process[channel]);
4552 if (p && p->gnutls_p && p->infd
4553 && ((emacs_gnutls_record_check_pending
4554 (p->gnutls_state))
4555 > 0))
4557 nfds++;
4558 FD_SET (p->infd, &Available);
4562 else
4564 /* Check this specific channel. */
4565 if (wait_proc->gnutls_p /* Check for valid process. */
4566 /* Do we have pending data? */
4567 && ((emacs_gnutls_record_check_pending
4568 (wait_proc->gnutls_state))
4569 > 0))
4571 nfds = 1;
4572 /* Set to Available. */
4573 FD_SET (wait_proc->infd, &Available);
4577 #endif
4580 xerrno = errno;
4582 /* Make C-g and alarm signals set flags again */
4583 clear_waiting_for_input ();
4585 /* If we woke up due to SIGWINCH, actually change size now. */
4586 do_pending_window_change (0);
4588 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4589 /* We waited the full specified time, so return now. */
4590 break;
4591 if (nfds < 0)
4593 if (xerrno == EINTR)
4594 no_avail = 1;
4595 else if (xerrno == EBADF)
4596 emacs_abort ();
4597 else
4598 report_file_errno ("Failed select", Qnil, xerrno);
4601 if (no_avail)
4603 FD_ZERO (&Available);
4604 check_write = 0;
4607 /* Check for keyboard input */
4608 /* If there is any, return immediately
4609 to give it higher priority than subprocesses */
4611 if (read_kbd != 0)
4613 unsigned old_timers_run = timers_run;
4614 struct buffer *old_buffer = current_buffer;
4615 Lisp_Object old_window = selected_window;
4616 bool leave = 0;
4618 if (detect_input_pending_run_timers (do_display))
4620 swallow_events (do_display);
4621 if (detect_input_pending_run_timers (do_display))
4622 leave = 1;
4625 /* If a timer has run, this might have changed buffers
4626 an alike. Make read_key_sequence aware of that. */
4627 if (timers_run != old_timers_run
4628 && waiting_for_user_input_p == -1
4629 && (old_buffer != current_buffer
4630 || !EQ (old_window, selected_window)))
4631 record_asynch_buffer_change ();
4633 if (leave)
4634 break;
4637 /* If there is unread keyboard input, also return. */
4638 if (read_kbd != 0
4639 && requeued_events_pending_p ())
4640 break;
4642 /* If we are not checking for keyboard input now,
4643 do process events (but don't run any timers).
4644 This is so that X events will be processed.
4645 Otherwise they may have to wait until polling takes place.
4646 That would causes delays in pasting selections, for example.
4648 (We used to do this only if wait_for_cell.) */
4649 if (read_kbd == 0 && detect_input_pending ())
4651 swallow_events (do_display);
4652 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4653 if (detect_input_pending ())
4654 break;
4655 #endif
4658 /* Exit now if the cell we're waiting for became non-nil. */
4659 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4660 break;
4662 #ifdef USABLE_SIGIO
4663 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4664 go read it. This can happen with X on BSD after logging out.
4665 In that case, there really is no input and no SIGIO,
4666 but select says there is input. */
4668 if (read_kbd && interrupt_input
4669 && keyboard_bit_set (&Available) && ! noninteractive)
4670 handle_input_available_signal (SIGIO);
4671 #endif
4673 if (! wait_proc)
4674 got_some_input |= nfds > 0;
4676 /* If checking input just got us a size-change event from X,
4677 obey it now if we should. */
4678 if (read_kbd || ! NILP (wait_for_cell))
4679 do_pending_window_change (0);
4681 /* Check for data from a process. */
4682 if (no_avail || nfds == 0)
4683 continue;
4685 for (channel = 0; channel <= max_input_desc; ++channel)
4687 struct fd_callback_data *d = &fd_callback_info[channel];
4688 if (d->func
4689 && ((d->condition & FOR_READ
4690 && FD_ISSET (channel, &Available))
4691 || (d->condition & FOR_WRITE
4692 && FD_ISSET (channel, &write_mask))))
4693 d->func (channel, d->data);
4696 for (channel = 0; channel <= max_process_desc; channel++)
4698 if (FD_ISSET (channel, &Available)
4699 && FD_ISSET (channel, &non_keyboard_wait_mask)
4700 && !FD_ISSET (channel, &non_process_wait_mask))
4702 int nread;
4704 /* If waiting for this channel, arrange to return as
4705 soon as no more input to be processed. No more
4706 waiting. */
4707 if (wait_channel == channel)
4709 wait_channel = -1;
4710 nsecs = -1;
4711 got_some_input = 1;
4713 proc = chan_process[channel];
4714 if (NILP (proc))
4715 continue;
4717 /* If this is a server stream socket, accept connection. */
4718 if (EQ (XPROCESS (proc)->status, Qlisten))
4720 server_accept_connection (proc, channel);
4721 continue;
4724 /* Read data from the process, starting with our
4725 buffered-ahead character if we have one. */
4727 nread = read_process_output (proc, channel);
4728 if (nread > 0)
4730 /* Since read_process_output can run a filter,
4731 which can call accept-process-output,
4732 don't try to read from any other processes
4733 before doing the select again. */
4734 FD_ZERO (&Available);
4736 if (do_display)
4737 redisplay_preserve_echo_area (12);
4739 #ifdef EWOULDBLOCK
4740 else if (nread == -1 && errno == EWOULDBLOCK)
4742 #endif
4743 else if (nread == -1 && errno == EAGAIN)
4745 #ifdef WINDOWSNT
4746 /* FIXME: Is this special case still needed? */
4747 /* Note that we cannot distinguish between no input
4748 available now and a closed pipe.
4749 With luck, a closed pipe will be accompanied by
4750 subprocess termination and SIGCHLD. */
4751 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4753 #endif
4754 #ifdef HAVE_PTYS
4755 /* On some OSs with ptys, when the process on one end of
4756 a pty exits, the other end gets an error reading with
4757 errno = EIO instead of getting an EOF (0 bytes read).
4758 Therefore, if we get an error reading and errno =
4759 EIO, just continue, because the child process has
4760 exited and should clean itself up soon (e.g. when we
4761 get a SIGCHLD). */
4762 else if (nread == -1 && errno == EIO)
4764 struct Lisp_Process *p = XPROCESS (proc);
4766 /* Clear the descriptor now, so we only raise the
4767 signal once. */
4768 FD_CLR (channel, &input_wait_mask);
4769 FD_CLR (channel, &non_keyboard_wait_mask);
4771 if (p->pid == -2)
4773 /* If the EIO occurs on a pty, the SIGCHLD handler's
4774 waitpid call will not find the process object to
4775 delete. Do it here. */
4776 p->tick = ++process_tick;
4777 pset_status (p, Qfailed);
4780 #endif /* HAVE_PTYS */
4781 /* If we can detect process termination, don't consider the
4782 process gone just because its pipe is closed. */
4783 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4785 else
4787 /* Preserve status of processes already terminated. */
4788 XPROCESS (proc)->tick = ++process_tick;
4789 deactivate_process (proc);
4790 if (XPROCESS (proc)->raw_status_new)
4791 update_status (XPROCESS (proc));
4792 if (EQ (XPROCESS (proc)->status, Qrun))
4793 pset_status (XPROCESS (proc),
4794 list2 (Qexit, make_number (256)));
4797 #ifdef NON_BLOCKING_CONNECT
4798 if (FD_ISSET (channel, &Writeok)
4799 && FD_ISSET (channel, &connect_wait_mask))
4801 struct Lisp_Process *p;
4803 FD_CLR (channel, &connect_wait_mask);
4804 FD_CLR (channel, &write_mask);
4805 if (--num_pending_connects < 0)
4806 emacs_abort ();
4808 proc = chan_process[channel];
4809 if (NILP (proc))
4810 continue;
4812 p = XPROCESS (proc);
4814 #ifdef GNU_LINUX
4815 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4816 So only use it on systems where it is known to work. */
4818 socklen_t xlen = sizeof (xerrno);
4819 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4820 xerrno = errno;
4822 #else
4824 struct sockaddr pname;
4825 int pnamelen = sizeof (pname);
4827 /* If connection failed, getpeername will fail. */
4828 xerrno = 0;
4829 if (getpeername (channel, &pname, &pnamelen) < 0)
4831 /* Obtain connect failure code through error slippage. */
4832 char dummy;
4833 xerrno = errno;
4834 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
4835 xerrno = errno;
4838 #endif
4839 if (xerrno)
4841 p->tick = ++process_tick;
4842 pset_status (p, list2 (Qfailed, make_number (xerrno)));
4843 deactivate_process (proc);
4845 else
4847 pset_status (p, Qrun);
4848 /* Execute the sentinel here. If we had relied on
4849 status_notify to do it later, it will read input
4850 from the process before calling the sentinel. */
4851 exec_sentinel (proc, build_string ("open\n"));
4852 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
4854 FD_SET (p->infd, &input_wait_mask);
4855 FD_SET (p->infd, &non_keyboard_wait_mask);
4859 #endif /* NON_BLOCKING_CONNECT */
4860 } /* End for each file descriptor. */
4861 } /* End while exit conditions not met. */
4863 unbind_to (count, Qnil);
4865 /* If calling from keyboard input, do not quit
4866 since we want to return C-g as an input character.
4867 Otherwise, do pending quit if requested. */
4868 if (read_kbd >= 0)
4870 /* Prevent input_pending from remaining set if we quit. */
4871 clear_input_pending ();
4872 QUIT;
4875 return got_some_input;
4878 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4880 static Lisp_Object
4881 read_process_output_call (Lisp_Object fun_and_args)
4883 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4886 static Lisp_Object
4887 read_process_output_error_handler (Lisp_Object error_val)
4889 cmd_error_internal (error_val, "error in process filter: ");
4890 Vinhibit_quit = Qt;
4891 update_echo_area ();
4892 Fsleep_for (make_number (2), Qnil);
4893 return Qt;
4896 static void
4897 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
4898 ssize_t nbytes,
4899 struct coding_system *coding);
4901 /* Read pending output from the process channel,
4902 starting with our buffered-ahead character if we have one.
4903 Yield number of decoded characters read.
4905 This function reads at most 4096 characters.
4906 If you want to read all available subprocess output,
4907 you must call it repeatedly until it returns zero.
4909 The characters read are decoded according to PROC's coding-system
4910 for decoding. */
4912 static int
4913 read_process_output (Lisp_Object proc, register int channel)
4915 register ssize_t nbytes;
4916 char *chars;
4917 register struct Lisp_Process *p = XPROCESS (proc);
4918 struct coding_system *coding = proc_decode_coding_system[channel];
4919 int carryover = p->decoding_carryover;
4920 int readmax = 4096;
4921 ptrdiff_t count = SPECPDL_INDEX ();
4922 Lisp_Object odeactivate;
4924 chars = alloca (carryover + readmax);
4925 if (carryover)
4926 /* See the comment above. */
4927 memcpy (chars, SDATA (p->decoding_buf), carryover);
4929 #ifdef DATAGRAM_SOCKETS
4930 /* We have a working select, so proc_buffered_char is always -1. */
4931 if (DATAGRAM_CHAN_P (channel))
4933 socklen_t len = datagram_address[channel].len;
4934 nbytes = recvfrom (channel, chars + carryover, readmax,
4935 0, datagram_address[channel].sa, &len);
4937 else
4938 #endif
4940 bool buffered = proc_buffered_char[channel] >= 0;
4941 if (buffered)
4943 chars[carryover] = proc_buffered_char[channel];
4944 proc_buffered_char[channel] = -1;
4946 #ifdef HAVE_GNUTLS
4947 if (p->gnutls_p)
4948 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
4949 readmax - buffered);
4950 else
4951 #endif
4952 nbytes = emacs_read (channel, chars + carryover + buffered,
4953 readmax - buffered);
4954 #ifdef ADAPTIVE_READ_BUFFERING
4955 if (nbytes > 0 && p->adaptive_read_buffering)
4957 int delay = p->read_output_delay;
4958 if (nbytes < 256)
4960 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
4962 if (delay == 0)
4963 process_output_delay_count++;
4964 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
4967 else if (delay > 0 && nbytes == readmax - buffered)
4969 delay -= READ_OUTPUT_DELAY_INCREMENT;
4970 if (delay == 0)
4971 process_output_delay_count--;
4973 p->read_output_delay = delay;
4974 if (delay)
4976 p->read_output_skip = 1;
4977 process_output_skip = 1;
4980 #endif
4981 nbytes += buffered;
4982 nbytes += buffered && nbytes <= 0;
4985 p->decoding_carryover = 0;
4987 /* At this point, NBYTES holds number of bytes just received
4988 (including the one in proc_buffered_char[channel]). */
4989 if (nbytes <= 0)
4991 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
4992 return nbytes;
4993 coding->mode |= CODING_MODE_LAST_BLOCK;
4996 /* Now set NBYTES how many bytes we must decode. */
4997 nbytes += carryover;
4999 odeactivate = Vdeactivate_mark;
5000 /* There's no good reason to let process filters change the current
5001 buffer, and many callers of accept-process-output, sit-for, and
5002 friends don't expect current-buffer to be changed from under them. */
5003 record_unwind_current_buffer ();
5005 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5007 /* Handling the process output should not deactivate the mark. */
5008 Vdeactivate_mark = odeactivate;
5010 unbind_to (count, Qnil);
5011 return nbytes;
5014 static void
5015 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5016 ssize_t nbytes,
5017 struct coding_system *coding)
5019 Lisp_Object outstream = p->filter;
5020 Lisp_Object text;
5021 bool outer_running_asynch_code = running_asynch_code;
5022 int waiting = waiting_for_user_input_p;
5024 /* No need to gcpro these, because all we do with them later
5025 is test them for EQness, and none of them should be a string. */
5026 #if 0
5027 Lisp_Object obuffer, okeymap;
5028 XSETBUFFER (obuffer, current_buffer);
5029 okeymap = BVAR (current_buffer, keymap);
5030 #endif
5032 /* We inhibit quit here instead of just catching it so that
5033 hitting ^G when a filter happens to be running won't screw
5034 it up. */
5035 specbind (Qinhibit_quit, Qt);
5036 specbind (Qlast_nonmenu_event, Qt);
5038 /* In case we get recursively called,
5039 and we already saved the match data nonrecursively,
5040 save the same match data in safely recursive fashion. */
5041 if (outer_running_asynch_code)
5043 Lisp_Object tem;
5044 /* Don't clobber the CURRENT match data, either! */
5045 tem = Fmatch_data (Qnil, Qnil, Qnil);
5046 restore_search_regs ();
5047 record_unwind_save_match_data ();
5048 Fset_match_data (tem, Qt);
5051 /* For speed, if a search happens within this code,
5052 save the match data in a special nonrecursive fashion. */
5053 running_asynch_code = 1;
5055 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5056 text = coding->dst_object;
5057 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5058 /* A new coding system might be found. */
5059 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5061 pset_decode_coding_system (p, Vlast_coding_system_used);
5063 /* Don't call setup_coding_system for
5064 proc_decode_coding_system[channel] here. It is done in
5065 detect_coding called via decode_coding above. */
5067 /* If a coding system for encoding is not yet decided, we set
5068 it as the same as coding-system for decoding.
5070 But, before doing that we must check if
5071 proc_encode_coding_system[p->outfd] surely points to a
5072 valid memory because p->outfd will be changed once EOF is
5073 sent to the process. */
5074 if (NILP (p->encode_coding_system)
5075 && proc_encode_coding_system[p->outfd])
5077 pset_encode_coding_system
5078 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5079 setup_coding_system (p->encode_coding_system,
5080 proc_encode_coding_system[p->outfd]);
5084 if (coding->carryover_bytes > 0)
5086 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5087 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5088 memcpy (SDATA (p->decoding_buf), coding->carryover,
5089 coding->carryover_bytes);
5090 p->decoding_carryover = coding->carryover_bytes;
5092 if (SBYTES (text) > 0)
5093 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5094 sometimes it's simply wrong to wrap (e.g. when called from
5095 accept-process-output). */
5096 internal_condition_case_1 (read_process_output_call,
5097 list3 (outstream, make_lisp_proc (p), text),
5098 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5099 read_process_output_error_handler);
5101 /* If we saved the match data nonrecursively, restore it now. */
5102 restore_search_regs ();
5103 running_asynch_code = outer_running_asynch_code;
5105 /* Restore waiting_for_user_input_p as it was
5106 when we were called, in case the filter clobbered it. */
5107 waiting_for_user_input_p = waiting;
5109 #if 0 /* Call record_asynch_buffer_change unconditionally,
5110 because we might have changed minor modes or other things
5111 that affect key bindings. */
5112 if (! EQ (Fcurrent_buffer (), obuffer)
5113 || ! EQ (current_buffer->keymap, okeymap))
5114 #endif
5115 /* But do it only if the caller is actually going to read events.
5116 Otherwise there's no need to make him wake up, and it could
5117 cause trouble (for example it would make sit_for return). */
5118 if (waiting_for_user_input_p == -1)
5119 record_asynch_buffer_change ();
5122 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5123 Sinternal_default_process_filter, 2, 2, 0,
5124 doc: /* Function used as default process filter. */)
5125 (Lisp_Object proc, Lisp_Object text)
5127 struct Lisp_Process *p;
5128 ptrdiff_t opoint;
5130 CHECK_PROCESS (proc);
5131 p = XPROCESS (proc);
5132 CHECK_STRING (text);
5134 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5136 Lisp_Object old_read_only;
5137 ptrdiff_t old_begv, old_zv;
5138 ptrdiff_t old_begv_byte, old_zv_byte;
5139 ptrdiff_t before, before_byte;
5140 ptrdiff_t opoint_byte;
5141 struct buffer *b;
5143 Fset_buffer (p->buffer);
5144 opoint = PT;
5145 opoint_byte = PT_BYTE;
5146 old_read_only = BVAR (current_buffer, read_only);
5147 old_begv = BEGV;
5148 old_zv = ZV;
5149 old_begv_byte = BEGV_BYTE;
5150 old_zv_byte = ZV_BYTE;
5152 bset_read_only (current_buffer, Qnil);
5154 /* Insert new output into buffer
5155 at the current end-of-output marker,
5156 thus preserving logical ordering of input and output. */
5157 if (XMARKER (p->mark)->buffer)
5158 SET_PT_BOTH (clip_to_bounds (BEGV,
5159 marker_position (p->mark), ZV),
5160 clip_to_bounds (BEGV_BYTE,
5161 marker_byte_position (p->mark),
5162 ZV_BYTE));
5163 else
5164 SET_PT_BOTH (ZV, ZV_BYTE);
5165 before = PT;
5166 before_byte = PT_BYTE;
5168 /* If the output marker is outside of the visible region, save
5169 the restriction and widen. */
5170 if (! (BEGV <= PT && PT <= ZV))
5171 Fwiden ();
5173 /* Adjust the multibyteness of TEXT to that of the buffer. */
5174 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5175 != ! STRING_MULTIBYTE (text))
5176 text = (STRING_MULTIBYTE (text)
5177 ? Fstring_as_unibyte (text)
5178 : Fstring_to_multibyte (text));
5179 /* Insert before markers in case we are inserting where
5180 the buffer's mark is, and the user's next command is Meta-y. */
5181 insert_from_string_before_markers (text, 0, 0,
5182 SCHARS (text), SBYTES (text), 0);
5184 /* Make sure the process marker's position is valid when the
5185 process buffer is changed in the signal_after_change above.
5186 W3 is known to do that. */
5187 if (BUFFERP (p->buffer)
5188 && (b = XBUFFER (p->buffer), b != current_buffer))
5189 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5190 else
5191 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5193 update_mode_lines++;
5195 /* Make sure opoint and the old restrictions
5196 float ahead of any new text just as point would. */
5197 if (opoint >= before)
5199 opoint += PT - before;
5200 opoint_byte += PT_BYTE - before_byte;
5202 if (old_begv > before)
5204 old_begv += PT - before;
5205 old_begv_byte += PT_BYTE - before_byte;
5207 if (old_zv >= before)
5209 old_zv += PT - before;
5210 old_zv_byte += PT_BYTE - before_byte;
5213 /* If the restriction isn't what it should be, set it. */
5214 if (old_begv != BEGV || old_zv != ZV)
5215 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5217 bset_read_only (current_buffer, old_read_only);
5218 SET_PT_BOTH (opoint, opoint_byte);
5220 return Qnil;
5223 /* Sending data to subprocess. */
5225 /* In send_process, when a write fails temporarily,
5226 wait_reading_process_output is called. It may execute user code,
5227 e.g. timers, that attempts to write new data to the same process.
5228 We must ensure that data is sent in the right order, and not
5229 interspersed half-completed with other writes (Bug#10815). This is
5230 handled by the write_queue element of struct process. It is a list
5231 with each entry having the form
5233 (string . (offset . length))
5235 where STRING is a lisp string, OFFSET is the offset into the
5236 string's byte sequence from which we should begin to send, and
5237 LENGTH is the number of bytes left to send. */
5239 /* Create a new entry in write_queue.
5240 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5241 BUF is a pointer to the string sequence of the input_obj or a C
5242 string in case of Qt or Qnil. */
5244 static void
5245 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5246 const char *buf, ptrdiff_t len, bool front)
5248 ptrdiff_t offset;
5249 Lisp_Object entry, obj;
5251 if (STRINGP (input_obj))
5253 offset = buf - SSDATA (input_obj);
5254 obj = input_obj;
5256 else
5258 offset = 0;
5259 obj = make_unibyte_string (buf, len);
5262 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5264 if (front)
5265 pset_write_queue (p, Fcons (entry, p->write_queue));
5266 else
5267 pset_write_queue (p, nconc2 (p->write_queue, list1 (entry)));
5270 /* Remove the first element in the write_queue of process P, put its
5271 contents in OBJ, BUF and LEN, and return true. If the
5272 write_queue is empty, return false. */
5274 static bool
5275 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5276 const char **buf, ptrdiff_t *len)
5278 Lisp_Object entry, offset_length;
5279 ptrdiff_t offset;
5281 if (NILP (p->write_queue))
5282 return 0;
5284 entry = XCAR (p->write_queue);
5285 pset_write_queue (p, XCDR (p->write_queue));
5287 *obj = XCAR (entry);
5288 offset_length = XCDR (entry);
5290 *len = XINT (XCDR (offset_length));
5291 offset = XINT (XCAR (offset_length));
5292 *buf = SSDATA (*obj) + offset;
5294 return 1;
5297 /* Send some data to process PROC.
5298 BUF is the beginning of the data; LEN is the number of characters.
5299 OBJECT is the Lisp object that the data comes from. If OBJECT is
5300 nil or t, it means that the data comes from C string.
5302 If OBJECT is not nil, the data is encoded by PROC's coding-system
5303 for encoding before it is sent.
5305 This function can evaluate Lisp code and can garbage collect. */
5307 static void
5308 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5309 Lisp_Object object)
5311 struct Lisp_Process *p = XPROCESS (proc);
5312 ssize_t rv;
5313 struct coding_system *coding;
5315 if (p->raw_status_new)
5316 update_status (p);
5317 if (! EQ (p->status, Qrun))
5318 error ("Process %s not running", SDATA (p->name));
5319 if (p->outfd < 0)
5320 error ("Output file descriptor of %s is closed", SDATA (p->name));
5322 coding = proc_encode_coding_system[p->outfd];
5323 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5325 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5326 || (BUFFERP (object)
5327 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5328 || EQ (object, Qt))
5330 pset_encode_coding_system
5331 (p, complement_process_encoding_system (p->encode_coding_system));
5332 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5334 /* The coding system for encoding was changed to raw-text
5335 because we sent a unibyte text previously. Now we are
5336 sending a multibyte text, thus we must encode it by the
5337 original coding system specified for the current process.
5339 Another reason we come here is that the coding system
5340 was just complemented and a new one was returned by
5341 complement_process_encoding_system. */
5342 setup_coding_system (p->encode_coding_system, coding);
5343 Vlast_coding_system_used = p->encode_coding_system;
5345 coding->src_multibyte = 1;
5347 else
5349 coding->src_multibyte = 0;
5350 /* For sending a unibyte text, character code conversion should
5351 not take place but EOL conversion should. So, setup raw-text
5352 or one of the subsidiary if we have not yet done it. */
5353 if (CODING_REQUIRE_ENCODING (coding))
5355 if (CODING_REQUIRE_FLUSHING (coding))
5357 /* But, before changing the coding, we must flush out data. */
5358 coding->mode |= CODING_MODE_LAST_BLOCK;
5359 send_process (proc, "", 0, Qt);
5360 coding->mode &= CODING_MODE_LAST_BLOCK;
5362 setup_coding_system (raw_text_coding_system
5363 (Vlast_coding_system_used),
5364 coding);
5365 coding->src_multibyte = 0;
5368 coding->dst_multibyte = 0;
5370 if (CODING_REQUIRE_ENCODING (coding))
5372 coding->dst_object = Qt;
5373 if (BUFFERP (object))
5375 ptrdiff_t from_byte, from, to;
5376 ptrdiff_t save_pt, save_pt_byte;
5377 struct buffer *cur = current_buffer;
5379 set_buffer_internal (XBUFFER (object));
5380 save_pt = PT, save_pt_byte = PT_BYTE;
5382 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5383 from = BYTE_TO_CHAR (from_byte);
5384 to = BYTE_TO_CHAR (from_byte + len);
5385 TEMP_SET_PT_BOTH (from, from_byte);
5386 encode_coding_object (coding, object, from, from_byte,
5387 to, from_byte + len, Qt);
5388 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5389 set_buffer_internal (cur);
5391 else if (STRINGP (object))
5393 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5394 SBYTES (object), Qt);
5396 else
5398 coding->dst_object = make_unibyte_string (buf, len);
5399 coding->produced = len;
5402 len = coding->produced;
5403 object = coding->dst_object;
5404 buf = SSDATA (object);
5407 /* If there is already data in the write_queue, put the new data
5408 in the back of queue. Otherwise, ignore it. */
5409 if (!NILP (p->write_queue))
5410 write_queue_push (p, object, buf, len, 0);
5412 do /* while !NILP (p->write_queue) */
5414 ptrdiff_t cur_len = -1;
5415 const char *cur_buf;
5416 Lisp_Object cur_object;
5418 /* If write_queue is empty, ignore it. */
5419 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5421 cur_len = len;
5422 cur_buf = buf;
5423 cur_object = object;
5426 while (cur_len > 0)
5428 /* Send this batch, using one or more write calls. */
5429 ptrdiff_t written = 0;
5430 int outfd = p->outfd;
5431 #ifdef DATAGRAM_SOCKETS
5432 if (DATAGRAM_CHAN_P (outfd))
5434 rv = sendto (outfd, cur_buf, cur_len,
5435 0, datagram_address[outfd].sa,
5436 datagram_address[outfd].len);
5437 if (rv >= 0)
5438 written = rv;
5439 else if (errno == EMSGSIZE)
5440 report_file_error ("Sending datagram", proc);
5442 else
5443 #endif
5445 #ifdef HAVE_GNUTLS
5446 if (p->gnutls_p)
5447 written = emacs_gnutls_write (p, cur_buf, cur_len);
5448 else
5449 #endif
5450 written = emacs_write_sig (outfd, cur_buf, cur_len);
5451 rv = (written ? 0 : -1);
5452 #ifdef ADAPTIVE_READ_BUFFERING
5453 if (p->read_output_delay > 0
5454 && p->adaptive_read_buffering == 1)
5456 p->read_output_delay = 0;
5457 process_output_delay_count--;
5458 p->read_output_skip = 0;
5460 #endif
5463 if (rv < 0)
5465 if (errno == EAGAIN
5466 #ifdef EWOULDBLOCK
5467 || errno == EWOULDBLOCK
5468 #endif
5470 /* Buffer is full. Wait, accepting input;
5471 that may allow the program
5472 to finish doing output and read more. */
5474 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5475 /* A gross hack to work around a bug in FreeBSD.
5476 In the following sequence, read(2) returns
5477 bogus data:
5479 write(2) 1022 bytes
5480 write(2) 954 bytes, get EAGAIN
5481 read(2) 1024 bytes in process_read_output
5482 read(2) 11 bytes in process_read_output
5484 That is, read(2) returns more bytes than have
5485 ever been written successfully. The 1033 bytes
5486 read are the 1022 bytes written successfully
5487 after processing (for example with CRs added if
5488 the terminal is set up that way which it is
5489 here). The same bytes will be seen again in a
5490 later read(2), without the CRs. */
5492 if (errno == EAGAIN)
5494 int flags = FWRITE;
5495 ioctl (p->outfd, TIOCFLUSH, &flags);
5497 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5499 /* Put what we should have written in wait_queue. */
5500 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5501 wait_reading_process_output (0, 20 * 1000 * 1000,
5502 0, 0, Qnil, NULL, 0);
5503 /* Reread queue, to see what is left. */
5504 break;
5506 else if (errno == EPIPE)
5508 p->raw_status_new = 0;
5509 pset_status (p, list2 (Qexit, make_number (256)));
5510 p->tick = ++process_tick;
5511 deactivate_process (proc);
5512 error ("process %s no longer connected to pipe; closed it",
5513 SDATA (p->name));
5515 else
5516 /* This is a real error. */
5517 report_file_error ("Writing to process", proc);
5519 cur_buf += written;
5520 cur_len -= written;
5523 while (!NILP (p->write_queue));
5526 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5527 3, 3, 0,
5528 doc: /* Send current contents of region as input to PROCESS.
5529 PROCESS may be a process, a buffer, the name of a process or buffer, or
5530 nil, indicating the current buffer's process.
5531 Called from program, takes three arguments, PROCESS, START and END.
5532 If the region is more than 500 characters long,
5533 it is sent in several bunches. This may happen even for shorter regions.
5534 Output from processes can arrive in between bunches. */)
5535 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5537 Lisp_Object proc = get_process (process);
5538 ptrdiff_t start_byte, end_byte;
5540 validate_region (&start, &end);
5542 start_byte = CHAR_TO_BYTE (XINT (start));
5543 end_byte = CHAR_TO_BYTE (XINT (end));
5545 if (XINT (start) < GPT && XINT (end) > GPT)
5546 move_gap_both (XINT (start), start_byte);
5548 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5549 end_byte - start_byte, Fcurrent_buffer ());
5551 return Qnil;
5554 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5555 2, 2, 0,
5556 doc: /* Send PROCESS the contents of STRING as input.
5557 PROCESS may be a process, a buffer, the name of a process or buffer, or
5558 nil, indicating the current buffer's process.
5559 If STRING is more than 500 characters long,
5560 it is sent in several bunches. This may happen even for shorter strings.
5561 Output from processes can arrive in between bunches. */)
5562 (Lisp_Object process, Lisp_Object string)
5564 Lisp_Object proc;
5565 CHECK_STRING (string);
5566 proc = get_process (process);
5567 send_process (proc, SSDATA (string),
5568 SBYTES (string), string);
5569 return Qnil;
5572 /* Return the foreground process group for the tty/pty that
5573 the process P uses. */
5574 static pid_t
5575 emacs_get_tty_pgrp (struct Lisp_Process *p)
5577 pid_t gid = -1;
5579 #ifdef TIOCGPGRP
5580 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5582 int fd;
5583 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5584 master side. Try the slave side. */
5585 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5587 if (fd != -1)
5589 ioctl (fd, TIOCGPGRP, &gid);
5590 emacs_close (fd);
5593 #endif /* defined (TIOCGPGRP ) */
5595 return gid;
5598 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5599 Sprocess_running_child_p, 0, 1, 0,
5600 doc: /* Return t if PROCESS has given the terminal to a child.
5601 If the operating system does not make it possible to find out,
5602 return t unconditionally. */)
5603 (Lisp_Object process)
5605 /* Initialize in case ioctl doesn't exist or gives an error,
5606 in a way that will cause returning t. */
5607 pid_t gid;
5608 Lisp_Object proc;
5609 struct Lisp_Process *p;
5611 proc = get_process (process);
5612 p = XPROCESS (proc);
5614 if (!EQ (p->type, Qreal))
5615 error ("Process %s is not a subprocess",
5616 SDATA (p->name));
5617 if (p->infd < 0)
5618 error ("Process %s is not active",
5619 SDATA (p->name));
5621 gid = emacs_get_tty_pgrp (p);
5623 if (gid == p->pid)
5624 return Qnil;
5625 return Qt;
5628 /* send a signal number SIGNO to PROCESS.
5629 If CURRENT_GROUP is t, that means send to the process group
5630 that currently owns the terminal being used to communicate with PROCESS.
5631 This is used for various commands in shell mode.
5632 If CURRENT_GROUP is lambda, that means send to the process group
5633 that currently owns the terminal, but only if it is NOT the shell itself.
5635 If NOMSG is false, insert signal-announcements into process's buffers
5636 right away.
5638 If we can, we try to signal PROCESS by sending control characters
5639 down the pty. This allows us to signal inferiors who have changed
5640 their uid, for which kill would return an EPERM error. */
5642 static void
5643 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5644 bool nomsg)
5646 Lisp_Object proc;
5647 struct Lisp_Process *p;
5648 pid_t gid;
5649 bool no_pgrp = 0;
5651 proc = get_process (process);
5652 p = XPROCESS (proc);
5654 if (!EQ (p->type, Qreal))
5655 error ("Process %s is not a subprocess",
5656 SDATA (p->name));
5657 if (p->infd < 0)
5658 error ("Process %s is not active",
5659 SDATA (p->name));
5661 if (!p->pty_flag)
5662 current_group = Qnil;
5664 /* If we are using pgrps, get a pgrp number and make it negative. */
5665 if (NILP (current_group))
5666 /* Send the signal to the shell's process group. */
5667 gid = p->pid;
5668 else
5670 #ifdef SIGNALS_VIA_CHARACTERS
5671 /* If possible, send signals to the entire pgrp
5672 by sending an input character to it. */
5674 struct termios t;
5675 cc_t *sig_char = NULL;
5677 tcgetattr (p->infd, &t);
5679 switch (signo)
5681 case SIGINT:
5682 sig_char = &t.c_cc[VINTR];
5683 break;
5685 case SIGQUIT:
5686 sig_char = &t.c_cc[VQUIT];
5687 break;
5689 case SIGTSTP:
5690 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5691 sig_char = &t.c_cc[VSWTCH];
5692 #else
5693 sig_char = &t.c_cc[VSUSP];
5694 #endif
5695 break;
5698 if (sig_char && *sig_char != CDISABLE)
5700 send_process (proc, (char *) sig_char, 1, Qnil);
5701 return;
5703 /* If we can't send the signal with a character,
5704 fall through and send it another way. */
5706 /* The code above may fall through if it can't
5707 handle the signal. */
5708 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5710 #ifdef TIOCGPGRP
5711 /* Get the current pgrp using the tty itself, if we have that.
5712 Otherwise, use the pty to get the pgrp.
5713 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5714 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5715 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5716 His patch indicates that if TIOCGPGRP returns an error, then
5717 we should just assume that p->pid is also the process group id. */
5719 gid = emacs_get_tty_pgrp (p);
5721 if (gid == -1)
5722 /* If we can't get the information, assume
5723 the shell owns the tty. */
5724 gid = p->pid;
5726 /* It is not clear whether anything really can set GID to -1.
5727 Perhaps on some system one of those ioctls can or could do so.
5728 Or perhaps this is vestigial. */
5729 if (gid == -1)
5730 no_pgrp = 1;
5731 #else /* ! defined (TIOCGPGRP ) */
5732 /* Can't select pgrps on this system, so we know that
5733 the child itself heads the pgrp. */
5734 gid = p->pid;
5735 #endif /* ! defined (TIOCGPGRP ) */
5737 /* If current_group is lambda, and the shell owns the terminal,
5738 don't send any signal. */
5739 if (EQ (current_group, Qlambda) && gid == p->pid)
5740 return;
5743 switch (signo)
5745 #ifdef SIGCONT
5746 case SIGCONT:
5747 p->raw_status_new = 0;
5748 pset_status (p, Qrun);
5749 p->tick = ++process_tick;
5750 if (!nomsg)
5752 status_notify (NULL);
5753 redisplay_preserve_echo_area (13);
5755 break;
5756 #endif /* ! defined (SIGCONT) */
5757 case SIGINT:
5758 case SIGQUIT:
5759 case SIGKILL:
5760 flush_pending_output (p->infd);
5761 break;
5764 /* If we don't have process groups, send the signal to the immediate
5765 subprocess. That isn't really right, but it's better than any
5766 obvious alternative. */
5767 if (no_pgrp)
5769 kill (p->pid, signo);
5770 return;
5773 /* gid may be a pid, or minus a pgrp's number */
5774 #ifdef TIOCSIGSEND
5775 if (!NILP (current_group))
5777 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
5778 kill (-gid, signo);
5780 else
5782 gid = - p->pid;
5783 kill (gid, signo);
5785 #else /* ! defined (TIOCSIGSEND) */
5786 kill (-gid, signo);
5787 #endif /* ! defined (TIOCSIGSEND) */
5790 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5791 doc: /* Interrupt process PROCESS.
5792 PROCESS may be a process, a buffer, or the name of a process or buffer.
5793 No arg or nil means current buffer's process.
5794 Second arg CURRENT-GROUP non-nil means send signal to
5795 the current process-group of the process's controlling terminal
5796 rather than to the process's own process group.
5797 If the process is a shell, this means interrupt current subjob
5798 rather than the shell.
5800 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5801 don't send the signal. */)
5802 (Lisp_Object process, Lisp_Object current_group)
5804 process_send_signal (process, SIGINT, current_group, 0);
5805 return process;
5808 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5809 doc: /* Kill process PROCESS. May be process or name of one.
5810 See function `interrupt-process' for more details on usage. */)
5811 (Lisp_Object process, Lisp_Object current_group)
5813 process_send_signal (process, SIGKILL, current_group, 0);
5814 return process;
5817 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5818 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5819 See function `interrupt-process' for more details on usage. */)
5820 (Lisp_Object process, Lisp_Object current_group)
5822 process_send_signal (process, SIGQUIT, current_group, 0);
5823 return process;
5826 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
5827 doc: /* Stop process PROCESS. May be process or name of one.
5828 See function `interrupt-process' for more details on usage.
5829 If PROCESS is a network or serial process, inhibit handling of incoming
5830 traffic. */)
5831 (Lisp_Object process, Lisp_Object current_group)
5833 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5835 struct Lisp_Process *p;
5837 p = XPROCESS (process);
5838 if (NILP (p->command)
5839 && p->infd >= 0)
5841 FD_CLR (p->infd, &input_wait_mask);
5842 FD_CLR (p->infd, &non_keyboard_wait_mask);
5844 pset_command (p, Qt);
5845 return process;
5847 #ifndef SIGTSTP
5848 error ("No SIGTSTP support");
5849 #else
5850 process_send_signal (process, SIGTSTP, current_group, 0);
5851 #endif
5852 return process;
5855 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
5856 doc: /* Continue process PROCESS. May be process or name of one.
5857 See function `interrupt-process' for more details on usage.
5858 If PROCESS is a network or serial process, resume handling of incoming
5859 traffic. */)
5860 (Lisp_Object process, Lisp_Object current_group)
5862 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5864 struct Lisp_Process *p;
5866 p = XPROCESS (process);
5867 if (EQ (p->command, Qt)
5868 && p->infd >= 0
5869 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
5871 FD_SET (p->infd, &input_wait_mask);
5872 FD_SET (p->infd, &non_keyboard_wait_mask);
5873 #ifdef WINDOWSNT
5874 if (fd_info[ p->infd ].flags & FILE_SERIAL)
5875 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
5876 #else /* not WINDOWSNT */
5877 tcflush (p->infd, TCIFLUSH);
5878 #endif /* not WINDOWSNT */
5880 pset_command (p, Qnil);
5881 return process;
5883 #ifdef SIGCONT
5884 process_send_signal (process, SIGCONT, current_group, 0);
5885 #else
5886 error ("No SIGCONT support");
5887 #endif
5888 return process;
5891 /* Return the integer value of the signal whose abbreviation is ABBR,
5892 or a negative number if there is no such signal. */
5893 static int
5894 abbr_to_signal (char const *name)
5896 int i, signo;
5897 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
5899 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
5900 name += 3;
5902 for (i = 0; i < sizeof sigbuf; i++)
5904 sigbuf[i] = c_toupper (name[i]);
5905 if (! sigbuf[i])
5906 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
5909 return -1;
5912 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
5913 2, 2, "sProcess (name or number): \nnSignal code: ",
5914 doc: /* Send PROCESS the signal with code SIGCODE.
5915 PROCESS may also be a number specifying the process id of the
5916 process to signal; in this case, the process need not be a child of
5917 this Emacs.
5918 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5919 (Lisp_Object process, Lisp_Object sigcode)
5921 pid_t pid;
5922 int signo;
5924 if (STRINGP (process))
5926 Lisp_Object tem = Fget_process (process);
5927 if (NILP (tem))
5929 Lisp_Object process_number =
5930 string_to_number (SSDATA (process), 10, 1);
5931 if (INTEGERP (process_number) || FLOATP (process_number))
5932 tem = process_number;
5934 process = tem;
5936 else if (!NUMBERP (process))
5937 process = get_process (process);
5939 if (NILP (process))
5940 return process;
5942 if (NUMBERP (process))
5943 CONS_TO_INTEGER (process, pid_t, pid);
5944 else
5946 CHECK_PROCESS (process);
5947 pid = XPROCESS (process)->pid;
5948 if (pid <= 0)
5949 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
5952 if (INTEGERP (sigcode))
5954 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
5955 signo = XINT (sigcode);
5957 else
5959 char *name;
5961 CHECK_SYMBOL (sigcode);
5962 name = SSDATA (SYMBOL_NAME (sigcode));
5964 signo = abbr_to_signal (name);
5965 if (signo < 0)
5966 error ("Undefined signal name %s", name);
5969 return make_number (kill (pid, signo));
5972 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
5973 doc: /* Make PROCESS see end-of-file in its input.
5974 EOF comes after any text already sent to it.
5975 PROCESS may be a process, a buffer, the name of a process or buffer, or
5976 nil, indicating the current buffer's process.
5977 If PROCESS is a network connection, or is a process communicating
5978 through a pipe (as opposed to a pty), then you cannot send any more
5979 text to PROCESS after you call this function.
5980 If PROCESS is a serial process, wait until all output written to the
5981 process has been transmitted to the serial port. */)
5982 (Lisp_Object process)
5984 Lisp_Object proc;
5985 struct coding_system *coding;
5987 if (DATAGRAM_CONN_P (process))
5988 return process;
5990 proc = get_process (process);
5991 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
5993 /* Make sure the process is really alive. */
5994 if (XPROCESS (proc)->raw_status_new)
5995 update_status (XPROCESS (proc));
5996 if (! EQ (XPROCESS (proc)->status, Qrun))
5997 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
5999 if (CODING_REQUIRE_FLUSHING (coding))
6001 coding->mode |= CODING_MODE_LAST_BLOCK;
6002 send_process (proc, "", 0, Qnil);
6005 if (XPROCESS (proc)->pty_flag)
6006 send_process (proc, "\004", 1, Qnil);
6007 else if (EQ (XPROCESS (proc)->type, Qserial))
6009 #ifndef WINDOWSNT
6010 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6011 report_file_error ("Failed tcdrain", Qnil);
6012 #endif /* not WINDOWSNT */
6013 /* Do nothing on Windows because writes are blocking. */
6015 else
6017 int old_outfd, new_outfd;
6019 #ifdef HAVE_SHUTDOWN
6020 /* If this is a network connection, or socketpair is used
6021 for communication with the subprocess, call shutdown to cause EOF.
6022 (In some old system, shutdown to socketpair doesn't work.
6023 Then we just can't win.) */
6024 if (EQ (XPROCESS (proc)->type, Qnetwork)
6025 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6026 shutdown (XPROCESS (proc)->outfd, 1);
6027 /* In case of socketpair, outfd == infd, so don't close it. */
6028 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6029 emacs_close (XPROCESS (proc)->outfd);
6030 #else /* not HAVE_SHUTDOWN */
6031 emacs_close (XPROCESS (proc)->outfd);
6032 #endif /* not HAVE_SHUTDOWN */
6033 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6034 if (new_outfd < 0)
6035 emacs_abort ();
6036 old_outfd = XPROCESS (proc)->outfd;
6038 if (!proc_encode_coding_system[new_outfd])
6039 proc_encode_coding_system[new_outfd]
6040 = xmalloc (sizeof (struct coding_system));
6041 *proc_encode_coding_system[new_outfd]
6042 = *proc_encode_coding_system[old_outfd];
6043 memset (proc_encode_coding_system[old_outfd], 0,
6044 sizeof (struct coding_system));
6046 XPROCESS (proc)->outfd = new_outfd;
6048 return process;
6051 /* The main Emacs thread records child processes in three places:
6053 - Vprocess_alist, for asynchronous subprocesses, which are child
6054 processes visible to Lisp.
6056 - deleted_pid_list, for child processes invisible to Lisp,
6057 typically because of delete-process. These are recorded so that
6058 the processes can be reaped when they exit, so that the operating
6059 system's process table is not cluttered by zombies.
6061 - the local variable PID in Fcall_process, call_process_cleanup and
6062 call_process_kill, for synchronous subprocesses.
6063 record_unwind_protect is used to make sure this process is not
6064 forgotten: if the user interrupts call-process and the child
6065 process refuses to exit immediately even with two C-g's,
6066 call_process_kill adds PID's contents to deleted_pid_list before
6067 returning.
6069 The main Emacs thread invokes waitpid only on child processes that
6070 it creates and that have not been reaped. This avoid races on
6071 platforms such as GTK, where other threads create their own
6072 subprocesses which the main thread should not reap. For example,
6073 if the main thread attempted to reap an already-reaped child, it
6074 might inadvertently reap a GTK-created process that happened to
6075 have the same process ID. */
6077 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6078 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6079 keep track of its own children. GNUstep is similar. */
6081 static void dummy_handler (int sig) {}
6082 static signal_handler_t volatile lib_child_handler;
6084 /* Handle a SIGCHLD signal by looking for known child processes of
6085 Emacs whose status have changed. For each one found, record its
6086 new status.
6088 All we do is change the status; we do not run sentinels or print
6089 notifications. That is saved for the next time keyboard input is
6090 done, in order to avoid timing errors.
6092 ** WARNING: this can be called during garbage collection.
6093 Therefore, it must not be fooled by the presence of mark bits in
6094 Lisp objects.
6096 ** USG WARNING: Although it is not obvious from the documentation
6097 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6098 signal() before executing at least one wait(), otherwise the
6099 handler will be called again, resulting in an infinite loop. The
6100 relevant portion of the documentation reads "SIGCLD signals will be
6101 queued and the signal-catching function will be continually
6102 reentered until the queue is empty". Invoking signal() causes the
6103 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6104 Inc.
6106 ** Malloc WARNING: This should never call malloc either directly or
6107 indirectly; if it does, that is a bug */
6109 static void
6110 handle_child_signal (int sig)
6112 Lisp_Object tail;
6114 /* Find the process that signaled us, and record its status. */
6116 /* The process can have been deleted by Fdelete_process, or have
6117 been started asynchronously by Fcall_process. */
6118 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6120 bool all_pids_are_fixnums
6121 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6122 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6123 Lisp_Object xpid = XCAR (tail);
6124 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6126 pid_t deleted_pid;
6127 if (INTEGERP (xpid))
6128 deleted_pid = XINT (xpid);
6129 else
6130 deleted_pid = XFLOAT_DATA (xpid);
6131 if (child_status_changed (deleted_pid, 0, 0))
6132 XSETCAR (tail, Qnil);
6136 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6137 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6139 Lisp_Object proc = XCDR (XCAR (tail));
6140 struct Lisp_Process *p = XPROCESS (proc);
6141 int status;
6143 if (p->alive
6144 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6146 /* Change the status of the process that was found. */
6147 p->tick = ++process_tick;
6148 p->raw_status = status;
6149 p->raw_status_new = 1;
6151 /* If process has terminated, stop waiting for its output. */
6152 if (WIFSIGNALED (status) || WIFEXITED (status))
6154 bool clear_desc_flag = 0;
6155 p->alive = 0;
6156 if (p->infd >= 0)
6157 clear_desc_flag = 1;
6159 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6160 if (clear_desc_flag)
6162 FD_CLR (p->infd, &input_wait_mask);
6163 FD_CLR (p->infd, &non_keyboard_wait_mask);
6169 lib_child_handler (sig);
6170 #ifdef NS_IMPL_GNUSTEP
6171 /* NSTask in GNUStep sets its child handler each time it is called.
6172 So we must re-set ours. */
6173 catch_child_signal();
6174 #endif
6177 static void
6178 deliver_child_signal (int sig)
6180 deliver_process_signal (sig, handle_child_signal);
6184 static Lisp_Object
6185 exec_sentinel_error_handler (Lisp_Object error_val)
6187 cmd_error_internal (error_val, "error in process sentinel: ");
6188 Vinhibit_quit = Qt;
6189 update_echo_area ();
6190 Fsleep_for (make_number (2), Qnil);
6191 return Qt;
6194 static void
6195 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6197 Lisp_Object sentinel, odeactivate;
6198 struct Lisp_Process *p = XPROCESS (proc);
6199 ptrdiff_t count = SPECPDL_INDEX ();
6200 bool outer_running_asynch_code = running_asynch_code;
6201 int waiting = waiting_for_user_input_p;
6203 if (inhibit_sentinels)
6204 return;
6206 /* No need to gcpro these, because all we do with them later
6207 is test them for EQness, and none of them should be a string. */
6208 odeactivate = Vdeactivate_mark;
6209 #if 0
6210 Lisp_Object obuffer, okeymap;
6211 XSETBUFFER (obuffer, current_buffer);
6212 okeymap = BVAR (current_buffer, keymap);
6213 #endif
6215 /* There's no good reason to let sentinels change the current
6216 buffer, and many callers of accept-process-output, sit-for, and
6217 friends don't expect current-buffer to be changed from under them. */
6218 record_unwind_current_buffer ();
6220 sentinel = p->sentinel;
6222 /* Inhibit quit so that random quits don't screw up a running filter. */
6223 specbind (Qinhibit_quit, Qt);
6224 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6226 /* In case we get recursively called,
6227 and we already saved the match data nonrecursively,
6228 save the same match data in safely recursive fashion. */
6229 if (outer_running_asynch_code)
6231 Lisp_Object tem;
6232 tem = Fmatch_data (Qnil, Qnil, Qnil);
6233 restore_search_regs ();
6234 record_unwind_save_match_data ();
6235 Fset_match_data (tem, Qt);
6238 /* For speed, if a search happens within this code,
6239 save the match data in a special nonrecursive fashion. */
6240 running_asynch_code = 1;
6242 internal_condition_case_1 (read_process_output_call,
6243 list3 (sentinel, proc, reason),
6244 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6245 exec_sentinel_error_handler);
6247 /* If we saved the match data nonrecursively, restore it now. */
6248 restore_search_regs ();
6249 running_asynch_code = outer_running_asynch_code;
6251 Vdeactivate_mark = odeactivate;
6253 /* Restore waiting_for_user_input_p as it was
6254 when we were called, in case the filter clobbered it. */
6255 waiting_for_user_input_p = waiting;
6257 #if 0
6258 if (! EQ (Fcurrent_buffer (), obuffer)
6259 || ! EQ (current_buffer->keymap, okeymap))
6260 #endif
6261 /* But do it only if the caller is actually going to read events.
6262 Otherwise there's no need to make him wake up, and it could
6263 cause trouble (for example it would make sit_for return). */
6264 if (waiting_for_user_input_p == -1)
6265 record_asynch_buffer_change ();
6267 unbind_to (count, Qnil);
6270 /* Report all recent events of a change in process status
6271 (either run the sentinel or output a message).
6272 This is usually done while Emacs is waiting for keyboard input
6273 but can be done at other times. */
6275 static void
6276 status_notify (struct Lisp_Process *deleting_process)
6278 register Lisp_Object proc;
6279 Lisp_Object tail, msg;
6280 struct gcpro gcpro1, gcpro2;
6282 tail = Qnil;
6283 msg = Qnil;
6284 /* We need to gcpro tail; if read_process_output calls a filter
6285 which deletes a process and removes the cons to which tail points
6286 from Vprocess_alist, and then causes a GC, tail is an unprotected
6287 reference. */
6288 GCPRO2 (tail, msg);
6290 /* Set this now, so that if new processes are created by sentinels
6291 that we run, we get called again to handle their status changes. */
6292 update_tick = process_tick;
6294 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6296 Lisp_Object symbol;
6297 register struct Lisp_Process *p;
6299 proc = Fcdr (XCAR (tail));
6300 p = XPROCESS (proc);
6302 if (p->tick != p->update_tick)
6304 p->update_tick = p->tick;
6306 /* If process is still active, read any output that remains. */
6307 while (! EQ (p->filter, Qt)
6308 && ! EQ (p->status, Qconnect)
6309 && ! EQ (p->status, Qlisten)
6310 /* Network or serial process not stopped: */
6311 && ! EQ (p->command, Qt)
6312 && p->infd >= 0
6313 && p != deleting_process
6314 && read_process_output (proc, p->infd) > 0);
6316 /* Get the text to use for the message. */
6317 if (p->raw_status_new)
6318 update_status (p);
6319 msg = status_message (p);
6321 /* If process is terminated, deactivate it or delete it. */
6322 symbol = p->status;
6323 if (CONSP (p->status))
6324 symbol = XCAR (p->status);
6326 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6327 || EQ (symbol, Qclosed))
6329 if (delete_exited_processes)
6330 remove_process (proc);
6331 else
6332 deactivate_process (proc);
6335 /* The actions above may have further incremented p->tick.
6336 So set p->update_tick again so that an error in the sentinel will
6337 not cause this code to be run again. */
6338 p->update_tick = p->tick;
6339 /* Now output the message suitably. */
6340 exec_sentinel (proc, msg);
6342 } /* end for */
6344 update_mode_lines++; /* In case buffers use %s in mode-line-format. */
6345 UNGCPRO;
6348 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6349 Sinternal_default_process_sentinel, 2, 2, 0,
6350 doc: /* Function used as default sentinel for processes. */)
6351 (Lisp_Object proc, Lisp_Object msg)
6353 Lisp_Object buffer, symbol;
6354 struct Lisp_Process *p;
6355 CHECK_PROCESS (proc);
6356 p = XPROCESS (proc);
6357 buffer = p->buffer;
6358 symbol = p->status;
6359 if (CONSP (symbol))
6360 symbol = XCAR (symbol);
6362 if (!EQ (symbol, Qrun) && !NILP (buffer))
6364 Lisp_Object tem;
6365 struct buffer *old = current_buffer;
6366 ptrdiff_t opoint, opoint_byte;
6367 ptrdiff_t before, before_byte;
6369 /* Avoid error if buffer is deleted
6370 (probably that's why the process is dead, too). */
6371 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6372 return Qnil;
6373 Fset_buffer (buffer);
6375 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6376 msg = (code_convert_string_norecord
6377 (msg, Vlocale_coding_system, 1));
6379 opoint = PT;
6380 opoint_byte = PT_BYTE;
6381 /* Insert new output into buffer
6382 at the current end-of-output marker,
6383 thus preserving logical ordering of input and output. */
6384 if (XMARKER (p->mark)->buffer)
6385 Fgoto_char (p->mark);
6386 else
6387 SET_PT_BOTH (ZV, ZV_BYTE);
6389 before = PT;
6390 before_byte = PT_BYTE;
6392 tem = BVAR (current_buffer, read_only);
6393 bset_read_only (current_buffer, Qnil);
6394 insert_string ("\nProcess ");
6395 { /* FIXME: temporary kludge. */
6396 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6397 insert_string (" ");
6398 Finsert (1, &msg);
6399 bset_read_only (current_buffer, tem);
6400 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6402 if (opoint >= before)
6403 SET_PT_BOTH (opoint + (PT - before),
6404 opoint_byte + (PT_BYTE - before_byte));
6405 else
6406 SET_PT_BOTH (opoint, opoint_byte);
6408 set_buffer_internal (old);
6410 return Qnil;
6414 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6415 Sset_process_coding_system, 1, 3, 0,
6416 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6417 DECODING will be used to decode subprocess output and ENCODING to
6418 encode subprocess input. */)
6419 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6421 register struct Lisp_Process *p;
6423 CHECK_PROCESS (process);
6424 p = XPROCESS (process);
6425 if (p->infd < 0)
6426 error ("Input file descriptor of %s closed", SDATA (p->name));
6427 if (p->outfd < 0)
6428 error ("Output file descriptor of %s closed", SDATA (p->name));
6429 Fcheck_coding_system (decoding);
6430 Fcheck_coding_system (encoding);
6431 encoding = coding_inherit_eol_type (encoding, Qnil);
6432 pset_decode_coding_system (p, decoding);
6433 pset_encode_coding_system (p, encoding);
6434 setup_process_coding_systems (process);
6436 return Qnil;
6439 DEFUN ("process-coding-system",
6440 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6441 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6442 (register Lisp_Object process)
6444 CHECK_PROCESS (process);
6445 return Fcons (XPROCESS (process)->decode_coding_system,
6446 XPROCESS (process)->encode_coding_system);
6449 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6450 Sset_process_filter_multibyte, 2, 2, 0,
6451 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6452 If FLAG is non-nil, the filter is given multibyte strings.
6453 If FLAG is nil, the filter is given unibyte strings. In this case,
6454 all character code conversion except for end-of-line conversion is
6455 suppressed. */)
6456 (Lisp_Object process, Lisp_Object flag)
6458 register struct Lisp_Process *p;
6460 CHECK_PROCESS (process);
6461 p = XPROCESS (process);
6462 if (NILP (flag))
6463 pset_decode_coding_system
6464 (p, raw_text_coding_system (p->decode_coding_system));
6465 setup_process_coding_systems (process);
6467 return Qnil;
6470 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6471 Sprocess_filter_multibyte_p, 1, 1, 0,
6472 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6473 (Lisp_Object process)
6475 register struct Lisp_Process *p;
6476 struct coding_system *coding;
6478 CHECK_PROCESS (process);
6479 p = XPROCESS (process);
6480 coding = proc_decode_coding_system[p->infd];
6481 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6487 # ifdef HAVE_GPM
6489 void
6490 add_gpm_wait_descriptor (int desc)
6492 add_keyboard_wait_descriptor (desc);
6495 void
6496 delete_gpm_wait_descriptor (int desc)
6498 delete_keyboard_wait_descriptor (desc);
6501 # endif
6503 # ifdef USABLE_SIGIO
6505 /* Return true if *MASK has a bit set
6506 that corresponds to one of the keyboard input descriptors. */
6508 static bool
6509 keyboard_bit_set (fd_set *mask)
6511 int fd;
6513 for (fd = 0; fd <= max_input_desc; fd++)
6514 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6515 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6516 return 1;
6518 return 0;
6520 # endif
6522 #else /* not subprocesses */
6524 /* Defined on msdos.c. */
6525 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6526 EMACS_TIME *, void *);
6528 /* Implementation of wait_reading_process_output, assuming that there
6529 are no subprocesses. Used only by the MS-DOS build.
6531 Wait for timeout to elapse and/or keyboard input to be available.
6533 TIME_LIMIT is:
6534 timeout in seconds
6535 If negative, gobble data immediately available but don't wait for any.
6537 NSECS is:
6538 an additional duration to wait, measured in nanoseconds
6539 If TIME_LIMIT is zero, then:
6540 If NSECS == 0, there is no limit.
6541 If NSECS > 0, the timeout consists of NSECS only.
6542 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6544 READ_KBD is:
6545 0 to ignore keyboard input, or
6546 1 to return when input is available, or
6547 -1 means caller will actually read the input, so don't throw to
6548 the quit handler.
6550 see full version for other parameters. We know that wait_proc will
6551 always be NULL, since `subprocesses' isn't defined.
6553 DO_DISPLAY means redisplay should be done to show subprocess
6554 output that arrives.
6556 Return true if we received input from any process. */
6558 bool
6559 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6560 bool do_display,
6561 Lisp_Object wait_for_cell,
6562 struct Lisp_Process *wait_proc, int just_wait_proc)
6564 register int nfds;
6565 EMACS_TIME end_time, timeout;
6567 if (time_limit < 0)
6569 time_limit = 0;
6570 nsecs = -1;
6572 else if (TYPE_MAXIMUM (time_t) < time_limit)
6573 time_limit = TYPE_MAXIMUM (time_t);
6575 /* What does time_limit really mean? */
6576 if (time_limit || nsecs > 0)
6578 timeout = make_emacs_time (time_limit, nsecs);
6579 end_time = add_emacs_time (current_emacs_time (), timeout);
6582 /* Turn off periodic alarms (in case they are in use)
6583 and then turn off any other atimers,
6584 because the select emulator uses alarms. */
6585 stop_polling ();
6586 turn_on_atimers (0);
6588 while (1)
6590 bool timeout_reduced_for_timers = 0;
6591 SELECT_TYPE waitchannels;
6592 int xerrno;
6594 /* If calling from keyboard input, do not quit
6595 since we want to return C-g as an input character.
6596 Otherwise, do pending quit if requested. */
6597 if (read_kbd >= 0)
6598 QUIT;
6600 /* Exit now if the cell we're waiting for became non-nil. */
6601 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6602 break;
6604 /* Compute time from now till when time limit is up. */
6605 /* Exit if already run out. */
6606 if (nsecs < 0)
6608 /* A negative timeout means
6609 gobble output available now
6610 but don't wait at all. */
6612 timeout = make_emacs_time (0, 0);
6614 else if (time_limit || nsecs > 0)
6616 EMACS_TIME now = current_emacs_time ();
6617 if (EMACS_TIME_LE (end_time, now))
6618 break;
6619 timeout = sub_emacs_time (end_time, now);
6621 else
6623 timeout = make_emacs_time (100000, 0);
6626 /* If our caller will not immediately handle keyboard events,
6627 run timer events directly.
6628 (Callers that will immediately read keyboard events
6629 call timer_delay on their own.) */
6630 if (NILP (wait_for_cell))
6632 EMACS_TIME timer_delay;
6636 unsigned old_timers_run = timers_run;
6637 timer_delay = timer_check ();
6638 if (timers_run != old_timers_run && do_display)
6639 /* We must retry, since a timer may have requeued itself
6640 and that could alter the time delay. */
6641 redisplay_preserve_echo_area (14);
6642 else
6643 break;
6645 while (!detect_input_pending ());
6647 /* If there is unread keyboard input, also return. */
6648 if (read_kbd != 0
6649 && requeued_events_pending_p ())
6650 break;
6652 if (EMACS_TIME_VALID_P (timer_delay) && nsecs >= 0)
6654 if (EMACS_TIME_LT (timer_delay, timeout))
6656 timeout = timer_delay;
6657 timeout_reduced_for_timers = 1;
6662 /* Cause C-g and alarm signals to take immediate action,
6663 and cause input available signals to zero out timeout. */
6664 if (read_kbd < 0)
6665 set_waiting_for_input (&timeout);
6667 /* If a frame has been newly mapped and needs updating,
6668 reprocess its display stuff. */
6669 if (frame_garbaged && do_display)
6671 clear_waiting_for_input ();
6672 redisplay_preserve_echo_area (15);
6673 if (read_kbd < 0)
6674 set_waiting_for_input (&timeout);
6677 /* Wait till there is something to do. */
6678 FD_ZERO (&waitchannels);
6679 if (read_kbd && detect_input_pending ())
6680 nfds = 0;
6681 else
6683 if (read_kbd || !NILP (wait_for_cell))
6684 FD_SET (0, &waitchannels);
6685 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
6688 xerrno = errno;
6690 /* Make C-g and alarm signals set flags again */
6691 clear_waiting_for_input ();
6693 /* If we woke up due to SIGWINCH, actually change size now. */
6694 do_pending_window_change (0);
6696 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
6697 /* We waited the full specified time, so return now. */
6698 break;
6700 if (nfds == -1)
6702 /* If the system call was interrupted, then go around the
6703 loop again. */
6704 if (xerrno == EINTR)
6705 FD_ZERO (&waitchannels);
6706 else
6707 report_file_errno ("Failed select", Qnil, xerrno);
6710 /* Check for keyboard input */
6712 if (read_kbd
6713 && detect_input_pending_run_timers (do_display))
6715 swallow_events (do_display);
6716 if (detect_input_pending_run_timers (do_display))
6717 break;
6720 /* If there is unread keyboard input, also return. */
6721 if (read_kbd
6722 && requeued_events_pending_p ())
6723 break;
6725 /* If wait_for_cell. check for keyboard input
6726 but don't run any timers.
6727 ??? (It seems wrong to me to check for keyboard
6728 input at all when wait_for_cell, but the code
6729 has been this way since July 1994.
6730 Try changing this after version 19.31.) */
6731 if (! NILP (wait_for_cell)
6732 && detect_input_pending ())
6734 swallow_events (do_display);
6735 if (detect_input_pending ())
6736 break;
6739 /* Exit now if the cell we're waiting for became non-nil. */
6740 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6741 break;
6744 start_polling ();
6746 return 0;
6749 #endif /* not subprocesses */
6751 /* The following functions are needed even if async subprocesses are
6752 not supported. Some of them are no-op stubs in that case. */
6754 /* Add DESC to the set of keyboard input descriptors. */
6756 void
6757 add_keyboard_wait_descriptor (int desc)
6759 #ifdef subprocesses /* actually means "not MSDOS" */
6760 FD_SET (desc, &input_wait_mask);
6761 FD_SET (desc, &non_process_wait_mask);
6762 if (desc > max_input_desc)
6763 max_input_desc = desc;
6764 #endif
6767 /* From now on, do not expect DESC to give keyboard input. */
6769 void
6770 delete_keyboard_wait_descriptor (int desc)
6772 #ifdef subprocesses
6773 FD_CLR (desc, &input_wait_mask);
6774 FD_CLR (desc, &non_process_wait_mask);
6775 delete_input_desc (desc);
6776 #endif
6779 /* Setup coding systems of PROCESS. */
6781 void
6782 setup_process_coding_systems (Lisp_Object process)
6784 #ifdef subprocesses
6785 struct Lisp_Process *p = XPROCESS (process);
6786 int inch = p->infd;
6787 int outch = p->outfd;
6788 Lisp_Object coding_system;
6790 if (inch < 0 || outch < 0)
6791 return;
6793 if (!proc_decode_coding_system[inch])
6794 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
6795 coding_system = p->decode_coding_system;
6796 if (EQ (p->filter, Qinternal_default_process_filter)
6797 && BUFFERP (p->buffer))
6799 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
6800 coding_system = raw_text_coding_system (coding_system);
6802 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
6804 if (!proc_encode_coding_system[outch])
6805 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
6806 setup_coding_system (p->encode_coding_system,
6807 proc_encode_coding_system[outch]);
6808 #endif
6811 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
6812 doc: /* Return the (or a) process associated with BUFFER.
6813 BUFFER may be a buffer or the name of one. */)
6814 (register Lisp_Object buffer)
6816 #ifdef subprocesses
6817 register Lisp_Object buf, tail, proc;
6819 if (NILP (buffer)) return Qnil;
6820 buf = Fget_buffer (buffer);
6821 if (NILP (buf)) return Qnil;
6823 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6825 proc = Fcdr (XCAR (tail));
6826 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
6827 return proc;
6829 #endif /* subprocesses */
6830 return Qnil;
6833 DEFUN ("process-inherit-coding-system-flag",
6834 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
6835 1, 1, 0,
6836 doc: /* Return the value of inherit-coding-system flag for PROCESS.
6837 If this flag is t, `buffer-file-coding-system' of the buffer
6838 associated with PROCESS will inherit the coding system used to decode
6839 the process output. */)
6840 (register Lisp_Object process)
6842 #ifdef subprocesses
6843 CHECK_PROCESS (process);
6844 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
6845 #else
6846 /* Ignore the argument and return the value of
6847 inherit-process-coding-system. */
6848 return inherit_process_coding_system ? Qt : Qnil;
6849 #endif
6852 /* Kill all processes associated with `buffer'.
6853 If `buffer' is nil, kill all processes */
6855 void
6856 kill_buffer_processes (Lisp_Object buffer)
6858 #ifdef subprocesses
6859 Lisp_Object tail, proc;
6861 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6863 proc = XCDR (XCAR (tail));
6864 if (PROCESSP (proc)
6865 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
6867 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6868 Fdelete_process (proc);
6869 else if (XPROCESS (proc)->infd >= 0)
6870 process_send_signal (proc, SIGHUP, Qnil, 1);
6873 #else /* subprocesses */
6874 /* Since we have no subprocesses, this does nothing. */
6875 #endif /* subprocesses */
6878 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
6879 Swaiting_for_user_input_p, 0, 0, 0,
6880 doc: /* Return non-nil if Emacs is waiting for input from the user.
6881 This is intended for use by asynchronous process output filters and sentinels. */)
6882 (void)
6884 #ifdef subprocesses
6885 return (waiting_for_user_input_p ? Qt : Qnil);
6886 #else
6887 return Qnil;
6888 #endif
6891 /* Stop reading input from keyboard sources. */
6893 void
6894 hold_keyboard_input (void)
6896 kbd_is_on_hold = 1;
6899 /* Resume reading input from keyboard sources. */
6901 void
6902 unhold_keyboard_input (void)
6904 kbd_is_on_hold = 0;
6907 /* Return true if keyboard input is on hold, zero otherwise. */
6909 bool
6910 kbd_on_hold_p (void)
6912 return kbd_is_on_hold;
6916 /* Enumeration of and access to system processes a-la ps(1). */
6918 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
6919 0, 0, 0,
6920 doc: /* Return a list of numerical process IDs of all running processes.
6921 If this functionality is unsupported, return nil.
6923 See `process-attributes' for getting attributes of a process given its ID. */)
6924 (void)
6926 return list_system_processes ();
6929 DEFUN ("process-attributes", Fprocess_attributes,
6930 Sprocess_attributes, 1, 1, 0,
6931 doc: /* Return attributes of the process given by its PID, a number.
6933 Value is an alist where each element is a cons cell of the form
6935 \(KEY . VALUE)
6937 If this functionality is unsupported, the value is nil.
6939 See `list-system-processes' for getting a list of all process IDs.
6941 The KEYs of the attributes that this function may return are listed
6942 below, together with the type of the associated VALUE (in parentheses).
6943 Not all platforms support all of these attributes; unsupported
6944 attributes will not appear in the returned alist.
6945 Unless explicitly indicated otherwise, numbers can have either
6946 integer or floating point values.
6948 euid -- Effective user User ID of the process (number)
6949 user -- User name corresponding to euid (string)
6950 egid -- Effective user Group ID of the process (number)
6951 group -- Group name corresponding to egid (string)
6952 comm -- Command name (executable name only) (string)
6953 state -- Process state code, such as "S", "R", or "T" (string)
6954 ppid -- Parent process ID (number)
6955 pgrp -- Process group ID (number)
6956 sess -- Session ID, i.e. process ID of session leader (number)
6957 ttname -- Controlling tty name (string)
6958 tpgid -- ID of foreground process group on the process's tty (number)
6959 minflt -- number of minor page faults (number)
6960 majflt -- number of major page faults (number)
6961 cminflt -- cumulative number of minor page faults (number)
6962 cmajflt -- cumulative number of major page faults (number)
6963 utime -- user time used by the process, in (current-time) format,
6964 which is a list of integers (HIGH LOW USEC PSEC)
6965 stime -- system time used by the process (current-time)
6966 time -- sum of utime and stime (current-time)
6967 cutime -- user time used by the process and its children (current-time)
6968 cstime -- system time used by the process and its children (current-time)
6969 ctime -- sum of cutime and cstime (current-time)
6970 pri -- priority of the process (number)
6971 nice -- nice value of the process (number)
6972 thcount -- process thread count (number)
6973 start -- time the process started (current-time)
6974 vsize -- virtual memory size of the process in KB's (number)
6975 rss -- resident set size of the process in KB's (number)
6976 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
6977 pcpu -- percents of CPU time used by the process (floating-point number)
6978 pmem -- percents of total physical memory used by process's resident set
6979 (floating-point number)
6980 args -- command line which invoked the process (string). */)
6981 ( Lisp_Object pid)
6983 return system_process_attributes (pid);
6986 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
6987 Invoke this after init_process_emacs, and after glib and/or GNUstep
6988 futz with the SIGCHLD handler, but before Emacs forks any children.
6989 This function's caller should block SIGCHLD. */
6991 #ifndef NS_IMPL_GNUSTEP
6992 static
6993 #endif
6994 void
6995 catch_child_signal (void)
6997 struct sigaction action, old_action;
6998 emacs_sigaction_init (&action, deliver_child_signal);
6999 block_child_signal ();
7000 sigaction (SIGCHLD, &action, &old_action);
7001 eassert (! (old_action.sa_flags & SA_SIGINFO));
7003 if (old_action.sa_handler != deliver_child_signal)
7004 lib_child_handler
7005 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7006 ? dummy_handler
7007 : old_action.sa_handler);
7008 unblock_child_signal ();
7012 /* This is not called "init_process" because that is the name of a
7013 Mach system call, so it would cause problems on Darwin systems. */
7014 void
7015 init_process_emacs (void)
7017 #ifdef subprocesses
7018 register int i;
7020 inhibit_sentinels = 0;
7022 #ifndef CANNOT_DUMP
7023 if (! noninteractive || initialized)
7024 #endif
7026 #if defined HAVE_GLIB && !defined WINDOWSNT
7027 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7028 this should always fail, but is enough to initialize glib's
7029 private SIGCHLD handler, allowing catch_child_signal to copy
7030 it into lib_child_handler. */
7031 g_source_unref (g_child_watch_source_new (getpid ()));
7032 #endif
7033 catch_child_signal ();
7036 FD_ZERO (&input_wait_mask);
7037 FD_ZERO (&non_keyboard_wait_mask);
7038 FD_ZERO (&non_process_wait_mask);
7039 FD_ZERO (&write_mask);
7040 max_process_desc = max_input_desc = -1;
7041 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7043 #ifdef NON_BLOCKING_CONNECT
7044 FD_ZERO (&connect_wait_mask);
7045 num_pending_connects = 0;
7046 #endif
7048 #ifdef ADAPTIVE_READ_BUFFERING
7049 process_output_delay_count = 0;
7050 process_output_skip = 0;
7051 #endif
7053 /* Don't do this, it caused infinite select loops. The display
7054 method should call add_keyboard_wait_descriptor on stdin if it
7055 needs that. */
7056 #if 0
7057 FD_SET (0, &input_wait_mask);
7058 #endif
7060 Vprocess_alist = Qnil;
7061 deleted_pid_list = Qnil;
7062 for (i = 0; i < MAXDESC; i++)
7064 chan_process[i] = Qnil;
7065 proc_buffered_char[i] = -1;
7067 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7068 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7069 #ifdef DATAGRAM_SOCKETS
7070 memset (datagram_address, 0, sizeof datagram_address);
7071 #endif
7074 Lisp_Object subfeatures = Qnil;
7075 const struct socket_options *sopt;
7077 #define ADD_SUBFEATURE(key, val) \
7078 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7080 #ifdef NON_BLOCKING_CONNECT
7081 ADD_SUBFEATURE (QCnowait, Qt);
7082 #endif
7083 #ifdef DATAGRAM_SOCKETS
7084 ADD_SUBFEATURE (QCtype, Qdatagram);
7085 #endif
7086 #ifdef HAVE_SEQPACKET
7087 ADD_SUBFEATURE (QCtype, Qseqpacket);
7088 #endif
7089 #ifdef HAVE_LOCAL_SOCKETS
7090 ADD_SUBFEATURE (QCfamily, Qlocal);
7091 #endif
7092 ADD_SUBFEATURE (QCfamily, Qipv4);
7093 #ifdef AF_INET6
7094 ADD_SUBFEATURE (QCfamily, Qipv6);
7095 #endif
7096 #ifdef HAVE_GETSOCKNAME
7097 ADD_SUBFEATURE (QCservice, Qt);
7098 #endif
7099 ADD_SUBFEATURE (QCserver, Qt);
7101 for (sopt = socket_options; sopt->name; sopt++)
7102 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7104 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7107 #if defined (DARWIN_OS)
7108 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7109 processes. As such, we only change the default value. */
7110 if (initialized)
7112 char const *release = (STRINGP (Voperating_system_release)
7113 ? SSDATA (Voperating_system_release)
7114 : 0);
7115 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7116 Vprocess_connection_type = Qnil;
7119 #endif
7120 #endif /* subprocesses */
7121 kbd_is_on_hold = 0;
7124 void
7125 syms_of_process (void)
7127 #ifdef subprocesses
7129 DEFSYM (Qprocessp, "processp");
7130 DEFSYM (Qrun, "run");
7131 DEFSYM (Qstop, "stop");
7132 DEFSYM (Qsignal, "signal");
7134 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7135 here again.
7137 Qexit = intern_c_string ("exit");
7138 staticpro (&Qexit); */
7140 DEFSYM (Qopen, "open");
7141 DEFSYM (Qclosed, "closed");
7142 DEFSYM (Qconnect, "connect");
7143 DEFSYM (Qfailed, "failed");
7144 DEFSYM (Qlisten, "listen");
7145 DEFSYM (Qlocal, "local");
7146 DEFSYM (Qipv4, "ipv4");
7147 #ifdef AF_INET6
7148 DEFSYM (Qipv6, "ipv6");
7149 #endif
7150 DEFSYM (Qdatagram, "datagram");
7151 DEFSYM (Qseqpacket, "seqpacket");
7153 DEFSYM (QCport, ":port");
7154 DEFSYM (QCspeed, ":speed");
7155 DEFSYM (QCprocess, ":process");
7157 DEFSYM (QCbytesize, ":bytesize");
7158 DEFSYM (QCstopbits, ":stopbits");
7159 DEFSYM (QCparity, ":parity");
7160 DEFSYM (Qodd, "odd");
7161 DEFSYM (Qeven, "even");
7162 DEFSYM (QCflowcontrol, ":flowcontrol");
7163 DEFSYM (Qhw, "hw");
7164 DEFSYM (Qsw, "sw");
7165 DEFSYM (QCsummary, ":summary");
7167 DEFSYM (Qreal, "real");
7168 DEFSYM (Qnetwork, "network");
7169 DEFSYM (Qserial, "serial");
7170 DEFSYM (QCbuffer, ":buffer");
7171 DEFSYM (QChost, ":host");
7172 DEFSYM (QCservice, ":service");
7173 DEFSYM (QClocal, ":local");
7174 DEFSYM (QCremote, ":remote");
7175 DEFSYM (QCcoding, ":coding");
7176 DEFSYM (QCserver, ":server");
7177 DEFSYM (QCnowait, ":nowait");
7178 DEFSYM (QCsentinel, ":sentinel");
7179 DEFSYM (QClog, ":log");
7180 DEFSYM (QCnoquery, ":noquery");
7181 DEFSYM (QCstop, ":stop");
7182 DEFSYM (QCoptions, ":options");
7183 DEFSYM (QCplist, ":plist");
7185 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7187 staticpro (&Vprocess_alist);
7188 staticpro (&deleted_pid_list);
7190 #endif /* subprocesses */
7192 DEFSYM (QCname, ":name");
7193 DEFSYM (QCtype, ":type");
7195 DEFSYM (Qeuid, "euid");
7196 DEFSYM (Qegid, "egid");
7197 DEFSYM (Quser, "user");
7198 DEFSYM (Qgroup, "group");
7199 DEFSYM (Qcomm, "comm");
7200 DEFSYM (Qstate, "state");
7201 DEFSYM (Qppid, "ppid");
7202 DEFSYM (Qpgrp, "pgrp");
7203 DEFSYM (Qsess, "sess");
7204 DEFSYM (Qttname, "ttname");
7205 DEFSYM (Qtpgid, "tpgid");
7206 DEFSYM (Qminflt, "minflt");
7207 DEFSYM (Qmajflt, "majflt");
7208 DEFSYM (Qcminflt, "cminflt");
7209 DEFSYM (Qcmajflt, "cmajflt");
7210 DEFSYM (Qutime, "utime");
7211 DEFSYM (Qstime, "stime");
7212 DEFSYM (Qtime, "time");
7213 DEFSYM (Qcutime, "cutime");
7214 DEFSYM (Qcstime, "cstime");
7215 DEFSYM (Qctime, "ctime");
7216 DEFSYM (Qinternal_default_process_sentinel,
7217 "internal-default-process-sentinel");
7218 DEFSYM (Qinternal_default_process_filter,
7219 "internal-default-process-filter");
7220 DEFSYM (Qpri, "pri");
7221 DEFSYM (Qnice, "nice");
7222 DEFSYM (Qthcount, "thcount");
7223 DEFSYM (Qstart, "start");
7224 DEFSYM (Qvsize, "vsize");
7225 DEFSYM (Qrss, "rss");
7226 DEFSYM (Qetime, "etime");
7227 DEFSYM (Qpcpu, "pcpu");
7228 DEFSYM (Qpmem, "pmem");
7229 DEFSYM (Qargs, "args");
7231 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7232 doc: /* Non-nil means delete processes immediately when they exit.
7233 A value of nil means don't delete them until `list-processes' is run. */);
7235 delete_exited_processes = 1;
7237 #ifdef subprocesses
7238 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7239 doc: /* Control type of device used to communicate with subprocesses.
7240 Values are nil to use a pipe, or t or `pty' to use a pty.
7241 The value has no effect if the system has no ptys or if all ptys are busy:
7242 then a pipe is used in any case.
7243 The value takes effect when `start-process' is called. */);
7244 Vprocess_connection_type = Qt;
7246 #ifdef ADAPTIVE_READ_BUFFERING
7247 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7248 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7249 On some systems, when Emacs reads the output from a subprocess, the output data
7250 is read in very small blocks, potentially resulting in very poor performance.
7251 This behavior can be remedied to some extent by setting this variable to a
7252 non-nil value, as it will automatically delay reading from such processes, to
7253 allow them to produce more output before Emacs tries to read it.
7254 If the value is t, the delay is reset after each write to the process; any other
7255 non-nil value means that the delay is not reset on write.
7256 The variable takes effect when `start-process' is called. */);
7257 Vprocess_adaptive_read_buffering = Qt;
7258 #endif
7260 defsubr (&Sprocessp);
7261 defsubr (&Sget_process);
7262 defsubr (&Sdelete_process);
7263 defsubr (&Sprocess_status);
7264 defsubr (&Sprocess_exit_status);
7265 defsubr (&Sprocess_id);
7266 defsubr (&Sprocess_name);
7267 defsubr (&Sprocess_tty_name);
7268 defsubr (&Sprocess_command);
7269 defsubr (&Sset_process_buffer);
7270 defsubr (&Sprocess_buffer);
7271 defsubr (&Sprocess_mark);
7272 defsubr (&Sset_process_filter);
7273 defsubr (&Sprocess_filter);
7274 defsubr (&Sset_process_sentinel);
7275 defsubr (&Sprocess_sentinel);
7276 defsubr (&Sset_process_window_size);
7277 defsubr (&Sset_process_inherit_coding_system_flag);
7278 defsubr (&Sset_process_query_on_exit_flag);
7279 defsubr (&Sprocess_query_on_exit_flag);
7280 defsubr (&Sprocess_contact);
7281 defsubr (&Sprocess_plist);
7282 defsubr (&Sset_process_plist);
7283 defsubr (&Sprocess_list);
7284 defsubr (&Sstart_process);
7285 defsubr (&Sserial_process_configure);
7286 defsubr (&Smake_serial_process);
7287 defsubr (&Sset_network_process_option);
7288 defsubr (&Smake_network_process);
7289 defsubr (&Sformat_network_address);
7290 #if defined (HAVE_NET_IF_H)
7291 #ifdef SIOCGIFCONF
7292 defsubr (&Snetwork_interface_list);
7293 #endif
7294 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
7295 defsubr (&Snetwork_interface_info);
7296 #endif
7297 #endif /* defined (HAVE_NET_IF_H) */
7298 #ifdef DATAGRAM_SOCKETS
7299 defsubr (&Sprocess_datagram_address);
7300 defsubr (&Sset_process_datagram_address);
7301 #endif
7302 defsubr (&Saccept_process_output);
7303 defsubr (&Sprocess_send_region);
7304 defsubr (&Sprocess_send_string);
7305 defsubr (&Sinterrupt_process);
7306 defsubr (&Skill_process);
7307 defsubr (&Squit_process);
7308 defsubr (&Sstop_process);
7309 defsubr (&Scontinue_process);
7310 defsubr (&Sprocess_running_child_p);
7311 defsubr (&Sprocess_send_eof);
7312 defsubr (&Ssignal_process);
7313 defsubr (&Swaiting_for_user_input_p);
7314 defsubr (&Sprocess_type);
7315 defsubr (&Sinternal_default_process_sentinel);
7316 defsubr (&Sinternal_default_process_filter);
7317 defsubr (&Sset_process_coding_system);
7318 defsubr (&Sprocess_coding_system);
7319 defsubr (&Sset_process_filter_multibyte);
7320 defsubr (&Sprocess_filter_multibyte_p);
7322 #endif /* subprocesses */
7324 defsubr (&Sget_buffer_process);
7325 defsubr (&Sprocess_inherit_coding_system_flag);
7326 defsubr (&Slist_system_processes);
7327 defsubr (&Sprocess_attributes);