* info.el (Info-try-follow-nearest-node): Move search for footnote
[emacs.git] / src / process.c
blob3f062b6db16a3fb6c0eeeeeb0e4eaa529c160fd8
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 <netinet/in.h>
82 #include <arpa/nameser.h>
83 #include <resolv.h>
84 #endif
86 #ifdef HAVE_UTIL_H
87 #include <util.h>
88 #endif
90 #ifdef HAVE_PTY_H
91 #include <pty.h>
92 #endif
94 #include <c-ctype.h>
95 #include <sig2str.h>
97 #endif /* subprocesses */
99 #include "systime.h"
100 #include "systty.h"
102 #include "window.h"
103 #include "character.h"
104 #include "buffer.h"
105 #include "coding.h"
106 #include "process.h"
107 #include "frame.h"
108 #include "termhooks.h"
109 #include "termopts.h"
110 #include "commands.h"
111 #include "keyboard.h"
112 #include "blockinput.h"
113 #include "dispextern.h"
114 #include "composite.h"
115 #include "atimer.h"
116 #include "sysselect.h"
117 #include "syssignal.h"
118 #include "syswait.h"
119 #ifdef HAVE_GNUTLS
120 #include "gnutls.h"
121 #endif
123 #ifdef HAVE_WINDOW_SYSTEM
124 #include TERM_HEADER
125 #endif /* HAVE_WINDOW_SYSTEM */
127 #ifdef HAVE_GLIB
128 #include "xgselect.h"
129 #ifndef WINDOWSNT
130 #include <glib.h>
131 #endif
132 #endif
134 #ifdef WINDOWSNT
135 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
136 EMACS_TIME *, void *);
137 #endif
139 /* Work around GCC 4.7.0 bug with strict overflow checking; see
140 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
141 These lines can be removed once the GCC bug is fixed. */
142 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
143 # pragma GCC diagnostic ignored "-Wstrict-overflow"
144 #endif
146 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
147 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
148 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
149 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
150 Lisp_Object QCname, QCtype;
152 /* True if keyboard input is on hold, zero otherwise. */
154 static bool kbd_is_on_hold;
156 /* Nonzero means don't run process sentinels. This is used
157 when exiting. */
158 bool inhibit_sentinels;
160 #ifdef subprocesses
162 Lisp_Object Qprocessp;
163 static Lisp_Object Qrun, Qstop, Qsignal;
164 static Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
165 Lisp_Object Qlocal;
166 static Lisp_Object Qipv4, Qdatagram, Qseqpacket;
167 static Lisp_Object Qreal, Qnetwork, Qserial;
168 #ifdef AF_INET6
169 static Lisp_Object Qipv6;
170 #endif
171 static Lisp_Object QCport, QCprocess;
172 Lisp_Object QCspeed;
173 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
174 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
175 static Lisp_Object QCbuffer, QChost, QCservice;
176 static Lisp_Object QClocal, QCremote, QCcoding;
177 static Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
178 static Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
179 static Lisp_Object Qlast_nonmenu_event;
180 static Lisp_Object Qinternal_default_process_sentinel;
181 static Lisp_Object Qinternal_default_process_filter;
183 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
184 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
185 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
186 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
188 /* Number of events of change of status of a process. */
189 static EMACS_INT process_tick;
190 /* Number of events for which the user or sentinel has been notified. */
191 static EMACS_INT update_tick;
193 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
195 /* Only W32 has this, it really means that select can't take write mask. */
196 #ifdef BROKEN_NON_BLOCKING_CONNECT
197 #undef NON_BLOCKING_CONNECT
198 #define SELECT_CANT_DO_WRITE_MASK
199 #else
200 #ifndef NON_BLOCKING_CONNECT
201 #ifdef HAVE_SELECT
202 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
203 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
204 #define NON_BLOCKING_CONNECT
205 #endif /* EWOULDBLOCK || EINPROGRESS */
206 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
207 #endif /* HAVE_SELECT */
208 #endif /* NON_BLOCKING_CONNECT */
209 #endif /* BROKEN_NON_BLOCKING_CONNECT */
211 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
212 this system. We need to read full packets, so we need a
213 "non-destructive" select. So we require either native select,
214 or emulation of select using FIONREAD. */
216 #ifndef BROKEN_DATAGRAM_SOCKETS
217 # if defined HAVE_SELECT || defined USABLE_FIONREAD
218 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
219 # define DATAGRAM_SOCKETS
220 # endif
221 # endif
222 #endif
224 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
225 # define HAVE_SEQPACKET
226 #endif
228 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
229 #define ADAPTIVE_READ_BUFFERING
230 #endif
232 #ifdef ADAPTIVE_READ_BUFFERING
233 #define READ_OUTPUT_DELAY_INCREMENT (EMACS_TIME_RESOLUTION / 100)
234 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
235 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
237 /* Number of processes which have a non-zero read_output_delay,
238 and therefore might be delayed for adaptive read buffering. */
240 static int process_output_delay_count;
242 /* True if any process has non-nil read_output_skip. */
244 static bool process_output_skip;
246 #else
247 #define process_output_delay_count 0
248 #endif
250 static void create_process (Lisp_Object, char **, Lisp_Object);
251 #ifdef USABLE_SIGIO
252 static bool keyboard_bit_set (SELECT_TYPE *);
253 #endif
254 static void deactivate_process (Lisp_Object);
255 static void status_notify (struct Lisp_Process *);
256 static int read_process_output (Lisp_Object, int);
257 static void handle_child_signal (int);
258 static void create_pty (Lisp_Object);
260 /* If we support a window system, turn on the code to poll periodically
261 to detect C-g. It isn't actually used when doing interrupt input. */
262 #ifdef HAVE_WINDOW_SYSTEM
263 #define POLL_FOR_INPUT
264 #endif
266 static Lisp_Object get_process (register Lisp_Object name);
267 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
269 /* Mask of bits indicating the descriptors that we wait for input on. */
271 static SELECT_TYPE input_wait_mask;
273 /* Mask that excludes keyboard input descriptor(s). */
275 static SELECT_TYPE non_keyboard_wait_mask;
277 /* Mask that excludes process input descriptor(s). */
279 static SELECT_TYPE non_process_wait_mask;
281 /* Mask for selecting for write. */
283 static SELECT_TYPE write_mask;
285 #ifdef NON_BLOCKING_CONNECT
286 /* Mask of bits indicating the descriptors that we wait for connect to
287 complete on. Once they complete, they are removed from this mask
288 and added to the input_wait_mask and non_keyboard_wait_mask. */
290 static SELECT_TYPE connect_wait_mask;
292 /* Number of bits set in connect_wait_mask. */
293 static int num_pending_connects;
294 #endif /* NON_BLOCKING_CONNECT */
296 /* The largest descriptor currently in use for a process object. */
297 static int max_process_desc;
299 /* The largest descriptor currently in use for input. */
300 static int max_input_desc;
302 /* Indexed by descriptor, gives the process (if any) for that descriptor */
303 static Lisp_Object chan_process[MAXDESC];
305 /* Alist of elements (NAME . PROCESS) */
306 static Lisp_Object Vprocess_alist;
308 /* Buffered-ahead input char from process, indexed by channel.
309 -1 means empty (no char is buffered).
310 Used on sys V where the only way to tell if there is any
311 output from the process is to read at least one char.
312 Always -1 on systems that support FIONREAD. */
314 static int proc_buffered_char[MAXDESC];
316 /* Table of `struct coding-system' for each process. */
317 static struct coding_system *proc_decode_coding_system[MAXDESC];
318 static struct coding_system *proc_encode_coding_system[MAXDESC];
320 #ifdef DATAGRAM_SOCKETS
321 /* Table of `partner address' for datagram sockets. */
322 static struct sockaddr_and_len {
323 struct sockaddr *sa;
324 int len;
325 } datagram_address[MAXDESC];
326 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
327 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
328 #else
329 #define DATAGRAM_CHAN_P(chan) (0)
330 #define DATAGRAM_CONN_P(proc) (0)
331 #endif
333 /* These setters are used only in this file, so they can be private. */
334 static void
335 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
337 p->buffer = val;
339 static void
340 pset_command (struct Lisp_Process *p, Lisp_Object val)
342 p->command = val;
344 static void
345 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
347 p->decode_coding_system = val;
349 static void
350 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
352 p->decoding_buf = val;
354 static void
355 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
357 p->encode_coding_system = val;
359 static void
360 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
362 p->encoding_buf = val;
364 static void
365 pset_filter (struct Lisp_Process *p, Lisp_Object val)
367 p->filter = NILP (val) ? Qinternal_default_process_filter : val;
369 static void
370 pset_log (struct Lisp_Process *p, Lisp_Object val)
372 p->log = val;
374 static void
375 pset_mark (struct Lisp_Process *p, Lisp_Object val)
377 p->mark = val;
379 static void
380 pset_name (struct Lisp_Process *p, Lisp_Object val)
382 p->name = val;
384 static void
385 pset_plist (struct Lisp_Process *p, Lisp_Object val)
387 p->plist = val;
389 static void
390 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
392 p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
394 static void
395 pset_status (struct Lisp_Process *p, Lisp_Object val)
397 p->status = val;
399 static void
400 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
402 p->tty_name = val;
404 static void
405 pset_type (struct Lisp_Process *p, Lisp_Object val)
407 p->type = val;
409 static void
410 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
412 p->write_queue = val;
417 static struct fd_callback_data
419 fd_callback func;
420 void *data;
421 #define FOR_READ 1
422 #define FOR_WRITE 2
423 int condition; /* mask of the defines above. */
424 } fd_callback_info[MAXDESC];
427 /* Add a file descriptor FD to be monitored for when read is possible.
428 When read is possible, call FUNC with argument DATA. */
430 void
431 add_read_fd (int fd, fd_callback func, void *data)
433 eassert (fd < MAXDESC);
434 add_keyboard_wait_descriptor (fd);
436 fd_callback_info[fd].func = func;
437 fd_callback_info[fd].data = data;
438 fd_callback_info[fd].condition |= FOR_READ;
441 /* Stop monitoring file descriptor FD for when read is possible. */
443 void
444 delete_read_fd (int fd)
446 eassert (fd < MAXDESC);
447 delete_keyboard_wait_descriptor (fd);
449 fd_callback_info[fd].condition &= ~FOR_READ;
450 if (fd_callback_info[fd].condition == 0)
452 fd_callback_info[fd].func = 0;
453 fd_callback_info[fd].data = 0;
457 /* Add a file descriptor FD to be monitored for when write is possible.
458 When write is possible, call FUNC with argument DATA. */
460 void
461 add_write_fd (int fd, fd_callback func, void *data)
463 eassert (fd < MAXDESC);
464 FD_SET (fd, &write_mask);
465 if (fd > max_input_desc)
466 max_input_desc = fd;
468 fd_callback_info[fd].func = func;
469 fd_callback_info[fd].data = data;
470 fd_callback_info[fd].condition |= FOR_WRITE;
473 /* Stop monitoring file descriptor FD for when write is possible. */
475 void
476 delete_write_fd (int fd)
478 int lim = max_input_desc;
480 eassert (fd < MAXDESC);
481 FD_CLR (fd, &write_mask);
482 fd_callback_info[fd].condition &= ~FOR_WRITE;
483 if (fd_callback_info[fd].condition == 0)
485 fd_callback_info[fd].func = 0;
486 fd_callback_info[fd].data = 0;
488 if (fd == max_input_desc)
489 for (fd = lim; fd >= 0; fd--)
490 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
492 max_input_desc = fd;
493 break;
500 /* Compute the Lisp form of the process status, p->status, from
501 the numeric status that was returned by `wait'. */
503 static Lisp_Object status_convert (int);
505 static void
506 update_status (struct Lisp_Process *p)
508 eassert (p->raw_status_new);
509 pset_status (p, status_convert (p->raw_status));
510 p->raw_status_new = 0;
513 /* Convert a process status word in Unix format to
514 the list that we use internally. */
516 static Lisp_Object
517 status_convert (int w)
519 if (WIFSTOPPED (w))
520 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
521 else if (WIFEXITED (w))
522 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
523 WCOREDUMP (w) ? Qt : Qnil));
524 else if (WIFSIGNALED (w))
525 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
526 WCOREDUMP (w) ? Qt : Qnil));
527 else
528 return Qrun;
531 /* Given a status-list, extract the three pieces of information
532 and store them individually through the three pointers. */
534 static void
535 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, bool *coredump)
537 Lisp_Object tem;
539 if (SYMBOLP (l))
541 *symbol = l;
542 *code = 0;
543 *coredump = 0;
545 else
547 *symbol = XCAR (l);
548 tem = XCDR (l);
549 *code = XFASTINT (XCAR (tem));
550 tem = XCDR (tem);
551 *coredump = !NILP (tem);
555 /* Return a string describing a process status list. */
557 static Lisp_Object
558 status_message (struct Lisp_Process *p)
560 Lisp_Object status = p->status;
561 Lisp_Object symbol;
562 int code;
563 bool coredump;
564 Lisp_Object string, string2;
566 decode_status (status, &symbol, &code, &coredump);
568 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
570 char const *signame;
571 synchronize_system_messages_locale ();
572 signame = strsignal (code);
573 if (signame == 0)
574 string = build_string ("unknown");
575 else
577 int c1, c2;
579 string = build_unibyte_string (signame);
580 if (! NILP (Vlocale_coding_system))
581 string = (code_convert_string_norecord
582 (string, Vlocale_coding_system, 0));
583 c1 = STRING_CHAR (SDATA (string));
584 c2 = downcase (c1);
585 if (c1 != c2)
586 Faset (string, make_number (0), make_number (c2));
588 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
589 return concat2 (string, string2);
591 else if (EQ (symbol, Qexit))
593 if (NETCONN1_P (p))
594 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
595 if (code == 0)
596 return build_string ("finished\n");
597 string = Fnumber_to_string (make_number (code));
598 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
599 return concat3 (build_string ("exited abnormally with code "),
600 string, string2);
602 else if (EQ (symbol, Qfailed))
604 string = Fnumber_to_string (make_number (code));
605 string2 = build_string ("\n");
606 return concat3 (build_string ("failed with code "),
607 string, string2);
609 else
610 return Fcopy_sequence (Fsymbol_name (symbol));
613 #ifdef HAVE_PTYS
615 /* The file name of the pty opened by allocate_pty. */
616 static char pty_name[24];
618 /* Open an available pty, returning a file descriptor.
619 Return -1 on failure.
620 The file name of the terminal corresponding to the pty
621 is left in the variable pty_name. */
623 static int
624 allocate_pty (void)
626 int fd;
628 #ifdef PTY_ITERATION
629 PTY_ITERATION
630 #else
631 register int c, i;
632 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
633 for (i = 0; i < 16; i++)
634 #endif
636 #ifdef PTY_NAME_SPRINTF
637 PTY_NAME_SPRINTF
638 #else
639 sprintf (pty_name, "/dev/pty%c%x", c, i);
640 #endif /* no PTY_NAME_SPRINTF */
642 #ifdef PTY_OPEN
643 PTY_OPEN;
644 #else /* no PTY_OPEN */
645 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
646 #endif /* no PTY_OPEN */
648 if (fd >= 0)
650 /* check to make certain that both sides are available
651 this avoids a nasty yet stupid bug in rlogins */
652 #ifdef PTY_TTY_NAME_SPRINTF
653 PTY_TTY_NAME_SPRINTF
654 #else
655 sprintf (pty_name, "/dev/tty%c%x", c, i);
656 #endif /* no PTY_TTY_NAME_SPRINTF */
657 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
659 emacs_close (fd);
660 # ifndef __sgi
661 continue;
662 # else
663 return -1;
664 # endif /* __sgi */
666 setup_pty (fd);
667 return fd;
670 return -1;
672 #endif /* HAVE_PTYS */
674 static Lisp_Object
675 make_process (Lisp_Object name)
677 register Lisp_Object val, tem, name1;
678 register struct Lisp_Process *p;
679 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
680 printmax_t i;
682 p = allocate_process ();
683 /* Initialize Lisp data. Note that allocate_process initializes all
684 Lisp data to nil, so do it only for slots which should not be nil. */
685 pset_status (p, Qrun);
686 pset_mark (p, Fmake_marker ());
688 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
689 non-Lisp data, so do it only for slots which should not be zero. */
690 p->infd = -1;
691 p->outfd = -1;
693 #ifdef HAVE_GNUTLS
694 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
695 #endif
697 /* If name is already in use, modify it until it is unused. */
699 name1 = name;
700 for (i = 1; ; i++)
702 tem = Fget_process (name1);
703 if (NILP (tem)) break;
704 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
706 name = name1;
707 pset_name (p, name);
708 pset_sentinel (p, Qinternal_default_process_sentinel);
709 pset_filter (p, Qinternal_default_process_filter);
710 XSETPROCESS (val, p);
711 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
712 return val;
715 static void
716 remove_process (register Lisp_Object proc)
718 register Lisp_Object pair;
720 pair = Frassq (proc, Vprocess_alist);
721 Vprocess_alist = Fdelq (pair, Vprocess_alist);
723 deactivate_process (proc);
727 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
728 doc: /* Return t if OBJECT is a process. */)
729 (Lisp_Object object)
731 return PROCESSP (object) ? Qt : Qnil;
734 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
735 doc: /* Return the process named NAME, or nil if there is none. */)
736 (register Lisp_Object name)
738 if (PROCESSP (name))
739 return name;
740 CHECK_STRING (name);
741 return Fcdr (Fassoc (name, Vprocess_alist));
744 /* This is how commands for the user decode process arguments. It
745 accepts a process, a process name, a buffer, a buffer name, or nil.
746 Buffers denote the first process in the buffer, and nil denotes the
747 current buffer. */
749 static Lisp_Object
750 get_process (register Lisp_Object name)
752 register Lisp_Object proc, obj;
753 if (STRINGP (name))
755 obj = Fget_process (name);
756 if (NILP (obj))
757 obj = Fget_buffer (name);
758 if (NILP (obj))
759 error ("Process %s does not exist", SDATA (name));
761 else if (NILP (name))
762 obj = Fcurrent_buffer ();
763 else
764 obj = name;
766 /* Now obj should be either a buffer object or a process object.
768 if (BUFFERP (obj))
770 proc = Fget_buffer_process (obj);
771 if (NILP (proc))
772 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
774 else
776 CHECK_PROCESS (obj);
777 proc = obj;
779 return proc;
783 /* Fdelete_process promises to immediately forget about the process, but in
784 reality, Emacs needs to remember those processes until they have been
785 treated by the SIGCHLD handler and waitpid has been invoked on them;
786 otherwise they might fill up the kernel's process table.
788 Some processes created by call-process are also put onto this list. */
789 static Lisp_Object deleted_pid_list;
791 void
792 record_deleted_pid (pid_t pid)
794 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
795 /* GC treated elements set to nil. */
796 Fdelq (Qnil, deleted_pid_list));
800 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
801 doc: /* Delete PROCESS: kill it and forget about it immediately.
802 PROCESS may be a process, a buffer, the name of a process or buffer, or
803 nil, indicating the current buffer's process. */)
804 (register Lisp_Object process)
806 register struct Lisp_Process *p;
808 process = get_process (process);
809 p = XPROCESS (process);
811 p->raw_status_new = 0;
812 if (NETCONN1_P (p) || SERIALCONN1_P (p))
814 pset_status (p, Fcons (Qexit, Fcons (make_number (0), Qnil)));
815 p->tick = ++process_tick;
816 status_notify (p);
817 redisplay_preserve_echo_area (13);
819 else
821 if (p->alive)
822 record_kill_process (p);
824 if (p->infd >= 0)
826 /* Update P's status, since record_kill_process will make the
827 SIGCHLD handler update deleted_pid_list, not *P. */
828 Lisp_Object symbol;
829 if (p->raw_status_new)
830 update_status (p);
831 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
832 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
833 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
835 p->tick = ++process_tick;
836 status_notify (p);
837 redisplay_preserve_echo_area (13);
840 remove_process (process);
841 return Qnil;
844 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
845 doc: /* Return the status of PROCESS.
846 The returned value is one of the following symbols:
847 run -- for a process that is running.
848 stop -- for a process stopped but continuable.
849 exit -- for a process that has exited.
850 signal -- for a process that has got a fatal signal.
851 open -- for a network stream connection that is open.
852 listen -- for a network stream server that is listening.
853 closed -- for a network stream connection that is closed.
854 connect -- when waiting for a non-blocking connection to complete.
855 failed -- when a non-blocking connection has failed.
856 nil -- if arg is a process name and no such process exists.
857 PROCESS may be a process, a buffer, the name of a process, or
858 nil, indicating the current buffer's process. */)
859 (register Lisp_Object process)
861 register struct Lisp_Process *p;
862 register Lisp_Object status;
864 if (STRINGP (process))
865 process = Fget_process (process);
866 else
867 process = get_process (process);
869 if (NILP (process))
870 return process;
872 p = XPROCESS (process);
873 if (p->raw_status_new)
874 update_status (p);
875 status = p->status;
876 if (CONSP (status))
877 status = XCAR (status);
878 if (NETCONN1_P (p) || SERIALCONN1_P (p))
880 if (EQ (status, Qexit))
881 status = Qclosed;
882 else if (EQ (p->command, Qt))
883 status = Qstop;
884 else if (EQ (status, Qrun))
885 status = Qopen;
887 return status;
890 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
891 1, 1, 0,
892 doc: /* Return the exit status of PROCESS or the signal number that killed it.
893 If PROCESS has not yet exited or died, return 0. */)
894 (register Lisp_Object process)
896 CHECK_PROCESS (process);
897 if (XPROCESS (process)->raw_status_new)
898 update_status (XPROCESS (process));
899 if (CONSP (XPROCESS (process)->status))
900 return XCAR (XCDR (XPROCESS (process)->status));
901 return make_number (0);
904 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
905 doc: /* Return the process id of PROCESS.
906 This is the pid of the external process which PROCESS uses or talks to.
907 For a network connection, this value is nil. */)
908 (register Lisp_Object process)
910 pid_t pid;
912 CHECK_PROCESS (process);
913 pid = XPROCESS (process)->pid;
914 return (pid ? make_fixnum_or_float (pid) : Qnil);
917 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
918 doc: /* Return the name of PROCESS, as a string.
919 This is the name of the program invoked in PROCESS,
920 possibly modified to make it unique among process names. */)
921 (register Lisp_Object process)
923 CHECK_PROCESS (process);
924 return XPROCESS (process)->name;
927 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
928 doc: /* Return the command that was executed to start PROCESS.
929 This is a list of strings, the first string being the program executed
930 and the rest of the strings being the arguments given to it.
931 For a network or serial process, this is nil (process is running) or t
932 \(process is stopped). */)
933 (register Lisp_Object process)
935 CHECK_PROCESS (process);
936 return XPROCESS (process)->command;
939 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
940 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
941 This is the terminal that the process itself reads and writes on,
942 not the name of the pty that Emacs uses to talk with that terminal. */)
943 (register Lisp_Object process)
945 CHECK_PROCESS (process);
946 return XPROCESS (process)->tty_name;
949 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
950 2, 2, 0,
951 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
952 Return BUFFER. */)
953 (register Lisp_Object process, Lisp_Object buffer)
955 struct Lisp_Process *p;
957 CHECK_PROCESS (process);
958 if (!NILP (buffer))
959 CHECK_BUFFER (buffer);
960 p = XPROCESS (process);
961 pset_buffer (p, buffer);
962 if (NETCONN1_P (p) || SERIALCONN1_P (p))
963 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
964 setup_process_coding_systems (process);
965 return buffer;
968 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
969 1, 1, 0,
970 doc: /* Return the buffer PROCESS is associated with.
971 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
972 (register Lisp_Object process)
974 CHECK_PROCESS (process);
975 return XPROCESS (process)->buffer;
978 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
979 1, 1, 0,
980 doc: /* Return the marker for the end of the last output from PROCESS. */)
981 (register Lisp_Object process)
983 CHECK_PROCESS (process);
984 return XPROCESS (process)->mark;
987 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
988 2, 2, 0,
989 doc: /* Give PROCESS the filter function FILTER; nil means default.
990 A value of t means stop accepting output from the process.
992 When a process has a non-default filter, its buffer is not used for output.
993 Instead, each time it does output, the entire string of output is
994 passed to the filter.
996 The filter gets two arguments: the process and the string of output.
997 The string argument is normally a multibyte string, except:
998 - if the process' input coding system is no-conversion or raw-text,
999 it is a unibyte string (the non-converted input), or else
1000 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1001 string (the result of converting the decoded input multibyte
1002 string to unibyte with `string-make-unibyte'). */)
1003 (register Lisp_Object process, Lisp_Object filter)
1005 struct Lisp_Process *p;
1007 CHECK_PROCESS (process);
1008 p = XPROCESS (process);
1010 /* Don't signal an error if the process' input file descriptor
1011 is closed. This could make debugging Lisp more difficult,
1012 for example when doing something like
1014 (setq process (start-process ...))
1015 (debug)
1016 (set-process-filter process ...) */
1018 if (NILP (filter))
1019 filter = Qinternal_default_process_filter;
1021 if (p->infd >= 0)
1023 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1025 FD_CLR (p->infd, &input_wait_mask);
1026 FD_CLR (p->infd, &non_keyboard_wait_mask);
1028 else if (EQ (p->filter, Qt)
1029 /* Network or serial process not stopped: */
1030 && !EQ (p->command, Qt))
1032 FD_SET (p->infd, &input_wait_mask);
1033 FD_SET (p->infd, &non_keyboard_wait_mask);
1037 pset_filter (p, filter);
1038 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1039 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1040 setup_process_coding_systems (process);
1041 return filter;
1044 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1045 1, 1, 0,
1046 doc: /* Return the filter function of PROCESS.
1047 See `set-process-filter' for more info on filter functions. */)
1048 (register Lisp_Object process)
1050 CHECK_PROCESS (process);
1051 return XPROCESS (process)->filter;
1054 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1055 2, 2, 0,
1056 doc: /* Give PROCESS the sentinel SENTINEL; nil for default.
1057 The sentinel is called as a function when the process changes state.
1058 It gets two arguments: the process, and a string describing the change. */)
1059 (register Lisp_Object process, Lisp_Object sentinel)
1061 struct Lisp_Process *p;
1063 CHECK_PROCESS (process);
1064 p = XPROCESS (process);
1066 if (NILP (sentinel))
1067 sentinel = Qinternal_default_process_sentinel;
1069 pset_sentinel (p, sentinel);
1070 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1071 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1072 return sentinel;
1075 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1076 1, 1, 0,
1077 doc: /* Return the sentinel of PROCESS.
1078 See `set-process-sentinel' for more info on sentinels. */)
1079 (register Lisp_Object process)
1081 CHECK_PROCESS (process);
1082 return XPROCESS (process)->sentinel;
1085 DEFUN ("set-process-window-size", Fset_process_window_size,
1086 Sset_process_window_size, 3, 3, 0,
1087 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1088 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
1090 CHECK_PROCESS (process);
1091 CHECK_RANGED_INTEGER (height, 0, INT_MAX);
1092 CHECK_RANGED_INTEGER (width, 0, INT_MAX);
1094 if (XPROCESS (process)->infd < 0
1095 || set_window_size (XPROCESS (process)->infd,
1096 XINT (height), XINT (width)) <= 0)
1097 return Qnil;
1098 else
1099 return Qt;
1102 DEFUN ("set-process-inherit-coding-system-flag",
1103 Fset_process_inherit_coding_system_flag,
1104 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1105 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1106 If the second argument FLAG is non-nil, then the variable
1107 `buffer-file-coding-system' of the buffer associated with PROCESS
1108 will be bound to the value of the coding system used to decode
1109 the process output.
1111 This is useful when the coding system specified for the process buffer
1112 leaves either the character code conversion or the end-of-line conversion
1113 unspecified, or if the coding system used to decode the process output
1114 is more appropriate for saving the process buffer.
1116 Binding the variable `inherit-process-coding-system' to non-nil before
1117 starting the process is an alternative way of setting the inherit flag
1118 for the process which will run.
1120 This function returns FLAG. */)
1121 (register Lisp_Object process, Lisp_Object flag)
1123 CHECK_PROCESS (process);
1124 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1125 return flag;
1128 DEFUN ("set-process-query-on-exit-flag",
1129 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1130 2, 2, 0,
1131 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1132 If the second argument FLAG is non-nil, Emacs will query the user before
1133 exiting or killing a buffer if PROCESS is running. This function
1134 returns FLAG. */)
1135 (register Lisp_Object process, Lisp_Object flag)
1137 CHECK_PROCESS (process);
1138 XPROCESS (process)->kill_without_query = NILP (flag);
1139 return flag;
1142 DEFUN ("process-query-on-exit-flag",
1143 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1144 1, 1, 0,
1145 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1146 (register Lisp_Object process)
1148 CHECK_PROCESS (process);
1149 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1152 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1153 1, 2, 0,
1154 doc: /* Return the contact info of PROCESS; t for a real child.
1155 For a network or serial connection, the value depends on the optional
1156 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1157 SERVICE) for a network connection or (PORT SPEED) for a serial
1158 connection. If KEY is t, the complete contact information for the
1159 connection is returned, else the specific value for the keyword KEY is
1160 returned. See `make-network-process' or `make-serial-process' for a
1161 list of keywords. */)
1162 (register Lisp_Object process, Lisp_Object key)
1164 Lisp_Object contact;
1166 CHECK_PROCESS (process);
1167 contact = XPROCESS (process)->childp;
1169 #ifdef DATAGRAM_SOCKETS
1170 if (DATAGRAM_CONN_P (process)
1171 && (EQ (key, Qt) || EQ (key, QCremote)))
1172 contact = Fplist_put (contact, QCremote,
1173 Fprocess_datagram_address (process));
1174 #endif
1176 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1177 return contact;
1178 if (NILP (key) && NETCONN_P (process))
1179 return Fcons (Fplist_get (contact, QChost),
1180 Fcons (Fplist_get (contact, QCservice), Qnil));
1181 if (NILP (key) && SERIALCONN_P (process))
1182 return Fcons (Fplist_get (contact, QCport),
1183 Fcons (Fplist_get (contact, QCspeed), Qnil));
1184 return Fplist_get (contact, key);
1187 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1188 1, 1, 0,
1189 doc: /* Return the plist of PROCESS. */)
1190 (register Lisp_Object process)
1192 CHECK_PROCESS (process);
1193 return XPROCESS (process)->plist;
1196 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1197 2, 2, 0,
1198 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1199 (register Lisp_Object process, Lisp_Object plist)
1201 CHECK_PROCESS (process);
1202 CHECK_LIST (plist);
1204 pset_plist (XPROCESS (process), plist);
1205 return plist;
1208 #if 0 /* Turned off because we don't currently record this info
1209 in the process. Perhaps add it. */
1210 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1211 doc: /* Return the connection type of PROCESS.
1212 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1213 a socket connection. */)
1214 (Lisp_Object process)
1216 return XPROCESS (process)->type;
1218 #endif
1220 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1221 doc: /* Return the connection type of PROCESS.
1222 The value is either the symbol `real', `network', or `serial'.
1223 PROCESS may be a process, a buffer, the name of a process or buffer, or
1224 nil, indicating the current buffer's process. */)
1225 (Lisp_Object process)
1227 Lisp_Object proc;
1228 proc = get_process (process);
1229 return XPROCESS (proc)->type;
1232 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1233 1, 2, 0,
1234 doc: /* Convert network ADDRESS from internal format to a string.
1235 A 4 or 5 element vector represents an IPv4 address (with port number).
1236 An 8 or 9 element vector represents an IPv6 address (with port number).
1237 If optional second argument OMIT-PORT is non-nil, don't include a port
1238 number in the string, even when present in ADDRESS.
1239 Returns nil if format of ADDRESS is invalid. */)
1240 (Lisp_Object address, Lisp_Object omit_port)
1242 if (NILP (address))
1243 return Qnil;
1245 if (STRINGP (address)) /* AF_LOCAL */
1246 return address;
1248 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1250 register struct Lisp_Vector *p = XVECTOR (address);
1251 ptrdiff_t size = p->header.size;
1252 Lisp_Object args[10];
1253 int nargs, i;
1255 if (size == 4 || (size == 5 && !NILP (omit_port)))
1257 args[0] = build_string ("%d.%d.%d.%d");
1258 nargs = 4;
1260 else if (size == 5)
1262 args[0] = build_string ("%d.%d.%d.%d:%d");
1263 nargs = 5;
1265 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1267 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1268 nargs = 8;
1270 else if (size == 9)
1272 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1273 nargs = 9;
1275 else
1276 return Qnil;
1278 for (i = 0; i < nargs; i++)
1280 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1281 return Qnil;
1283 if (nargs <= 5 /* IPv4 */
1284 && i < 4 /* host, not port */
1285 && XINT (p->contents[i]) > 255)
1286 return Qnil;
1288 args[i+1] = p->contents[i];
1291 return Fformat (nargs+1, args);
1294 if (CONSP (address))
1296 Lisp_Object args[2];
1297 args[0] = build_string ("<Family %d>");
1298 args[1] = Fcar (address);
1299 return Fformat (2, args);
1302 return Qnil;
1305 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1306 doc: /* Return a list of all processes. */)
1307 (void)
1309 return Fmapcar (Qcdr, Vprocess_alist);
1312 /* Starting asynchronous inferior processes. */
1314 static Lisp_Object start_process_unwind (Lisp_Object proc);
1316 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1317 doc: /* Start a program in a subprocess. Return the process object for it.
1318 NAME is name for process. It is modified if necessary to make it unique.
1319 BUFFER is the buffer (or buffer name) to associate with the process.
1321 Process output (both standard output and standard error streams) goes
1322 at end of BUFFER, unless you specify an output stream or filter
1323 function to handle the output. BUFFER may also be nil, meaning that
1324 this process is not associated with any buffer.
1326 PROGRAM is the program file name. It is searched for in `exec-path'
1327 (which see). If nil, just associate a pty with the buffer. Remaining
1328 arguments are strings to give program as arguments.
1330 If you want to separate standard output from standard error, invoke
1331 the command through a shell and redirect one of them using the shell
1332 syntax.
1334 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1335 (ptrdiff_t nargs, Lisp_Object *args)
1337 Lisp_Object buffer, name, program, proc, current_dir, tem;
1338 register unsigned char **new_argv;
1339 ptrdiff_t i;
1340 ptrdiff_t count = SPECPDL_INDEX ();
1342 buffer = args[1];
1343 if (!NILP (buffer))
1344 buffer = Fget_buffer_create (buffer);
1346 /* Make sure that the child will be able to chdir to the current
1347 buffer's current directory, or its unhandled equivalent. We
1348 can't just have the child check for an error when it does the
1349 chdir, since it's in a vfork.
1351 We have to GCPRO around this because Fexpand_file_name and
1352 Funhandled_file_name_directory might call a file name handling
1353 function. The argument list is protected by the caller, so all
1354 we really have to worry about is buffer. */
1356 struct gcpro gcpro1, gcpro2;
1358 current_dir = BVAR (current_buffer, directory);
1360 GCPRO2 (buffer, current_dir);
1362 current_dir = Funhandled_file_name_directory (current_dir);
1363 if (NILP (current_dir))
1364 /* If the file name handler says that current_dir is unreachable, use
1365 a sensible default. */
1366 current_dir = build_string ("~/");
1367 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1368 if (NILP (Ffile_accessible_directory_p (current_dir)))
1369 report_file_error ("Setting current directory",
1370 Fcons (BVAR (current_buffer, directory), Qnil));
1372 UNGCPRO;
1375 name = args[0];
1376 CHECK_STRING (name);
1378 program = args[2];
1380 if (!NILP (program))
1381 CHECK_STRING (program);
1383 proc = make_process (name);
1384 /* If an error occurs and we can't start the process, we want to
1385 remove it from the process list. This means that each error
1386 check in create_process doesn't need to call remove_process
1387 itself; it's all taken care of here. */
1388 record_unwind_protect (start_process_unwind, proc);
1390 pset_childp (XPROCESS (proc), Qt);
1391 pset_plist (XPROCESS (proc), Qnil);
1392 pset_type (XPROCESS (proc), Qreal);
1393 pset_buffer (XPROCESS (proc), buffer);
1394 pset_sentinel (XPROCESS (proc), Qinternal_default_process_sentinel);
1395 pset_filter (XPROCESS (proc), Qinternal_default_process_filter);
1396 pset_command (XPROCESS (proc), Flist (nargs - 2, args + 2));
1398 #ifdef HAVE_GNUTLS
1399 /* AKA GNUTLS_INITSTAGE(proc). */
1400 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1401 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1402 #endif
1404 #ifdef ADAPTIVE_READ_BUFFERING
1405 XPROCESS (proc)->adaptive_read_buffering
1406 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1407 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1408 #endif
1410 /* Make the process marker point into the process buffer (if any). */
1411 if (BUFFERP (buffer))
1412 set_marker_both (XPROCESS (proc)->mark, buffer,
1413 BUF_ZV (XBUFFER (buffer)),
1414 BUF_ZV_BYTE (XBUFFER (buffer)));
1417 /* Decide coding systems for communicating with the process. Here
1418 we don't setup the structure coding_system nor pay attention to
1419 unibyte mode. They are done in create_process. */
1421 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1422 Lisp_Object coding_systems = Qt;
1423 Lisp_Object val, *args2;
1424 struct gcpro gcpro1, gcpro2;
1426 val = Vcoding_system_for_read;
1427 if (NILP (val))
1429 args2 = alloca ((nargs + 1) * sizeof *args2);
1430 args2[0] = Qstart_process;
1431 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1432 GCPRO2 (proc, current_dir);
1433 if (!NILP (program))
1434 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1435 UNGCPRO;
1436 if (CONSP (coding_systems))
1437 val = XCAR (coding_systems);
1438 else if (CONSP (Vdefault_process_coding_system))
1439 val = XCAR (Vdefault_process_coding_system);
1441 pset_decode_coding_system (XPROCESS (proc), val);
1443 val = Vcoding_system_for_write;
1444 if (NILP (val))
1446 if (EQ (coding_systems, Qt))
1448 args2 = alloca ((nargs + 1) * sizeof *args2);
1449 args2[0] = Qstart_process;
1450 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1451 GCPRO2 (proc, current_dir);
1452 if (!NILP (program))
1453 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1454 UNGCPRO;
1456 if (CONSP (coding_systems))
1457 val = XCDR (coding_systems);
1458 else if (CONSP (Vdefault_process_coding_system))
1459 val = XCDR (Vdefault_process_coding_system);
1461 pset_encode_coding_system (XPROCESS (proc), val);
1462 /* Note: At this moment, the above coding system may leave
1463 text-conversion or eol-conversion unspecified. They will be
1464 decided after we read output from the process and decode it by
1465 some coding system, or just before we actually send a text to
1466 the process. */
1470 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1471 XPROCESS (proc)->decoding_carryover = 0;
1472 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1474 XPROCESS (proc)->inherit_coding_system_flag
1475 = !(NILP (buffer) || !inherit_process_coding_system);
1477 if (!NILP (program))
1479 /* If program file name is not absolute, search our path for it.
1480 Put the name we will really use in TEM. */
1481 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1482 && !(SCHARS (program) > 1
1483 && IS_DEVICE_SEP (SREF (program, 1))))
1485 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1487 tem = Qnil;
1488 GCPRO4 (name, program, buffer, current_dir);
1489 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1490 UNGCPRO;
1491 if (NILP (tem))
1492 report_file_error ("Searching for program", Fcons (program, Qnil));
1493 tem = Fexpand_file_name (tem, Qnil);
1495 else
1497 if (!NILP (Ffile_directory_p (program)))
1498 error ("Specified program for new process is a directory");
1499 tem = program;
1502 /* If program file name starts with /: for quoting a magic name,
1503 discard that. */
1504 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1505 && SREF (tem, 1) == ':')
1506 tem = Fsubstring (tem, make_number (2), Qnil);
1509 Lisp_Object arg_encoding = Qnil;
1510 struct gcpro gcpro1;
1511 GCPRO1 (tem);
1513 /* Encode the file name and put it in NEW_ARGV.
1514 That's where the child will use it to execute the program. */
1515 tem = Fcons (ENCODE_FILE (tem), Qnil);
1517 /* Here we encode arguments by the coding system used for sending
1518 data to the process. We don't support using different coding
1519 systems for encoding arguments and for encoding data sent to the
1520 process. */
1522 for (i = 3; i < nargs; i++)
1524 tem = Fcons (args[i], tem);
1525 CHECK_STRING (XCAR (tem));
1526 if (STRING_MULTIBYTE (XCAR (tem)))
1528 if (NILP (arg_encoding))
1529 arg_encoding = (complement_process_encoding_system
1530 (XPROCESS (proc)->encode_coding_system));
1531 XSETCAR (tem,
1532 code_convert_string_norecord
1533 (XCAR (tem), arg_encoding, 1));
1537 UNGCPRO;
1540 /* Now that everything is encoded we can collect the strings into
1541 NEW_ARGV. */
1542 new_argv = alloca ((nargs - 1) * sizeof *new_argv);
1543 new_argv[nargs - 2] = 0;
1545 for (i = nargs - 2; i-- != 0; )
1547 new_argv[i] = SDATA (XCAR (tem));
1548 tem = XCDR (tem);
1551 create_process (proc, (char **) new_argv, current_dir);
1553 else
1554 create_pty (proc);
1556 return unbind_to (count, proc);
1559 /* This function is the unwind_protect form for Fstart_process. If
1560 PROC doesn't have its pid set, then we know someone has signaled
1561 an error and the process wasn't started successfully, so we should
1562 remove it from the process list. */
1563 static Lisp_Object
1564 start_process_unwind (Lisp_Object proc)
1566 if (!PROCESSP (proc))
1567 emacs_abort ();
1569 /* Was PROC started successfully?
1570 -2 is used for a pty with no process, eg for gdb. */
1571 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1572 remove_process (proc);
1574 return Qnil;
1577 static void
1578 create_process_1 (struct atimer *timer)
1580 /* Nothing to do. */
1584 static void
1585 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1587 int inchannel, outchannel;
1588 pid_t pid;
1589 int sv[2];
1590 #ifndef WINDOWSNT
1591 int wait_child_setup[2];
1592 #endif
1593 int forkin, forkout;
1594 bool pty_flag = 0;
1595 Lisp_Object lisp_pty_name = Qnil;
1596 Lisp_Object encoded_current_dir;
1598 inchannel = outchannel = -1;
1600 #ifdef HAVE_PTYS
1601 if (!NILP (Vprocess_connection_type))
1602 outchannel = inchannel = allocate_pty ();
1604 if (inchannel >= 0)
1606 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1607 /* On most USG systems it does not work to open the pty's tty here,
1608 then close it and reopen it in the child. */
1609 /* Don't let this terminal become our controlling terminal
1610 (in case we don't have one). */
1611 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1612 if (forkin < 0)
1613 report_file_error ("Opening pty", Qnil);
1614 #else
1615 forkin = forkout = -1;
1616 #endif /* not USG, or USG_SUBTTY_WORKS */
1617 pty_flag = 1;
1618 lisp_pty_name = build_string (pty_name);
1620 else
1621 #endif /* HAVE_PTYS */
1623 int tem;
1624 tem = pipe (sv);
1625 if (tem < 0)
1626 report_file_error ("Creating pipe", Qnil);
1627 inchannel = sv[0];
1628 forkout = sv[1];
1629 tem = pipe (sv);
1630 if (tem < 0)
1632 emacs_close (inchannel);
1633 emacs_close (forkout);
1634 report_file_error ("Creating pipe", Qnil);
1636 outchannel = sv[1];
1637 forkin = sv[0];
1640 #ifndef WINDOWSNT
1642 int tem;
1644 tem = pipe (wait_child_setup);
1645 if (tem < 0)
1646 report_file_error ("Creating pipe", Qnil);
1647 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1648 if (tem >= 0)
1649 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1650 if (tem < 0)
1652 emacs_close (wait_child_setup[0]);
1653 emacs_close (wait_child_setup[1]);
1654 report_file_error ("Setting file descriptor flags", Qnil);
1657 #endif
1659 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1660 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1662 /* Record this as an active process, with its channels.
1663 As a result, child_setup will close Emacs's side of the pipes. */
1664 chan_process[inchannel] = process;
1665 XPROCESS (process)->infd = inchannel;
1666 XPROCESS (process)->outfd = outchannel;
1668 /* Previously we recorded the tty descriptor used in the subprocess.
1669 It was only used for getting the foreground tty process, so now
1670 we just reopen the device (see emacs_get_tty_pgrp) as this is
1671 more portable (see USG_SUBTTY_WORKS above). */
1673 XPROCESS (process)->pty_flag = pty_flag;
1674 pset_status (XPROCESS (process), Qrun);
1676 FD_SET (inchannel, &input_wait_mask);
1677 FD_SET (inchannel, &non_keyboard_wait_mask);
1678 if (inchannel > max_process_desc)
1679 max_process_desc = inchannel;
1681 /* This may signal an error. */
1682 setup_process_coding_systems (process);
1684 encoded_current_dir = ENCODE_FILE (current_dir);
1686 block_input ();
1687 block_child_signal ();
1688 catch_child_signal ();
1690 #ifndef WINDOWSNT
1691 /* vfork, and prevent local vars from being clobbered by the vfork. */
1693 Lisp_Object volatile encoded_current_dir_volatile = encoded_current_dir;
1694 Lisp_Object volatile lisp_pty_name_volatile = lisp_pty_name;
1695 Lisp_Object volatile process_volatile = process;
1696 bool volatile pty_flag_volatile = pty_flag;
1697 char **volatile new_argv_volatile = new_argv;
1698 int volatile forkin_volatile = forkin;
1699 int volatile forkout_volatile = forkout;
1700 int volatile wait_child_setup_0_volatile = wait_child_setup[0];
1701 int volatile wait_child_setup_1_volatile = wait_child_setup[1];
1703 pid = vfork ();
1705 encoded_current_dir = encoded_current_dir_volatile;
1706 lisp_pty_name = lisp_pty_name_volatile;
1707 process = process_volatile;
1708 pty_flag = pty_flag_volatile;
1709 new_argv = new_argv_volatile;
1710 forkin = forkin_volatile;
1711 forkout = forkout_volatile;
1712 wait_child_setup[0] = wait_child_setup_0_volatile;
1713 wait_child_setup[1] = wait_child_setup_1_volatile;
1716 if (pid == 0)
1717 #endif /* not WINDOWSNT */
1719 int xforkin = forkin;
1720 int xforkout = forkout;
1722 /* Make the pty be the controlling terminal of the process. */
1723 #ifdef HAVE_PTYS
1724 /* First, disconnect its current controlling terminal. */
1725 /* We tried doing setsid only if pty_flag, but it caused
1726 process_set_signal to fail on SGI when using a pipe. */
1727 setsid ();
1728 /* Make the pty's terminal the controlling terminal. */
1729 if (pty_flag && xforkin >= 0)
1731 #ifdef TIOCSCTTY
1732 /* We ignore the return value
1733 because faith@cs.unc.edu says that is necessary on Linux. */
1734 ioctl (xforkin, TIOCSCTTY, 0);
1735 #endif
1737 #if defined (LDISC1)
1738 if (pty_flag && xforkin >= 0)
1740 struct termios t;
1741 tcgetattr (xforkin, &t);
1742 t.c_lflag = LDISC1;
1743 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1744 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1746 #else
1747 #if defined (NTTYDISC) && defined (TIOCSETD)
1748 if (pty_flag && xforkin >= 0)
1750 /* Use new line discipline. */
1751 int ldisc = NTTYDISC;
1752 ioctl (xforkin, TIOCSETD, &ldisc);
1754 #endif
1755 #endif
1756 #ifdef TIOCNOTTY
1757 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1758 can do TIOCSPGRP only to the process's controlling tty. */
1759 if (pty_flag)
1761 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1762 I can't test it since I don't have 4.3. */
1763 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1764 if (j >= 0)
1766 ioctl (j, TIOCNOTTY, 0);
1767 emacs_close (j);
1770 #endif /* TIOCNOTTY */
1772 #if !defined (DONT_REOPEN_PTY)
1773 /*** There is a suggestion that this ought to be a
1774 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1775 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1776 that system does seem to need this code, even though
1777 both TIOCSCTTY is defined. */
1778 /* Now close the pty (if we had it open) and reopen it.
1779 This makes the pty the controlling terminal of the subprocess. */
1780 if (pty_flag)
1783 /* I wonder if emacs_close (emacs_open (pty_name, ...))
1784 would work? */
1785 if (xforkin >= 0)
1786 emacs_close (xforkin);
1787 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
1789 if (xforkin < 0)
1791 emacs_write (1, "Couldn't open the pty terminal ", 31);
1792 emacs_write (1, pty_name, strlen (pty_name));
1793 emacs_write (1, "\n", 1);
1794 _exit (1);
1798 #endif /* not DONT_REOPEN_PTY */
1800 #ifdef SETUP_SLAVE_PTY
1801 if (pty_flag)
1803 SETUP_SLAVE_PTY;
1805 #endif /* SETUP_SLAVE_PTY */
1806 #ifdef AIX
1807 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
1808 Now reenable it in the child, so it will die when we want it to. */
1809 if (pty_flag)
1810 signal (SIGHUP, SIG_DFL);
1811 #endif
1812 #endif /* HAVE_PTYS */
1814 signal (SIGINT, SIG_DFL);
1815 signal (SIGQUIT, SIG_DFL);
1817 /* Emacs ignores SIGPIPE, but the child should not. */
1818 signal (SIGPIPE, SIG_DFL);
1820 /* Stop blocking SIGCHLD in the child. */
1821 unblock_child_signal ();
1823 if (pty_flag)
1824 child_setup_tty (xforkout);
1825 #ifdef WINDOWSNT
1826 pid = child_setup (xforkin, xforkout, xforkout,
1827 new_argv, 1, encoded_current_dir);
1828 #else /* not WINDOWSNT */
1829 emacs_close (wait_child_setup[0]);
1830 child_setup (xforkin, xforkout, xforkout,
1831 new_argv, 1, encoded_current_dir);
1832 #endif /* not WINDOWSNT */
1835 /* Back in the parent process. */
1837 XPROCESS (process)->pid = pid;
1838 if (pid >= 0)
1839 XPROCESS (process)->alive = 1;
1841 /* Stop blocking in the parent. */
1842 unblock_child_signal ();
1843 unblock_input ();
1845 if (pid < 0)
1847 if (forkin >= 0)
1848 emacs_close (forkin);
1849 if (forkin != forkout && forkout >= 0)
1850 emacs_close (forkout);
1852 else
1854 /* vfork succeeded. */
1856 #ifdef WINDOWSNT
1857 register_child (pid, inchannel);
1858 #endif /* WINDOWSNT */
1860 /* If the subfork execv fails, and it exits,
1861 this close hangs. I don't know why.
1862 So have an interrupt jar it loose. */
1864 struct atimer *timer;
1865 EMACS_TIME offset = make_emacs_time (1, 0);
1867 stop_polling ();
1868 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
1870 if (forkin >= 0)
1871 emacs_close (forkin);
1873 cancel_atimer (timer);
1874 start_polling ();
1877 if (forkin != forkout && forkout >= 0)
1878 emacs_close (forkout);
1880 pset_tty_name (XPROCESS (process), lisp_pty_name);
1882 #ifndef WINDOWSNT
1883 /* Wait for child_setup to complete in case that vfork is
1884 actually defined as fork. The descriptor wait_child_setup[1]
1885 of a pipe is closed at the child side either by close-on-exec
1886 on successful execve or the _exit call in child_setup. */
1888 char dummy;
1890 emacs_close (wait_child_setup[1]);
1891 emacs_read (wait_child_setup[0], &dummy, 1);
1892 emacs_close (wait_child_setup[0]);
1894 #endif
1897 /* Now generate the error if vfork failed. */
1898 if (pid < 0)
1899 report_file_error ("Doing vfork", Qnil);
1902 void
1903 create_pty (Lisp_Object process)
1905 int inchannel, outchannel;
1906 bool pty_flag = 0;
1908 inchannel = outchannel = -1;
1910 #ifdef HAVE_PTYS
1911 if (!NILP (Vprocess_connection_type))
1912 outchannel = inchannel = allocate_pty ();
1914 if (inchannel >= 0)
1916 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1917 /* On most USG systems it does not work to open the pty's tty here,
1918 then close it and reopen it in the child. */
1919 /* Don't let this terminal become our controlling terminal
1920 (in case we don't have one). */
1921 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1922 if (forkout < 0)
1923 report_file_error ("Opening pty", Qnil);
1924 #if defined (DONT_REOPEN_PTY)
1925 /* In the case that vfork is defined as fork, the parent process
1926 (Emacs) may send some data before the child process completes
1927 tty options setup. So we setup tty before forking. */
1928 child_setup_tty (forkout);
1929 #endif /* DONT_REOPEN_PTY */
1930 #endif /* not USG, or USG_SUBTTY_WORKS */
1931 pty_flag = 1;
1933 #endif /* HAVE_PTYS */
1935 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1936 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1938 /* Record this as an active process, with its channels.
1939 As a result, child_setup will close Emacs's side of the pipes. */
1940 chan_process[inchannel] = process;
1941 XPROCESS (process)->infd = inchannel;
1942 XPROCESS (process)->outfd = outchannel;
1944 /* Previously we recorded the tty descriptor used in the subprocess.
1945 It was only used for getting the foreground tty process, so now
1946 we just reopen the device (see emacs_get_tty_pgrp) as this is
1947 more portable (see USG_SUBTTY_WORKS above). */
1949 XPROCESS (process)->pty_flag = pty_flag;
1950 pset_status (XPROCESS (process), Qrun);
1951 setup_process_coding_systems (process);
1953 FD_SET (inchannel, &input_wait_mask);
1954 FD_SET (inchannel, &non_keyboard_wait_mask);
1955 if (inchannel > max_process_desc)
1956 max_process_desc = inchannel;
1958 XPROCESS (process)->pid = -2;
1959 #ifdef HAVE_PTYS
1960 if (pty_flag)
1961 pset_tty_name (XPROCESS (process), build_string (pty_name));
1962 else
1963 #endif
1964 pset_tty_name (XPROCESS (process), Qnil);
1968 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1969 The address family of sa is not included in the result. */
1971 static Lisp_Object
1972 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
1974 Lisp_Object address;
1975 int i;
1976 unsigned char *cp;
1977 register struct Lisp_Vector *p;
1979 /* Workaround for a bug in getsockname on BSD: Names bound to
1980 sockets in the UNIX domain are inaccessible; getsockname returns
1981 a zero length name. */
1982 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
1983 return empty_unibyte_string;
1985 switch (sa->sa_family)
1987 case AF_INET:
1989 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
1990 len = sizeof (sin->sin_addr) + 1;
1991 address = Fmake_vector (make_number (len), Qnil);
1992 p = XVECTOR (address);
1993 p->contents[--len] = make_number (ntohs (sin->sin_port));
1994 cp = (unsigned char *) &sin->sin_addr;
1995 break;
1997 #ifdef AF_INET6
1998 case AF_INET6:
2000 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2001 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2002 len = sizeof (sin6->sin6_addr)/2 + 1;
2003 address = Fmake_vector (make_number (len), Qnil);
2004 p = XVECTOR (address);
2005 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2006 for (i = 0; i < len; i++)
2007 p->contents[i] = make_number (ntohs (ip6[i]));
2008 return address;
2010 #endif
2011 #ifdef HAVE_LOCAL_SOCKETS
2012 case AF_LOCAL:
2014 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2015 for (i = 0; i < sizeof (sockun->sun_path); i++)
2016 if (sockun->sun_path[i] == 0)
2017 break;
2018 return make_unibyte_string (sockun->sun_path, i);
2020 #endif
2021 default:
2022 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2023 address = Fcons (make_number (sa->sa_family),
2024 Fmake_vector (make_number (len), Qnil));
2025 p = XVECTOR (XCDR (address));
2026 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2027 break;
2030 i = 0;
2031 while (i < len)
2032 p->contents[i++] = make_number (*cp++);
2034 return address;
2038 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2040 static int
2041 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2043 register struct Lisp_Vector *p;
2045 if (VECTORP (address))
2047 p = XVECTOR (address);
2048 if (p->header.size == 5)
2050 *familyp = AF_INET;
2051 return sizeof (struct sockaddr_in);
2053 #ifdef AF_INET6
2054 else if (p->header.size == 9)
2056 *familyp = AF_INET6;
2057 return sizeof (struct sockaddr_in6);
2059 #endif
2061 #ifdef HAVE_LOCAL_SOCKETS
2062 else if (STRINGP (address))
2064 *familyp = AF_LOCAL;
2065 return sizeof (struct sockaddr_un);
2067 #endif
2068 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2069 && VECTORP (XCDR (address)))
2071 struct sockaddr *sa;
2072 *familyp = XINT (XCAR (address));
2073 p = XVECTOR (XCDR (address));
2074 return p->header.size + sizeof (sa->sa_family);
2076 return 0;
2079 /* Convert an address object (vector or string) to an internal sockaddr.
2081 The address format has been basically validated by
2082 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2083 it could have come from user data. So if FAMILY is not valid,
2084 we return after zeroing *SA. */
2086 static void
2087 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2089 register struct Lisp_Vector *p;
2090 register unsigned char *cp = NULL;
2091 register int i;
2092 EMACS_INT hostport;
2094 memset (sa, 0, len);
2096 if (VECTORP (address))
2098 p = XVECTOR (address);
2099 if (family == AF_INET)
2101 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2102 len = sizeof (sin->sin_addr) + 1;
2103 hostport = XINT (p->contents[--len]);
2104 sin->sin_port = htons (hostport);
2105 cp = (unsigned char *)&sin->sin_addr;
2106 sa->sa_family = family;
2108 #ifdef AF_INET6
2109 else if (family == AF_INET6)
2111 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2112 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2113 len = sizeof (sin6->sin6_addr) + 1;
2114 hostport = XINT (p->contents[--len]);
2115 sin6->sin6_port = htons (hostport);
2116 for (i = 0; i < len; i++)
2117 if (INTEGERP (p->contents[i]))
2119 int j = XFASTINT (p->contents[i]) & 0xffff;
2120 ip6[i] = ntohs (j);
2122 sa->sa_family = family;
2123 return;
2125 #endif
2126 else
2127 return;
2129 else if (STRINGP (address))
2131 #ifdef HAVE_LOCAL_SOCKETS
2132 if (family == AF_LOCAL)
2134 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2135 cp = SDATA (address);
2136 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2137 sockun->sun_path[i] = *cp++;
2138 sa->sa_family = family;
2140 #endif
2141 return;
2143 else
2145 p = XVECTOR (XCDR (address));
2146 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2149 for (i = 0; i < len; i++)
2150 if (INTEGERP (p->contents[i]))
2151 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2154 #ifdef DATAGRAM_SOCKETS
2155 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2156 1, 1, 0,
2157 doc: /* Get the current datagram address associated with PROCESS. */)
2158 (Lisp_Object process)
2160 int channel;
2162 CHECK_PROCESS (process);
2164 if (!DATAGRAM_CONN_P (process))
2165 return Qnil;
2167 channel = XPROCESS (process)->infd;
2168 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2169 datagram_address[channel].len);
2172 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2173 2, 2, 0,
2174 doc: /* Set the datagram address for PROCESS to ADDRESS.
2175 Returns nil upon error setting address, ADDRESS otherwise. */)
2176 (Lisp_Object process, Lisp_Object address)
2178 int channel;
2179 int family, len;
2181 CHECK_PROCESS (process);
2183 if (!DATAGRAM_CONN_P (process))
2184 return Qnil;
2186 channel = XPROCESS (process)->infd;
2188 len = get_lisp_to_sockaddr_size (address, &family);
2189 if (len == 0 || datagram_address[channel].len != len)
2190 return Qnil;
2191 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2192 return address;
2194 #endif
2197 static const struct socket_options {
2198 /* The name of this option. Should be lowercase version of option
2199 name without SO_ prefix. */
2200 const char *name;
2201 /* Option level SOL_... */
2202 int optlevel;
2203 /* Option number SO_... */
2204 int optnum;
2205 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2206 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2207 } socket_options[] =
2209 #ifdef SO_BINDTODEVICE
2210 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2211 #endif
2212 #ifdef SO_BROADCAST
2213 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2214 #endif
2215 #ifdef SO_DONTROUTE
2216 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2217 #endif
2218 #ifdef SO_KEEPALIVE
2219 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2220 #endif
2221 #ifdef SO_LINGER
2222 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2223 #endif
2224 #ifdef SO_OOBINLINE
2225 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2226 #endif
2227 #ifdef SO_PRIORITY
2228 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2229 #endif
2230 #ifdef SO_REUSEADDR
2231 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2232 #endif
2233 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2236 /* Set option OPT to value VAL on socket S.
2238 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2239 Signals an error if setting a known option fails.
2242 static int
2243 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2245 char *name;
2246 const struct socket_options *sopt;
2247 int ret = 0;
2249 CHECK_SYMBOL (opt);
2251 name = SSDATA (SYMBOL_NAME (opt));
2252 for (sopt = socket_options; sopt->name; sopt++)
2253 if (strcmp (name, sopt->name) == 0)
2254 break;
2256 switch (sopt->opttype)
2258 case SOPT_BOOL:
2260 int optval;
2261 optval = NILP (val) ? 0 : 1;
2262 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2263 &optval, sizeof (optval));
2264 break;
2267 case SOPT_INT:
2269 int optval;
2270 if (TYPE_RANGED_INTEGERP (int, val))
2271 optval = XINT (val);
2272 else
2273 error ("Bad option value for %s", name);
2274 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2275 &optval, sizeof (optval));
2276 break;
2279 #ifdef SO_BINDTODEVICE
2280 case SOPT_IFNAME:
2282 char devname[IFNAMSIZ+1];
2284 /* This is broken, at least in the Linux 2.4 kernel.
2285 To unbind, the arg must be a zero integer, not the empty string.
2286 This should work on all systems. KFS. 2003-09-23. */
2287 memset (devname, 0, sizeof devname);
2288 if (STRINGP (val))
2290 char *arg = SSDATA (val);
2291 int len = min (strlen (arg), IFNAMSIZ);
2292 memcpy (devname, arg, len);
2294 else if (!NILP (val))
2295 error ("Bad option value for %s", name);
2296 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2297 devname, IFNAMSIZ);
2298 break;
2300 #endif
2302 #ifdef SO_LINGER
2303 case SOPT_LINGER:
2305 struct linger linger;
2307 linger.l_onoff = 1;
2308 linger.l_linger = 0;
2309 if (TYPE_RANGED_INTEGERP (int, val))
2310 linger.l_linger = XINT (val);
2311 else
2312 linger.l_onoff = NILP (val) ? 0 : 1;
2313 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2314 &linger, sizeof (linger));
2315 break;
2317 #endif
2319 default:
2320 return 0;
2323 if (ret < 0)
2324 report_file_error ("Cannot set network option",
2325 Fcons (opt, Fcons (val, Qnil)));
2326 return (1 << sopt->optbit);
2330 DEFUN ("set-network-process-option",
2331 Fset_network_process_option, Sset_network_process_option,
2332 3, 4, 0,
2333 doc: /* For network process PROCESS set option OPTION to value VALUE.
2334 See `make-network-process' for a list of options and values.
2335 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2336 OPTION is not a supported option, return nil instead; otherwise return t. */)
2337 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2339 int s;
2340 struct Lisp_Process *p;
2342 CHECK_PROCESS (process);
2343 p = XPROCESS (process);
2344 if (!NETCONN1_P (p))
2345 error ("Process is not a network process");
2347 s = p->infd;
2348 if (s < 0)
2349 error ("Process is not running");
2351 if (set_socket_option (s, option, value))
2353 pset_childp (p, Fplist_put (p->childp, option, value));
2354 return Qt;
2357 if (NILP (no_error))
2358 error ("Unknown or unsupported option");
2360 return Qnil;
2364 DEFUN ("serial-process-configure",
2365 Fserial_process_configure,
2366 Sserial_process_configure,
2367 0, MANY, 0,
2368 doc: /* Configure speed, bytesize, etc. of a serial process.
2370 Arguments are specified as keyword/argument pairs. Attributes that
2371 are not given are re-initialized from the process's current
2372 configuration (available via the function `process-contact') or set to
2373 reasonable default values. The following arguments are defined:
2375 :process PROCESS
2376 :name NAME
2377 :buffer BUFFER
2378 :port PORT
2379 -- Any of these arguments can be given to identify the process that is
2380 to be configured. If none of these arguments is given, the current
2381 buffer's process is used.
2383 :speed SPEED -- SPEED is the speed of the serial port in bits per
2384 second, also called baud rate. Any value can be given for SPEED, but
2385 most serial ports work only at a few defined values between 1200 and
2386 115200, with 9600 being the most common value. If SPEED is nil, the
2387 serial port is not configured any further, i.e., all other arguments
2388 are ignored. This may be useful for special serial ports such as
2389 Bluetooth-to-serial converters which can only be configured through AT
2390 commands. A value of nil for SPEED can be used only when passed
2391 through `make-serial-process' or `serial-term'.
2393 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2394 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2396 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2397 `odd' (use odd parity), or the symbol `even' (use even parity). If
2398 PARITY is not given, no parity is used.
2400 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2401 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2402 is not given or nil, 1 stopbit is used.
2404 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2405 flowcontrol to be used, which is either nil (don't use flowcontrol),
2406 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2407 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2408 flowcontrol is used.
2410 `serial-process-configure' is called by `make-serial-process' for the
2411 initial configuration of the serial port.
2413 Examples:
2415 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2417 \(serial-process-configure
2418 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2420 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2422 usage: (serial-process-configure &rest ARGS) */)
2423 (ptrdiff_t nargs, Lisp_Object *args)
2425 struct Lisp_Process *p;
2426 Lisp_Object contact = Qnil;
2427 Lisp_Object proc = Qnil;
2428 struct gcpro gcpro1;
2430 contact = Flist (nargs, args);
2431 GCPRO1 (contact);
2433 proc = Fplist_get (contact, QCprocess);
2434 if (NILP (proc))
2435 proc = Fplist_get (contact, QCname);
2436 if (NILP (proc))
2437 proc = Fplist_get (contact, QCbuffer);
2438 if (NILP (proc))
2439 proc = Fplist_get (contact, QCport);
2440 proc = get_process (proc);
2441 p = XPROCESS (proc);
2442 if (!EQ (p->type, Qserial))
2443 error ("Not a serial process");
2445 if (NILP (Fplist_get (p->childp, QCspeed)))
2447 UNGCPRO;
2448 return Qnil;
2451 serial_configure (p, contact);
2453 UNGCPRO;
2454 return Qnil;
2457 /* Used by make-serial-process to recover from errors. */
2458 static Lisp_Object
2459 make_serial_process_unwind (Lisp_Object proc)
2461 if (!PROCESSP (proc))
2462 emacs_abort ();
2463 remove_process (proc);
2464 return Qnil;
2467 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2468 0, MANY, 0,
2469 doc: /* Create and return a serial port process.
2471 In Emacs, serial port connections are represented by process objects,
2472 so input and output work as for subprocesses, and `delete-process'
2473 closes a serial port connection. However, a serial process has no
2474 process id, it cannot be signaled, and the status codes are different
2475 from normal processes.
2477 `make-serial-process' creates a process and a buffer, on which you
2478 probably want to use `process-send-string'. Try \\[serial-term] for
2479 an interactive terminal. See below for examples.
2481 Arguments are specified as keyword/argument pairs. The following
2482 arguments are defined:
2484 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2485 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2486 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2487 the backslashes in strings).
2489 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2490 which this function calls.
2492 :name NAME -- NAME is the name of the process. If NAME is not given,
2493 the value of PORT is used.
2495 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2496 with the process. Process output goes at the end of that buffer,
2497 unless you specify an output stream or filter function to handle the
2498 output. If BUFFER is not given, the value of NAME is used.
2500 :coding CODING -- If CODING is a symbol, it specifies the coding
2501 system used for both reading and writing for this process. If CODING
2502 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2503 ENCODING is used for writing.
2505 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2506 the process is running. If BOOL is not given, query before exiting.
2508 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2509 In the stopped state, a serial process does not accept incoming data,
2510 but you can send outgoing data. The stopped state is cleared by
2511 `continue-process' and set by `stop-process'.
2513 :filter FILTER -- Install FILTER as the process filter.
2515 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2517 :plist PLIST -- Install PLIST as the initial plist of the process.
2519 :bytesize
2520 :parity
2521 :stopbits
2522 :flowcontrol
2523 -- This function calls `serial-process-configure' to handle these
2524 arguments.
2526 The original argument list, possibly modified by later configuration,
2527 is available via the function `process-contact'.
2529 Examples:
2531 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2533 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2535 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2537 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2539 usage: (make-serial-process &rest ARGS) */)
2540 (ptrdiff_t nargs, Lisp_Object *args)
2542 int fd = -1;
2543 Lisp_Object proc, contact, port;
2544 struct Lisp_Process *p;
2545 struct gcpro gcpro1;
2546 Lisp_Object name, buffer;
2547 Lisp_Object tem, val;
2548 ptrdiff_t specpdl_count;
2550 if (nargs == 0)
2551 return Qnil;
2553 contact = Flist (nargs, args);
2554 GCPRO1 (contact);
2556 port = Fplist_get (contact, QCport);
2557 if (NILP (port))
2558 error ("No port specified");
2559 CHECK_STRING (port);
2561 if (NILP (Fplist_member (contact, QCspeed)))
2562 error (":speed not specified");
2563 if (!NILP (Fplist_get (contact, QCspeed)))
2564 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2566 name = Fplist_get (contact, QCname);
2567 if (NILP (name))
2568 name = port;
2569 CHECK_STRING (name);
2570 proc = make_process (name);
2571 specpdl_count = SPECPDL_INDEX ();
2572 record_unwind_protect (make_serial_process_unwind, proc);
2573 p = XPROCESS (proc);
2575 fd = serial_open (SSDATA (port));
2576 p->infd = fd;
2577 p->outfd = fd;
2578 if (fd > max_process_desc)
2579 max_process_desc = fd;
2580 chan_process[fd] = proc;
2582 buffer = Fplist_get (contact, QCbuffer);
2583 if (NILP (buffer))
2584 buffer = name;
2585 buffer = Fget_buffer_create (buffer);
2586 pset_buffer (p, buffer);
2588 pset_childp (p, contact);
2589 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2590 pset_type (p, Qserial);
2591 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2592 pset_filter (p, Fplist_get (contact, QCfilter));
2593 pset_log (p, Qnil);
2594 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2595 p->kill_without_query = 1;
2596 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2597 pset_command (p, Qt);
2598 p->pty_flag = 0;
2600 if (!EQ (p->command, Qt))
2602 FD_SET (fd, &input_wait_mask);
2603 FD_SET (fd, &non_keyboard_wait_mask);
2606 if (BUFFERP (buffer))
2608 set_marker_both (p->mark, buffer,
2609 BUF_ZV (XBUFFER (buffer)),
2610 BUF_ZV_BYTE (XBUFFER (buffer)));
2613 tem = Fplist_member (contact, QCcoding);
2614 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2615 tem = Qnil;
2617 val = Qnil;
2618 if (!NILP (tem))
2620 val = XCAR (XCDR (tem));
2621 if (CONSP (val))
2622 val = XCAR (val);
2624 else if (!NILP (Vcoding_system_for_read))
2625 val = Vcoding_system_for_read;
2626 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2627 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2628 val = Qnil;
2629 pset_decode_coding_system (p, val);
2631 val = Qnil;
2632 if (!NILP (tem))
2634 val = XCAR (XCDR (tem));
2635 if (CONSP (val))
2636 val = XCDR (val);
2638 else if (!NILP (Vcoding_system_for_write))
2639 val = Vcoding_system_for_write;
2640 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2641 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2642 val = Qnil;
2643 pset_encode_coding_system (p, val);
2645 setup_process_coding_systems (proc);
2646 pset_decoding_buf (p, empty_unibyte_string);
2647 p->decoding_carryover = 0;
2648 pset_encoding_buf (p, empty_unibyte_string);
2649 p->inherit_coding_system_flag
2650 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2652 Fserial_process_configure (nargs, args);
2654 specpdl_ptr = specpdl + specpdl_count;
2656 UNGCPRO;
2657 return proc;
2660 /* Create a network stream/datagram client/server process. Treated
2661 exactly like a normal process when reading and writing. Primary
2662 differences are in status display and process deletion. A network
2663 connection has no PID; you cannot signal it. All you can do is
2664 stop/continue it and deactivate/close it via delete-process */
2666 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2667 0, MANY, 0,
2668 doc: /* Create and return a network server or client process.
2670 In Emacs, network connections are represented by process objects, so
2671 input and output work as for subprocesses and `delete-process' closes
2672 a network connection. However, a network process has no process id,
2673 it cannot be signaled, and the status codes are different from normal
2674 processes.
2676 Arguments are specified as keyword/argument pairs. The following
2677 arguments are defined:
2679 :name NAME -- NAME is name for process. It is modified if necessary
2680 to make it unique.
2682 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2683 with the process. Process output goes at end of that buffer, unless
2684 you specify an output stream or filter function to handle the output.
2685 BUFFER may be also nil, meaning that this process is not associated
2686 with any buffer.
2688 :host HOST -- HOST is name of the host to connect to, or its IP
2689 address. The symbol `local' specifies the local host. If specified
2690 for a server process, it must be a valid name or address for the local
2691 host, and only clients connecting to that address will be accepted.
2693 :service SERVICE -- SERVICE is name of the service desired, or an
2694 integer specifying a port number to connect to. If SERVICE is t,
2695 a random port number is selected for the server. (If Emacs was
2696 compiled with getaddrinfo, a port number can also be specified as a
2697 string, e.g. "80", as well as an integer. This is not portable.)
2699 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2700 stream type connection, `datagram' creates a datagram type connection,
2701 `seqpacket' creates a reliable datagram connection.
2703 :family FAMILY -- FAMILY is the address (and protocol) family for the
2704 service specified by HOST and SERVICE. The default (nil) is to use
2705 whatever address family (IPv4 or IPv6) that is defined for the host
2706 and port number specified by HOST and SERVICE. Other address families
2707 supported are:
2708 local -- for a local (i.e. UNIX) address specified by SERVICE.
2709 ipv4 -- use IPv4 address family only.
2710 ipv6 -- use IPv6 address family only.
2712 :local ADDRESS -- ADDRESS is the local address used for the connection.
2713 This parameter is ignored when opening a client process. When specified
2714 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2716 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2717 connection. This parameter is ignored when opening a stream server
2718 process. For a datagram server process, it specifies the initial
2719 setting of the remote datagram address. When specified for a client
2720 process, the FAMILY, HOST, and SERVICE args are ignored.
2722 The format of ADDRESS depends on the address family:
2723 - An IPv4 address is represented as an vector of integers [A B C D P]
2724 corresponding to numeric IP address A.B.C.D and port number P.
2725 - A local address is represented as a string with the address in the
2726 local address space.
2727 - An "unsupported family" address is represented by a cons (F . AV)
2728 where F is the family number and AV is a vector containing the socket
2729 address data with one element per address data byte. Do not rely on
2730 this format in portable code, as it may depend on implementation
2731 defined constants, data sizes, and data structure alignment.
2733 :coding CODING -- If CODING is a symbol, it specifies the coding
2734 system used for both reading and writing for this process. If CODING
2735 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2736 ENCODING is used for writing.
2738 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2739 return without waiting for the connection to complete; instead, the
2740 sentinel function will be called with second arg matching "open" (if
2741 successful) or "failed" when the connect completes. Default is to use
2742 a blocking connect (i.e. wait) for stream type connections.
2744 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2745 running when Emacs is exited.
2747 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2748 In the stopped state, a server process does not accept new
2749 connections, and a client process does not handle incoming traffic.
2750 The stopped state is cleared by `continue-process' and set by
2751 `stop-process'.
2753 :filter FILTER -- Install FILTER as the process filter.
2755 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2756 process filter are multibyte, otherwise they are unibyte.
2757 If this keyword is not specified, the strings are multibyte if
2758 the default value of `enable-multibyte-characters' is non-nil.
2760 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2762 :log LOG -- Install LOG as the server process log function. This
2763 function is called when the server accepts a network connection from a
2764 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2765 is the server process, CLIENT is the new process for the connection,
2766 and MESSAGE is a string.
2768 :plist PLIST -- Install PLIST as the new process' initial plist.
2770 :server QLEN -- if QLEN is non-nil, create a server process for the
2771 specified FAMILY, SERVICE, and connection type (stream or datagram).
2772 If QLEN is an integer, it is used as the max. length of the server's
2773 pending connection queue (also known as the backlog); the default
2774 queue length is 5. Default is to create a client process.
2776 The following network options can be specified for this connection:
2778 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2779 :dontroute BOOL -- Only send to directly connected hosts.
2780 :keepalive BOOL -- Send keep-alive messages on network stream.
2781 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2782 :oobinline BOOL -- Place out-of-band data in receive data stream.
2783 :priority INT -- Set protocol defined priority for sent packets.
2784 :reuseaddr BOOL -- Allow reusing a recently used local address
2785 (this is allowed by default for a server process).
2786 :bindtodevice NAME -- bind to interface NAME. Using this may require
2787 special privileges on some systems.
2789 Consult the relevant system programmer's manual pages for more
2790 information on using these options.
2793 A server process will listen for and accept connections from clients.
2794 When a client connection is accepted, a new network process is created
2795 for the connection with the following parameters:
2797 - The client's process name is constructed by concatenating the server
2798 process' NAME and a client identification string.
2799 - If the FILTER argument is non-nil, the client process will not get a
2800 separate process buffer; otherwise, the client's process buffer is a newly
2801 created buffer named after the server process' BUFFER name or process
2802 NAME concatenated with the client identification string.
2803 - The connection type and the process filter and sentinel parameters are
2804 inherited from the server process' TYPE, FILTER and SENTINEL.
2805 - The client process' contact info is set according to the client's
2806 addressing information (typically an IP address and a port number).
2807 - The client process' plist is initialized from the server's plist.
2809 Notice that the FILTER and SENTINEL args are never used directly by
2810 the server process. Also, the BUFFER argument is not used directly by
2811 the server process, but via the optional :log function, accepted (and
2812 failed) connections may be logged in the server process' buffer.
2814 The original argument list, modified with the actual connection
2815 information, is available via the `process-contact' function.
2817 usage: (make-network-process &rest ARGS) */)
2818 (ptrdiff_t nargs, Lisp_Object *args)
2820 Lisp_Object proc;
2821 Lisp_Object contact;
2822 struct Lisp_Process *p;
2823 #ifdef HAVE_GETADDRINFO
2824 struct addrinfo ai, *res, *lres;
2825 struct addrinfo hints;
2826 const char *portstring;
2827 char portbuf[128];
2828 #else /* HAVE_GETADDRINFO */
2829 struct _emacs_addrinfo
2831 int ai_family;
2832 int ai_socktype;
2833 int ai_protocol;
2834 int ai_addrlen;
2835 struct sockaddr *ai_addr;
2836 struct _emacs_addrinfo *ai_next;
2837 } ai, *res, *lres;
2838 #endif /* HAVE_GETADDRINFO */
2839 struct sockaddr_in address_in;
2840 #ifdef HAVE_LOCAL_SOCKETS
2841 struct sockaddr_un address_un;
2842 #endif
2843 int port;
2844 int ret = 0;
2845 int xerrno = 0;
2846 int s = -1, outch, inch;
2847 struct gcpro gcpro1;
2848 ptrdiff_t count = SPECPDL_INDEX ();
2849 ptrdiff_t count1;
2850 Lisp_Object QCaddress; /* one of QClocal or QCremote */
2851 Lisp_Object tem;
2852 Lisp_Object name, buffer, host, service, address;
2853 Lisp_Object filter, sentinel;
2854 bool is_non_blocking_client = 0;
2855 bool is_server = 0;
2856 int backlog = 5;
2857 int socktype;
2858 int family = -1;
2860 if (nargs == 0)
2861 return Qnil;
2863 /* Save arguments for process-contact and clone-process. */
2864 contact = Flist (nargs, args);
2865 GCPRO1 (contact);
2867 #ifdef WINDOWSNT
2868 /* Ensure socket support is loaded if available. */
2869 init_winsock (TRUE);
2870 #endif
2872 /* :type TYPE (nil: stream, datagram */
2873 tem = Fplist_get (contact, QCtype);
2874 if (NILP (tem))
2875 socktype = SOCK_STREAM;
2876 #ifdef DATAGRAM_SOCKETS
2877 else if (EQ (tem, Qdatagram))
2878 socktype = SOCK_DGRAM;
2879 #endif
2880 #ifdef HAVE_SEQPACKET
2881 else if (EQ (tem, Qseqpacket))
2882 socktype = SOCK_SEQPACKET;
2883 #endif
2884 else
2885 error ("Unsupported connection type");
2887 /* :server BOOL */
2888 tem = Fplist_get (contact, QCserver);
2889 if (!NILP (tem))
2891 /* Don't support network sockets when non-blocking mode is
2892 not available, since a blocked Emacs is not useful. */
2893 is_server = 1;
2894 if (TYPE_RANGED_INTEGERP (int, tem))
2895 backlog = XINT (tem);
2898 /* Make QCaddress an alias for :local (server) or :remote (client). */
2899 QCaddress = is_server ? QClocal : QCremote;
2901 /* :nowait BOOL */
2902 if (!is_server && socktype != SOCK_DGRAM
2903 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2905 #ifndef NON_BLOCKING_CONNECT
2906 error ("Non-blocking connect not supported");
2907 #else
2908 is_non_blocking_client = 1;
2909 #endif
2912 name = Fplist_get (contact, QCname);
2913 buffer = Fplist_get (contact, QCbuffer);
2914 filter = Fplist_get (contact, QCfilter);
2915 sentinel = Fplist_get (contact, QCsentinel);
2917 CHECK_STRING (name);
2919 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2920 ai.ai_socktype = socktype;
2921 ai.ai_protocol = 0;
2922 ai.ai_next = NULL;
2923 res = &ai;
2925 /* :local ADDRESS or :remote ADDRESS */
2926 address = Fplist_get (contact, QCaddress);
2927 if (!NILP (address))
2929 host = service = Qnil;
2931 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2932 error ("Malformed :address");
2933 ai.ai_family = family;
2934 ai.ai_addr = alloca (ai.ai_addrlen);
2935 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
2936 goto open_socket;
2939 /* :family FAMILY -- nil (for Inet), local, or integer. */
2940 tem = Fplist_get (contact, QCfamily);
2941 if (NILP (tem))
2943 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
2944 family = AF_UNSPEC;
2945 #else
2946 family = AF_INET;
2947 #endif
2949 #ifdef HAVE_LOCAL_SOCKETS
2950 else if (EQ (tem, Qlocal))
2951 family = AF_LOCAL;
2952 #endif
2953 #ifdef AF_INET6
2954 else if (EQ (tem, Qipv6))
2955 family = AF_INET6;
2956 #endif
2957 else if (EQ (tem, Qipv4))
2958 family = AF_INET;
2959 else if (TYPE_RANGED_INTEGERP (int, tem))
2960 family = XINT (tem);
2961 else
2962 error ("Unknown address family");
2964 ai.ai_family = family;
2966 /* :service SERVICE -- string, integer (port number), or t (random port). */
2967 service = Fplist_get (contact, QCservice);
2969 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2970 host = Fplist_get (contact, QChost);
2971 if (!NILP (host))
2973 if (EQ (host, Qlocal))
2974 /* Depending on setup, "localhost" may map to different IPv4 and/or
2975 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
2976 host = build_string ("127.0.0.1");
2977 CHECK_STRING (host);
2980 #ifdef HAVE_LOCAL_SOCKETS
2981 if (family == AF_LOCAL)
2983 if (!NILP (host))
2985 message (":family local ignores the :host \"%s\" property",
2986 SDATA (host));
2987 contact = Fplist_put (contact, QChost, Qnil);
2988 host = Qnil;
2990 CHECK_STRING (service);
2991 memset (&address_un, 0, sizeof address_un);
2992 address_un.sun_family = AF_LOCAL;
2993 if (sizeof address_un.sun_path <= SBYTES (service))
2994 error ("Service name too long");
2995 strcpy (address_un.sun_path, SSDATA (service));
2996 ai.ai_addr = (struct sockaddr *) &address_un;
2997 ai.ai_addrlen = sizeof address_un;
2998 goto open_socket;
3000 #endif
3002 /* Slow down polling to every ten seconds.
3003 Some kernels have a bug which causes retrying connect to fail
3004 after a connect. Polling can interfere with gethostbyname too. */
3005 #ifdef POLL_FOR_INPUT
3006 if (socktype != SOCK_DGRAM)
3008 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3009 bind_polling_period (10);
3011 #endif
3013 #ifdef HAVE_GETADDRINFO
3014 /* If we have a host, use getaddrinfo to resolve both host and service.
3015 Otherwise, use getservbyname to lookup the service. */
3016 if (!NILP (host))
3019 /* SERVICE can either be a string or int.
3020 Convert to a C string for later use by getaddrinfo. */
3021 if (EQ (service, Qt))
3022 portstring = "0";
3023 else if (INTEGERP (service))
3025 sprintf (portbuf, "%"pI"d", XINT (service));
3026 portstring = portbuf;
3028 else
3030 CHECK_STRING (service);
3031 portstring = SSDATA (service);
3034 immediate_quit = 1;
3035 QUIT;
3036 memset (&hints, 0, sizeof (hints));
3037 hints.ai_flags = 0;
3038 hints.ai_family = family;
3039 hints.ai_socktype = socktype;
3040 hints.ai_protocol = 0;
3042 #ifdef HAVE_RES_INIT
3043 res_init ();
3044 #endif
3046 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3047 if (ret)
3048 #ifdef HAVE_GAI_STRERROR
3049 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3050 #else
3051 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3052 #endif
3053 immediate_quit = 0;
3055 goto open_socket;
3057 #endif /* HAVE_GETADDRINFO */
3059 /* We end up here if getaddrinfo is not defined, or in case no hostname
3060 has been specified (e.g. for a local server process). */
3062 if (EQ (service, Qt))
3063 port = 0;
3064 else if (INTEGERP (service))
3065 port = htons ((unsigned short) XINT (service));
3066 else
3068 struct servent *svc_info;
3069 CHECK_STRING (service);
3070 svc_info = getservbyname (SSDATA (service),
3071 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3072 if (svc_info == 0)
3073 error ("Unknown service: %s", SDATA (service));
3074 port = svc_info->s_port;
3077 memset (&address_in, 0, sizeof address_in);
3078 address_in.sin_family = family;
3079 address_in.sin_addr.s_addr = INADDR_ANY;
3080 address_in.sin_port = port;
3082 #ifndef HAVE_GETADDRINFO
3083 if (!NILP (host))
3085 struct hostent *host_info_ptr;
3087 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3088 as it may `hang' Emacs for a very long time. */
3089 immediate_quit = 1;
3090 QUIT;
3092 #ifdef HAVE_RES_INIT
3093 res_init ();
3094 #endif
3096 host_info_ptr = gethostbyname (SDATA (host));
3097 immediate_quit = 0;
3099 if (host_info_ptr)
3101 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3102 host_info_ptr->h_length);
3103 family = host_info_ptr->h_addrtype;
3104 address_in.sin_family = family;
3106 else
3107 /* Attempt to interpret host as numeric inet address */
3109 unsigned long numeric_addr;
3110 numeric_addr = inet_addr (SSDATA (host));
3111 if (numeric_addr == -1)
3112 error ("Unknown host \"%s\"", SDATA (host));
3114 memcpy (&address_in.sin_addr, &numeric_addr,
3115 sizeof (address_in.sin_addr));
3119 #endif /* not HAVE_GETADDRINFO */
3121 ai.ai_family = family;
3122 ai.ai_addr = (struct sockaddr *) &address_in;
3123 ai.ai_addrlen = sizeof address_in;
3125 open_socket:
3127 /* Do this in case we never enter the for-loop below. */
3128 count1 = SPECPDL_INDEX ();
3129 s = -1;
3131 for (lres = res; lres; lres = lres->ai_next)
3133 ptrdiff_t optn;
3134 int optbits;
3136 #ifdef WINDOWSNT
3137 retry_connect:
3138 #endif
3140 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3141 if (s < 0)
3143 xerrno = errno;
3144 continue;
3147 #ifdef DATAGRAM_SOCKETS
3148 if (!is_server && socktype == SOCK_DGRAM)
3149 break;
3150 #endif /* DATAGRAM_SOCKETS */
3152 #ifdef NON_BLOCKING_CONNECT
3153 if (is_non_blocking_client)
3155 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3156 if (ret < 0)
3158 xerrno = errno;
3159 emacs_close (s);
3160 s = -1;
3161 continue;
3164 #endif
3166 /* Make us close S if quit. */
3167 record_unwind_protect (close_file_unwind, make_number (s));
3169 /* Parse network options in the arg list.
3170 We simply ignore anything which isn't a known option (including other keywords).
3171 An error is signaled if setting a known option fails. */
3172 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3173 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3175 if (is_server)
3177 /* Configure as a server socket. */
3179 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3180 explicit :reuseaddr key to override this. */
3181 #ifdef HAVE_LOCAL_SOCKETS
3182 if (family != AF_LOCAL)
3183 #endif
3184 if (!(optbits & (1 << OPIX_REUSEADDR)))
3186 int optval = 1;
3187 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3188 report_file_error ("Cannot set reuse option on server socket", Qnil);
3191 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3192 report_file_error ("Cannot bind server socket", Qnil);
3194 #ifdef HAVE_GETSOCKNAME
3195 if (EQ (service, Qt))
3197 struct sockaddr_in sa1;
3198 socklen_t len1 = sizeof (sa1);
3199 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3201 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3202 service = make_number (ntohs (sa1.sin_port));
3203 contact = Fplist_put (contact, QCservice, service);
3206 #endif
3208 if (socktype != SOCK_DGRAM && listen (s, backlog))
3209 report_file_error ("Cannot listen on server socket", Qnil);
3211 break;
3214 immediate_quit = 1;
3215 QUIT;
3217 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3218 xerrno = errno;
3220 if (ret == 0 || xerrno == EISCONN)
3222 /* The unwind-protect will be discarded afterwards.
3223 Likewise for immediate_quit. */
3224 break;
3227 #ifdef NON_BLOCKING_CONNECT
3228 #ifdef EINPROGRESS
3229 if (is_non_blocking_client && xerrno == EINPROGRESS)
3230 break;
3231 #else
3232 #ifdef EWOULDBLOCK
3233 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3234 break;
3235 #endif
3236 #endif
3237 #endif
3239 #ifndef WINDOWSNT
3240 if (xerrno == EINTR)
3242 /* Unlike most other syscalls connect() cannot be called
3243 again. (That would return EALREADY.) The proper way to
3244 wait for completion is pselect(). */
3245 int sc;
3246 socklen_t len;
3247 SELECT_TYPE fdset;
3248 retry_select:
3249 FD_ZERO (&fdset);
3250 FD_SET (s, &fdset);
3251 QUIT;
3252 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3253 if (sc == -1)
3255 if (errno == EINTR)
3256 goto retry_select;
3257 else
3258 report_file_error ("select failed", Qnil);
3260 eassert (sc > 0);
3262 len = sizeof xerrno;
3263 eassert (FD_ISSET (s, &fdset));
3264 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3265 report_file_error ("getsockopt failed", Qnil);
3266 if (xerrno)
3267 errno = xerrno, report_file_error ("error during connect", Qnil);
3268 else
3269 break;
3271 #endif /* !WINDOWSNT */
3273 immediate_quit = 0;
3275 /* Discard the unwind protect closing S. */
3276 specpdl_ptr = specpdl + count1;
3277 emacs_close (s);
3278 s = -1;
3280 #ifdef WINDOWSNT
3281 if (xerrno == EINTR)
3282 goto retry_connect;
3283 #endif
3286 if (s >= 0)
3288 #ifdef DATAGRAM_SOCKETS
3289 if (socktype == SOCK_DGRAM)
3291 if (datagram_address[s].sa)
3292 emacs_abort ();
3293 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3294 datagram_address[s].len = lres->ai_addrlen;
3295 if (is_server)
3297 Lisp_Object remote;
3298 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3299 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3301 int rfamily, rlen;
3302 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3303 if (rlen != 0 && rfamily == lres->ai_family
3304 && rlen == lres->ai_addrlen)
3305 conv_lisp_to_sockaddr (rfamily, remote,
3306 datagram_address[s].sa, rlen);
3309 else
3310 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3312 #endif
3313 contact = Fplist_put (contact, QCaddress,
3314 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3315 #ifdef HAVE_GETSOCKNAME
3316 if (!is_server)
3318 struct sockaddr_in sa1;
3319 socklen_t len1 = sizeof (sa1);
3320 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3321 contact = Fplist_put (contact, QClocal,
3322 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3324 #endif
3327 immediate_quit = 0;
3329 #ifdef HAVE_GETADDRINFO
3330 if (res != &ai)
3332 block_input ();
3333 freeaddrinfo (res);
3334 unblock_input ();
3336 #endif
3338 /* Discard the unwind protect for closing S, if any. */
3339 specpdl_ptr = specpdl + count1;
3341 /* Unwind bind_polling_period and request_sigio. */
3342 unbind_to (count, Qnil);
3344 if (s < 0)
3346 /* If non-blocking got this far - and failed - assume non-blocking is
3347 not supported after all. This is probably a wrong assumption, but
3348 the normal blocking calls to open-network-stream handles this error
3349 better. */
3350 if (is_non_blocking_client)
3351 return Qnil;
3353 errno = xerrno;
3354 if (is_server)
3355 report_file_error ("make server process failed", contact);
3356 else
3357 report_file_error ("make client process failed", contact);
3360 inch = s;
3361 outch = s;
3363 if (!NILP (buffer))
3364 buffer = Fget_buffer_create (buffer);
3365 proc = make_process (name);
3367 chan_process[inch] = proc;
3369 fcntl (inch, F_SETFL, O_NONBLOCK);
3371 p = XPROCESS (proc);
3373 pset_childp (p, contact);
3374 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3375 pset_type (p, Qnetwork);
3377 pset_buffer (p, buffer);
3378 pset_sentinel (p, sentinel);
3379 pset_filter (p, filter);
3380 pset_log (p, Fplist_get (contact, QClog));
3381 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3382 p->kill_without_query = 1;
3383 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3384 pset_command (p, Qt);
3385 p->pid = 0;
3386 p->infd = inch;
3387 p->outfd = outch;
3388 if (is_server && socktype != SOCK_DGRAM)
3389 pset_status (p, Qlisten);
3391 /* Make the process marker point into the process buffer (if any). */
3392 if (BUFFERP (buffer))
3393 set_marker_both (p->mark, buffer,
3394 BUF_ZV (XBUFFER (buffer)),
3395 BUF_ZV_BYTE (XBUFFER (buffer)));
3397 #ifdef NON_BLOCKING_CONNECT
3398 if (is_non_blocking_client)
3400 /* We may get here if connect did succeed immediately. However,
3401 in that case, we still need to signal this like a non-blocking
3402 connection. */
3403 pset_status (p, Qconnect);
3404 if (!FD_ISSET (inch, &connect_wait_mask))
3406 FD_SET (inch, &connect_wait_mask);
3407 FD_SET (inch, &write_mask);
3408 num_pending_connects++;
3411 else
3412 #endif
3413 /* A server may have a client filter setting of Qt, but it must
3414 still listen for incoming connects unless it is stopped. */
3415 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3416 || (EQ (p->status, Qlisten) && NILP (p->command)))
3418 FD_SET (inch, &input_wait_mask);
3419 FD_SET (inch, &non_keyboard_wait_mask);
3422 if (inch > max_process_desc)
3423 max_process_desc = inch;
3425 tem = Fplist_member (contact, QCcoding);
3426 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3427 tem = Qnil; /* No error message (too late!). */
3430 /* Setup coding systems for communicating with the network stream. */
3431 struct gcpro gcpro1;
3432 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3433 Lisp_Object coding_systems = Qt;
3434 Lisp_Object fargs[5], val;
3436 if (!NILP (tem))
3438 val = XCAR (XCDR (tem));
3439 if (CONSP (val))
3440 val = XCAR (val);
3442 else if (!NILP (Vcoding_system_for_read))
3443 val = Vcoding_system_for_read;
3444 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3445 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3446 /* We dare not decode end-of-line format by setting VAL to
3447 Qraw_text, because the existing Emacs Lisp libraries
3448 assume that they receive bare code including a sequence of
3449 CR LF. */
3450 val = Qnil;
3451 else
3453 if (NILP (host) || NILP (service))
3454 coding_systems = Qnil;
3455 else
3457 fargs[0] = Qopen_network_stream, fargs[1] = name,
3458 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3459 GCPRO1 (proc);
3460 coding_systems = Ffind_operation_coding_system (5, fargs);
3461 UNGCPRO;
3463 if (CONSP (coding_systems))
3464 val = XCAR (coding_systems);
3465 else if (CONSP (Vdefault_process_coding_system))
3466 val = XCAR (Vdefault_process_coding_system);
3467 else
3468 val = Qnil;
3470 pset_decode_coding_system (p, val);
3472 if (!NILP (tem))
3474 val = XCAR (XCDR (tem));
3475 if (CONSP (val))
3476 val = XCDR (val);
3478 else if (!NILP (Vcoding_system_for_write))
3479 val = Vcoding_system_for_write;
3480 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3481 val = Qnil;
3482 else
3484 if (EQ (coding_systems, Qt))
3486 if (NILP (host) || NILP (service))
3487 coding_systems = Qnil;
3488 else
3490 fargs[0] = Qopen_network_stream, fargs[1] = name,
3491 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3492 GCPRO1 (proc);
3493 coding_systems = Ffind_operation_coding_system (5, fargs);
3494 UNGCPRO;
3497 if (CONSP (coding_systems))
3498 val = XCDR (coding_systems);
3499 else if (CONSP (Vdefault_process_coding_system))
3500 val = XCDR (Vdefault_process_coding_system);
3501 else
3502 val = Qnil;
3504 pset_encode_coding_system (p, val);
3506 setup_process_coding_systems (proc);
3508 pset_decoding_buf (p, empty_unibyte_string);
3509 p->decoding_carryover = 0;
3510 pset_encoding_buf (p, empty_unibyte_string);
3512 p->inherit_coding_system_flag
3513 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3515 UNGCPRO;
3516 return proc;
3520 #if defined (HAVE_NET_IF_H)
3522 #ifdef SIOCGIFCONF
3523 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3524 doc: /* Return an alist of all network interfaces and their network address.
3525 Each element is a cons, the car of which is a string containing the
3526 interface name, and the cdr is the network address in internal
3527 format; see the description of ADDRESS in `make-network-process'. */)
3528 (void)
3530 struct ifconf ifconf;
3531 struct ifreq *ifreq;
3532 void *buf = NULL;
3533 ptrdiff_t buf_size = 512;
3534 int s;
3535 Lisp_Object res;
3537 s = socket (AF_INET, SOCK_STREAM, 0);
3538 if (s < 0)
3539 return Qnil;
3543 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3544 ifconf.ifc_buf = buf;
3545 ifconf.ifc_len = buf_size;
3546 if (ioctl (s, SIOCGIFCONF, &ifconf))
3548 close (s);
3549 xfree (buf);
3550 return Qnil;
3553 while (ifconf.ifc_len == buf_size);
3555 close (s);
3557 res = Qnil;
3558 ifreq = ifconf.ifc_req;
3559 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3561 struct ifreq *ifq = ifreq;
3562 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3563 #define SIZEOF_IFREQ(sif) \
3564 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3565 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3567 int len = SIZEOF_IFREQ (ifq);
3568 #else
3569 int len = sizeof (*ifreq);
3570 #endif
3571 char namebuf[sizeof (ifq->ifr_name) + 1];
3572 ifreq = (struct ifreq *) ((char *) ifreq + len);
3574 if (ifq->ifr_addr.sa_family != AF_INET)
3575 continue;
3577 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3578 namebuf[sizeof (ifq->ifr_name)] = 0;
3579 res = Fcons (Fcons (build_string (namebuf),
3580 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3581 sizeof (struct sockaddr))),
3582 res);
3585 xfree (buf);
3586 return res;
3588 #endif /* SIOCGIFCONF */
3590 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3592 struct ifflag_def {
3593 int flag_bit;
3594 const char *flag_sym;
3597 static const struct ifflag_def ifflag_table[] = {
3598 #ifdef IFF_UP
3599 { IFF_UP, "up" },
3600 #endif
3601 #ifdef IFF_BROADCAST
3602 { IFF_BROADCAST, "broadcast" },
3603 #endif
3604 #ifdef IFF_DEBUG
3605 { IFF_DEBUG, "debug" },
3606 #endif
3607 #ifdef IFF_LOOPBACK
3608 { IFF_LOOPBACK, "loopback" },
3609 #endif
3610 #ifdef IFF_POINTOPOINT
3611 { IFF_POINTOPOINT, "pointopoint" },
3612 #endif
3613 #ifdef IFF_RUNNING
3614 { IFF_RUNNING, "running" },
3615 #endif
3616 #ifdef IFF_NOARP
3617 { IFF_NOARP, "noarp" },
3618 #endif
3619 #ifdef IFF_PROMISC
3620 { IFF_PROMISC, "promisc" },
3621 #endif
3622 #ifdef IFF_NOTRAILERS
3623 #ifdef NS_IMPL_COCOA
3624 /* Really means smart, notrailers is obsolete */
3625 { IFF_NOTRAILERS, "smart" },
3626 #else
3627 { IFF_NOTRAILERS, "notrailers" },
3628 #endif
3629 #endif
3630 #ifdef IFF_ALLMULTI
3631 { IFF_ALLMULTI, "allmulti" },
3632 #endif
3633 #ifdef IFF_MASTER
3634 { IFF_MASTER, "master" },
3635 #endif
3636 #ifdef IFF_SLAVE
3637 { IFF_SLAVE, "slave" },
3638 #endif
3639 #ifdef IFF_MULTICAST
3640 { IFF_MULTICAST, "multicast" },
3641 #endif
3642 #ifdef IFF_PORTSEL
3643 { IFF_PORTSEL, "portsel" },
3644 #endif
3645 #ifdef IFF_AUTOMEDIA
3646 { IFF_AUTOMEDIA, "automedia" },
3647 #endif
3648 #ifdef IFF_DYNAMIC
3649 { IFF_DYNAMIC, "dynamic" },
3650 #endif
3651 #ifdef IFF_OACTIVE
3652 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3653 #endif
3654 #ifdef IFF_SIMPLEX
3655 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3656 #endif
3657 #ifdef IFF_LINK0
3658 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3659 #endif
3660 #ifdef IFF_LINK1
3661 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3662 #endif
3663 #ifdef IFF_LINK2
3664 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3665 #endif
3666 { 0, 0 }
3669 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3670 doc: /* Return information about network interface named IFNAME.
3671 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3672 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3673 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3674 FLAGS is the current flags of the interface. */)
3675 (Lisp_Object ifname)
3677 struct ifreq rq;
3678 Lisp_Object res = Qnil;
3679 Lisp_Object elt;
3680 int s;
3681 bool any = 0;
3682 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3683 && defined HAVE_GETIFADDRS && defined LLADDR)
3684 struct ifaddrs *ifap;
3685 #endif
3687 CHECK_STRING (ifname);
3689 if (sizeof rq.ifr_name <= SBYTES (ifname))
3690 error ("interface name too long");
3691 strcpy (rq.ifr_name, SSDATA (ifname));
3693 s = socket (AF_INET, SOCK_STREAM, 0);
3694 if (s < 0)
3695 return Qnil;
3697 elt = Qnil;
3698 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3699 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3701 int flags = rq.ifr_flags;
3702 const struct ifflag_def *fp;
3703 int fnum;
3705 /* If flags is smaller than int (i.e. short) it may have the high bit set
3706 due to IFF_MULTICAST. In that case, sign extending it into
3707 an int is wrong. */
3708 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3709 flags = (unsigned short) rq.ifr_flags;
3711 any = 1;
3712 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3714 if (flags & fp->flag_bit)
3716 elt = Fcons (intern (fp->flag_sym), elt);
3717 flags -= fp->flag_bit;
3720 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3722 if (flags & 1)
3724 elt = Fcons (make_number (fnum), elt);
3728 #endif
3729 res = Fcons (elt, res);
3731 elt = Qnil;
3732 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3733 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3735 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3736 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3737 int n;
3739 any = 1;
3740 for (n = 0; n < 6; n++)
3741 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3742 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3744 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3745 if (getifaddrs (&ifap) != -1)
3747 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3748 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3749 struct ifaddrs *it;
3751 for (it = ifap; it != NULL; it = it->ifa_next)
3753 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3754 unsigned char linkaddr[6];
3755 int n;
3757 if (it->ifa_addr->sa_family != AF_LINK
3758 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3759 || sdl->sdl_alen != 6)
3760 continue;
3762 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3763 for (n = 0; n < 6; n++)
3764 p->contents[n] = make_number (linkaddr[n]);
3766 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
3767 break;
3770 #ifdef HAVE_FREEIFADDRS
3771 freeifaddrs (ifap);
3772 #endif
3774 #endif /* HAVE_GETIFADDRS && LLADDR */
3776 res = Fcons (elt, res);
3778 elt = Qnil;
3779 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3780 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3782 any = 1;
3783 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3784 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3785 #else
3786 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3787 #endif
3789 #endif
3790 res = Fcons (elt, res);
3792 elt = Qnil;
3793 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3794 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3796 any = 1;
3797 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3799 #endif
3800 res = Fcons (elt, res);
3802 elt = Qnil;
3803 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3804 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3806 any = 1;
3807 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3809 #endif
3810 res = Fcons (elt, res);
3812 close (s);
3814 return any ? res : Qnil;
3816 #endif
3817 #endif /* defined (HAVE_NET_IF_H) */
3819 /* Turn off input and output for process PROC. */
3821 static void
3822 deactivate_process (Lisp_Object proc)
3824 register int inchannel, outchannel;
3825 register struct Lisp_Process *p = XPROCESS (proc);
3827 #ifdef HAVE_GNUTLS
3828 /* Delete GnuTLS structures in PROC, if any. */
3829 emacs_gnutls_deinit (proc);
3830 #endif /* HAVE_GNUTLS */
3832 inchannel = p->infd;
3833 outchannel = p->outfd;
3835 #ifdef ADAPTIVE_READ_BUFFERING
3836 if (p->read_output_delay > 0)
3838 if (--process_output_delay_count < 0)
3839 process_output_delay_count = 0;
3840 p->read_output_delay = 0;
3841 p->read_output_skip = 0;
3843 #endif
3845 if (inchannel >= 0)
3847 /* Beware SIGCHLD hereabouts. */
3848 flush_pending_output (inchannel);
3849 emacs_close (inchannel);
3850 if (outchannel >= 0 && outchannel != inchannel)
3851 emacs_close (outchannel);
3853 p->infd = -1;
3854 p->outfd = -1;
3855 #ifdef DATAGRAM_SOCKETS
3856 if (DATAGRAM_CHAN_P (inchannel))
3858 xfree (datagram_address[inchannel].sa);
3859 datagram_address[inchannel].sa = 0;
3860 datagram_address[inchannel].len = 0;
3862 #endif
3863 chan_process[inchannel] = Qnil;
3864 FD_CLR (inchannel, &input_wait_mask);
3865 FD_CLR (inchannel, &non_keyboard_wait_mask);
3866 #ifdef NON_BLOCKING_CONNECT
3867 if (FD_ISSET (inchannel, &connect_wait_mask))
3869 FD_CLR (inchannel, &connect_wait_mask);
3870 FD_CLR (inchannel, &write_mask);
3871 if (--num_pending_connects < 0)
3872 emacs_abort ();
3874 #endif
3875 if (inchannel == max_process_desc)
3877 int i;
3878 /* We just closed the highest-numbered process input descriptor,
3879 so recompute the highest-numbered one now. */
3880 max_process_desc = 0;
3881 for (i = 0; i < MAXDESC; i++)
3882 if (!NILP (chan_process[i]))
3883 max_process_desc = i;
3889 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3890 0, 4, 0,
3891 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3892 It is read into the process' buffers or given to their filter functions.
3893 Non-nil arg PROCESS means do not return until some output has been received
3894 from PROCESS.
3896 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
3897 and milliseconds to wait; return after that much time whether or not
3898 there is any subprocess output. If SECONDS is a floating point number,
3899 it specifies a fractional number of seconds to wait.
3900 The MILLISEC argument is obsolete and should be avoided.
3902 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
3903 from PROCESS, suspending reading output from other processes.
3904 If JUST-THIS-ONE is an integer, don't run any timers either.
3905 Return non-nil if we received any output before the timeout expired. */)
3906 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
3908 intmax_t secs;
3909 int nsecs;
3911 if (! NILP (process))
3912 CHECK_PROCESS (process);
3913 else
3914 just_this_one = Qnil;
3916 if (!NILP (millisec))
3917 { /* Obsolete calling convention using integers rather than floats. */
3918 CHECK_NUMBER (millisec);
3919 if (NILP (seconds))
3920 seconds = make_float (XINT (millisec) / 1000.0);
3921 else
3923 CHECK_NUMBER (seconds);
3924 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
3928 secs = 0;
3929 nsecs = -1;
3931 if (!NILP (seconds))
3933 if (INTEGERP (seconds))
3935 if (XINT (seconds) > 0)
3937 secs = XINT (seconds);
3938 nsecs = 0;
3941 else if (FLOATP (seconds))
3943 if (XFLOAT_DATA (seconds) > 0)
3945 EMACS_TIME t = EMACS_TIME_FROM_DOUBLE (XFLOAT_DATA (seconds));
3946 secs = min (EMACS_SECS (t), WAIT_READING_MAX);
3947 nsecs = EMACS_NSECS (t);
3950 else
3951 wrong_type_argument (Qnumberp, seconds);
3953 else if (! NILP (process))
3954 nsecs = 0;
3956 return
3957 (wait_reading_process_output (secs, nsecs, 0, 0,
3958 Qnil,
3959 !NILP (process) ? XPROCESS (process) : NULL,
3960 NILP (just_this_one) ? 0 :
3961 !INTEGERP (just_this_one) ? 1 : -1)
3962 ? Qt : Qnil);
3965 /* Accept a connection for server process SERVER on CHANNEL. */
3967 static EMACS_INT connect_counter = 0;
3969 static void
3970 server_accept_connection (Lisp_Object server, int channel)
3972 Lisp_Object proc, caller, name, buffer;
3973 Lisp_Object contact, host, service;
3974 struct Lisp_Process *ps= XPROCESS (server);
3975 struct Lisp_Process *p;
3976 int s;
3977 union u_sockaddr {
3978 struct sockaddr sa;
3979 struct sockaddr_in in;
3980 #ifdef AF_INET6
3981 struct sockaddr_in6 in6;
3982 #endif
3983 #ifdef HAVE_LOCAL_SOCKETS
3984 struct sockaddr_un un;
3985 #endif
3986 } saddr;
3987 socklen_t len = sizeof saddr;
3989 s = accept (channel, &saddr.sa, &len);
3991 if (s < 0)
3993 int code = errno;
3995 if (code == EAGAIN)
3996 return;
3997 #ifdef EWOULDBLOCK
3998 if (code == EWOULDBLOCK)
3999 return;
4000 #endif
4002 if (!NILP (ps->log))
4003 call3 (ps->log, server, Qnil,
4004 concat3 (build_string ("accept failed with code"),
4005 Fnumber_to_string (make_number (code)),
4006 build_string ("\n")));
4007 return;
4010 connect_counter++;
4012 /* Setup a new process to handle the connection. */
4014 /* Generate a unique identification of the caller, and build contact
4015 information for this process. */
4016 host = Qt;
4017 service = Qnil;
4018 switch (saddr.sa.sa_family)
4020 case AF_INET:
4022 Lisp_Object args[5];
4023 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4024 args[0] = build_string ("%d.%d.%d.%d");
4025 args[1] = make_number (*ip++);
4026 args[2] = make_number (*ip++);
4027 args[3] = make_number (*ip++);
4028 args[4] = make_number (*ip++);
4029 host = Fformat (5, args);
4030 service = make_number (ntohs (saddr.in.sin_port));
4032 args[0] = build_string (" <%s:%d>");
4033 args[1] = host;
4034 args[2] = service;
4035 caller = Fformat (3, args);
4037 break;
4039 #ifdef AF_INET6
4040 case AF_INET6:
4042 Lisp_Object args[9];
4043 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4044 int i;
4045 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4046 for (i = 0; i < 8; i++)
4047 args[i+1] = make_number (ntohs (ip6[i]));
4048 host = Fformat (9, args);
4049 service = make_number (ntohs (saddr.in.sin_port));
4051 args[0] = build_string (" <[%s]:%d>");
4052 args[1] = host;
4053 args[2] = service;
4054 caller = Fformat (3, args);
4056 break;
4057 #endif
4059 #ifdef HAVE_LOCAL_SOCKETS
4060 case AF_LOCAL:
4061 #endif
4062 default:
4063 caller = Fnumber_to_string (make_number (connect_counter));
4064 caller = concat3 (build_string (" <"), caller, build_string (">"));
4065 break;
4068 /* Create a new buffer name for this process if it doesn't have a
4069 filter. The new buffer name is based on the buffer name or
4070 process name of the server process concatenated with the caller
4071 identification. */
4073 if (!(EQ (ps->filter, Qinternal_default_process_filter)
4074 || EQ (ps->filter, Qt)))
4075 buffer = Qnil;
4076 else
4078 buffer = ps->buffer;
4079 if (!NILP (buffer))
4080 buffer = Fbuffer_name (buffer);
4081 else
4082 buffer = ps->name;
4083 if (!NILP (buffer))
4085 buffer = concat2 (buffer, caller);
4086 buffer = Fget_buffer_create (buffer);
4090 /* Generate a unique name for the new server process. Combine the
4091 server process name with the caller identification. */
4093 name = concat2 (ps->name, caller);
4094 proc = make_process (name);
4096 chan_process[s] = proc;
4098 fcntl (s, F_SETFL, O_NONBLOCK);
4100 p = XPROCESS (proc);
4102 /* Build new contact information for this setup. */
4103 contact = Fcopy_sequence (ps->childp);
4104 contact = Fplist_put (contact, QCserver, Qnil);
4105 contact = Fplist_put (contact, QChost, host);
4106 if (!NILP (service))
4107 contact = Fplist_put (contact, QCservice, service);
4108 contact = Fplist_put (contact, QCremote,
4109 conv_sockaddr_to_lisp (&saddr.sa, len));
4110 #ifdef HAVE_GETSOCKNAME
4111 len = sizeof saddr;
4112 if (getsockname (s, &saddr.sa, &len) == 0)
4113 contact = Fplist_put (contact, QClocal,
4114 conv_sockaddr_to_lisp (&saddr.sa, len));
4115 #endif
4117 pset_childp (p, contact);
4118 pset_plist (p, Fcopy_sequence (ps->plist));
4119 pset_type (p, Qnetwork);
4121 pset_buffer (p, buffer);
4122 pset_sentinel (p, ps->sentinel);
4123 pset_filter (p, ps->filter);
4124 pset_command (p, Qnil);
4125 p->pid = 0;
4126 p->infd = s;
4127 p->outfd = s;
4128 pset_status (p, Qrun);
4130 /* Client processes for accepted connections are not stopped initially. */
4131 if (!EQ (p->filter, Qt))
4133 FD_SET (s, &input_wait_mask);
4134 FD_SET (s, &non_keyboard_wait_mask);
4137 if (s > max_process_desc)
4138 max_process_desc = s;
4140 /* Setup coding system for new process based on server process.
4141 This seems to be the proper thing to do, as the coding system
4142 of the new process should reflect the settings at the time the
4143 server socket was opened; not the current settings. */
4145 pset_decode_coding_system (p, ps->decode_coding_system);
4146 pset_encode_coding_system (p, ps->encode_coding_system);
4147 setup_process_coding_systems (proc);
4149 pset_decoding_buf (p, empty_unibyte_string);
4150 p->decoding_carryover = 0;
4151 pset_encoding_buf (p, empty_unibyte_string);
4153 p->inherit_coding_system_flag
4154 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4156 if (!NILP (ps->log))
4157 call3 (ps->log, server, proc,
4158 concat3 (build_string ("accept from "),
4159 (STRINGP (host) ? host : build_string ("-")),
4160 build_string ("\n")));
4162 exec_sentinel (proc,
4163 concat3 (build_string ("open from "),
4164 (STRINGP (host) ? host : build_string ("-")),
4165 build_string ("\n")));
4168 /* This variable is different from waiting_for_input in keyboard.c.
4169 It is used to communicate to a lisp process-filter/sentinel (via the
4170 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4171 for user-input when that process-filter was called.
4172 waiting_for_input cannot be used as that is by definition 0 when
4173 lisp code is being evalled.
4174 This is also used in record_asynch_buffer_change.
4175 For that purpose, this must be 0
4176 when not inside wait_reading_process_output. */
4177 static int waiting_for_user_input_p;
4179 static Lisp_Object
4180 wait_reading_process_output_unwind (Lisp_Object data)
4182 waiting_for_user_input_p = XINT (data);
4183 return Qnil;
4186 /* This is here so breakpoints can be put on it. */
4187 static void
4188 wait_reading_process_output_1 (void)
4192 /* Read and dispose of subprocess output while waiting for timeout to
4193 elapse and/or keyboard input to be available.
4195 TIME_LIMIT is:
4196 timeout in seconds
4197 If negative, gobble data immediately available but don't wait for any.
4199 NSECS is:
4200 an additional duration to wait, measured in nanoseconds
4201 If TIME_LIMIT is zero, then:
4202 If NSECS == 0, there is no limit.
4203 If NSECS > 0, the timeout consists of NSECS only.
4204 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4206 READ_KBD is:
4207 0 to ignore keyboard input, or
4208 1 to return when input is available, or
4209 -1 meaning caller will actually read the input, so don't throw to
4210 the quit handler, or
4212 DO_DISPLAY means redisplay should be done to show subprocess
4213 output that arrives.
4215 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4216 (and gobble terminal input into the buffer if any arrives).
4218 If WAIT_PROC is specified, wait until something arrives from that
4219 process. The return value is true if we read some input from
4220 that process.
4222 If JUST_WAIT_PROC is nonzero, handle only output from WAIT_PROC
4223 (suspending output from other processes). A negative value
4224 means don't run any timers either.
4226 If WAIT_PROC is specified, then the function returns true if we
4227 received input from that process before the timeout elapsed.
4228 Otherwise, return true if we received input from any process. */
4230 bool
4231 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4232 bool do_display,
4233 Lisp_Object wait_for_cell,
4234 struct Lisp_Process *wait_proc, int just_wait_proc)
4236 int channel, nfds;
4237 SELECT_TYPE Available;
4238 SELECT_TYPE Writeok;
4239 bool check_write;
4240 int check_delay;
4241 bool no_avail;
4242 int xerrno;
4243 Lisp_Object proc;
4244 EMACS_TIME timeout, end_time;
4245 int wait_channel = -1;
4246 bool got_some_input = 0;
4247 ptrdiff_t count = SPECPDL_INDEX ();
4249 FD_ZERO (&Available);
4250 FD_ZERO (&Writeok);
4252 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4253 && !(CONSP (wait_proc->status)
4254 && EQ (XCAR (wait_proc->status), Qexit)))
4255 message1 ("Blocking call to accept-process-output with quit inhibited!!");
4257 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4258 if (wait_proc != NULL)
4259 wait_channel = wait_proc->infd;
4261 record_unwind_protect (wait_reading_process_output_unwind,
4262 make_number (waiting_for_user_input_p));
4263 waiting_for_user_input_p = read_kbd;
4265 if (time_limit < 0)
4267 time_limit = 0;
4268 nsecs = -1;
4270 else if (TYPE_MAXIMUM (time_t) < time_limit)
4271 time_limit = TYPE_MAXIMUM (time_t);
4273 /* Since we may need to wait several times,
4274 compute the absolute time to return at. */
4275 if (time_limit || nsecs > 0)
4277 timeout = make_emacs_time (time_limit, nsecs);
4278 end_time = add_emacs_time (current_emacs_time (), timeout);
4281 while (1)
4283 bool timeout_reduced_for_timers = 0;
4285 /* If calling from keyboard input, do not quit
4286 since we want to return C-g as an input character.
4287 Otherwise, do pending quit if requested. */
4288 if (read_kbd >= 0)
4289 QUIT;
4290 else if (pending_signals)
4291 process_pending_signals ();
4293 /* Exit now if the cell we're waiting for became non-nil. */
4294 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4295 break;
4297 /* Compute time from now till when time limit is up. */
4298 /* Exit if already run out. */
4299 if (nsecs < 0)
4301 /* A negative timeout means
4302 gobble output available now
4303 but don't wait at all. */
4305 timeout = make_emacs_time (0, 0);
4307 else if (time_limit || nsecs > 0)
4309 EMACS_TIME now = current_emacs_time ();
4310 if (EMACS_TIME_LE (end_time, now))
4311 break;
4312 timeout = sub_emacs_time (end_time, now);
4314 else
4316 timeout = make_emacs_time (100000, 0);
4319 /* Normally we run timers here.
4320 But not if wait_for_cell; in those cases,
4321 the wait is supposed to be short,
4322 and those callers cannot handle running arbitrary Lisp code here. */
4323 if (NILP (wait_for_cell)
4324 && just_wait_proc >= 0)
4326 EMACS_TIME timer_delay;
4330 unsigned old_timers_run = timers_run;
4331 struct buffer *old_buffer = current_buffer;
4332 Lisp_Object old_window = selected_window;
4334 timer_delay = timer_check ();
4336 /* If a timer has run, this might have changed buffers
4337 an alike. Make read_key_sequence aware of that. */
4338 if (timers_run != old_timers_run
4339 && (old_buffer != current_buffer
4340 || !EQ (old_window, selected_window))
4341 && waiting_for_user_input_p == -1)
4342 record_asynch_buffer_change ();
4344 if (timers_run != old_timers_run && do_display)
4345 /* We must retry, since a timer may have requeued itself
4346 and that could alter the time_delay. */
4347 redisplay_preserve_echo_area (9);
4348 else
4349 break;
4351 while (!detect_input_pending ());
4353 /* If there is unread keyboard input, also return. */
4354 if (read_kbd != 0
4355 && requeued_events_pending_p ())
4356 break;
4358 /* A negative timeout means do not wait at all. */
4359 if (nsecs >= 0)
4361 if (EMACS_TIME_VALID_P (timer_delay))
4363 if (EMACS_TIME_LT (timer_delay, timeout))
4365 timeout = timer_delay;
4366 timeout_reduced_for_timers = 1;
4369 else
4371 /* This is so a breakpoint can be put here. */
4372 wait_reading_process_output_1 ();
4377 /* Cause C-g and alarm signals to take immediate action,
4378 and cause input available signals to zero out timeout.
4380 It is important that we do this before checking for process
4381 activity. If we get a SIGCHLD after the explicit checks for
4382 process activity, timeout is the only way we will know. */
4383 if (read_kbd < 0)
4384 set_waiting_for_input (&timeout);
4386 /* If status of something has changed, and no input is
4387 available, notify the user of the change right away. After
4388 this explicit check, we'll let the SIGCHLD handler zap
4389 timeout to get our attention. */
4390 if (update_tick != process_tick)
4392 SELECT_TYPE Atemp;
4393 SELECT_TYPE Ctemp;
4395 if (kbd_on_hold_p ())
4396 FD_ZERO (&Atemp);
4397 else
4398 Atemp = input_wait_mask;
4399 Ctemp = write_mask;
4401 timeout = make_emacs_time (0, 0);
4402 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4403 &Atemp,
4404 #ifdef NON_BLOCKING_CONNECT
4405 (num_pending_connects > 0 ? &Ctemp : NULL),
4406 #else
4407 NULL,
4408 #endif
4409 NULL, &timeout, NULL)
4410 <= 0))
4412 /* It's okay for us to do this and then continue with
4413 the loop, since timeout has already been zeroed out. */
4414 clear_waiting_for_input ();
4415 status_notify (NULL);
4416 if (do_display) redisplay_preserve_echo_area (13);
4420 /* Don't wait for output from a non-running process. Just
4421 read whatever data has already been received. */
4422 if (wait_proc && wait_proc->raw_status_new)
4423 update_status (wait_proc);
4424 if (wait_proc
4425 && ! EQ (wait_proc->status, Qrun)
4426 && ! EQ (wait_proc->status, Qconnect))
4428 bool read_some_bytes = 0;
4430 clear_waiting_for_input ();
4431 XSETPROCESS (proc, wait_proc);
4433 /* Read data from the process, until we exhaust it. */
4434 while (wait_proc->infd >= 0)
4436 int nread = read_process_output (proc, wait_proc->infd);
4438 if (nread == 0)
4439 break;
4441 if (nread > 0)
4442 got_some_input = read_some_bytes = 1;
4443 else if (nread == -1 && (errno == EIO || errno == EAGAIN))
4444 break;
4445 #ifdef EWOULDBLOCK
4446 else if (nread == -1 && EWOULDBLOCK == errno)
4447 break;
4448 #endif
4450 if (read_some_bytes && do_display)
4451 redisplay_preserve_echo_area (10);
4453 break;
4456 /* Wait till there is something to do */
4458 if (wait_proc && just_wait_proc)
4460 if (wait_proc->infd < 0) /* Terminated */
4461 break;
4462 FD_SET (wait_proc->infd, &Available);
4463 check_delay = 0;
4464 check_write = 0;
4466 else if (!NILP (wait_for_cell))
4468 Available = non_process_wait_mask;
4469 check_delay = 0;
4470 check_write = 0;
4472 else
4474 if (! read_kbd)
4475 Available = non_keyboard_wait_mask;
4476 else
4477 Available = input_wait_mask;
4478 Writeok = write_mask;
4479 #ifdef SELECT_CANT_DO_WRITE_MASK
4480 check_write = 0;
4481 #else
4482 check_write = 1;
4483 #endif
4484 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4487 /* If frame size has changed or the window is newly mapped,
4488 redisplay now, before we start to wait. There is a race
4489 condition here; if a SIGIO arrives between now and the select
4490 and indicates that a frame is trashed, the select may block
4491 displaying a trashed screen. */
4492 if (frame_garbaged && do_display)
4494 clear_waiting_for_input ();
4495 redisplay_preserve_echo_area (11);
4496 if (read_kbd < 0)
4497 set_waiting_for_input (&timeout);
4500 /* Skip the `select' call if input is available and we're
4501 waiting for keyboard input or a cell change (which can be
4502 triggered by processing X events). In the latter case, set
4503 nfds to 1 to avoid breaking the loop. */
4504 no_avail = 0;
4505 if ((read_kbd || !NILP (wait_for_cell))
4506 && detect_input_pending ())
4508 nfds = read_kbd ? 0 : 1;
4509 no_avail = 1;
4512 if (!no_avail)
4515 #ifdef ADAPTIVE_READ_BUFFERING
4516 /* Set the timeout for adaptive read buffering if any
4517 process has non-zero read_output_skip and non-zero
4518 read_output_delay, and we are not reading output for a
4519 specific wait_channel. It is not executed if
4520 Vprocess_adaptive_read_buffering is nil. */
4521 if (process_output_skip && check_delay > 0)
4523 int nsecs = EMACS_NSECS (timeout);
4524 if (EMACS_SECS (timeout) > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4525 nsecs = READ_OUTPUT_DELAY_MAX;
4526 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4528 proc = chan_process[channel];
4529 if (NILP (proc))
4530 continue;
4531 /* Find minimum non-zero read_output_delay among the
4532 processes with non-zero read_output_skip. */
4533 if (XPROCESS (proc)->read_output_delay > 0)
4535 check_delay--;
4536 if (!XPROCESS (proc)->read_output_skip)
4537 continue;
4538 FD_CLR (channel, &Available);
4539 XPROCESS (proc)->read_output_skip = 0;
4540 if (XPROCESS (proc)->read_output_delay < nsecs)
4541 nsecs = XPROCESS (proc)->read_output_delay;
4544 timeout = make_emacs_time (0, nsecs);
4545 process_output_skip = 0;
4547 #endif
4549 #if defined (HAVE_NS)
4550 nfds = ns_select
4551 #elif defined (HAVE_GLIB)
4552 nfds = xg_select
4553 #else
4554 nfds = pselect
4555 #endif
4556 (max (max_process_desc, max_input_desc) + 1,
4557 &Available,
4558 (check_write ? &Writeok : (SELECT_TYPE *)0),
4559 NULL, &timeout, NULL);
4561 #ifdef HAVE_GNUTLS
4562 /* GnuTLS buffers data internally. In lowat mode it leaves
4563 some data in the TCP buffers so that select works, but
4564 with custom pull/push functions we need to check if some
4565 data is available in the buffers manually. */
4566 if (nfds == 0)
4568 if (! wait_proc)
4570 /* We're not waiting on a specific process, so loop
4571 through all the channels and check for data.
4572 This is a workaround needed for some versions of
4573 the gnutls library -- 2.12.14 has been confirmed
4574 to need it. See
4575 http://comments.gmane.org/gmane.emacs.devel/145074 */
4576 for (channel = 0; channel < MAXDESC; ++channel)
4577 if (! NILP (chan_process[channel]))
4579 struct Lisp_Process *p =
4580 XPROCESS (chan_process[channel]);
4581 if (p && p->gnutls_p && p->infd
4582 && ((emacs_gnutls_record_check_pending
4583 (p->gnutls_state))
4584 > 0))
4586 nfds++;
4587 FD_SET (p->infd, &Available);
4591 else
4593 /* Check this specific channel. */
4594 if (wait_proc->gnutls_p /* Check for valid process. */
4595 /* Do we have pending data? */
4596 && ((emacs_gnutls_record_check_pending
4597 (wait_proc->gnutls_state))
4598 > 0))
4600 nfds = 1;
4601 /* Set to Available. */
4602 FD_SET (wait_proc->infd, &Available);
4606 #endif
4609 xerrno = errno;
4611 /* Make C-g and alarm signals set flags again */
4612 clear_waiting_for_input ();
4614 /* If we woke up due to SIGWINCH, actually change size now. */
4615 do_pending_window_change (0);
4617 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4618 /* We waited the full specified time, so return now. */
4619 break;
4620 if (nfds < 0)
4622 if (xerrno == EINTR)
4623 no_avail = 1;
4624 else if (xerrno == EBADF)
4626 #ifdef AIX
4627 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4628 the child's closure of the pts gives the parent a SIGHUP, and
4629 the ptc file descriptor is automatically closed,
4630 yielding EBADF here or at select() call above.
4631 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4632 in m/ibmrt-aix.h), and here we just ignore the select error.
4633 Cleanup occurs c/o status_notify after SIGCHLD. */
4634 no_avail = 1; /* Cannot depend on values returned */
4635 #else
4636 emacs_abort ();
4637 #endif
4639 else
4640 error ("select error: %s", emacs_strerror (xerrno));
4643 if (no_avail)
4645 FD_ZERO (&Available);
4646 check_write = 0;
4649 /* Check for keyboard input */
4650 /* If there is any, return immediately
4651 to give it higher priority than subprocesses */
4653 if (read_kbd != 0)
4655 unsigned old_timers_run = timers_run;
4656 struct buffer *old_buffer = current_buffer;
4657 Lisp_Object old_window = selected_window;
4658 bool leave = 0;
4660 if (detect_input_pending_run_timers (do_display))
4662 swallow_events (do_display);
4663 if (detect_input_pending_run_timers (do_display))
4664 leave = 1;
4667 /* If a timer has run, this might have changed buffers
4668 an alike. Make read_key_sequence aware of that. */
4669 if (timers_run != old_timers_run
4670 && waiting_for_user_input_p == -1
4671 && (old_buffer != current_buffer
4672 || !EQ (old_window, selected_window)))
4673 record_asynch_buffer_change ();
4675 if (leave)
4676 break;
4679 /* If there is unread keyboard input, also return. */
4680 if (read_kbd != 0
4681 && requeued_events_pending_p ())
4682 break;
4684 /* If we are not checking for keyboard input now,
4685 do process events (but don't run any timers).
4686 This is so that X events will be processed.
4687 Otherwise they may have to wait until polling takes place.
4688 That would causes delays in pasting selections, for example.
4690 (We used to do this only if wait_for_cell.) */
4691 if (read_kbd == 0 && detect_input_pending ())
4693 swallow_events (do_display);
4694 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4695 if (detect_input_pending ())
4696 break;
4697 #endif
4700 /* Exit now if the cell we're waiting for became non-nil. */
4701 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4702 break;
4704 #ifdef USABLE_SIGIO
4705 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4706 go read it. This can happen with X on BSD after logging out.
4707 In that case, there really is no input and no SIGIO,
4708 but select says there is input. */
4710 if (read_kbd && interrupt_input
4711 && keyboard_bit_set (&Available) && ! noninteractive)
4712 handle_input_available_signal (SIGIO);
4713 #endif
4715 if (! wait_proc)
4716 got_some_input |= nfds > 0;
4718 /* If checking input just got us a size-change event from X,
4719 obey it now if we should. */
4720 if (read_kbd || ! NILP (wait_for_cell))
4721 do_pending_window_change (0);
4723 /* Check for data from a process. */
4724 if (no_avail || nfds == 0)
4725 continue;
4727 for (channel = 0; channel <= max_input_desc; ++channel)
4729 struct fd_callback_data *d = &fd_callback_info[channel];
4730 if (d->func
4731 && ((d->condition & FOR_READ
4732 && FD_ISSET (channel, &Available))
4733 || (d->condition & FOR_WRITE
4734 && FD_ISSET (channel, &write_mask))))
4735 d->func (channel, d->data);
4738 for (channel = 0; channel <= max_process_desc; channel++)
4740 if (FD_ISSET (channel, &Available)
4741 && FD_ISSET (channel, &non_keyboard_wait_mask)
4742 && !FD_ISSET (channel, &non_process_wait_mask))
4744 int nread;
4746 /* If waiting for this channel, arrange to return as
4747 soon as no more input to be processed. No more
4748 waiting. */
4749 if (wait_channel == channel)
4751 wait_channel = -1;
4752 nsecs = -1;
4753 got_some_input = 1;
4755 proc = chan_process[channel];
4756 if (NILP (proc))
4757 continue;
4759 /* If this is a server stream socket, accept connection. */
4760 if (EQ (XPROCESS (proc)->status, Qlisten))
4762 server_accept_connection (proc, channel);
4763 continue;
4766 /* Read data from the process, starting with our
4767 buffered-ahead character if we have one. */
4769 nread = read_process_output (proc, channel);
4770 if (nread > 0)
4772 /* Since read_process_output can run a filter,
4773 which can call accept-process-output,
4774 don't try to read from any other processes
4775 before doing the select again. */
4776 FD_ZERO (&Available);
4778 if (do_display)
4779 redisplay_preserve_echo_area (12);
4781 #ifdef EWOULDBLOCK
4782 else if (nread == -1 && errno == EWOULDBLOCK)
4784 #endif
4785 else if (nread == -1 && errno == EAGAIN)
4787 #ifdef WINDOWSNT
4788 /* FIXME: Is this special case still needed? */
4789 /* Note that we cannot distinguish between no input
4790 available now and a closed pipe.
4791 With luck, a closed pipe will be accompanied by
4792 subprocess termination and SIGCHLD. */
4793 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4795 #endif
4796 #ifdef HAVE_PTYS
4797 /* On some OSs with ptys, when the process on one end of
4798 a pty exits, the other end gets an error reading with
4799 errno = EIO instead of getting an EOF (0 bytes read).
4800 Therefore, if we get an error reading and errno =
4801 EIO, just continue, because the child process has
4802 exited and should clean itself up soon (e.g. when we
4803 get a SIGCHLD). */
4804 else if (nread == -1 && errno == EIO)
4806 struct Lisp_Process *p = XPROCESS (proc);
4808 /* Clear the descriptor now, so we only raise the
4809 signal once. */
4810 FD_CLR (channel, &input_wait_mask);
4811 FD_CLR (channel, &non_keyboard_wait_mask);
4813 if (p->pid == -2)
4815 /* If the EIO occurs on a pty, the SIGCHLD handler's
4816 waitpid call will not find the process object to
4817 delete. Do it here. */
4818 p->tick = ++process_tick;
4819 pset_status (p, Qfailed);
4822 #endif /* HAVE_PTYS */
4823 /* If we can detect process termination, don't consider the
4824 process gone just because its pipe is closed. */
4825 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4827 else
4829 /* Preserve status of processes already terminated. */
4830 XPROCESS (proc)->tick = ++process_tick;
4831 deactivate_process (proc);
4832 if (XPROCESS (proc)->raw_status_new)
4833 update_status (XPROCESS (proc));
4834 if (EQ (XPROCESS (proc)->status, Qrun))
4835 pset_status (XPROCESS (proc),
4836 list2 (Qexit, make_number (256)));
4839 #ifdef NON_BLOCKING_CONNECT
4840 if (FD_ISSET (channel, &Writeok)
4841 && FD_ISSET (channel, &connect_wait_mask))
4843 struct Lisp_Process *p;
4845 FD_CLR (channel, &connect_wait_mask);
4846 FD_CLR (channel, &write_mask);
4847 if (--num_pending_connects < 0)
4848 emacs_abort ();
4850 proc = chan_process[channel];
4851 if (NILP (proc))
4852 continue;
4854 p = XPROCESS (proc);
4856 #ifdef GNU_LINUX
4857 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4858 So only use it on systems where it is known to work. */
4860 socklen_t xlen = sizeof (xerrno);
4861 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4862 xerrno = errno;
4864 #else
4866 struct sockaddr pname;
4867 int pnamelen = sizeof (pname);
4869 /* If connection failed, getpeername will fail. */
4870 xerrno = 0;
4871 if (getpeername (channel, &pname, &pnamelen) < 0)
4873 /* Obtain connect failure code through error slippage. */
4874 char dummy;
4875 xerrno = errno;
4876 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
4877 xerrno = errno;
4880 #endif
4881 if (xerrno)
4883 p->tick = ++process_tick;
4884 pset_status (p, list2 (Qfailed, make_number (xerrno)));
4885 deactivate_process (proc);
4887 else
4889 pset_status (p, Qrun);
4890 /* Execute the sentinel here. If we had relied on
4891 status_notify to do it later, it will read input
4892 from the process before calling the sentinel. */
4893 exec_sentinel (proc, build_string ("open\n"));
4894 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
4896 FD_SET (p->infd, &input_wait_mask);
4897 FD_SET (p->infd, &non_keyboard_wait_mask);
4901 #endif /* NON_BLOCKING_CONNECT */
4902 } /* End for each file descriptor. */
4903 } /* End while exit conditions not met. */
4905 unbind_to (count, Qnil);
4907 /* If calling from keyboard input, do not quit
4908 since we want to return C-g as an input character.
4909 Otherwise, do pending quit if requested. */
4910 if (read_kbd >= 0)
4912 /* Prevent input_pending from remaining set if we quit. */
4913 clear_input_pending ();
4914 QUIT;
4917 return got_some_input;
4920 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4922 static Lisp_Object
4923 read_process_output_call (Lisp_Object fun_and_args)
4925 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4928 static Lisp_Object
4929 read_process_output_error_handler (Lisp_Object error_val)
4931 cmd_error_internal (error_val, "error in process filter: ");
4932 Vinhibit_quit = Qt;
4933 update_echo_area ();
4934 Fsleep_for (make_number (2), Qnil);
4935 return Qt;
4938 static void
4939 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
4940 ssize_t nbytes,
4941 struct coding_system *coding);
4943 /* Read pending output from the process channel,
4944 starting with our buffered-ahead character if we have one.
4945 Yield number of decoded characters read.
4947 This function reads at most 4096 characters.
4948 If you want to read all available subprocess output,
4949 you must call it repeatedly until it returns zero.
4951 The characters read are decoded according to PROC's coding-system
4952 for decoding. */
4954 static int
4955 read_process_output (Lisp_Object proc, register int channel)
4957 register ssize_t nbytes;
4958 char *chars;
4959 register struct Lisp_Process *p = XPROCESS (proc);
4960 struct coding_system *coding = proc_decode_coding_system[channel];
4961 int carryover = p->decoding_carryover;
4962 int readmax = 4096;
4963 ptrdiff_t count = SPECPDL_INDEX ();
4964 Lisp_Object odeactivate;
4966 chars = alloca (carryover + readmax);
4967 if (carryover)
4968 /* See the comment above. */
4969 memcpy (chars, SDATA (p->decoding_buf), carryover);
4971 #ifdef DATAGRAM_SOCKETS
4972 /* We have a working select, so proc_buffered_char is always -1. */
4973 if (DATAGRAM_CHAN_P (channel))
4975 socklen_t len = datagram_address[channel].len;
4976 nbytes = recvfrom (channel, chars + carryover, readmax,
4977 0, datagram_address[channel].sa, &len);
4979 else
4980 #endif
4982 bool buffered = proc_buffered_char[channel] >= 0;
4983 if (buffered)
4985 chars[carryover] = proc_buffered_char[channel];
4986 proc_buffered_char[channel] = -1;
4988 #ifdef HAVE_GNUTLS
4989 if (p->gnutls_p)
4990 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
4991 readmax - buffered);
4992 else
4993 #endif
4994 nbytes = emacs_read (channel, chars + carryover + buffered,
4995 readmax - buffered);
4996 #ifdef ADAPTIVE_READ_BUFFERING
4997 if (nbytes > 0 && p->adaptive_read_buffering)
4999 int delay = p->read_output_delay;
5000 if (nbytes < 256)
5002 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5004 if (delay == 0)
5005 process_output_delay_count++;
5006 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5009 else if (delay > 0 && nbytes == readmax - buffered)
5011 delay -= READ_OUTPUT_DELAY_INCREMENT;
5012 if (delay == 0)
5013 process_output_delay_count--;
5015 p->read_output_delay = delay;
5016 if (delay)
5018 p->read_output_skip = 1;
5019 process_output_skip = 1;
5022 #endif
5023 nbytes += buffered;
5024 nbytes += buffered && nbytes <= 0;
5027 p->decoding_carryover = 0;
5029 /* At this point, NBYTES holds number of bytes just received
5030 (including the one in proc_buffered_char[channel]). */
5031 if (nbytes <= 0)
5033 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5034 return nbytes;
5035 coding->mode |= CODING_MODE_LAST_BLOCK;
5038 /* Now set NBYTES how many bytes we must decode. */
5039 nbytes += carryover;
5041 odeactivate = Vdeactivate_mark;
5042 /* There's no good reason to let process filters change the current
5043 buffer, and many callers of accept-process-output, sit-for, and
5044 friends don't expect current-buffer to be changed from under them. */
5045 record_unwind_current_buffer ();
5047 read_and_dispose_of_process_output (p, chars, nbytes, coding);
5049 /* Handling the process output should not deactivate the mark. */
5050 Vdeactivate_mark = odeactivate;
5052 unbind_to (count, Qnil);
5053 return nbytes;
5056 static void
5057 read_and_dispose_of_process_output (struct Lisp_Process *p, char *chars,
5058 ssize_t nbytes,
5059 struct coding_system *coding)
5061 Lisp_Object outstream = p->filter;
5062 Lisp_Object text;
5063 bool outer_running_asynch_code = running_asynch_code;
5064 int waiting = waiting_for_user_input_p;
5066 /* No need to gcpro these, because all we do with them later
5067 is test them for EQness, and none of them should be a string. */
5068 #if 0
5069 Lisp_Object obuffer, okeymap;
5070 XSETBUFFER (obuffer, current_buffer);
5071 okeymap = BVAR (current_buffer, keymap);
5072 #endif
5074 /* We inhibit quit here instead of just catching it so that
5075 hitting ^G when a filter happens to be running won't screw
5076 it up. */
5077 specbind (Qinhibit_quit, Qt);
5078 specbind (Qlast_nonmenu_event, Qt);
5080 /* In case we get recursively called,
5081 and we already saved the match data nonrecursively,
5082 save the same match data in safely recursive fashion. */
5083 if (outer_running_asynch_code)
5085 Lisp_Object tem;
5086 /* Don't clobber the CURRENT match data, either! */
5087 tem = Fmatch_data (Qnil, Qnil, Qnil);
5088 restore_search_regs ();
5089 record_unwind_save_match_data ();
5090 Fset_match_data (tem, Qt);
5093 /* For speed, if a search happens within this code,
5094 save the match data in a special nonrecursive fashion. */
5095 running_asynch_code = 1;
5097 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5098 text = coding->dst_object;
5099 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5100 /* A new coding system might be found. */
5101 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5103 pset_decode_coding_system (p, Vlast_coding_system_used);
5105 /* Don't call setup_coding_system for
5106 proc_decode_coding_system[channel] here. It is done in
5107 detect_coding called via decode_coding above. */
5109 /* If a coding system for encoding is not yet decided, we set
5110 it as the same as coding-system for decoding.
5112 But, before doing that we must check if
5113 proc_encode_coding_system[p->outfd] surely points to a
5114 valid memory because p->outfd will be changed once EOF is
5115 sent to the process. */
5116 if (NILP (p->encode_coding_system)
5117 && proc_encode_coding_system[p->outfd])
5119 pset_encode_coding_system
5120 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5121 setup_coding_system (p->encode_coding_system,
5122 proc_encode_coding_system[p->outfd]);
5126 if (coding->carryover_bytes > 0)
5128 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5129 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5130 memcpy (SDATA (p->decoding_buf), coding->carryover,
5131 coding->carryover_bytes);
5132 p->decoding_carryover = coding->carryover_bytes;
5134 if (SBYTES (text) > 0)
5135 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5136 sometimes it's simply wrong to wrap (e.g. when called from
5137 accept-process-output). */
5138 internal_condition_case_1 (read_process_output_call,
5139 Fcons (outstream,
5140 Fcons (make_lisp_proc (p),
5141 Fcons (text, Qnil))),
5142 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5143 read_process_output_error_handler);
5145 /* If we saved the match data nonrecursively, restore it now. */
5146 restore_search_regs ();
5147 running_asynch_code = outer_running_asynch_code;
5149 /* Restore waiting_for_user_input_p as it was
5150 when we were called, in case the filter clobbered it. */
5151 waiting_for_user_input_p = waiting;
5153 #if 0 /* Call record_asynch_buffer_change unconditionally,
5154 because we might have changed minor modes or other things
5155 that affect key bindings. */
5156 if (! EQ (Fcurrent_buffer (), obuffer)
5157 || ! EQ (current_buffer->keymap, okeymap))
5158 #endif
5159 /* But do it only if the caller is actually going to read events.
5160 Otherwise there's no need to make him wake up, and it could
5161 cause trouble (for example it would make sit_for return). */
5162 if (waiting_for_user_input_p == -1)
5163 record_asynch_buffer_change ();
5166 DEFUN ("internal-default-process-filter", Finternal_default_process_filter,
5167 Sinternal_default_process_filter, 2, 2, 0,
5168 doc: /* Function used as default process filter. */)
5169 (Lisp_Object proc, Lisp_Object text)
5171 struct Lisp_Process *p;
5172 ptrdiff_t opoint;
5174 CHECK_PROCESS (proc);
5175 p = XPROCESS (proc);
5176 CHECK_STRING (text);
5178 if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5180 Lisp_Object old_read_only;
5181 ptrdiff_t old_begv, old_zv;
5182 ptrdiff_t old_begv_byte, old_zv_byte;
5183 ptrdiff_t before, before_byte;
5184 ptrdiff_t opoint_byte;
5185 struct buffer *b;
5187 Fset_buffer (p->buffer);
5188 opoint = PT;
5189 opoint_byte = PT_BYTE;
5190 old_read_only = BVAR (current_buffer, read_only);
5191 old_begv = BEGV;
5192 old_zv = ZV;
5193 old_begv_byte = BEGV_BYTE;
5194 old_zv_byte = ZV_BYTE;
5196 bset_read_only (current_buffer, Qnil);
5198 /* Insert new output into buffer
5199 at the current end-of-output marker,
5200 thus preserving logical ordering of input and output. */
5201 if (XMARKER (p->mark)->buffer)
5202 SET_PT_BOTH (clip_to_bounds (BEGV,
5203 marker_position (p->mark), ZV),
5204 clip_to_bounds (BEGV_BYTE,
5205 marker_byte_position (p->mark),
5206 ZV_BYTE));
5207 else
5208 SET_PT_BOTH (ZV, ZV_BYTE);
5209 before = PT;
5210 before_byte = PT_BYTE;
5212 /* If the output marker is outside of the visible region, save
5213 the restriction and widen. */
5214 if (! (BEGV <= PT && PT <= ZV))
5215 Fwiden ();
5217 /* Adjust the multibyteness of TEXT to that of the buffer. */
5218 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5219 != ! STRING_MULTIBYTE (text))
5220 text = (STRING_MULTIBYTE (text)
5221 ? Fstring_as_unibyte (text)
5222 : Fstring_to_multibyte (text));
5223 /* Insert before markers in case we are inserting where
5224 the buffer's mark is, and the user's next command is Meta-y. */
5225 insert_from_string_before_markers (text, 0, 0,
5226 SCHARS (text), SBYTES (text), 0);
5228 /* Make sure the process marker's position is valid when the
5229 process buffer is changed in the signal_after_change above.
5230 W3 is known to do that. */
5231 if (BUFFERP (p->buffer)
5232 && (b = XBUFFER (p->buffer), b != current_buffer))
5233 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5234 else
5235 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5237 update_mode_lines++;
5239 /* Make sure opoint and the old restrictions
5240 float ahead of any new text just as point would. */
5241 if (opoint >= before)
5243 opoint += PT - before;
5244 opoint_byte += PT_BYTE - before_byte;
5246 if (old_begv > before)
5248 old_begv += PT - before;
5249 old_begv_byte += PT_BYTE - before_byte;
5251 if (old_zv >= before)
5253 old_zv += PT - before;
5254 old_zv_byte += PT_BYTE - before_byte;
5257 /* If the restriction isn't what it should be, set it. */
5258 if (old_begv != BEGV || old_zv != ZV)
5259 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5261 bset_read_only (current_buffer, old_read_only);
5262 SET_PT_BOTH (opoint, opoint_byte);
5264 return Qnil;
5267 /* Sending data to subprocess. */
5269 /* In send_process, when a write fails temporarily,
5270 wait_reading_process_output is called. It may execute user code,
5271 e.g. timers, that attempts to write new data to the same process.
5272 We must ensure that data is sent in the right order, and not
5273 interspersed half-completed with other writes (Bug#10815). This is
5274 handled by the write_queue element of struct process. It is a list
5275 with each entry having the form
5277 (string . (offset . length))
5279 where STRING is a lisp string, OFFSET is the offset into the
5280 string's byte sequence from which we should begin to send, and
5281 LENGTH is the number of bytes left to send. */
5283 /* Create a new entry in write_queue.
5284 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5285 BUF is a pointer to the string sequence of the input_obj or a C
5286 string in case of Qt or Qnil. */
5288 static void
5289 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5290 const char *buf, ptrdiff_t len, bool front)
5292 ptrdiff_t offset;
5293 Lisp_Object entry, obj;
5295 if (STRINGP (input_obj))
5297 offset = buf - SSDATA (input_obj);
5298 obj = input_obj;
5300 else
5302 offset = 0;
5303 obj = make_unibyte_string (buf, len);
5306 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5308 if (front)
5309 pset_write_queue (p, Fcons (entry, p->write_queue));
5310 else
5311 pset_write_queue (p, nconc2 (p->write_queue, Fcons (entry, Qnil)));
5314 /* Remove the first element in the write_queue of process P, put its
5315 contents in OBJ, BUF and LEN, and return true. If the
5316 write_queue is empty, return false. */
5318 static bool
5319 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5320 const char **buf, ptrdiff_t *len)
5322 Lisp_Object entry, offset_length;
5323 ptrdiff_t offset;
5325 if (NILP (p->write_queue))
5326 return 0;
5328 entry = XCAR (p->write_queue);
5329 pset_write_queue (p, XCDR (p->write_queue));
5331 *obj = XCAR (entry);
5332 offset_length = XCDR (entry);
5334 *len = XINT (XCDR (offset_length));
5335 offset = XINT (XCAR (offset_length));
5336 *buf = SSDATA (*obj) + offset;
5338 return 1;
5341 /* Send some data to process PROC.
5342 BUF is the beginning of the data; LEN is the number of characters.
5343 OBJECT is the Lisp object that the data comes from. If OBJECT is
5344 nil or t, it means that the data comes from C string.
5346 If OBJECT is not nil, the data is encoded by PROC's coding-system
5347 for encoding before it is sent.
5349 This function can evaluate Lisp code and can garbage collect. */
5351 static void
5352 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5353 Lisp_Object object)
5355 struct Lisp_Process *p = XPROCESS (proc);
5356 ssize_t rv;
5357 struct coding_system *coding;
5359 if (p->raw_status_new)
5360 update_status (p);
5361 if (! EQ (p->status, Qrun))
5362 error ("Process %s not running", SDATA (p->name));
5363 if (p->outfd < 0)
5364 error ("Output file descriptor of %s is closed", SDATA (p->name));
5366 coding = proc_encode_coding_system[p->outfd];
5367 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5369 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5370 || (BUFFERP (object)
5371 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5372 || EQ (object, Qt))
5374 pset_encode_coding_system
5375 (p, complement_process_encoding_system (p->encode_coding_system));
5376 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5378 /* The coding system for encoding was changed to raw-text
5379 because we sent a unibyte text previously. Now we are
5380 sending a multibyte text, thus we must encode it by the
5381 original coding system specified for the current process.
5383 Another reason we come here is that the coding system
5384 was just complemented and a new one was returned by
5385 complement_process_encoding_system. */
5386 setup_coding_system (p->encode_coding_system, coding);
5387 Vlast_coding_system_used = p->encode_coding_system;
5389 coding->src_multibyte = 1;
5391 else
5393 coding->src_multibyte = 0;
5394 /* For sending a unibyte text, character code conversion should
5395 not take place but EOL conversion should. So, setup raw-text
5396 or one of the subsidiary if we have not yet done it. */
5397 if (CODING_REQUIRE_ENCODING (coding))
5399 if (CODING_REQUIRE_FLUSHING (coding))
5401 /* But, before changing the coding, we must flush out data. */
5402 coding->mode |= CODING_MODE_LAST_BLOCK;
5403 send_process (proc, "", 0, Qt);
5404 coding->mode &= CODING_MODE_LAST_BLOCK;
5406 setup_coding_system (raw_text_coding_system
5407 (Vlast_coding_system_used),
5408 coding);
5409 coding->src_multibyte = 0;
5412 coding->dst_multibyte = 0;
5414 if (CODING_REQUIRE_ENCODING (coding))
5416 coding->dst_object = Qt;
5417 if (BUFFERP (object))
5419 ptrdiff_t from_byte, from, to;
5420 ptrdiff_t save_pt, save_pt_byte;
5421 struct buffer *cur = current_buffer;
5423 set_buffer_internal (XBUFFER (object));
5424 save_pt = PT, save_pt_byte = PT_BYTE;
5426 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5427 from = BYTE_TO_CHAR (from_byte);
5428 to = BYTE_TO_CHAR (from_byte + len);
5429 TEMP_SET_PT_BOTH (from, from_byte);
5430 encode_coding_object (coding, object, from, from_byte,
5431 to, from_byte + len, Qt);
5432 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5433 set_buffer_internal (cur);
5435 else if (STRINGP (object))
5437 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5438 SBYTES (object), Qt);
5440 else
5442 coding->dst_object = make_unibyte_string (buf, len);
5443 coding->produced = len;
5446 len = coding->produced;
5447 object = coding->dst_object;
5448 buf = SSDATA (object);
5451 /* If there is already data in the write_queue, put the new data
5452 in the back of queue. Otherwise, ignore it. */
5453 if (!NILP (p->write_queue))
5454 write_queue_push (p, object, buf, len, 0);
5456 do /* while !NILP (p->write_queue) */
5458 ptrdiff_t cur_len = -1;
5459 const char *cur_buf;
5460 Lisp_Object cur_object;
5462 /* If write_queue is empty, ignore it. */
5463 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5465 cur_len = len;
5466 cur_buf = buf;
5467 cur_object = object;
5470 while (cur_len > 0)
5472 /* Send this batch, using one or more write calls. */
5473 ptrdiff_t written = 0;
5474 int outfd = p->outfd;
5475 #ifdef DATAGRAM_SOCKETS
5476 if (DATAGRAM_CHAN_P (outfd))
5478 rv = sendto (outfd, cur_buf, cur_len,
5479 0, datagram_address[outfd].sa,
5480 datagram_address[outfd].len);
5481 if (rv >= 0)
5482 written = rv;
5483 else if (errno == EMSGSIZE)
5484 report_file_error ("sending datagram", Fcons (proc, Qnil));
5486 else
5487 #endif
5489 #ifdef HAVE_GNUTLS
5490 if (p->gnutls_p)
5491 written = emacs_gnutls_write (p, cur_buf, cur_len);
5492 else
5493 #endif
5494 written = emacs_write (outfd, cur_buf, cur_len);
5495 rv = (written ? 0 : -1);
5496 #ifdef ADAPTIVE_READ_BUFFERING
5497 if (p->read_output_delay > 0
5498 && p->adaptive_read_buffering == 1)
5500 p->read_output_delay = 0;
5501 process_output_delay_count--;
5502 p->read_output_skip = 0;
5504 #endif
5507 if (rv < 0)
5509 if (errno == EAGAIN
5510 #ifdef EWOULDBLOCK
5511 || errno == EWOULDBLOCK
5512 #endif
5514 /* Buffer is full. Wait, accepting input;
5515 that may allow the program
5516 to finish doing output and read more. */
5518 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5519 /* A gross hack to work around a bug in FreeBSD.
5520 In the following sequence, read(2) returns
5521 bogus data:
5523 write(2) 1022 bytes
5524 write(2) 954 bytes, get EAGAIN
5525 read(2) 1024 bytes in process_read_output
5526 read(2) 11 bytes in process_read_output
5528 That is, read(2) returns more bytes than have
5529 ever been written successfully. The 1033 bytes
5530 read are the 1022 bytes written successfully
5531 after processing (for example with CRs added if
5532 the terminal is set up that way which it is
5533 here). The same bytes will be seen again in a
5534 later read(2), without the CRs. */
5536 if (errno == EAGAIN)
5538 int flags = FWRITE;
5539 ioctl (p->outfd, TIOCFLUSH, &flags);
5541 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5543 /* Put what we should have written in wait_queue. */
5544 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5545 wait_reading_process_output (0, 20 * 1000 * 1000,
5546 0, 0, Qnil, NULL, 0);
5547 /* Reread queue, to see what is left. */
5548 break;
5550 else if (errno == EPIPE)
5552 p->raw_status_new = 0;
5553 pset_status (p, list2 (Qexit, make_number (256)));
5554 p->tick = ++process_tick;
5555 deactivate_process (proc);
5556 error ("process %s no longer connected to pipe; closed it",
5557 SDATA (p->name));
5559 else
5560 /* This is a real error. */
5561 report_file_error ("writing to process", Fcons (proc, Qnil));
5563 cur_buf += written;
5564 cur_len -= written;
5567 while (!NILP (p->write_queue));
5570 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5571 3, 3, 0,
5572 doc: /* Send current contents of region as input to PROCESS.
5573 PROCESS may be a process, a buffer, the name of a process or buffer, or
5574 nil, indicating the current buffer's process.
5575 Called from program, takes three arguments, PROCESS, START and END.
5576 If the region is more than 500 characters long,
5577 it is sent in several bunches. This may happen even for shorter regions.
5578 Output from processes can arrive in between bunches. */)
5579 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5581 Lisp_Object proc = get_process (process);
5582 ptrdiff_t start_byte, end_byte;
5584 validate_region (&start, &end);
5586 start_byte = CHAR_TO_BYTE (XINT (start));
5587 end_byte = CHAR_TO_BYTE (XINT (end));
5589 if (XINT (start) < GPT && XINT (end) > GPT)
5590 move_gap_both (XINT (start), start_byte);
5592 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5593 end_byte - start_byte, Fcurrent_buffer ());
5595 return Qnil;
5598 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5599 2, 2, 0,
5600 doc: /* Send PROCESS the contents of STRING as input.
5601 PROCESS may be a process, a buffer, the name of a process or buffer, or
5602 nil, indicating the current buffer's process.
5603 If STRING is more than 500 characters long,
5604 it is sent in several bunches. This may happen even for shorter strings.
5605 Output from processes can arrive in between bunches. */)
5606 (Lisp_Object process, Lisp_Object string)
5608 Lisp_Object proc;
5609 CHECK_STRING (string);
5610 proc = get_process (process);
5611 send_process (proc, SSDATA (string),
5612 SBYTES (string), string);
5613 return Qnil;
5616 /* Return the foreground process group for the tty/pty that
5617 the process P uses. */
5618 static pid_t
5619 emacs_get_tty_pgrp (struct Lisp_Process *p)
5621 pid_t gid = -1;
5623 #ifdef TIOCGPGRP
5624 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5626 int fd;
5627 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5628 master side. Try the slave side. */
5629 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5631 if (fd != -1)
5633 ioctl (fd, TIOCGPGRP, &gid);
5634 emacs_close (fd);
5637 #endif /* defined (TIOCGPGRP ) */
5639 return gid;
5642 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5643 Sprocess_running_child_p, 0, 1, 0,
5644 doc: /* Return t if PROCESS has given the terminal to a child.
5645 If the operating system does not make it possible to find out,
5646 return t unconditionally. */)
5647 (Lisp_Object process)
5649 /* Initialize in case ioctl doesn't exist or gives an error,
5650 in a way that will cause returning t. */
5651 pid_t gid;
5652 Lisp_Object proc;
5653 struct Lisp_Process *p;
5655 proc = get_process (process);
5656 p = XPROCESS (proc);
5658 if (!EQ (p->type, Qreal))
5659 error ("Process %s is not a subprocess",
5660 SDATA (p->name));
5661 if (p->infd < 0)
5662 error ("Process %s is not active",
5663 SDATA (p->name));
5665 gid = emacs_get_tty_pgrp (p);
5667 if (gid == p->pid)
5668 return Qnil;
5669 return Qt;
5672 /* send a signal number SIGNO to PROCESS.
5673 If CURRENT_GROUP is t, that means send to the process group
5674 that currently owns the terminal being used to communicate with PROCESS.
5675 This is used for various commands in shell mode.
5676 If CURRENT_GROUP is lambda, that means send to the process group
5677 that currently owns the terminal, but only if it is NOT the shell itself.
5679 If NOMSG is false, insert signal-announcements into process's buffers
5680 right away.
5682 If we can, we try to signal PROCESS by sending control characters
5683 down the pty. This allows us to signal inferiors who have changed
5684 their uid, for which kill would return an EPERM error. */
5686 static void
5687 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5688 bool nomsg)
5690 Lisp_Object proc;
5691 struct Lisp_Process *p;
5692 pid_t gid;
5693 bool no_pgrp = 0;
5695 proc = get_process (process);
5696 p = XPROCESS (proc);
5698 if (!EQ (p->type, Qreal))
5699 error ("Process %s is not a subprocess",
5700 SDATA (p->name));
5701 if (p->infd < 0)
5702 error ("Process %s is not active",
5703 SDATA (p->name));
5705 if (!p->pty_flag)
5706 current_group = Qnil;
5708 /* If we are using pgrps, get a pgrp number and make it negative. */
5709 if (NILP (current_group))
5710 /* Send the signal to the shell's process group. */
5711 gid = p->pid;
5712 else
5714 #ifdef SIGNALS_VIA_CHARACTERS
5715 /* If possible, send signals to the entire pgrp
5716 by sending an input character to it. */
5718 struct termios t;
5719 cc_t *sig_char = NULL;
5721 tcgetattr (p->infd, &t);
5723 switch (signo)
5725 case SIGINT:
5726 sig_char = &t.c_cc[VINTR];
5727 break;
5729 case SIGQUIT:
5730 sig_char = &t.c_cc[VQUIT];
5731 break;
5733 case SIGTSTP:
5734 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5735 sig_char = &t.c_cc[VSWTCH];
5736 #else
5737 sig_char = &t.c_cc[VSUSP];
5738 #endif
5739 break;
5742 if (sig_char && *sig_char != CDISABLE)
5744 send_process (proc, (char *) sig_char, 1, Qnil);
5745 return;
5747 /* If we can't send the signal with a character,
5748 fall through and send it another way. */
5750 /* The code above may fall through if it can't
5751 handle the signal. */
5752 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5754 #ifdef TIOCGPGRP
5755 /* Get the current pgrp using the tty itself, if we have that.
5756 Otherwise, use the pty to get the pgrp.
5757 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5758 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5759 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5760 His patch indicates that if TIOCGPGRP returns an error, then
5761 we should just assume that p->pid is also the process group id. */
5763 gid = emacs_get_tty_pgrp (p);
5765 if (gid == -1)
5766 /* If we can't get the information, assume
5767 the shell owns the tty. */
5768 gid = p->pid;
5770 /* It is not clear whether anything really can set GID to -1.
5771 Perhaps on some system one of those ioctls can or could do so.
5772 Or perhaps this is vestigial. */
5773 if (gid == -1)
5774 no_pgrp = 1;
5775 #else /* ! defined (TIOCGPGRP ) */
5776 /* Can't select pgrps on this system, so we know that
5777 the child itself heads the pgrp. */
5778 gid = p->pid;
5779 #endif /* ! defined (TIOCGPGRP ) */
5781 /* If current_group is lambda, and the shell owns the terminal,
5782 don't send any signal. */
5783 if (EQ (current_group, Qlambda) && gid == p->pid)
5784 return;
5787 switch (signo)
5789 #ifdef SIGCONT
5790 case SIGCONT:
5791 p->raw_status_new = 0;
5792 pset_status (p, Qrun);
5793 p->tick = ++process_tick;
5794 if (!nomsg)
5796 status_notify (NULL);
5797 redisplay_preserve_echo_area (13);
5799 break;
5800 #endif /* ! defined (SIGCONT) */
5801 case SIGINT:
5802 case SIGQUIT:
5803 case SIGKILL:
5804 flush_pending_output (p->infd);
5805 break;
5808 /* If we don't have process groups, send the signal to the immediate
5809 subprocess. That isn't really right, but it's better than any
5810 obvious alternative. */
5811 if (no_pgrp)
5813 kill (p->pid, signo);
5814 return;
5817 /* gid may be a pid, or minus a pgrp's number */
5818 #ifdef TIOCSIGSEND
5819 if (!NILP (current_group))
5821 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
5822 kill (-gid, signo);
5824 else
5826 gid = - p->pid;
5827 kill (gid, signo);
5829 #else /* ! defined (TIOCSIGSEND) */
5830 kill (-gid, signo);
5831 #endif /* ! defined (TIOCSIGSEND) */
5834 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5835 doc: /* Interrupt process PROCESS.
5836 PROCESS may be a process, a buffer, or the name of a process or buffer.
5837 No arg or nil means current buffer's process.
5838 Second arg CURRENT-GROUP non-nil means send signal to
5839 the current process-group of the process's controlling terminal
5840 rather than to the process's own process group.
5841 If the process is a shell, this means interrupt current subjob
5842 rather than the shell.
5844 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5845 don't send the signal. */)
5846 (Lisp_Object process, Lisp_Object current_group)
5848 process_send_signal (process, SIGINT, current_group, 0);
5849 return process;
5852 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5853 doc: /* Kill process PROCESS. May be process or name of one.
5854 See function `interrupt-process' for more details on usage. */)
5855 (Lisp_Object process, Lisp_Object current_group)
5857 process_send_signal (process, SIGKILL, current_group, 0);
5858 return process;
5861 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5862 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5863 See function `interrupt-process' for more details on usage. */)
5864 (Lisp_Object process, Lisp_Object current_group)
5866 process_send_signal (process, SIGQUIT, current_group, 0);
5867 return process;
5870 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
5871 doc: /* Stop process PROCESS. May be process or name of one.
5872 See function `interrupt-process' for more details on usage.
5873 If PROCESS is a network or serial process, inhibit handling of incoming
5874 traffic. */)
5875 (Lisp_Object process, Lisp_Object current_group)
5877 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5879 struct Lisp_Process *p;
5881 p = XPROCESS (process);
5882 if (NILP (p->command)
5883 && p->infd >= 0)
5885 FD_CLR (p->infd, &input_wait_mask);
5886 FD_CLR (p->infd, &non_keyboard_wait_mask);
5888 pset_command (p, Qt);
5889 return process;
5891 #ifndef SIGTSTP
5892 error ("No SIGTSTP support");
5893 #else
5894 process_send_signal (process, SIGTSTP, current_group, 0);
5895 #endif
5896 return process;
5899 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
5900 doc: /* Continue process PROCESS. May be process or name of one.
5901 See function `interrupt-process' for more details on usage.
5902 If PROCESS is a network or serial process, resume handling of incoming
5903 traffic. */)
5904 (Lisp_Object process, Lisp_Object current_group)
5906 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5908 struct Lisp_Process *p;
5910 p = XPROCESS (process);
5911 if (EQ (p->command, Qt)
5912 && p->infd >= 0
5913 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
5915 FD_SET (p->infd, &input_wait_mask);
5916 FD_SET (p->infd, &non_keyboard_wait_mask);
5917 #ifdef WINDOWSNT
5918 if (fd_info[ p->infd ].flags & FILE_SERIAL)
5919 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
5920 #else /* not WINDOWSNT */
5921 tcflush (p->infd, TCIFLUSH);
5922 #endif /* not WINDOWSNT */
5924 pset_command (p, Qnil);
5925 return process;
5927 #ifdef SIGCONT
5928 process_send_signal (process, SIGCONT, current_group, 0);
5929 #else
5930 error ("No SIGCONT support");
5931 #endif
5932 return process;
5935 /* Return the integer value of the signal whose abbreviation is ABBR,
5936 or a negative number if there is no such signal. */
5937 static int
5938 abbr_to_signal (char const *name)
5940 int i, signo;
5941 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
5943 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
5944 name += 3;
5946 for (i = 0; i < sizeof sigbuf; i++)
5948 sigbuf[i] = c_toupper (name[i]);
5949 if (! sigbuf[i])
5950 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
5953 return -1;
5956 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
5957 2, 2, "sProcess (name or number): \nnSignal code: ",
5958 doc: /* Send PROCESS the signal with code SIGCODE.
5959 PROCESS may also be a number specifying the process id of the
5960 process to signal; in this case, the process need not be a child of
5961 this Emacs.
5962 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5963 (Lisp_Object process, Lisp_Object sigcode)
5965 pid_t pid;
5966 int signo;
5968 if (STRINGP (process))
5970 Lisp_Object tem = Fget_process (process);
5971 if (NILP (tem))
5973 Lisp_Object process_number =
5974 string_to_number (SSDATA (process), 10, 1);
5975 if (INTEGERP (process_number) || FLOATP (process_number))
5976 tem = process_number;
5978 process = tem;
5980 else if (!NUMBERP (process))
5981 process = get_process (process);
5983 if (NILP (process))
5984 return process;
5986 if (NUMBERP (process))
5987 CONS_TO_INTEGER (process, pid_t, pid);
5988 else
5990 CHECK_PROCESS (process);
5991 pid = XPROCESS (process)->pid;
5992 if (pid <= 0)
5993 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
5996 if (INTEGERP (sigcode))
5998 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
5999 signo = XINT (sigcode);
6001 else
6003 char *name;
6005 CHECK_SYMBOL (sigcode);
6006 name = SSDATA (SYMBOL_NAME (sigcode));
6008 signo = abbr_to_signal (name);
6009 if (signo < 0)
6010 error ("Undefined signal name %s", name);
6013 return make_number (kill (pid, signo));
6016 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6017 doc: /* Make PROCESS see end-of-file in its input.
6018 EOF comes after any text already sent to it.
6019 PROCESS may be a process, a buffer, the name of a process or buffer, or
6020 nil, indicating the current buffer's process.
6021 If PROCESS is a network connection, or is a process communicating
6022 through a pipe (as opposed to a pty), then you cannot send any more
6023 text to PROCESS after you call this function.
6024 If PROCESS is a serial process, wait until all output written to the
6025 process has been transmitted to the serial port. */)
6026 (Lisp_Object process)
6028 Lisp_Object proc;
6029 struct coding_system *coding;
6031 if (DATAGRAM_CONN_P (process))
6032 return process;
6034 proc = get_process (process);
6035 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6037 /* Make sure the process is really alive. */
6038 if (XPROCESS (proc)->raw_status_new)
6039 update_status (XPROCESS (proc));
6040 if (! EQ (XPROCESS (proc)->status, Qrun))
6041 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6043 if (CODING_REQUIRE_FLUSHING (coding))
6045 coding->mode |= CODING_MODE_LAST_BLOCK;
6046 send_process (proc, "", 0, Qnil);
6049 if (XPROCESS (proc)->pty_flag)
6050 send_process (proc, "\004", 1, Qnil);
6051 else if (EQ (XPROCESS (proc)->type, Qserial))
6053 #ifndef WINDOWSNT
6054 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6055 error ("tcdrain() failed: %s", emacs_strerror (errno));
6056 #endif /* not WINDOWSNT */
6057 /* Do nothing on Windows because writes are blocking. */
6059 else
6061 int old_outfd, new_outfd;
6063 #ifdef HAVE_SHUTDOWN
6064 /* If this is a network connection, or socketpair is used
6065 for communication with the subprocess, call shutdown to cause EOF.
6066 (In some old system, shutdown to socketpair doesn't work.
6067 Then we just can't win.) */
6068 if (EQ (XPROCESS (proc)->type, Qnetwork)
6069 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6070 shutdown (XPROCESS (proc)->outfd, 1);
6071 /* In case of socketpair, outfd == infd, so don't close it. */
6072 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6073 emacs_close (XPROCESS (proc)->outfd);
6074 #else /* not HAVE_SHUTDOWN */
6075 emacs_close (XPROCESS (proc)->outfd);
6076 #endif /* not HAVE_SHUTDOWN */
6077 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6078 if (new_outfd < 0)
6079 emacs_abort ();
6080 old_outfd = XPROCESS (proc)->outfd;
6082 if (!proc_encode_coding_system[new_outfd])
6083 proc_encode_coding_system[new_outfd]
6084 = xmalloc (sizeof (struct coding_system));
6085 *proc_encode_coding_system[new_outfd]
6086 = *proc_encode_coding_system[old_outfd];
6087 memset (proc_encode_coding_system[old_outfd], 0,
6088 sizeof (struct coding_system));
6090 XPROCESS (proc)->outfd = new_outfd;
6092 return process;
6095 /* The main Emacs thread records child processes in three places:
6097 - Vprocess_alist, for asynchronous subprocesses, which are child
6098 processes visible to Lisp.
6100 - deleted_pid_list, for child processes invisible to Lisp,
6101 typically because of delete-process. These are recorded so that
6102 the processes can be reaped when they exit, so that the operating
6103 system's process table is not cluttered by zombies.
6105 - the local variable PID in Fcall_process, call_process_cleanup and
6106 call_process_kill, for synchronous subprocesses.
6107 record_unwind_protect is used to make sure this process is not
6108 forgotten: if the user interrupts call-process and the child
6109 process refuses to exit immediately even with two C-g's,
6110 call_process_kill adds PID's contents to deleted_pid_list before
6111 returning.
6113 The main Emacs thread invokes waitpid only on child processes that
6114 it creates and that have not been reaped. This avoid races on
6115 platforms such as GTK, where other threads create their own
6116 subprocesses which the main thread should not reap. For example,
6117 if the main thread attempted to reap an already-reaped child, it
6118 might inadvertently reap a GTK-created process that happened to
6119 have the same process ID. */
6121 /* LIB_CHILD_HANDLER is a SIGCHLD handler that Emacs calls while doing
6122 its own SIGCHLD handling. On POSIXish systems, glib needs this to
6123 keep track of its own children. GNUstep is similar. */
6125 static void dummy_handler (int sig) {}
6126 static signal_handler_t volatile lib_child_handler;
6128 /* Handle a SIGCHLD signal by looking for known child processes of
6129 Emacs whose status have changed. For each one found, record its
6130 new status.
6132 All we do is change the status; we do not run sentinels or print
6133 notifications. That is saved for the next time keyboard input is
6134 done, in order to avoid timing errors.
6136 ** WARNING: this can be called during garbage collection.
6137 Therefore, it must not be fooled by the presence of mark bits in
6138 Lisp objects.
6140 ** USG WARNING: Although it is not obvious from the documentation
6141 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6142 signal() before executing at least one wait(), otherwise the
6143 handler will be called again, resulting in an infinite loop. The
6144 relevant portion of the documentation reads "SIGCLD signals will be
6145 queued and the signal-catching function will be continually
6146 reentered until the queue is empty". Invoking signal() causes the
6147 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6148 Inc.
6150 ** Malloc WARNING: This should never call malloc either directly or
6151 indirectly; if it does, that is a bug */
6153 static void
6154 handle_child_signal (int sig)
6156 Lisp_Object tail;
6158 /* Find the process that signaled us, and record its status. */
6160 /* The process can have been deleted by Fdelete_process, or have
6161 been started asynchronously by Fcall_process. */
6162 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6164 bool all_pids_are_fixnums
6165 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6166 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6167 Lisp_Object xpid = XCAR (tail);
6168 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6170 pid_t deleted_pid;
6171 if (INTEGERP (xpid))
6172 deleted_pid = XINT (xpid);
6173 else
6174 deleted_pid = XFLOAT_DATA (xpid);
6175 if (child_status_changed (deleted_pid, 0, 0))
6176 XSETCAR (tail, Qnil);
6180 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6181 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6183 Lisp_Object proc = XCDR (XCAR (tail));
6184 struct Lisp_Process *p = XPROCESS (proc);
6185 int status;
6187 if (p->alive
6188 && child_status_changed (p->pid, &status, WUNTRACED | WCONTINUED))
6190 /* Change the status of the process that was found. */
6191 p->tick = ++process_tick;
6192 p->raw_status = status;
6193 p->raw_status_new = 1;
6195 /* If process has terminated, stop waiting for its output. */
6196 if (WIFSIGNALED (status) || WIFEXITED (status))
6198 bool clear_desc_flag = 0;
6199 p->alive = 0;
6200 if (p->infd >= 0)
6201 clear_desc_flag = 1;
6203 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6204 if (clear_desc_flag)
6206 FD_CLR (p->infd, &input_wait_mask);
6207 FD_CLR (p->infd, &non_keyboard_wait_mask);
6213 lib_child_handler (sig);
6216 static void
6217 deliver_child_signal (int sig)
6219 deliver_process_signal (sig, handle_child_signal);
6223 static Lisp_Object
6224 exec_sentinel_error_handler (Lisp_Object error_val)
6226 cmd_error_internal (error_val, "error in process sentinel: ");
6227 Vinhibit_quit = Qt;
6228 update_echo_area ();
6229 Fsleep_for (make_number (2), Qnil);
6230 return Qt;
6233 static void
6234 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6236 Lisp_Object sentinel, odeactivate;
6237 struct Lisp_Process *p = XPROCESS (proc);
6238 ptrdiff_t count = SPECPDL_INDEX ();
6239 bool outer_running_asynch_code = running_asynch_code;
6240 int waiting = waiting_for_user_input_p;
6242 if (inhibit_sentinels)
6243 return;
6245 /* No need to gcpro these, because all we do with them later
6246 is test them for EQness, and none of them should be a string. */
6247 odeactivate = Vdeactivate_mark;
6248 #if 0
6249 Lisp_Object obuffer, okeymap;
6250 XSETBUFFER (obuffer, current_buffer);
6251 okeymap = BVAR (current_buffer, keymap);
6252 #endif
6254 /* There's no good reason to let sentinels change the current
6255 buffer, and many callers of accept-process-output, sit-for, and
6256 friends don't expect current-buffer to be changed from under them. */
6257 record_unwind_current_buffer ();
6259 sentinel = p->sentinel;
6261 /* Inhibit quit so that random quits don't screw up a running filter. */
6262 specbind (Qinhibit_quit, Qt);
6263 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6265 /* In case we get recursively called,
6266 and we already saved the match data nonrecursively,
6267 save the same match data in safely recursive fashion. */
6268 if (outer_running_asynch_code)
6270 Lisp_Object tem;
6271 tem = Fmatch_data (Qnil, Qnil, Qnil);
6272 restore_search_regs ();
6273 record_unwind_save_match_data ();
6274 Fset_match_data (tem, Qt);
6277 /* For speed, if a search happens within this code,
6278 save the match data in a special nonrecursive fashion. */
6279 running_asynch_code = 1;
6281 internal_condition_case_1 (read_process_output_call,
6282 Fcons (sentinel,
6283 Fcons (proc, Fcons (reason, Qnil))),
6284 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6285 exec_sentinel_error_handler);
6287 /* If we saved the match data nonrecursively, restore it now. */
6288 restore_search_regs ();
6289 running_asynch_code = outer_running_asynch_code;
6291 Vdeactivate_mark = odeactivate;
6293 /* Restore waiting_for_user_input_p as it was
6294 when we were called, in case the filter clobbered it. */
6295 waiting_for_user_input_p = waiting;
6297 #if 0
6298 if (! EQ (Fcurrent_buffer (), obuffer)
6299 || ! EQ (current_buffer->keymap, okeymap))
6300 #endif
6301 /* But do it only if the caller is actually going to read events.
6302 Otherwise there's no need to make him wake up, and it could
6303 cause trouble (for example it would make sit_for return). */
6304 if (waiting_for_user_input_p == -1)
6305 record_asynch_buffer_change ();
6307 unbind_to (count, Qnil);
6310 /* Report all recent events of a change in process status
6311 (either run the sentinel or output a message).
6312 This is usually done while Emacs is waiting for keyboard input
6313 but can be done at other times. */
6315 static void
6316 status_notify (struct Lisp_Process *deleting_process)
6318 register Lisp_Object proc;
6319 Lisp_Object tail, msg;
6320 struct gcpro gcpro1, gcpro2;
6322 tail = Qnil;
6323 msg = Qnil;
6324 /* We need to gcpro tail; if read_process_output calls a filter
6325 which deletes a process and removes the cons to which tail points
6326 from Vprocess_alist, and then causes a GC, tail is an unprotected
6327 reference. */
6328 GCPRO2 (tail, msg);
6330 /* Set this now, so that if new processes are created by sentinels
6331 that we run, we get called again to handle their status changes. */
6332 update_tick = process_tick;
6334 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6336 Lisp_Object symbol;
6337 register struct Lisp_Process *p;
6339 proc = Fcdr (XCAR (tail));
6340 p = XPROCESS (proc);
6342 if (p->tick != p->update_tick)
6344 p->update_tick = p->tick;
6346 /* If process is still active, read any output that remains. */
6347 while (! EQ (p->filter, Qt)
6348 && ! EQ (p->status, Qconnect)
6349 && ! EQ (p->status, Qlisten)
6350 /* Network or serial process not stopped: */
6351 && ! EQ (p->command, Qt)
6352 && p->infd >= 0
6353 && p != deleting_process
6354 && read_process_output (proc, p->infd) > 0);
6356 /* Get the text to use for the message. */
6357 if (p->raw_status_new)
6358 update_status (p);
6359 msg = status_message (p);
6361 /* If process is terminated, deactivate it or delete it. */
6362 symbol = p->status;
6363 if (CONSP (p->status))
6364 symbol = XCAR (p->status);
6366 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6367 || EQ (symbol, Qclosed))
6369 if (delete_exited_processes)
6370 remove_process (proc);
6371 else
6372 deactivate_process (proc);
6375 /* The actions above may have further incremented p->tick.
6376 So set p->update_tick again so that an error in the sentinel will
6377 not cause this code to be run again. */
6378 p->update_tick = p->tick;
6379 /* Now output the message suitably. */
6380 exec_sentinel (proc, msg);
6382 } /* end for */
6384 update_mode_lines++; /* In case buffers use %s in mode-line-format. */
6385 UNGCPRO;
6388 DEFUN ("internal-default-process-sentinel", Finternal_default_process_sentinel,
6389 Sinternal_default_process_sentinel, 2, 2, 0,
6390 doc: /* Function used as default sentinel for processes. */)
6391 (Lisp_Object proc, Lisp_Object msg)
6393 Lisp_Object buffer, symbol;
6394 struct Lisp_Process *p;
6395 CHECK_PROCESS (proc);
6396 p = XPROCESS (proc);
6397 buffer = p->buffer;
6398 symbol = p->status;
6399 if (CONSP (symbol))
6400 symbol = XCAR (symbol);
6402 if (!EQ (symbol, Qrun) && !NILP (buffer))
6404 Lisp_Object tem;
6405 struct buffer *old = current_buffer;
6406 ptrdiff_t opoint, opoint_byte;
6407 ptrdiff_t before, before_byte;
6409 /* Avoid error if buffer is deleted
6410 (probably that's why the process is dead, too). */
6411 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6412 return Qnil;
6413 Fset_buffer (buffer);
6415 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
6416 msg = (code_convert_string_norecord
6417 (msg, Vlocale_coding_system, 1));
6419 opoint = PT;
6420 opoint_byte = PT_BYTE;
6421 /* Insert new output into buffer
6422 at the current end-of-output marker,
6423 thus preserving logical ordering of input and output. */
6424 if (XMARKER (p->mark)->buffer)
6425 Fgoto_char (p->mark);
6426 else
6427 SET_PT_BOTH (ZV, ZV_BYTE);
6429 before = PT;
6430 before_byte = PT_BYTE;
6432 tem = BVAR (current_buffer, read_only);
6433 bset_read_only (current_buffer, Qnil);
6434 insert_string ("\nProcess ");
6435 { /* FIXME: temporary kludge. */
6436 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6437 insert_string (" ");
6438 Finsert (1, &msg);
6439 bset_read_only (current_buffer, tem);
6440 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6442 if (opoint >= before)
6443 SET_PT_BOTH (opoint + (PT - before),
6444 opoint_byte + (PT_BYTE - before_byte));
6445 else
6446 SET_PT_BOTH (opoint, opoint_byte);
6448 set_buffer_internal (old);
6450 return Qnil;
6454 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6455 Sset_process_coding_system, 1, 3, 0,
6456 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6457 DECODING will be used to decode subprocess output and ENCODING to
6458 encode subprocess input. */)
6459 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6461 register struct Lisp_Process *p;
6463 CHECK_PROCESS (process);
6464 p = XPROCESS (process);
6465 if (p->infd < 0)
6466 error ("Input file descriptor of %s closed", SDATA (p->name));
6467 if (p->outfd < 0)
6468 error ("Output file descriptor of %s closed", SDATA (p->name));
6469 Fcheck_coding_system (decoding);
6470 Fcheck_coding_system (encoding);
6471 encoding = coding_inherit_eol_type (encoding, Qnil);
6472 pset_decode_coding_system (p, decoding);
6473 pset_encode_coding_system (p, encoding);
6474 setup_process_coding_systems (process);
6476 return Qnil;
6479 DEFUN ("process-coding-system",
6480 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6481 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6482 (register Lisp_Object process)
6484 CHECK_PROCESS (process);
6485 return Fcons (XPROCESS (process)->decode_coding_system,
6486 XPROCESS (process)->encode_coding_system);
6489 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6490 Sset_process_filter_multibyte, 2, 2, 0,
6491 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6492 If FLAG is non-nil, the filter is given multibyte strings.
6493 If FLAG is nil, the filter is given unibyte strings. In this case,
6494 all character code conversion except for end-of-line conversion is
6495 suppressed. */)
6496 (Lisp_Object process, Lisp_Object flag)
6498 register struct Lisp_Process *p;
6500 CHECK_PROCESS (process);
6501 p = XPROCESS (process);
6502 if (NILP (flag))
6503 pset_decode_coding_system
6504 (p, raw_text_coding_system (p->decode_coding_system));
6505 setup_process_coding_systems (process);
6507 return Qnil;
6510 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6511 Sprocess_filter_multibyte_p, 1, 1, 0,
6512 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6513 (Lisp_Object process)
6515 register struct Lisp_Process *p;
6516 struct coding_system *coding;
6518 CHECK_PROCESS (process);
6519 p = XPROCESS (process);
6520 coding = proc_decode_coding_system[p->infd];
6521 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6527 # ifdef HAVE_GPM
6529 void
6530 add_gpm_wait_descriptor (int desc)
6532 add_keyboard_wait_descriptor (desc);
6535 void
6536 delete_gpm_wait_descriptor (int desc)
6538 delete_keyboard_wait_descriptor (desc);
6541 # endif
6543 # ifdef USABLE_SIGIO
6545 /* Return true if *MASK has a bit set
6546 that corresponds to one of the keyboard input descriptors. */
6548 static bool
6549 keyboard_bit_set (fd_set *mask)
6551 int fd;
6553 for (fd = 0; fd <= max_input_desc; fd++)
6554 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6555 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6556 return 1;
6558 return 0;
6560 # endif
6562 #else /* not subprocesses */
6564 /* Defined on msdos.c. */
6565 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6566 EMACS_TIME *, void *);
6568 /* Implementation of wait_reading_process_output, assuming that there
6569 are no subprocesses. Used only by the MS-DOS build.
6571 Wait for timeout to elapse and/or keyboard input to be available.
6573 TIME_LIMIT is:
6574 timeout in seconds
6575 If negative, gobble data immediately available but don't wait for any.
6577 NSECS is:
6578 an additional duration to wait, measured in nanoseconds
6579 If TIME_LIMIT is zero, then:
6580 If NSECS == 0, there is no limit.
6581 If NSECS > 0, the timeout consists of NSECS only.
6582 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6584 READ_KBD is:
6585 0 to ignore keyboard input, or
6586 1 to return when input is available, or
6587 -1 means caller will actually read the input, so don't throw to
6588 the quit handler.
6590 see full version for other parameters. We know that wait_proc will
6591 always be NULL, since `subprocesses' isn't defined.
6593 DO_DISPLAY means redisplay should be done to show subprocess
6594 output that arrives.
6596 Return true if we received input from any process. */
6598 bool
6599 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6600 bool do_display,
6601 Lisp_Object wait_for_cell,
6602 struct Lisp_Process *wait_proc, int just_wait_proc)
6604 register int nfds;
6605 EMACS_TIME end_time, timeout;
6607 if (time_limit < 0)
6609 time_limit = 0;
6610 nsecs = -1;
6612 else if (TYPE_MAXIMUM (time_t) < time_limit)
6613 time_limit = TYPE_MAXIMUM (time_t);
6615 /* What does time_limit really mean? */
6616 if (time_limit || nsecs > 0)
6618 timeout = make_emacs_time (time_limit, nsecs);
6619 end_time = add_emacs_time (current_emacs_time (), timeout);
6622 /* Turn off periodic alarms (in case they are in use)
6623 and then turn off any other atimers,
6624 because the select emulator uses alarms. */
6625 stop_polling ();
6626 turn_on_atimers (0);
6628 while (1)
6630 bool timeout_reduced_for_timers = 0;
6631 SELECT_TYPE waitchannels;
6632 int xerrno;
6634 /* If calling from keyboard input, do not quit
6635 since we want to return C-g as an input character.
6636 Otherwise, do pending quit if requested. */
6637 if (read_kbd >= 0)
6638 QUIT;
6640 /* Exit now if the cell we're waiting for became non-nil. */
6641 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6642 break;
6644 /* Compute time from now till when time limit is up. */
6645 /* Exit if already run out. */
6646 if (nsecs < 0)
6648 /* A negative timeout means
6649 gobble output available now
6650 but don't wait at all. */
6652 timeout = make_emacs_time (0, 0);
6654 else if (time_limit || nsecs > 0)
6656 EMACS_TIME now = current_emacs_time ();
6657 if (EMACS_TIME_LE (end_time, now))
6658 break;
6659 timeout = sub_emacs_time (end_time, now);
6661 else
6663 timeout = make_emacs_time (100000, 0);
6666 /* If our caller will not immediately handle keyboard events,
6667 run timer events directly.
6668 (Callers that will immediately read keyboard events
6669 call timer_delay on their own.) */
6670 if (NILP (wait_for_cell))
6672 EMACS_TIME timer_delay;
6676 unsigned old_timers_run = timers_run;
6677 timer_delay = timer_check ();
6678 if (timers_run != old_timers_run && do_display)
6679 /* We must retry, since a timer may have requeued itself
6680 and that could alter the time delay. */
6681 redisplay_preserve_echo_area (14);
6682 else
6683 break;
6685 while (!detect_input_pending ());
6687 /* If there is unread keyboard input, also return. */
6688 if (read_kbd != 0
6689 && requeued_events_pending_p ())
6690 break;
6692 if (EMACS_TIME_VALID_P (timer_delay) && nsecs >= 0)
6694 if (EMACS_TIME_LT (timer_delay, timeout))
6696 timeout = timer_delay;
6697 timeout_reduced_for_timers = 1;
6702 /* Cause C-g and alarm signals to take immediate action,
6703 and cause input available signals to zero out timeout. */
6704 if (read_kbd < 0)
6705 set_waiting_for_input (&timeout);
6707 /* If a frame has been newly mapped and needs updating,
6708 reprocess its display stuff. */
6709 if (frame_garbaged && do_display)
6711 clear_waiting_for_input ();
6712 redisplay_preserve_echo_area (15);
6713 if (read_kbd < 0)
6714 set_waiting_for_input (&timeout);
6717 /* Wait till there is something to do. */
6718 FD_ZERO (&waitchannels);
6719 if (read_kbd && detect_input_pending ())
6720 nfds = 0;
6721 else
6723 if (read_kbd || !NILP (wait_for_cell))
6724 FD_SET (0, &waitchannels);
6725 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
6728 xerrno = errno;
6730 /* Make C-g and alarm signals set flags again */
6731 clear_waiting_for_input ();
6733 /* If we woke up due to SIGWINCH, actually change size now. */
6734 do_pending_window_change (0);
6736 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
6737 /* We waited the full specified time, so return now. */
6738 break;
6740 if (nfds == -1)
6742 /* If the system call was interrupted, then go around the
6743 loop again. */
6744 if (xerrno == EINTR)
6745 FD_ZERO (&waitchannels);
6746 else
6747 error ("select error: %s", emacs_strerror (xerrno));
6750 /* Check for keyboard input */
6752 if (read_kbd
6753 && detect_input_pending_run_timers (do_display))
6755 swallow_events (do_display);
6756 if (detect_input_pending_run_timers (do_display))
6757 break;
6760 /* If there is unread keyboard input, also return. */
6761 if (read_kbd
6762 && requeued_events_pending_p ())
6763 break;
6765 /* If wait_for_cell. check for keyboard input
6766 but don't run any timers.
6767 ??? (It seems wrong to me to check for keyboard
6768 input at all when wait_for_cell, but the code
6769 has been this way since July 1994.
6770 Try changing this after version 19.31.) */
6771 if (! NILP (wait_for_cell)
6772 && detect_input_pending ())
6774 swallow_events (do_display);
6775 if (detect_input_pending ())
6776 break;
6779 /* Exit now if the cell we're waiting for became non-nil. */
6780 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6781 break;
6784 start_polling ();
6786 return 0;
6789 #endif /* not subprocesses */
6791 /* The following functions are needed even if async subprocesses are
6792 not supported. Some of them are no-op stubs in that case. */
6794 /* Add DESC to the set of keyboard input descriptors. */
6796 void
6797 add_keyboard_wait_descriptor (int desc)
6799 #ifdef subprocesses /* actually means "not MSDOS" */
6800 FD_SET (desc, &input_wait_mask);
6801 FD_SET (desc, &non_process_wait_mask);
6802 if (desc > max_input_desc)
6803 max_input_desc = desc;
6804 #endif
6807 /* From now on, do not expect DESC to give keyboard input. */
6809 void
6810 delete_keyboard_wait_descriptor (int desc)
6812 #ifdef subprocesses
6813 int fd;
6814 int lim = max_input_desc;
6816 FD_CLR (desc, &input_wait_mask);
6817 FD_CLR (desc, &non_process_wait_mask);
6819 if (desc == max_input_desc)
6820 for (fd = 0; fd < lim; fd++)
6821 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
6822 max_input_desc = fd;
6823 #endif
6826 /* Setup coding systems of PROCESS. */
6828 void
6829 setup_process_coding_systems (Lisp_Object process)
6831 #ifdef subprocesses
6832 struct Lisp_Process *p = XPROCESS (process);
6833 int inch = p->infd;
6834 int outch = p->outfd;
6835 Lisp_Object coding_system;
6837 if (inch < 0 || outch < 0)
6838 return;
6840 if (!proc_decode_coding_system[inch])
6841 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
6842 coding_system = p->decode_coding_system;
6843 if (EQ (p->filter, Qinternal_default_process_filter)
6844 && BUFFERP (p->buffer))
6846 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
6847 coding_system = raw_text_coding_system (coding_system);
6849 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
6851 if (!proc_encode_coding_system[outch])
6852 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
6853 setup_coding_system (p->encode_coding_system,
6854 proc_encode_coding_system[outch]);
6855 #endif
6858 /* Close all descriptors currently in use for communication
6859 with subprocess. This is used in a newly-forked subprocess
6860 to get rid of irrelevant descriptors. */
6862 void
6863 close_process_descs (void)
6865 #ifndef DOS_NT
6866 int i;
6867 for (i = 0; i < MAXDESC; i++)
6869 Lisp_Object process;
6870 process = chan_process[i];
6871 if (!NILP (process))
6873 int in = XPROCESS (process)->infd;
6874 int out = XPROCESS (process)->outfd;
6875 if (in >= 0)
6876 emacs_close (in);
6877 if (out >= 0 && in != out)
6878 emacs_close (out);
6881 #endif
6884 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
6885 doc: /* Return the (or a) process associated with BUFFER.
6886 BUFFER may be a buffer or the name of one. */)
6887 (register Lisp_Object buffer)
6889 #ifdef subprocesses
6890 register Lisp_Object buf, tail, proc;
6892 if (NILP (buffer)) return Qnil;
6893 buf = Fget_buffer (buffer);
6894 if (NILP (buf)) return Qnil;
6896 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6898 proc = Fcdr (XCAR (tail));
6899 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
6900 return proc;
6902 #endif /* subprocesses */
6903 return Qnil;
6906 DEFUN ("process-inherit-coding-system-flag",
6907 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
6908 1, 1, 0,
6909 doc: /* Return the value of inherit-coding-system flag for PROCESS.
6910 If this flag is t, `buffer-file-coding-system' of the buffer
6911 associated with PROCESS will inherit the coding system used to decode
6912 the process output. */)
6913 (register Lisp_Object process)
6915 #ifdef subprocesses
6916 CHECK_PROCESS (process);
6917 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
6918 #else
6919 /* Ignore the argument and return the value of
6920 inherit-process-coding-system. */
6921 return inherit_process_coding_system ? Qt : Qnil;
6922 #endif
6925 /* Kill all processes associated with `buffer'.
6926 If `buffer' is nil, kill all processes */
6928 void
6929 kill_buffer_processes (Lisp_Object buffer)
6931 #ifdef subprocesses
6932 Lisp_Object tail, proc;
6934 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6936 proc = XCDR (XCAR (tail));
6937 if (PROCESSP (proc)
6938 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
6940 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6941 Fdelete_process (proc);
6942 else if (XPROCESS (proc)->infd >= 0)
6943 process_send_signal (proc, SIGHUP, Qnil, 1);
6946 #else /* subprocesses */
6947 /* Since we have no subprocesses, this does nothing. */
6948 #endif /* subprocesses */
6951 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
6952 Swaiting_for_user_input_p, 0, 0, 0,
6953 doc: /* Return non-nil if Emacs is waiting for input from the user.
6954 This is intended for use by asynchronous process output filters and sentinels. */)
6955 (void)
6957 #ifdef subprocesses
6958 return (waiting_for_user_input_p ? Qt : Qnil);
6959 #else
6960 return Qnil;
6961 #endif
6964 /* Stop reading input from keyboard sources. */
6966 void
6967 hold_keyboard_input (void)
6969 kbd_is_on_hold = 1;
6972 /* Resume reading input from keyboard sources. */
6974 void
6975 unhold_keyboard_input (void)
6977 kbd_is_on_hold = 0;
6980 /* Return true if keyboard input is on hold, zero otherwise. */
6982 bool
6983 kbd_on_hold_p (void)
6985 return kbd_is_on_hold;
6989 /* Enumeration of and access to system processes a-la ps(1). */
6991 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
6992 0, 0, 0,
6993 doc: /* Return a list of numerical process IDs of all running processes.
6994 If this functionality is unsupported, return nil.
6996 See `process-attributes' for getting attributes of a process given its ID. */)
6997 (void)
6999 return list_system_processes ();
7002 DEFUN ("process-attributes", Fprocess_attributes,
7003 Sprocess_attributes, 1, 1, 0,
7004 doc: /* Return attributes of the process given by its PID, a number.
7006 Value is an alist where each element is a cons cell of the form
7008 \(KEY . VALUE)
7010 If this functionality is unsupported, the value is nil.
7012 See `list-system-processes' for getting a list of all process IDs.
7014 The KEYs of the attributes that this function may return are listed
7015 below, together with the type of the associated VALUE (in parentheses).
7016 Not all platforms support all of these attributes; unsupported
7017 attributes will not appear in the returned alist.
7018 Unless explicitly indicated otherwise, numbers can have either
7019 integer or floating point values.
7021 euid -- Effective user User ID of the process (number)
7022 user -- User name corresponding to euid (string)
7023 egid -- Effective user Group ID of the process (number)
7024 group -- Group name corresponding to egid (string)
7025 comm -- Command name (executable name only) (string)
7026 state -- Process state code, such as "S", "R", or "T" (string)
7027 ppid -- Parent process ID (number)
7028 pgrp -- Process group ID (number)
7029 sess -- Session ID, i.e. process ID of session leader (number)
7030 ttname -- Controlling tty name (string)
7031 tpgid -- ID of foreground process group on the process's tty (number)
7032 minflt -- number of minor page faults (number)
7033 majflt -- number of major page faults (number)
7034 cminflt -- cumulative number of minor page faults (number)
7035 cmajflt -- cumulative number of major page faults (number)
7036 utime -- user time used by the process, in (current-time) format,
7037 which is a list of integers (HIGH LOW USEC PSEC)
7038 stime -- system time used by the process (current-time)
7039 time -- sum of utime and stime (current-time)
7040 cutime -- user time used by the process and its children (current-time)
7041 cstime -- system time used by the process and its children (current-time)
7042 ctime -- sum of cutime and cstime (current-time)
7043 pri -- priority of the process (number)
7044 nice -- nice value of the process (number)
7045 thcount -- process thread count (number)
7046 start -- time the process started (current-time)
7047 vsize -- virtual memory size of the process in KB's (number)
7048 rss -- resident set size of the process in KB's (number)
7049 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7050 pcpu -- percents of CPU time used by the process (floating-point number)
7051 pmem -- percents of total physical memory used by process's resident set
7052 (floating-point number)
7053 args -- command line which invoked the process (string). */)
7054 ( Lisp_Object pid)
7056 return system_process_attributes (pid);
7059 /* Arrange to catch SIGCHLD if this hasn't already been arranged.
7060 Invoke this after init_process_emacs, and after glib and/or GNUstep
7061 futz with the SIGCHLD handler, but before Emacs forks any children.
7062 This function's caller should block SIGCHLD. */
7064 void
7065 catch_child_signal (void)
7067 struct sigaction action, old_action;
7069 #if !defined CANNOT_DUMP
7070 if (noninteractive && !initialized)
7071 return;
7072 #endif
7074 #ifndef NS_IMPL_GNUSTEP
7075 if (lib_child_handler)
7076 return;
7077 #endif
7079 #if defined HAVE_GLIB && !defined WINDOWSNT
7080 /* Tickle glib's child-handling code. Ask glib to wait for Emacs itself;
7081 this should always fail, but is enough to initialize glib's
7082 private SIGCHLD handler, allowing the code below to copy it into
7083 LIB_CHILD_HANDLER.
7085 Do this here, rather than early in Emacs initialization where it
7086 might make more sense, to try to avoid bugs in Cygwin glib (Bug#14569). */
7088 GSource *source = g_child_watch_source_new (getpid ());
7089 g_source_unref (source);
7091 #endif
7093 emacs_sigaction_init (&action, deliver_child_signal);
7094 sigaction (SIGCHLD, &action, &old_action);
7095 eassert (! (old_action.sa_flags & SA_SIGINFO));
7097 #ifdef NS_IMPL_GNUSTEP
7098 if (old_action.sa_handler == deliver_child_signal)
7099 return;
7100 #endif
7102 lib_child_handler
7103 = (old_action.sa_handler == SIG_DFL || old_action.sa_handler == SIG_IGN
7104 ? dummy_handler
7105 : old_action.sa_handler);
7109 /* This is not called "init_process" because that is the name of a
7110 Mach system call, so it would cause problems on Darwin systems. */
7111 void
7112 init_process_emacs (void)
7114 #ifdef subprocesses
7115 register int i;
7117 inhibit_sentinels = 0;
7119 FD_ZERO (&input_wait_mask);
7120 FD_ZERO (&non_keyboard_wait_mask);
7121 FD_ZERO (&non_process_wait_mask);
7122 FD_ZERO (&write_mask);
7123 max_process_desc = 0;
7124 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7126 #ifdef NON_BLOCKING_CONNECT
7127 FD_ZERO (&connect_wait_mask);
7128 num_pending_connects = 0;
7129 #endif
7131 #ifdef ADAPTIVE_READ_BUFFERING
7132 process_output_delay_count = 0;
7133 process_output_skip = 0;
7134 #endif
7136 /* Don't do this, it caused infinite select loops. The display
7137 method should call add_keyboard_wait_descriptor on stdin if it
7138 needs that. */
7139 #if 0
7140 FD_SET (0, &input_wait_mask);
7141 #endif
7143 Vprocess_alist = Qnil;
7144 deleted_pid_list = Qnil;
7145 for (i = 0; i < MAXDESC; i++)
7147 chan_process[i] = Qnil;
7148 proc_buffered_char[i] = -1;
7150 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7151 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7152 #ifdef DATAGRAM_SOCKETS
7153 memset (datagram_address, 0, sizeof datagram_address);
7154 #endif
7157 Lisp_Object subfeatures = Qnil;
7158 const struct socket_options *sopt;
7160 #define ADD_SUBFEATURE(key, val) \
7161 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7163 #ifdef NON_BLOCKING_CONNECT
7164 ADD_SUBFEATURE (QCnowait, Qt);
7165 #endif
7166 #ifdef DATAGRAM_SOCKETS
7167 ADD_SUBFEATURE (QCtype, Qdatagram);
7168 #endif
7169 #ifdef HAVE_SEQPACKET
7170 ADD_SUBFEATURE (QCtype, Qseqpacket);
7171 #endif
7172 #ifdef HAVE_LOCAL_SOCKETS
7173 ADD_SUBFEATURE (QCfamily, Qlocal);
7174 #endif
7175 ADD_SUBFEATURE (QCfamily, Qipv4);
7176 #ifdef AF_INET6
7177 ADD_SUBFEATURE (QCfamily, Qipv6);
7178 #endif
7179 #ifdef HAVE_GETSOCKNAME
7180 ADD_SUBFEATURE (QCservice, Qt);
7181 #endif
7182 ADD_SUBFEATURE (QCserver, Qt);
7184 for (sopt = socket_options; sopt->name; sopt++)
7185 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7187 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7190 #if defined (DARWIN_OS)
7191 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7192 processes. As such, we only change the default value. */
7193 if (initialized)
7195 char const *release = (STRINGP (Voperating_system_release)
7196 ? SSDATA (Voperating_system_release)
7197 : 0);
7198 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7199 Vprocess_connection_type = Qnil;
7202 #endif
7203 #endif /* subprocesses */
7204 kbd_is_on_hold = 0;
7207 void
7208 syms_of_process (void)
7210 #ifdef subprocesses
7212 DEFSYM (Qprocessp, "processp");
7213 DEFSYM (Qrun, "run");
7214 DEFSYM (Qstop, "stop");
7215 DEFSYM (Qsignal, "signal");
7217 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7218 here again.
7220 Qexit = intern_c_string ("exit");
7221 staticpro (&Qexit); */
7223 DEFSYM (Qopen, "open");
7224 DEFSYM (Qclosed, "closed");
7225 DEFSYM (Qconnect, "connect");
7226 DEFSYM (Qfailed, "failed");
7227 DEFSYM (Qlisten, "listen");
7228 DEFSYM (Qlocal, "local");
7229 DEFSYM (Qipv4, "ipv4");
7230 #ifdef AF_INET6
7231 DEFSYM (Qipv6, "ipv6");
7232 #endif
7233 DEFSYM (Qdatagram, "datagram");
7234 DEFSYM (Qseqpacket, "seqpacket");
7236 DEFSYM (QCport, ":port");
7237 DEFSYM (QCspeed, ":speed");
7238 DEFSYM (QCprocess, ":process");
7240 DEFSYM (QCbytesize, ":bytesize");
7241 DEFSYM (QCstopbits, ":stopbits");
7242 DEFSYM (QCparity, ":parity");
7243 DEFSYM (Qodd, "odd");
7244 DEFSYM (Qeven, "even");
7245 DEFSYM (QCflowcontrol, ":flowcontrol");
7246 DEFSYM (Qhw, "hw");
7247 DEFSYM (Qsw, "sw");
7248 DEFSYM (QCsummary, ":summary");
7250 DEFSYM (Qreal, "real");
7251 DEFSYM (Qnetwork, "network");
7252 DEFSYM (Qserial, "serial");
7253 DEFSYM (QCbuffer, ":buffer");
7254 DEFSYM (QChost, ":host");
7255 DEFSYM (QCservice, ":service");
7256 DEFSYM (QClocal, ":local");
7257 DEFSYM (QCremote, ":remote");
7258 DEFSYM (QCcoding, ":coding");
7259 DEFSYM (QCserver, ":server");
7260 DEFSYM (QCnowait, ":nowait");
7261 DEFSYM (QCsentinel, ":sentinel");
7262 DEFSYM (QClog, ":log");
7263 DEFSYM (QCnoquery, ":noquery");
7264 DEFSYM (QCstop, ":stop");
7265 DEFSYM (QCoptions, ":options");
7266 DEFSYM (QCplist, ":plist");
7268 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7270 staticpro (&Vprocess_alist);
7271 staticpro (&deleted_pid_list);
7273 #endif /* subprocesses */
7275 DEFSYM (QCname, ":name");
7276 DEFSYM (QCtype, ":type");
7278 DEFSYM (Qeuid, "euid");
7279 DEFSYM (Qegid, "egid");
7280 DEFSYM (Quser, "user");
7281 DEFSYM (Qgroup, "group");
7282 DEFSYM (Qcomm, "comm");
7283 DEFSYM (Qstate, "state");
7284 DEFSYM (Qppid, "ppid");
7285 DEFSYM (Qpgrp, "pgrp");
7286 DEFSYM (Qsess, "sess");
7287 DEFSYM (Qttname, "ttname");
7288 DEFSYM (Qtpgid, "tpgid");
7289 DEFSYM (Qminflt, "minflt");
7290 DEFSYM (Qmajflt, "majflt");
7291 DEFSYM (Qcminflt, "cminflt");
7292 DEFSYM (Qcmajflt, "cmajflt");
7293 DEFSYM (Qutime, "utime");
7294 DEFSYM (Qstime, "stime");
7295 DEFSYM (Qtime, "time");
7296 DEFSYM (Qcutime, "cutime");
7297 DEFSYM (Qcstime, "cstime");
7298 DEFSYM (Qctime, "ctime");
7299 DEFSYM (Qinternal_default_process_sentinel,
7300 "internal-default-process-sentinel");
7301 DEFSYM (Qinternal_default_process_filter,
7302 "internal-default-process-filter");
7303 DEFSYM (Qpri, "pri");
7304 DEFSYM (Qnice, "nice");
7305 DEFSYM (Qthcount, "thcount");
7306 DEFSYM (Qstart, "start");
7307 DEFSYM (Qvsize, "vsize");
7308 DEFSYM (Qrss, "rss");
7309 DEFSYM (Qetime, "etime");
7310 DEFSYM (Qpcpu, "pcpu");
7311 DEFSYM (Qpmem, "pmem");
7312 DEFSYM (Qargs, "args");
7314 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7315 doc: /* Non-nil means delete processes immediately when they exit.
7316 A value of nil means don't delete them until `list-processes' is run. */);
7318 delete_exited_processes = 1;
7320 #ifdef subprocesses
7321 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7322 doc: /* Control type of device used to communicate with subprocesses.
7323 Values are nil to use a pipe, or t or `pty' to use a pty.
7324 The value has no effect if the system has no ptys or if all ptys are busy:
7325 then a pipe is used in any case.
7326 The value takes effect when `start-process' is called. */);
7327 Vprocess_connection_type = Qt;
7329 #ifdef ADAPTIVE_READ_BUFFERING
7330 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7331 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7332 On some systems, when Emacs reads the output from a subprocess, the output data
7333 is read in very small blocks, potentially resulting in very poor performance.
7334 This behavior can be remedied to some extent by setting this variable to a
7335 non-nil value, as it will automatically delay reading from such processes, to
7336 allow them to produce more output before Emacs tries to read it.
7337 If the value is t, the delay is reset after each write to the process; any other
7338 non-nil value means that the delay is not reset on write.
7339 The variable takes effect when `start-process' is called. */);
7340 Vprocess_adaptive_read_buffering = Qt;
7341 #endif
7343 defsubr (&Sprocessp);
7344 defsubr (&Sget_process);
7345 defsubr (&Sdelete_process);
7346 defsubr (&Sprocess_status);
7347 defsubr (&Sprocess_exit_status);
7348 defsubr (&Sprocess_id);
7349 defsubr (&Sprocess_name);
7350 defsubr (&Sprocess_tty_name);
7351 defsubr (&Sprocess_command);
7352 defsubr (&Sset_process_buffer);
7353 defsubr (&Sprocess_buffer);
7354 defsubr (&Sprocess_mark);
7355 defsubr (&Sset_process_filter);
7356 defsubr (&Sprocess_filter);
7357 defsubr (&Sset_process_sentinel);
7358 defsubr (&Sprocess_sentinel);
7359 defsubr (&Sset_process_window_size);
7360 defsubr (&Sset_process_inherit_coding_system_flag);
7361 defsubr (&Sset_process_query_on_exit_flag);
7362 defsubr (&Sprocess_query_on_exit_flag);
7363 defsubr (&Sprocess_contact);
7364 defsubr (&Sprocess_plist);
7365 defsubr (&Sset_process_plist);
7366 defsubr (&Sprocess_list);
7367 defsubr (&Sstart_process);
7368 defsubr (&Sserial_process_configure);
7369 defsubr (&Smake_serial_process);
7370 defsubr (&Sset_network_process_option);
7371 defsubr (&Smake_network_process);
7372 defsubr (&Sformat_network_address);
7373 #if defined (HAVE_NET_IF_H)
7374 #ifdef SIOCGIFCONF
7375 defsubr (&Snetwork_interface_list);
7376 #endif
7377 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
7378 defsubr (&Snetwork_interface_info);
7379 #endif
7380 #endif /* defined (HAVE_NET_IF_H) */
7381 #ifdef DATAGRAM_SOCKETS
7382 defsubr (&Sprocess_datagram_address);
7383 defsubr (&Sset_process_datagram_address);
7384 #endif
7385 defsubr (&Saccept_process_output);
7386 defsubr (&Sprocess_send_region);
7387 defsubr (&Sprocess_send_string);
7388 defsubr (&Sinterrupt_process);
7389 defsubr (&Skill_process);
7390 defsubr (&Squit_process);
7391 defsubr (&Sstop_process);
7392 defsubr (&Scontinue_process);
7393 defsubr (&Sprocess_running_child_p);
7394 defsubr (&Sprocess_send_eof);
7395 defsubr (&Ssignal_process);
7396 defsubr (&Swaiting_for_user_input_p);
7397 defsubr (&Sprocess_type);
7398 defsubr (&Sinternal_default_process_sentinel);
7399 defsubr (&Sinternal_default_process_filter);
7400 defsubr (&Sset_process_coding_system);
7401 defsubr (&Sprocess_coding_system);
7402 defsubr (&Sset_process_filter_multibyte);
7403 defsubr (&Sprocess_filter_multibyte_p);
7405 #endif /* subprocesses */
7407 defsubr (&Sget_buffer_process);
7408 defsubr (&Sprocess_inherit_coding_system_flag);
7409 defsubr (&Slist_system_processes);
7410 defsubr (&Sprocess_attributes);