* doc/misc/calc.texi (ISO-8601): New section.
[emacs.git] / src / process.c
blob7b21d060cf877fab4d7bad689fb068fa2b73ec0e
1 /* Asynchronous subprocess control for GNU Emacs.
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2012
4 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
24 #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 #if defined (USE_GTK) || defined (HAVE_GCONF) || defined (HAVE_GSETTINGS)
128 #include "xgselect.h"
129 #endif
131 #ifdef WINDOWSNT
132 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
133 EMACS_TIME *, void *);
134 #endif
136 /* Work around GCC 4.7.0 bug with strict overflow checking; see
137 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
138 These lines can be removed once the GCC bug is fixed. */
139 #if (__GNUC__ == 4 && 3 <= __GNUC_MINOR__) || 4 < __GNUC__
140 # pragma GCC diagnostic ignored "-Wstrict-overflow"
141 #endif
143 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
144 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
145 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
146 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
147 Lisp_Object QCname, QCtype;
149 /* Non-zero if keyboard input is on hold, zero otherwise. */
151 static int kbd_is_on_hold;
153 /* Nonzero means don't run process sentinels. This is used
154 when exiting. */
155 int inhibit_sentinels;
157 #ifdef subprocesses
159 Lisp_Object Qprocessp;
160 static Lisp_Object Qrun, Qstop, Qsignal;
161 static Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
162 Lisp_Object Qlocal;
163 static Lisp_Object Qipv4, Qdatagram, Qseqpacket;
164 static Lisp_Object Qreal, Qnetwork, Qserial;
165 #ifdef AF_INET6
166 static Lisp_Object Qipv6;
167 #endif
168 static Lisp_Object QCport, QCprocess;
169 Lisp_Object QCspeed;
170 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
171 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
172 static Lisp_Object QCbuffer, QChost, QCservice;
173 static Lisp_Object QClocal, QCremote, QCcoding;
174 static Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
175 static Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
176 static Lisp_Object Qlast_nonmenu_event;
178 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
179 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
180 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
181 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
183 #ifndef HAVE_H_ERRNO
184 extern int h_errno;
185 #endif
187 /* Number of events of change of status of a process. */
188 static EMACS_INT process_tick;
189 /* Number of events for which the user or sentinel has been notified. */
190 static EMACS_INT update_tick;
192 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
194 /* Only W32 has this, it really means that select can't take write mask. */
195 #ifdef BROKEN_NON_BLOCKING_CONNECT
196 #undef NON_BLOCKING_CONNECT
197 #define SELECT_CANT_DO_WRITE_MASK
198 #else
199 #ifndef NON_BLOCKING_CONNECT
200 #ifdef HAVE_SELECT
201 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
202 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
203 #define NON_BLOCKING_CONNECT
204 #endif /* EWOULDBLOCK || EINPROGRESS */
205 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
206 #endif /* HAVE_SELECT */
207 #endif /* NON_BLOCKING_CONNECT */
208 #endif /* BROKEN_NON_BLOCKING_CONNECT */
210 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
211 this system. We need to read full packets, so we need a
212 "non-destructive" select. So we require either native select,
213 or emulation of select using FIONREAD. */
215 #ifndef BROKEN_DATAGRAM_SOCKETS
216 # if defined HAVE_SELECT || defined USABLE_FIONREAD
217 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
218 # define DATAGRAM_SOCKETS
219 # endif
220 # endif
221 #endif
223 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
224 # define HAVE_SEQPACKET
225 #endif
227 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
228 #define ADAPTIVE_READ_BUFFERING
229 #endif
231 #ifdef ADAPTIVE_READ_BUFFERING
232 #define READ_OUTPUT_DELAY_INCREMENT (EMACS_TIME_RESOLUTION / 100)
233 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
234 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
236 /* Number of processes which have a non-zero read_output_delay,
237 and therefore might be delayed for adaptive read buffering. */
239 static int process_output_delay_count;
241 /* Non-zero if any process has non-nil read_output_skip. */
243 static int process_output_skip;
245 #else
246 #define process_output_delay_count 0
247 #endif
249 static void create_process (Lisp_Object, char **, Lisp_Object);
250 #ifdef USABLE_SIGIO
251 static int keyboard_bit_set (SELECT_TYPE *);
252 #endif
253 static void deactivate_process (Lisp_Object);
254 static void status_notify (struct Lisp_Process *);
255 static int read_process_output (Lisp_Object, int);
256 static void handle_child_signal (int);
257 static void create_pty (Lisp_Object);
259 /* If we support a window system, turn on the code to poll periodically
260 to detect C-g. It isn't actually used when doing interrupt input. */
261 #ifdef HAVE_WINDOW_SYSTEM
262 #define POLL_FOR_INPUT
263 #endif
265 static Lisp_Object get_process (register Lisp_Object name);
266 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
268 /* Mask of bits indicating the descriptors that we wait for input on. */
270 static SELECT_TYPE input_wait_mask;
272 /* Mask that excludes keyboard input descriptor(s). */
274 static SELECT_TYPE non_keyboard_wait_mask;
276 /* Mask that excludes process input descriptor(s). */
278 static SELECT_TYPE non_process_wait_mask;
280 /* Mask for selecting for write. */
282 static SELECT_TYPE write_mask;
284 #ifdef NON_BLOCKING_CONNECT
285 /* Mask of bits indicating the descriptors that we wait for connect to
286 complete on. Once they complete, they are removed from this mask
287 and added to the input_wait_mask and non_keyboard_wait_mask. */
289 static SELECT_TYPE connect_wait_mask;
291 /* Number of bits set in connect_wait_mask. */
292 static int num_pending_connects;
293 #endif /* NON_BLOCKING_CONNECT */
295 /* The largest descriptor currently in use for a process object. */
296 static int max_process_desc;
298 /* The largest descriptor currently in use for input. */
299 static int max_input_desc;
301 /* Indexed by descriptor, gives the process (if any) for that descriptor */
302 static Lisp_Object chan_process[MAXDESC];
304 /* Alist of elements (NAME . PROCESS) */
305 static Lisp_Object Vprocess_alist;
307 /* Buffered-ahead input char from process, indexed by channel.
308 -1 means empty (no char is buffered).
309 Used on sys V where the only way to tell if there is any
310 output from the process is to read at least one char.
311 Always -1 on systems that support FIONREAD. */
313 static int proc_buffered_char[MAXDESC];
315 /* Table of `struct coding-system' for each process. */
316 static struct coding_system *proc_decode_coding_system[MAXDESC];
317 static struct coding_system *proc_encode_coding_system[MAXDESC];
319 #ifdef DATAGRAM_SOCKETS
320 /* Table of `partner address' for datagram sockets. */
321 static struct sockaddr_and_len {
322 struct sockaddr *sa;
323 int len;
324 } datagram_address[MAXDESC];
325 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
326 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
327 #else
328 #define DATAGRAM_CHAN_P(chan) (0)
329 #define DATAGRAM_CONN_P(proc) (0)
330 #endif
332 /* These setters are used only in this file, so they can be private. */
333 static void
334 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
336 p->buffer = val;
338 static void
339 pset_command (struct Lisp_Process *p, Lisp_Object val)
341 p->command = val;
343 static void
344 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
346 p->decode_coding_system = val;
348 static void
349 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
351 p->decoding_buf = val;
353 static void
354 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
356 p->encode_coding_system = val;
358 static void
359 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
361 p->encoding_buf = val;
363 static void
364 pset_filter (struct Lisp_Process *p, Lisp_Object val)
366 p->filter = val;
368 static void
369 pset_log (struct Lisp_Process *p, Lisp_Object val)
371 p->log = val;
373 static void
374 pset_mark (struct Lisp_Process *p, Lisp_Object val)
376 p->mark = val;
378 static void
379 pset_name (struct Lisp_Process *p, Lisp_Object val)
381 p->name = val;
383 static void
384 pset_plist (struct Lisp_Process *p, Lisp_Object val)
386 p->plist = val;
388 static void
389 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
391 p->sentinel = val;
393 static void
394 pset_status (struct Lisp_Process *p, Lisp_Object val)
396 p->status = val;
398 static void
399 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
401 p->tty_name = val;
403 static void
404 pset_type (struct Lisp_Process *p, Lisp_Object val)
406 p->type = val;
408 static void
409 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
411 p->write_queue = val;
416 static struct fd_callback_data
418 fd_callback func;
419 void *data;
420 #define FOR_READ 1
421 #define FOR_WRITE 2
422 int condition; /* mask of the defines above. */
423 } fd_callback_info[MAXDESC];
426 /* Add a file descriptor FD to be monitored for when read is possible.
427 When read is possible, call FUNC with argument DATA. */
429 void
430 add_read_fd (int fd, fd_callback func, void *data)
432 eassert (fd < MAXDESC);
433 add_keyboard_wait_descriptor (fd);
435 fd_callback_info[fd].func = func;
436 fd_callback_info[fd].data = data;
437 fd_callback_info[fd].condition |= FOR_READ;
440 /* Stop monitoring file descriptor FD for when read is possible. */
442 void
443 delete_read_fd (int fd)
445 eassert (fd < MAXDESC);
446 delete_keyboard_wait_descriptor (fd);
448 fd_callback_info[fd].condition &= ~FOR_READ;
449 if (fd_callback_info[fd].condition == 0)
451 fd_callback_info[fd].func = 0;
452 fd_callback_info[fd].data = 0;
456 /* Add a file descriptor FD to be monitored for when write is possible.
457 When write is possible, call FUNC with argument DATA. */
459 void
460 add_write_fd (int fd, fd_callback func, void *data)
462 eassert (fd < MAXDESC);
463 FD_SET (fd, &write_mask);
464 if (fd > max_input_desc)
465 max_input_desc = fd;
467 fd_callback_info[fd].func = func;
468 fd_callback_info[fd].data = data;
469 fd_callback_info[fd].condition |= FOR_WRITE;
472 /* Stop monitoring file descriptor FD for when write is possible. */
474 void
475 delete_write_fd (int fd)
477 int lim = max_input_desc;
479 eassert (fd < MAXDESC);
480 FD_CLR (fd, &write_mask);
481 fd_callback_info[fd].condition &= ~FOR_WRITE;
482 if (fd_callback_info[fd].condition == 0)
484 fd_callback_info[fd].func = 0;
485 fd_callback_info[fd].data = 0;
487 if (fd == max_input_desc)
488 for (fd = lim; fd >= 0; fd--)
489 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
491 max_input_desc = fd;
492 break;
499 /* Compute the Lisp form of the process status, p->status, from
500 the numeric status that was returned by `wait'. */
502 static Lisp_Object status_convert (int);
504 static void
505 update_status (struct Lisp_Process *p)
507 eassert (p->raw_status_new);
508 pset_status (p, status_convert (p->raw_status));
509 p->raw_status_new = 0;
512 /* Convert a process status word in Unix format to
513 the list that we use internally. */
515 static Lisp_Object
516 status_convert (int w)
518 if (WIFSTOPPED (w))
519 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
520 else if (WIFEXITED (w))
521 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
522 WCOREDUMP (w) ? Qt : Qnil));
523 else if (WIFSIGNALED (w))
524 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
525 WCOREDUMP (w) ? Qt : Qnil));
526 else
527 return Qrun;
530 /* Given a status-list, extract the three pieces of information
531 and store them individually through the three pointers. */
533 static void
534 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, int *coredump)
536 Lisp_Object tem;
538 if (SYMBOLP (l))
540 *symbol = l;
541 *code = 0;
542 *coredump = 0;
544 else
546 *symbol = XCAR (l);
547 tem = XCDR (l);
548 *code = XFASTINT (XCAR (tem));
549 tem = XCDR (tem);
550 *coredump = !NILP (tem);
554 /* Return a string describing a process status list. */
556 static Lisp_Object
557 status_message (struct Lisp_Process *p)
559 Lisp_Object status = p->status;
560 Lisp_Object symbol;
561 int code, coredump;
562 Lisp_Object string, string2;
564 decode_status (status, &symbol, &code, &coredump);
566 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
568 char const *signame;
569 synchronize_system_messages_locale ();
570 signame = strsignal (code);
571 if (signame == 0)
572 string = build_string ("unknown");
573 else
575 int c1, c2;
577 string = build_unibyte_string (signame);
578 if (! NILP (Vlocale_coding_system))
579 string = (code_convert_string_norecord
580 (string, Vlocale_coding_system, 0));
581 c1 = STRING_CHAR (SDATA (string));
582 c2 = downcase (c1);
583 if (c1 != c2)
584 Faset (string, make_number (0), make_number (c2));
586 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
587 return concat2 (string, string2);
589 else if (EQ (symbol, Qexit))
591 if (NETCONN1_P (p))
592 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
593 if (code == 0)
594 return build_string ("finished\n");
595 string = Fnumber_to_string (make_number (code));
596 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
597 return concat3 (build_string ("exited abnormally with code "),
598 string, string2);
600 else if (EQ (symbol, Qfailed))
602 string = Fnumber_to_string (make_number (code));
603 string2 = build_string ("\n");
604 return concat3 (build_string ("failed with code "),
605 string, string2);
607 else
608 return Fcopy_sequence (Fsymbol_name (symbol));
611 #ifdef HAVE_PTYS
613 /* The file name of the pty opened by allocate_pty. */
614 static char pty_name[24];
616 /* Open an available pty, returning a file descriptor.
617 Return -1 on failure.
618 The file name of the terminal corresponding to the pty
619 is left in the variable pty_name. */
621 static int
622 allocate_pty (void)
624 int fd;
626 #ifdef PTY_ITERATION
627 PTY_ITERATION
628 #else
629 register int c, i;
630 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
631 for (i = 0; i < 16; i++)
632 #endif
634 #ifdef PTY_NAME_SPRINTF
635 PTY_NAME_SPRINTF
636 #else
637 sprintf (pty_name, "/dev/pty%c%x", c, i);
638 #endif /* no PTY_NAME_SPRINTF */
640 #ifdef PTY_OPEN
641 PTY_OPEN;
642 #else /* no PTY_OPEN */
643 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
644 #endif /* no PTY_OPEN */
646 if (fd >= 0)
648 /* check to make certain that both sides are available
649 this avoids a nasty yet stupid bug in rlogins */
650 #ifdef PTY_TTY_NAME_SPRINTF
651 PTY_TTY_NAME_SPRINTF
652 #else
653 sprintf (pty_name, "/dev/tty%c%x", c, i);
654 #endif /* no PTY_TTY_NAME_SPRINTF */
655 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
657 emacs_close (fd);
658 # ifndef __sgi
659 continue;
660 # else
661 return -1;
662 # endif /* __sgi */
664 setup_pty (fd);
665 return fd;
668 return -1;
670 #endif /* HAVE_PTYS */
672 static Lisp_Object
673 make_process (Lisp_Object name)
675 register Lisp_Object val, tem, name1;
676 register struct Lisp_Process *p;
677 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
678 printmax_t i;
680 p = allocate_process ();
681 /* Initialize Lisp data. Note that allocate_process initializes all
682 Lisp data to nil, so do it only for slots which should not be nil. */
683 pset_status (p, Qrun);
684 pset_mark (p, Fmake_marker ());
686 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
687 non-Lisp data, so do it only for slots which should not be zero. */
688 p->infd = -1;
689 p->outfd = -1;
691 #ifdef HAVE_GNUTLS
692 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
693 #endif
695 /* If name is already in use, modify it until it is unused. */
697 name1 = name;
698 for (i = 1; ; i++)
700 tem = Fget_process (name1);
701 if (NILP (tem)) break;
702 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
704 name = name1;
705 pset_name (p, name);
706 XSETPROCESS (val, p);
707 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
708 return val;
711 static void
712 remove_process (register Lisp_Object proc)
714 register Lisp_Object pair;
716 pair = Frassq (proc, Vprocess_alist);
717 Vprocess_alist = Fdelq (pair, Vprocess_alist);
719 deactivate_process (proc);
723 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
724 doc: /* Return t if OBJECT is a process. */)
725 (Lisp_Object object)
727 return PROCESSP (object) ? Qt : Qnil;
730 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
731 doc: /* Return the process named NAME, or nil if there is none. */)
732 (register Lisp_Object name)
734 if (PROCESSP (name))
735 return name;
736 CHECK_STRING (name);
737 return Fcdr (Fassoc (name, Vprocess_alist));
740 /* This is how commands for the user decode process arguments. It
741 accepts a process, a process name, a buffer, a buffer name, or nil.
742 Buffers denote the first process in the buffer, and nil denotes the
743 current buffer. */
745 static Lisp_Object
746 get_process (register Lisp_Object name)
748 register Lisp_Object proc, obj;
749 if (STRINGP (name))
751 obj = Fget_process (name);
752 if (NILP (obj))
753 obj = Fget_buffer (name);
754 if (NILP (obj))
755 error ("Process %s does not exist", SDATA (name));
757 else if (NILP (name))
758 obj = Fcurrent_buffer ();
759 else
760 obj = name;
762 /* Now obj should be either a buffer object or a process object.
764 if (BUFFERP (obj))
766 proc = Fget_buffer_process (obj);
767 if (NILP (proc))
768 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
770 else
772 CHECK_PROCESS (obj);
773 proc = obj;
775 return proc;
779 /* Fdelete_process promises to immediately forget about the process, but in
780 reality, Emacs needs to remember those processes until they have been
781 treated by the SIGCHLD handler and waitpid has been invoked on them;
782 otherwise they might fill up the kernel's process table.
784 Some processes created by call-process are also put onto this list. */
785 static Lisp_Object deleted_pid_list;
787 void
788 record_deleted_pid (pid_t pid)
790 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
791 /* GC treated elements set to nil. */
792 Fdelq (Qnil, deleted_pid_list));
796 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
797 doc: /* Delete PROCESS: kill it and forget about it immediately.
798 PROCESS may be a process, a buffer, the name of a process or buffer, or
799 nil, indicating the current buffer's process. */)
800 (register Lisp_Object process)
802 register struct Lisp_Process *p;
804 process = get_process (process);
805 p = XPROCESS (process);
807 p->raw_status_new = 0;
808 if (NETCONN1_P (p) || SERIALCONN1_P (p))
810 pset_status (p, Fcons (Qexit, Fcons (make_number (0), Qnil)));
811 p->tick = ++process_tick;
812 status_notify (p);
813 redisplay_preserve_echo_area (13);
815 else
817 if (p->alive)
818 record_kill_process (p);
820 if (p->infd >= 0)
822 /* Update P's status, since record_kill_process will make the
823 SIGCHLD handler update deleted_pid_list, not *P. */
824 Lisp_Object symbol;
825 if (p->raw_status_new)
826 update_status (p);
827 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
828 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
829 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
831 p->tick = ++process_tick;
832 status_notify (p);
833 redisplay_preserve_echo_area (13);
836 remove_process (process);
837 return Qnil;
840 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
841 doc: /* Return the status of PROCESS.
842 The returned value is one of the following symbols:
843 run -- for a process that is running.
844 stop -- for a process stopped but continuable.
845 exit -- for a process that has exited.
846 signal -- for a process that has got a fatal signal.
847 open -- for a network stream connection that is open.
848 listen -- for a network stream server that is listening.
849 closed -- for a network stream connection that is closed.
850 connect -- when waiting for a non-blocking connection to complete.
851 failed -- when a non-blocking connection has failed.
852 nil -- if arg is a process name and no such process exists.
853 PROCESS may be a process, a buffer, the name of a process, or
854 nil, indicating the current buffer's process. */)
855 (register Lisp_Object process)
857 register struct Lisp_Process *p;
858 register Lisp_Object status;
860 if (STRINGP (process))
861 process = Fget_process (process);
862 else
863 process = get_process (process);
865 if (NILP (process))
866 return process;
868 p = XPROCESS (process);
869 if (p->raw_status_new)
870 update_status (p);
871 status = p->status;
872 if (CONSP (status))
873 status = XCAR (status);
874 if (NETCONN1_P (p) || SERIALCONN1_P (p))
876 if (EQ (status, Qexit))
877 status = Qclosed;
878 else if (EQ (p->command, Qt))
879 status = Qstop;
880 else if (EQ (status, Qrun))
881 status = Qopen;
883 return status;
886 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
887 1, 1, 0,
888 doc: /* Return the exit status of PROCESS or the signal number that killed it.
889 If PROCESS has not yet exited or died, return 0. */)
890 (register Lisp_Object process)
892 CHECK_PROCESS (process);
893 if (XPROCESS (process)->raw_status_new)
894 update_status (XPROCESS (process));
895 if (CONSP (XPROCESS (process)->status))
896 return XCAR (XCDR (XPROCESS (process)->status));
897 return make_number (0);
900 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
901 doc: /* Return the process id of PROCESS.
902 This is the pid of the external process which PROCESS uses or talks to.
903 For a network connection, this value is nil. */)
904 (register Lisp_Object process)
906 pid_t pid;
908 CHECK_PROCESS (process);
909 pid = XPROCESS (process)->pid;
910 return (pid ? make_fixnum_or_float (pid) : Qnil);
913 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
914 doc: /* Return the name of PROCESS, as a string.
915 This is the name of the program invoked in PROCESS,
916 possibly modified to make it unique among process names. */)
917 (register Lisp_Object process)
919 CHECK_PROCESS (process);
920 return XPROCESS (process)->name;
923 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
924 doc: /* Return the command that was executed to start PROCESS.
925 This is a list of strings, the first string being the program executed
926 and the rest of the strings being the arguments given to it.
927 For a network or serial process, this is nil (process is running) or t
928 \(process is stopped). */)
929 (register Lisp_Object process)
931 CHECK_PROCESS (process);
932 return XPROCESS (process)->command;
935 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
936 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
937 This is the terminal that the process itself reads and writes on,
938 not the name of the pty that Emacs uses to talk with that terminal. */)
939 (register Lisp_Object process)
941 CHECK_PROCESS (process);
942 return XPROCESS (process)->tty_name;
945 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
946 2, 2, 0,
947 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
948 Return BUFFER. */)
949 (register Lisp_Object process, Lisp_Object buffer)
951 struct Lisp_Process *p;
953 CHECK_PROCESS (process);
954 if (!NILP (buffer))
955 CHECK_BUFFER (buffer);
956 p = XPROCESS (process);
957 pset_buffer (p, buffer);
958 if (NETCONN1_P (p) || SERIALCONN1_P (p))
959 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
960 setup_process_coding_systems (process);
961 return buffer;
964 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
965 1, 1, 0,
966 doc: /* Return the buffer PROCESS is associated with.
967 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
968 (register Lisp_Object process)
970 CHECK_PROCESS (process);
971 return XPROCESS (process)->buffer;
974 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
975 1, 1, 0,
976 doc: /* Return the marker for the end of the last output from PROCESS. */)
977 (register Lisp_Object process)
979 CHECK_PROCESS (process);
980 return XPROCESS (process)->mark;
983 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
984 2, 2, 0,
985 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
986 A value of t means stop accepting output from the process.
988 When a process has a filter, its buffer is not used for output.
989 Instead, each time it does output, the entire string of output is
990 passed to the filter.
992 The filter gets two arguments: the process and the string of output.
993 The string argument is normally a multibyte string, except:
994 - if the process' input coding system is no-conversion or raw-text,
995 it is a unibyte string (the non-converted input), or else
996 - if `default-enable-multibyte-characters' is nil, it is a unibyte
997 string (the result of converting the decoded input multibyte
998 string to unibyte with `string-make-unibyte'). */)
999 (register Lisp_Object process, Lisp_Object filter)
1001 struct Lisp_Process *p;
1003 CHECK_PROCESS (process);
1004 p = XPROCESS (process);
1006 /* Don't signal an error if the process' input file descriptor
1007 is closed. This could make debugging Lisp more difficult,
1008 for example when doing something like
1010 (setq process (start-process ...))
1011 (debug)
1012 (set-process-filter process ...) */
1014 if (p->infd >= 0)
1016 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1018 FD_CLR (p->infd, &input_wait_mask);
1019 FD_CLR (p->infd, &non_keyboard_wait_mask);
1021 else if (EQ (p->filter, Qt)
1022 /* Network or serial process not stopped: */
1023 && !EQ (p->command, Qt))
1025 FD_SET (p->infd, &input_wait_mask);
1026 FD_SET (p->infd, &non_keyboard_wait_mask);
1030 pset_filter (p, filter);
1031 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1032 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1033 setup_process_coding_systems (process);
1034 return filter;
1037 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1038 1, 1, 0,
1039 doc: /* Returns the filter function of PROCESS; nil if none.
1040 See `set-process-filter' for more info on filter functions. */)
1041 (register Lisp_Object process)
1043 CHECK_PROCESS (process);
1044 return XPROCESS (process)->filter;
1047 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1048 2, 2, 0,
1049 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1050 The sentinel is called as a function when the process changes state.
1051 It gets two arguments: the process, and a string describing the change. */)
1052 (register Lisp_Object process, Lisp_Object sentinel)
1054 struct Lisp_Process *p;
1056 CHECK_PROCESS (process);
1057 p = XPROCESS (process);
1059 pset_sentinel (p, sentinel);
1060 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1061 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1062 return sentinel;
1065 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1066 1, 1, 0,
1067 doc: /* Return the sentinel of PROCESS; nil if none.
1068 See `set-process-sentinel' for more info on sentinels. */)
1069 (register Lisp_Object process)
1071 CHECK_PROCESS (process);
1072 return XPROCESS (process)->sentinel;
1075 DEFUN ("set-process-window-size", Fset_process_window_size,
1076 Sset_process_window_size, 3, 3, 0,
1077 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1078 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
1080 CHECK_PROCESS (process);
1081 CHECK_RANGED_INTEGER (height, 0, INT_MAX);
1082 CHECK_RANGED_INTEGER (width, 0, INT_MAX);
1084 if (XPROCESS (process)->infd < 0
1085 || set_window_size (XPROCESS (process)->infd,
1086 XINT (height), XINT (width)) <= 0)
1087 return Qnil;
1088 else
1089 return Qt;
1092 DEFUN ("set-process-inherit-coding-system-flag",
1093 Fset_process_inherit_coding_system_flag,
1094 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1095 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1096 If the second argument FLAG is non-nil, then the variable
1097 `buffer-file-coding-system' of the buffer associated with PROCESS
1098 will be bound to the value of the coding system used to decode
1099 the process output.
1101 This is useful when the coding system specified for the process buffer
1102 leaves either the character code conversion or the end-of-line conversion
1103 unspecified, or if the coding system used to decode the process output
1104 is more appropriate for saving the process buffer.
1106 Binding the variable `inherit-process-coding-system' to non-nil before
1107 starting the process is an alternative way of setting the inherit flag
1108 for the process which will run.
1110 This function returns FLAG. */)
1111 (register Lisp_Object process, Lisp_Object flag)
1113 CHECK_PROCESS (process);
1114 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1115 return flag;
1118 DEFUN ("set-process-query-on-exit-flag",
1119 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1120 2, 2, 0,
1121 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1122 If the second argument FLAG is non-nil, Emacs will query the user before
1123 exiting or killing a buffer if PROCESS is running. This function
1124 returns FLAG. */)
1125 (register Lisp_Object process, Lisp_Object flag)
1127 CHECK_PROCESS (process);
1128 XPROCESS (process)->kill_without_query = NILP (flag);
1129 return flag;
1132 DEFUN ("process-query-on-exit-flag",
1133 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1134 1, 1, 0,
1135 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1136 (register Lisp_Object process)
1138 CHECK_PROCESS (process);
1139 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1142 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1143 1, 2, 0,
1144 doc: /* Return the contact info of PROCESS; t for a real child.
1145 For a network or serial connection, the value depends on the optional
1146 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1147 SERVICE) for a network connection or (PORT SPEED) for a serial
1148 connection. If KEY is t, the complete contact information for the
1149 connection is returned, else the specific value for the keyword KEY is
1150 returned. See `make-network-process' or `make-serial-process' for a
1151 list of keywords. */)
1152 (register Lisp_Object process, Lisp_Object key)
1154 Lisp_Object contact;
1156 CHECK_PROCESS (process);
1157 contact = XPROCESS (process)->childp;
1159 #ifdef DATAGRAM_SOCKETS
1160 if (DATAGRAM_CONN_P (process)
1161 && (EQ (key, Qt) || EQ (key, QCremote)))
1162 contact = Fplist_put (contact, QCremote,
1163 Fprocess_datagram_address (process));
1164 #endif
1166 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1167 return contact;
1168 if (NILP (key) && NETCONN_P (process))
1169 return Fcons (Fplist_get (contact, QChost),
1170 Fcons (Fplist_get (contact, QCservice), Qnil));
1171 if (NILP (key) && SERIALCONN_P (process))
1172 return Fcons (Fplist_get (contact, QCport),
1173 Fcons (Fplist_get (contact, QCspeed), Qnil));
1174 return Fplist_get (contact, key);
1177 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1178 1, 1, 0,
1179 doc: /* Return the plist of PROCESS. */)
1180 (register Lisp_Object process)
1182 CHECK_PROCESS (process);
1183 return XPROCESS (process)->plist;
1186 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1187 2, 2, 0,
1188 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1189 (register Lisp_Object process, Lisp_Object plist)
1191 CHECK_PROCESS (process);
1192 CHECK_LIST (plist);
1194 pset_plist (XPROCESS (process), plist);
1195 return plist;
1198 #if 0 /* Turned off because we don't currently record this info
1199 in the process. Perhaps add it. */
1200 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1201 doc: /* Return the connection type of PROCESS.
1202 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1203 a socket connection. */)
1204 (Lisp_Object process)
1206 return XPROCESS (process)->type;
1208 #endif
1210 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1211 doc: /* Return the connection type of PROCESS.
1212 The value is either the symbol `real', `network', or `serial'.
1213 PROCESS may be a process, a buffer, the name of a process or buffer, or
1214 nil, indicating the current buffer's process. */)
1215 (Lisp_Object process)
1217 Lisp_Object proc;
1218 proc = get_process (process);
1219 return XPROCESS (proc)->type;
1222 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1223 1, 2, 0,
1224 doc: /* Convert network ADDRESS from internal format to a string.
1225 A 4 or 5 element vector represents an IPv4 address (with port number).
1226 An 8 or 9 element vector represents an IPv6 address (with port number).
1227 If optional second argument OMIT-PORT is non-nil, don't include a port
1228 number in the string, even when present in ADDRESS.
1229 Returns nil if format of ADDRESS is invalid. */)
1230 (Lisp_Object address, Lisp_Object omit_port)
1232 if (NILP (address))
1233 return Qnil;
1235 if (STRINGP (address)) /* AF_LOCAL */
1236 return address;
1238 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1240 register struct Lisp_Vector *p = XVECTOR (address);
1241 ptrdiff_t size = p->header.size;
1242 Lisp_Object args[10];
1243 int nargs, i;
1245 if (size == 4 || (size == 5 && !NILP (omit_port)))
1247 args[0] = build_string ("%d.%d.%d.%d");
1248 nargs = 4;
1250 else if (size == 5)
1252 args[0] = build_string ("%d.%d.%d.%d:%d");
1253 nargs = 5;
1255 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1257 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1258 nargs = 8;
1260 else if (size == 9)
1262 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1263 nargs = 9;
1265 else
1266 return Qnil;
1268 for (i = 0; i < nargs; i++)
1270 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1271 return Qnil;
1273 if (nargs <= 5 /* IPv4 */
1274 && i < 4 /* host, not port */
1275 && XINT (p->contents[i]) > 255)
1276 return Qnil;
1278 args[i+1] = p->contents[i];
1281 return Fformat (nargs+1, args);
1284 if (CONSP (address))
1286 Lisp_Object args[2];
1287 args[0] = build_string ("<Family %d>");
1288 args[1] = Fcar (address);
1289 return Fformat (2, args);
1292 return Qnil;
1295 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1296 doc: /* Return a list of all processes. */)
1297 (void)
1299 return Fmapcar (Qcdr, Vprocess_alist);
1302 /* Starting asynchronous inferior processes. */
1304 static Lisp_Object start_process_unwind (Lisp_Object proc);
1306 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1307 doc: /* Start a program in a subprocess. Return the process object for it.
1308 NAME is name for process. It is modified if necessary to make it unique.
1309 BUFFER is the buffer (or buffer name) to associate with the process.
1311 Process output (both standard output and standard error streams) goes
1312 at end of BUFFER, unless you specify an output stream or filter
1313 function to handle the output. BUFFER may also be nil, meaning that
1314 this process is not associated with any buffer.
1316 PROGRAM is the program file name. It is searched for in `exec-path'
1317 (which see). If nil, just associate a pty with the buffer. Remaining
1318 arguments are strings to give program as arguments.
1320 If you want to separate standard output from standard error, invoke
1321 the command through a shell and redirect one of them using the shell
1322 syntax.
1324 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1325 (ptrdiff_t nargs, Lisp_Object *args)
1327 Lisp_Object buffer, name, program, proc, current_dir, tem;
1328 register unsigned char **new_argv;
1329 ptrdiff_t i;
1330 ptrdiff_t count = SPECPDL_INDEX ();
1332 buffer = args[1];
1333 if (!NILP (buffer))
1334 buffer = Fget_buffer_create (buffer);
1336 /* Make sure that the child will be able to chdir to the current
1337 buffer's current directory, or its unhandled equivalent. We
1338 can't just have the child check for an error when it does the
1339 chdir, since it's in a vfork.
1341 We have to GCPRO around this because Fexpand_file_name and
1342 Funhandled_file_name_directory might call a file name handling
1343 function. The argument list is protected by the caller, so all
1344 we really have to worry about is buffer. */
1346 struct gcpro gcpro1, gcpro2;
1348 current_dir = BVAR (current_buffer, directory);
1350 GCPRO2 (buffer, current_dir);
1352 current_dir = Funhandled_file_name_directory (current_dir);
1353 if (NILP (current_dir))
1354 /* If the file name handler says that current_dir is unreachable, use
1355 a sensible default. */
1356 current_dir = build_string ("~/");
1357 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1358 if (NILP (Ffile_accessible_directory_p (current_dir)))
1359 report_file_error ("Setting current directory",
1360 Fcons (BVAR (current_buffer, directory), Qnil));
1362 UNGCPRO;
1365 name = args[0];
1366 CHECK_STRING (name);
1368 program = args[2];
1370 if (!NILP (program))
1371 CHECK_STRING (program);
1373 proc = make_process (name);
1374 /* If an error occurs and we can't start the process, we want to
1375 remove it from the process list. This means that each error
1376 check in create_process doesn't need to call remove_process
1377 itself; it's all taken care of here. */
1378 record_unwind_protect (start_process_unwind, proc);
1380 pset_childp (XPROCESS (proc), Qt);
1381 pset_plist (XPROCESS (proc), Qnil);
1382 pset_type (XPROCESS (proc), Qreal);
1383 pset_buffer (XPROCESS (proc), buffer);
1384 pset_sentinel (XPROCESS (proc), Qnil);
1385 pset_filter (XPROCESS (proc), Qnil);
1386 pset_command (XPROCESS (proc), Flist (nargs - 2, args + 2));
1388 #ifdef HAVE_GNUTLS
1389 /* AKA GNUTLS_INITSTAGE(proc). */
1390 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1391 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1392 #endif
1394 #ifdef ADAPTIVE_READ_BUFFERING
1395 XPROCESS (proc)->adaptive_read_buffering
1396 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1397 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1398 #endif
1400 /* Make the process marker point into the process buffer (if any). */
1401 if (BUFFERP (buffer))
1402 set_marker_both (XPROCESS (proc)->mark, buffer,
1403 BUF_ZV (XBUFFER (buffer)),
1404 BUF_ZV_BYTE (XBUFFER (buffer)));
1407 /* Decide coding systems for communicating with the process. Here
1408 we don't setup the structure coding_system nor pay attention to
1409 unibyte mode. They are done in create_process. */
1411 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1412 Lisp_Object coding_systems = Qt;
1413 Lisp_Object val, *args2;
1414 struct gcpro gcpro1, gcpro2;
1416 val = Vcoding_system_for_read;
1417 if (NILP (val))
1419 args2 = alloca ((nargs + 1) * sizeof *args2);
1420 args2[0] = Qstart_process;
1421 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1422 GCPRO2 (proc, current_dir);
1423 if (!NILP (program))
1424 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1425 UNGCPRO;
1426 if (CONSP (coding_systems))
1427 val = XCAR (coding_systems);
1428 else if (CONSP (Vdefault_process_coding_system))
1429 val = XCAR (Vdefault_process_coding_system);
1431 pset_decode_coding_system (XPROCESS (proc), val);
1433 val = Vcoding_system_for_write;
1434 if (NILP (val))
1436 if (EQ (coding_systems, Qt))
1438 args2 = alloca ((nargs + 1) * sizeof *args2);
1439 args2[0] = Qstart_process;
1440 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1441 GCPRO2 (proc, current_dir);
1442 if (!NILP (program))
1443 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1444 UNGCPRO;
1446 if (CONSP (coding_systems))
1447 val = XCDR (coding_systems);
1448 else if (CONSP (Vdefault_process_coding_system))
1449 val = XCDR (Vdefault_process_coding_system);
1451 pset_encode_coding_system (XPROCESS (proc), val);
1452 /* Note: At this moment, the above coding system may leave
1453 text-conversion or eol-conversion unspecified. They will be
1454 decided after we read output from the process and decode it by
1455 some coding system, or just before we actually send a text to
1456 the process. */
1460 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1461 XPROCESS (proc)->decoding_carryover = 0;
1462 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1464 XPROCESS (proc)->inherit_coding_system_flag
1465 = !(NILP (buffer) || !inherit_process_coding_system);
1467 if (!NILP (program))
1469 /* If program file name is not absolute, search our path for it.
1470 Put the name we will really use in TEM. */
1471 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1472 && !(SCHARS (program) > 1
1473 && IS_DEVICE_SEP (SREF (program, 1))))
1475 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1477 tem = Qnil;
1478 GCPRO4 (name, program, buffer, current_dir);
1479 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1480 UNGCPRO;
1481 if (NILP (tem))
1482 report_file_error ("Searching for program", Fcons (program, Qnil));
1483 tem = Fexpand_file_name (tem, Qnil);
1485 else
1487 if (!NILP (Ffile_directory_p (program)))
1488 error ("Specified program for new process is a directory");
1489 tem = program;
1492 /* If program file name starts with /: for quoting a magic name,
1493 discard that. */
1494 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1495 && SREF (tem, 1) == ':')
1496 tem = Fsubstring (tem, make_number (2), Qnil);
1499 Lisp_Object arg_encoding = Qnil;
1500 struct gcpro gcpro1;
1501 GCPRO1 (tem);
1503 /* Encode the file name and put it in NEW_ARGV.
1504 That's where the child will use it to execute the program. */
1505 tem = Fcons (ENCODE_FILE (tem), Qnil);
1507 /* Here we encode arguments by the coding system used for sending
1508 data to the process. We don't support using different coding
1509 systems for encoding arguments and for encoding data sent to the
1510 process. */
1512 for (i = 3; i < nargs; i++)
1514 tem = Fcons (args[i], tem);
1515 CHECK_STRING (XCAR (tem));
1516 if (STRING_MULTIBYTE (XCAR (tem)))
1518 if (NILP (arg_encoding))
1519 arg_encoding = (complement_process_encoding_system
1520 (XPROCESS (proc)->encode_coding_system));
1521 XSETCAR (tem,
1522 code_convert_string_norecord
1523 (XCAR (tem), arg_encoding, 1));
1527 UNGCPRO;
1530 /* Now that everything is encoded we can collect the strings into
1531 NEW_ARGV. */
1532 new_argv = alloca ((nargs - 1) * sizeof *new_argv);
1533 new_argv[nargs - 2] = 0;
1535 for (i = nargs - 2; i-- != 0; )
1537 new_argv[i] = SDATA (XCAR (tem));
1538 tem = XCDR (tem);
1541 create_process (proc, (char **) new_argv, current_dir);
1543 else
1544 create_pty (proc);
1546 return unbind_to (count, proc);
1549 /* This function is the unwind_protect form for Fstart_process. If
1550 PROC doesn't have its pid set, then we know someone has signaled
1551 an error and the process wasn't started successfully, so we should
1552 remove it from the process list. */
1553 static Lisp_Object
1554 start_process_unwind (Lisp_Object proc)
1556 if (!PROCESSP (proc))
1557 emacs_abort ();
1559 /* Was PROC started successfully?
1560 -2 is used for a pty with no process, eg for gdb. */
1561 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1562 remove_process (proc);
1564 return Qnil;
1567 static void
1568 create_process_1 (struct atimer *timer)
1570 /* Nothing to do. */
1574 static void
1575 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1577 int inchannel, outchannel;
1578 pid_t pid;
1579 int sv[2];
1580 #ifndef WINDOWSNT
1581 int wait_child_setup[2];
1582 #endif
1583 sigset_t blocked;
1584 /* Use volatile to protect variables from being clobbered by vfork. */
1585 volatile int forkin, forkout;
1586 volatile int pty_flag = 0;
1587 volatile Lisp_Object lisp_pty_name = Qnil;
1588 volatile Lisp_Object encoded_current_dir;
1590 inchannel = outchannel = -1;
1592 #ifdef HAVE_PTYS
1593 if (!NILP (Vprocess_connection_type))
1594 outchannel = inchannel = allocate_pty ();
1596 if (inchannel >= 0)
1598 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1599 /* On most USG systems it does not work to open the pty's tty here,
1600 then close it and reopen it in the child. */
1601 /* Don't let this terminal become our controlling terminal
1602 (in case we don't have one). */
1603 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1604 if (forkin < 0)
1605 report_file_error ("Opening pty", Qnil);
1606 #else
1607 forkin = forkout = -1;
1608 #endif /* not USG, or USG_SUBTTY_WORKS */
1609 pty_flag = 1;
1610 lisp_pty_name = build_string (pty_name);
1612 else
1613 #endif /* HAVE_PTYS */
1615 int tem;
1616 tem = pipe (sv);
1617 if (tem < 0)
1618 report_file_error ("Creating pipe", Qnil);
1619 inchannel = sv[0];
1620 forkout = sv[1];
1621 tem = pipe (sv);
1622 if (tem < 0)
1624 emacs_close (inchannel);
1625 emacs_close (forkout);
1626 report_file_error ("Creating pipe", Qnil);
1628 outchannel = sv[1];
1629 forkin = sv[0];
1632 #ifndef WINDOWSNT
1634 int tem;
1636 tem = pipe (wait_child_setup);
1637 if (tem < 0)
1638 report_file_error ("Creating pipe", Qnil);
1639 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1640 if (tem >= 0)
1641 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1642 if (tem < 0)
1644 emacs_close (wait_child_setup[0]);
1645 emacs_close (wait_child_setup[1]);
1646 report_file_error ("Setting file descriptor flags", Qnil);
1649 #endif
1651 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1652 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1654 /* Record this as an active process, with its channels.
1655 As a result, child_setup will close Emacs's side of the pipes. */
1656 chan_process[inchannel] = process;
1657 XPROCESS (process)->infd = inchannel;
1658 XPROCESS (process)->outfd = outchannel;
1660 /* Previously we recorded the tty descriptor used in the subprocess.
1661 It was only used for getting the foreground tty process, so now
1662 we just reopen the device (see emacs_get_tty_pgrp) as this is
1663 more portable (see USG_SUBTTY_WORKS above). */
1665 XPROCESS (process)->pty_flag = pty_flag;
1666 pset_status (XPROCESS (process), Qrun);
1668 FD_SET (inchannel, &input_wait_mask);
1669 FD_SET (inchannel, &non_keyboard_wait_mask);
1670 if (inchannel > max_process_desc)
1671 max_process_desc = inchannel;
1673 /* This may signal an error. */
1674 setup_process_coding_systems (process);
1676 encoded_current_dir = ENCODE_FILE (current_dir);
1678 block_input ();
1680 /* Block SIGCHLD until we have a chance to store the new fork's
1681 pid in its process structure. */
1682 sigemptyset (&blocked);
1683 sigaddset (&blocked, SIGCHLD);
1684 pthread_sigmask (SIG_BLOCK, &blocked, 0);
1686 #ifndef WINDOWSNT
1687 pid = vfork ();
1688 if (pid == 0)
1689 #endif /* not WINDOWSNT */
1691 int xforkin = forkin;
1692 int xforkout = forkout;
1694 /* Make the pty be the controlling terminal of the process. */
1695 #ifdef HAVE_PTYS
1696 /* First, disconnect its current controlling terminal. */
1697 /* We tried doing setsid only if pty_flag, but it caused
1698 process_set_signal to fail on SGI when using a pipe. */
1699 setsid ();
1700 /* Make the pty's terminal the controlling terminal. */
1701 if (pty_flag && xforkin >= 0)
1703 #ifdef TIOCSCTTY
1704 /* We ignore the return value
1705 because faith@cs.unc.edu says that is necessary on Linux. */
1706 ioctl (xforkin, TIOCSCTTY, 0);
1707 #endif
1709 #if defined (LDISC1)
1710 if (pty_flag && xforkin >= 0)
1712 struct termios t;
1713 tcgetattr (xforkin, &t);
1714 t.c_lflag = LDISC1;
1715 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1716 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1718 #else
1719 #if defined (NTTYDISC) && defined (TIOCSETD)
1720 if (pty_flag && xforkin >= 0)
1722 /* Use new line discipline. */
1723 int ldisc = NTTYDISC;
1724 ioctl (xforkin, TIOCSETD, &ldisc);
1726 #endif
1727 #endif
1728 #ifdef TIOCNOTTY
1729 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1730 can do TIOCSPGRP only to the process's controlling tty. */
1731 if (pty_flag)
1733 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1734 I can't test it since I don't have 4.3. */
1735 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1736 if (j >= 0)
1738 ioctl (j, TIOCNOTTY, 0);
1739 emacs_close (j);
1742 #endif /* TIOCNOTTY */
1744 #if !defined (DONT_REOPEN_PTY)
1745 /*** There is a suggestion that this ought to be a
1746 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1747 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1748 that system does seem to need this code, even though
1749 both TIOCSCTTY is defined. */
1750 /* Now close the pty (if we had it open) and reopen it.
1751 This makes the pty the controlling terminal of the subprocess. */
1752 if (pty_flag)
1755 /* I wonder if emacs_close (emacs_open (pty_name, ...))
1756 would work? */
1757 if (xforkin >= 0)
1758 emacs_close (xforkin);
1759 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
1761 if (xforkin < 0)
1763 emacs_write (1, "Couldn't open the pty terminal ", 31);
1764 emacs_write (1, pty_name, strlen (pty_name));
1765 emacs_write (1, "\n", 1);
1766 _exit (1);
1770 #endif /* not DONT_REOPEN_PTY */
1772 #ifdef SETUP_SLAVE_PTY
1773 if (pty_flag)
1775 SETUP_SLAVE_PTY;
1777 #endif /* SETUP_SLAVE_PTY */
1778 #ifdef AIX
1779 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
1780 Now reenable it in the child, so it will die when we want it to. */
1781 if (pty_flag)
1782 signal (SIGHUP, SIG_DFL);
1783 #endif
1784 #endif /* HAVE_PTYS */
1786 signal (SIGINT, SIG_DFL);
1787 signal (SIGQUIT, SIG_DFL);
1789 /* Emacs ignores SIGPIPE, but the child should not. */
1790 signal (SIGPIPE, SIG_DFL);
1792 /* Stop blocking signals in the child. */
1793 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
1795 if (pty_flag)
1796 child_setup_tty (xforkout);
1797 #ifdef WINDOWSNT
1798 pid = child_setup (xforkin, xforkout, xforkout,
1799 new_argv, 1, encoded_current_dir);
1800 #else /* not WINDOWSNT */
1801 emacs_close (wait_child_setup[0]);
1802 child_setup (xforkin, xforkout, xforkout,
1803 new_argv, 1, encoded_current_dir);
1804 #endif /* not WINDOWSNT */
1807 /* Back in the parent process. */
1809 XPROCESS (process)->pid = pid;
1810 if (0 <= pid)
1811 XPROCESS (process)->alive = 1;
1813 /* Stop blocking signals in the parent. */
1814 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
1815 unblock_input ();
1817 if (pid < 0)
1819 if (forkin >= 0)
1820 emacs_close (forkin);
1821 if (forkin != forkout && forkout >= 0)
1822 emacs_close (forkout);
1824 else
1826 /* vfork succeeded. */
1828 #ifdef WINDOWSNT
1829 register_child (pid, inchannel);
1830 #endif /* WINDOWSNT */
1832 /* If the subfork execv fails, and it exits,
1833 this close hangs. I don't know why.
1834 So have an interrupt jar it loose. */
1836 struct atimer *timer;
1837 EMACS_TIME offset = make_emacs_time (1, 0);
1839 stop_polling ();
1840 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
1842 if (forkin >= 0)
1843 emacs_close (forkin);
1845 cancel_atimer (timer);
1846 start_polling ();
1849 if (forkin != forkout && forkout >= 0)
1850 emacs_close (forkout);
1852 pset_tty_name (XPROCESS (process), lisp_pty_name);
1854 #ifndef WINDOWSNT
1855 /* Wait for child_setup to complete in case that vfork is
1856 actually defined as fork. The descriptor wait_child_setup[1]
1857 of a pipe is closed at the child side either by close-on-exec
1858 on successful execve or the _exit call in child_setup. */
1860 char dummy;
1862 emacs_close (wait_child_setup[1]);
1863 emacs_read (wait_child_setup[0], &dummy, 1);
1864 emacs_close (wait_child_setup[0]);
1866 #endif
1869 /* Now generate the error if vfork failed. */
1870 if (pid < 0)
1871 report_file_error ("Doing vfork", Qnil);
1874 void
1875 create_pty (Lisp_Object process)
1877 int inchannel, outchannel;
1878 int pty_flag = 0;
1880 inchannel = outchannel = -1;
1882 #ifdef HAVE_PTYS
1883 if (!NILP (Vprocess_connection_type))
1884 outchannel = inchannel = allocate_pty ();
1886 if (inchannel >= 0)
1888 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1889 /* On most USG systems it does not work to open the pty's tty here,
1890 then close it and reopen it in the child. */
1891 /* Don't let this terminal become our controlling terminal
1892 (in case we don't have one). */
1893 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1894 if (forkout < 0)
1895 report_file_error ("Opening pty", Qnil);
1896 #if defined (DONT_REOPEN_PTY)
1897 /* In the case that vfork is defined as fork, the parent process
1898 (Emacs) may send some data before the child process completes
1899 tty options setup. So we setup tty before forking. */
1900 child_setup_tty (forkout);
1901 #endif /* DONT_REOPEN_PTY */
1902 #endif /* not USG, or USG_SUBTTY_WORKS */
1903 pty_flag = 1;
1905 #endif /* HAVE_PTYS */
1907 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1908 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1910 /* Record this as an active process, with its channels.
1911 As a result, child_setup will close Emacs's side of the pipes. */
1912 chan_process[inchannel] = process;
1913 XPROCESS (process)->infd = inchannel;
1914 XPROCESS (process)->outfd = outchannel;
1916 /* Previously we recorded the tty descriptor used in the subprocess.
1917 It was only used for getting the foreground tty process, so now
1918 we just reopen the device (see emacs_get_tty_pgrp) as this is
1919 more portable (see USG_SUBTTY_WORKS above). */
1921 XPROCESS (process)->pty_flag = pty_flag;
1922 pset_status (XPROCESS (process), Qrun);
1923 setup_process_coding_systems (process);
1925 FD_SET (inchannel, &input_wait_mask);
1926 FD_SET (inchannel, &non_keyboard_wait_mask);
1927 if (inchannel > max_process_desc)
1928 max_process_desc = inchannel;
1930 XPROCESS (process)->pid = -2;
1931 #ifdef HAVE_PTYS
1932 if (pty_flag)
1933 pset_tty_name (XPROCESS (process), build_string (pty_name));
1934 else
1935 #endif
1936 pset_tty_name (XPROCESS (process), Qnil);
1940 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1941 The address family of sa is not included in the result. */
1943 static Lisp_Object
1944 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
1946 Lisp_Object address;
1947 int i;
1948 unsigned char *cp;
1949 register struct Lisp_Vector *p;
1951 /* Workaround for a bug in getsockname on BSD: Names bound to
1952 sockets in the UNIX domain are inaccessible; getsockname returns
1953 a zero length name. */
1954 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
1955 return empty_unibyte_string;
1957 switch (sa->sa_family)
1959 case AF_INET:
1961 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
1962 len = sizeof (sin->sin_addr) + 1;
1963 address = Fmake_vector (make_number (len), Qnil);
1964 p = XVECTOR (address);
1965 p->contents[--len] = make_number (ntohs (sin->sin_port));
1966 cp = (unsigned char *) &sin->sin_addr;
1967 break;
1969 #ifdef AF_INET6
1970 case AF_INET6:
1972 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
1973 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
1974 len = sizeof (sin6->sin6_addr)/2 + 1;
1975 address = Fmake_vector (make_number (len), Qnil);
1976 p = XVECTOR (address);
1977 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
1978 for (i = 0; i < len; i++)
1979 p->contents[i] = make_number (ntohs (ip6[i]));
1980 return address;
1982 #endif
1983 #ifdef HAVE_LOCAL_SOCKETS
1984 case AF_LOCAL:
1986 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
1987 for (i = 0; i < sizeof (sockun->sun_path); i++)
1988 if (sockun->sun_path[i] == 0)
1989 break;
1990 return make_unibyte_string (sockun->sun_path, i);
1992 #endif
1993 default:
1994 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
1995 address = Fcons (make_number (sa->sa_family),
1996 Fmake_vector (make_number (len), Qnil));
1997 p = XVECTOR (XCDR (address));
1998 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
1999 break;
2002 i = 0;
2003 while (i < len)
2004 p->contents[i++] = make_number (*cp++);
2006 return address;
2010 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2012 static int
2013 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2015 register struct Lisp_Vector *p;
2017 if (VECTORP (address))
2019 p = XVECTOR (address);
2020 if (p->header.size == 5)
2022 *familyp = AF_INET;
2023 return sizeof (struct sockaddr_in);
2025 #ifdef AF_INET6
2026 else if (p->header.size == 9)
2028 *familyp = AF_INET6;
2029 return sizeof (struct sockaddr_in6);
2031 #endif
2033 #ifdef HAVE_LOCAL_SOCKETS
2034 else if (STRINGP (address))
2036 *familyp = AF_LOCAL;
2037 return sizeof (struct sockaddr_un);
2039 #endif
2040 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2041 && VECTORP (XCDR (address)))
2043 struct sockaddr *sa;
2044 *familyp = XINT (XCAR (address));
2045 p = XVECTOR (XCDR (address));
2046 return p->header.size + sizeof (sa->sa_family);
2048 return 0;
2051 /* Convert an address object (vector or string) to an internal sockaddr.
2053 The address format has been basically validated by
2054 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2055 it could have come from user data. So if FAMILY is not valid,
2056 we return after zeroing *SA. */
2058 static void
2059 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2061 register struct Lisp_Vector *p;
2062 register unsigned char *cp = NULL;
2063 register int i;
2064 EMACS_INT hostport;
2066 memset (sa, 0, len);
2068 if (VECTORP (address))
2070 p = XVECTOR (address);
2071 if (family == AF_INET)
2073 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2074 len = sizeof (sin->sin_addr) + 1;
2075 hostport = XINT (p->contents[--len]);
2076 sin->sin_port = htons (hostport);
2077 cp = (unsigned char *)&sin->sin_addr;
2078 sa->sa_family = family;
2080 #ifdef AF_INET6
2081 else if (family == AF_INET6)
2083 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2084 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2085 len = sizeof (sin6->sin6_addr) + 1;
2086 hostport = XINT (p->contents[--len]);
2087 sin6->sin6_port = htons (hostport);
2088 for (i = 0; i < len; i++)
2089 if (INTEGERP (p->contents[i]))
2091 int j = XFASTINT (p->contents[i]) & 0xffff;
2092 ip6[i] = ntohs (j);
2094 sa->sa_family = family;
2095 return;
2097 #endif
2098 else
2099 return;
2101 else if (STRINGP (address))
2103 #ifdef HAVE_LOCAL_SOCKETS
2104 if (family == AF_LOCAL)
2106 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2107 cp = SDATA (address);
2108 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2109 sockun->sun_path[i] = *cp++;
2110 sa->sa_family = family;
2112 #endif
2113 return;
2115 else
2117 p = XVECTOR (XCDR (address));
2118 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2121 for (i = 0; i < len; i++)
2122 if (INTEGERP (p->contents[i]))
2123 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2126 #ifdef DATAGRAM_SOCKETS
2127 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2128 1, 1, 0,
2129 doc: /* Get the current datagram address associated with PROCESS. */)
2130 (Lisp_Object process)
2132 int channel;
2134 CHECK_PROCESS (process);
2136 if (!DATAGRAM_CONN_P (process))
2137 return Qnil;
2139 channel = XPROCESS (process)->infd;
2140 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2141 datagram_address[channel].len);
2144 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2145 2, 2, 0,
2146 doc: /* Set the datagram address for PROCESS to ADDRESS.
2147 Returns nil upon error setting address, ADDRESS otherwise. */)
2148 (Lisp_Object process, Lisp_Object address)
2150 int channel;
2151 int family, len;
2153 CHECK_PROCESS (process);
2155 if (!DATAGRAM_CONN_P (process))
2156 return Qnil;
2158 channel = XPROCESS (process)->infd;
2160 len = get_lisp_to_sockaddr_size (address, &family);
2161 if (datagram_address[channel].len != len)
2162 return Qnil;
2163 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2164 return address;
2166 #endif
2169 static const struct socket_options {
2170 /* The name of this option. Should be lowercase version of option
2171 name without SO_ prefix. */
2172 const char *name;
2173 /* Option level SOL_... */
2174 int optlevel;
2175 /* Option number SO_... */
2176 int optnum;
2177 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2178 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2179 } socket_options[] =
2181 #ifdef SO_BINDTODEVICE
2182 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2183 #endif
2184 #ifdef SO_BROADCAST
2185 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2186 #endif
2187 #ifdef SO_DONTROUTE
2188 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2189 #endif
2190 #ifdef SO_KEEPALIVE
2191 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2192 #endif
2193 #ifdef SO_LINGER
2194 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2195 #endif
2196 #ifdef SO_OOBINLINE
2197 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2198 #endif
2199 #ifdef SO_PRIORITY
2200 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2201 #endif
2202 #ifdef SO_REUSEADDR
2203 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2204 #endif
2205 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2208 /* Set option OPT to value VAL on socket S.
2210 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2211 Signals an error if setting a known option fails.
2214 static int
2215 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2217 char *name;
2218 const struct socket_options *sopt;
2219 int ret = 0;
2221 CHECK_SYMBOL (opt);
2223 name = SSDATA (SYMBOL_NAME (opt));
2224 for (sopt = socket_options; sopt->name; sopt++)
2225 if (strcmp (name, sopt->name) == 0)
2226 break;
2228 switch (sopt->opttype)
2230 case SOPT_BOOL:
2232 int optval;
2233 optval = NILP (val) ? 0 : 1;
2234 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2235 &optval, sizeof (optval));
2236 break;
2239 case SOPT_INT:
2241 int optval;
2242 if (TYPE_RANGED_INTEGERP (int, val))
2243 optval = XINT (val);
2244 else
2245 error ("Bad option value for %s", name);
2246 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2247 &optval, sizeof (optval));
2248 break;
2251 #ifdef SO_BINDTODEVICE
2252 case SOPT_IFNAME:
2254 char devname[IFNAMSIZ+1];
2256 /* This is broken, at least in the Linux 2.4 kernel.
2257 To unbind, the arg must be a zero integer, not the empty string.
2258 This should work on all systems. KFS. 2003-09-23. */
2259 memset (devname, 0, sizeof devname);
2260 if (STRINGP (val))
2262 char *arg = SSDATA (val);
2263 int len = min (strlen (arg), IFNAMSIZ);
2264 memcpy (devname, arg, len);
2266 else if (!NILP (val))
2267 error ("Bad option value for %s", name);
2268 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2269 devname, IFNAMSIZ);
2270 break;
2272 #endif
2274 #ifdef SO_LINGER
2275 case SOPT_LINGER:
2277 struct linger linger;
2279 linger.l_onoff = 1;
2280 linger.l_linger = 0;
2281 if (TYPE_RANGED_INTEGERP (int, val))
2282 linger.l_linger = XINT (val);
2283 else
2284 linger.l_onoff = NILP (val) ? 0 : 1;
2285 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2286 &linger, sizeof (linger));
2287 break;
2289 #endif
2291 default:
2292 return 0;
2295 if (ret < 0)
2296 report_file_error ("Cannot set network option",
2297 Fcons (opt, Fcons (val, Qnil)));
2298 return (1 << sopt->optbit);
2302 DEFUN ("set-network-process-option",
2303 Fset_network_process_option, Sset_network_process_option,
2304 3, 4, 0,
2305 doc: /* For network process PROCESS set option OPTION to value VALUE.
2306 See `make-network-process' for a list of options and values.
2307 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2308 OPTION is not a supported option, return nil instead; otherwise return t. */)
2309 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2311 int s;
2312 struct Lisp_Process *p;
2314 CHECK_PROCESS (process);
2315 p = XPROCESS (process);
2316 if (!NETCONN1_P (p))
2317 error ("Process is not a network process");
2319 s = p->infd;
2320 if (s < 0)
2321 error ("Process is not running");
2323 if (set_socket_option (s, option, value))
2325 pset_childp (p, Fplist_put (p->childp, option, value));
2326 return Qt;
2329 if (NILP (no_error))
2330 error ("Unknown or unsupported option");
2332 return Qnil;
2336 DEFUN ("serial-process-configure",
2337 Fserial_process_configure,
2338 Sserial_process_configure,
2339 0, MANY, 0,
2340 doc: /* Configure speed, bytesize, etc. of a serial process.
2342 Arguments are specified as keyword/argument pairs. Attributes that
2343 are not given are re-initialized from the process's current
2344 configuration (available via the function `process-contact') or set to
2345 reasonable default values. The following arguments are defined:
2347 :process PROCESS
2348 :name NAME
2349 :buffer BUFFER
2350 :port PORT
2351 -- Any of these arguments can be given to identify the process that is
2352 to be configured. If none of these arguments is given, the current
2353 buffer's process is used.
2355 :speed SPEED -- SPEED is the speed of the serial port in bits per
2356 second, also called baud rate. Any value can be given for SPEED, but
2357 most serial ports work only at a few defined values between 1200 and
2358 115200, with 9600 being the most common value. If SPEED is nil, the
2359 serial port is not configured any further, i.e., all other arguments
2360 are ignored. This may be useful for special serial ports such as
2361 Bluetooth-to-serial converters which can only be configured through AT
2362 commands. A value of nil for SPEED can be used only when passed
2363 through `make-serial-process' or `serial-term'.
2365 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2366 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2368 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2369 `odd' (use odd parity), or the symbol `even' (use even parity). If
2370 PARITY is not given, no parity is used.
2372 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2373 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2374 is not given or nil, 1 stopbit is used.
2376 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2377 flowcontrol to be used, which is either nil (don't use flowcontrol),
2378 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2379 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2380 flowcontrol is used.
2382 `serial-process-configure' is called by `make-serial-process' for the
2383 initial configuration of the serial port.
2385 Examples:
2387 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2389 \(serial-process-configure
2390 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2392 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2394 usage: (serial-process-configure &rest ARGS) */)
2395 (ptrdiff_t nargs, Lisp_Object *args)
2397 struct Lisp_Process *p;
2398 Lisp_Object contact = Qnil;
2399 Lisp_Object proc = Qnil;
2400 struct gcpro gcpro1;
2402 contact = Flist (nargs, args);
2403 GCPRO1 (contact);
2405 proc = Fplist_get (contact, QCprocess);
2406 if (NILP (proc))
2407 proc = Fplist_get (contact, QCname);
2408 if (NILP (proc))
2409 proc = Fplist_get (contact, QCbuffer);
2410 if (NILP (proc))
2411 proc = Fplist_get (contact, QCport);
2412 proc = get_process (proc);
2413 p = XPROCESS (proc);
2414 if (!EQ (p->type, Qserial))
2415 error ("Not a serial process");
2417 if (NILP (Fplist_get (p->childp, QCspeed)))
2419 UNGCPRO;
2420 return Qnil;
2423 serial_configure (p, contact);
2425 UNGCPRO;
2426 return Qnil;
2429 /* Used by make-serial-process to recover from errors. */
2430 static Lisp_Object
2431 make_serial_process_unwind (Lisp_Object proc)
2433 if (!PROCESSP (proc))
2434 emacs_abort ();
2435 remove_process (proc);
2436 return Qnil;
2439 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2440 0, MANY, 0,
2441 doc: /* Create and return a serial port process.
2443 In Emacs, serial port connections are represented by process objects,
2444 so input and output work as for subprocesses, and `delete-process'
2445 closes a serial port connection. However, a serial process has no
2446 process id, it cannot be signaled, and the status codes are different
2447 from normal processes.
2449 `make-serial-process' creates a process and a buffer, on which you
2450 probably want to use `process-send-string'. Try \\[serial-term] for
2451 an interactive terminal. See below for examples.
2453 Arguments are specified as keyword/argument pairs. The following
2454 arguments are defined:
2456 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2457 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2458 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2459 the backslashes in strings).
2461 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2462 which this function calls.
2464 :name NAME -- NAME is the name of the process. If NAME is not given,
2465 the value of PORT is used.
2467 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2468 with the process. Process output goes at the end of that buffer,
2469 unless you specify an output stream or filter function to handle the
2470 output. If BUFFER is not given, the value of NAME is used.
2472 :coding CODING -- If CODING is a symbol, it specifies the coding
2473 system used for both reading and writing for this process. If CODING
2474 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2475 ENCODING is used for writing.
2477 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2478 the process is running. If BOOL is not given, query before exiting.
2480 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2481 In the stopped state, a serial process does not accept incoming data,
2482 but you can send outgoing data. The stopped state is cleared by
2483 `continue-process' and set by `stop-process'.
2485 :filter FILTER -- Install FILTER as the process filter.
2487 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2489 :plist PLIST -- Install PLIST as the initial plist of the process.
2491 :bytesize
2492 :parity
2493 :stopbits
2494 :flowcontrol
2495 -- This function calls `serial-process-configure' to handle these
2496 arguments.
2498 The original argument list, possibly modified by later configuration,
2499 is available via the function `process-contact'.
2501 Examples:
2503 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2505 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2507 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2509 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2511 usage: (make-serial-process &rest ARGS) */)
2512 (ptrdiff_t nargs, Lisp_Object *args)
2514 int fd = -1;
2515 Lisp_Object proc, contact, port;
2516 struct Lisp_Process *p;
2517 struct gcpro gcpro1;
2518 Lisp_Object name, buffer;
2519 Lisp_Object tem, val;
2520 ptrdiff_t specpdl_count = -1;
2522 if (nargs == 0)
2523 return Qnil;
2525 contact = Flist (nargs, args);
2526 GCPRO1 (contact);
2528 port = Fplist_get (contact, QCport);
2529 if (NILP (port))
2530 error ("No port specified");
2531 CHECK_STRING (port);
2533 if (NILP (Fplist_member (contact, QCspeed)))
2534 error (":speed not specified");
2535 if (!NILP (Fplist_get (contact, QCspeed)))
2536 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2538 name = Fplist_get (contact, QCname);
2539 if (NILP (name))
2540 name = port;
2541 CHECK_STRING (name);
2542 proc = make_process (name);
2543 specpdl_count = SPECPDL_INDEX ();
2544 record_unwind_protect (make_serial_process_unwind, proc);
2545 p = XPROCESS (proc);
2547 fd = serial_open (SSDATA (port));
2548 p->infd = fd;
2549 p->outfd = fd;
2550 if (fd > max_process_desc)
2551 max_process_desc = fd;
2552 chan_process[fd] = proc;
2554 buffer = Fplist_get (contact, QCbuffer);
2555 if (NILP (buffer))
2556 buffer = name;
2557 buffer = Fget_buffer_create (buffer);
2558 pset_buffer (p, buffer);
2560 pset_childp (p, contact);
2561 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2562 pset_type (p, Qserial);
2563 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2564 pset_filter (p, Fplist_get (contact, QCfilter));
2565 pset_log (p, Qnil);
2566 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2567 p->kill_without_query = 1;
2568 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2569 pset_command (p, Qt);
2570 p->pty_flag = 0;
2572 if (!EQ (p->command, Qt))
2574 FD_SET (fd, &input_wait_mask);
2575 FD_SET (fd, &non_keyboard_wait_mask);
2578 if (BUFFERP (buffer))
2580 set_marker_both (p->mark, buffer,
2581 BUF_ZV (XBUFFER (buffer)),
2582 BUF_ZV_BYTE (XBUFFER (buffer)));
2585 tem = Fplist_member (contact, QCcoding);
2586 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2587 tem = Qnil;
2589 val = Qnil;
2590 if (!NILP (tem))
2592 val = XCAR (XCDR (tem));
2593 if (CONSP (val))
2594 val = XCAR (val);
2596 else if (!NILP (Vcoding_system_for_read))
2597 val = Vcoding_system_for_read;
2598 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2599 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2600 val = Qnil;
2601 pset_decode_coding_system (p, val);
2603 val = Qnil;
2604 if (!NILP (tem))
2606 val = XCAR (XCDR (tem));
2607 if (CONSP (val))
2608 val = XCDR (val);
2610 else if (!NILP (Vcoding_system_for_write))
2611 val = Vcoding_system_for_write;
2612 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2613 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2614 val = Qnil;
2615 pset_encode_coding_system (p, val);
2617 setup_process_coding_systems (proc);
2618 pset_decoding_buf (p, empty_unibyte_string);
2619 p->decoding_carryover = 0;
2620 pset_encoding_buf (p, empty_unibyte_string);
2621 p->inherit_coding_system_flag
2622 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2624 Fserial_process_configure (nargs, args);
2626 specpdl_ptr = specpdl + specpdl_count;
2628 UNGCPRO;
2629 return proc;
2632 /* Create a network stream/datagram client/server process. Treated
2633 exactly like a normal process when reading and writing. Primary
2634 differences are in status display and process deletion. A network
2635 connection has no PID; you cannot signal it. All you can do is
2636 stop/continue it and deactivate/close it via delete-process */
2638 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2639 0, MANY, 0,
2640 doc: /* Create and return a network server or client process.
2642 In Emacs, network connections are represented by process objects, so
2643 input and output work as for subprocesses and `delete-process' closes
2644 a network connection. However, a network process has no process id,
2645 it cannot be signaled, and the status codes are different from normal
2646 processes.
2648 Arguments are specified as keyword/argument pairs. The following
2649 arguments are defined:
2651 :name NAME -- NAME is name for process. It is modified if necessary
2652 to make it unique.
2654 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2655 with the process. Process output goes at end of that buffer, unless
2656 you specify an output stream or filter function to handle the output.
2657 BUFFER may be also nil, meaning that this process is not associated
2658 with any buffer.
2660 :host HOST -- HOST is name of the host to connect to, or its IP
2661 address. The symbol `local' specifies the local host. If specified
2662 for a server process, it must be a valid name or address for the local
2663 host, and only clients connecting to that address will be accepted.
2665 :service SERVICE -- SERVICE is name of the service desired, or an
2666 integer specifying a port number to connect to. If SERVICE is t,
2667 a random port number is selected for the server. (If Emacs was
2668 compiled with getaddrinfo, a port number can also be specified as a
2669 string, e.g. "80", as well as an integer. This is not portable.)
2671 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2672 stream type connection, `datagram' creates a datagram type connection,
2673 `seqpacket' creates a reliable datagram connection.
2675 :family FAMILY -- FAMILY is the address (and protocol) family for the
2676 service specified by HOST and SERVICE. The default (nil) is to use
2677 whatever address family (IPv4 or IPv6) that is defined for the host
2678 and port number specified by HOST and SERVICE. Other address families
2679 supported are:
2680 local -- for a local (i.e. UNIX) address specified by SERVICE.
2681 ipv4 -- use IPv4 address family only.
2682 ipv6 -- use IPv6 address family only.
2684 :local ADDRESS -- ADDRESS is the local address used for the connection.
2685 This parameter is ignored when opening a client process. When specified
2686 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2688 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2689 connection. This parameter is ignored when opening a stream server
2690 process. For a datagram server process, it specifies the initial
2691 setting of the remote datagram address. When specified for a client
2692 process, the FAMILY, HOST, and SERVICE args are ignored.
2694 The format of ADDRESS depends on the address family:
2695 - An IPv4 address is represented as an vector of integers [A B C D P]
2696 corresponding to numeric IP address A.B.C.D and port number P.
2697 - A local address is represented as a string with the address in the
2698 local address space.
2699 - An "unsupported family" address is represented by a cons (F . AV)
2700 where F is the family number and AV is a vector containing the socket
2701 address data with one element per address data byte. Do not rely on
2702 this format in portable code, as it may depend on implementation
2703 defined constants, data sizes, and data structure alignment.
2705 :coding CODING -- If CODING is a symbol, it specifies the coding
2706 system used for both reading and writing for this process. If CODING
2707 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2708 ENCODING is used for writing.
2710 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2711 return without waiting for the connection to complete; instead, the
2712 sentinel function will be called with second arg matching "open" (if
2713 successful) or "failed" when the connect completes. Default is to use
2714 a blocking connect (i.e. wait) for stream type connections.
2716 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2717 running when Emacs is exited.
2719 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2720 In the stopped state, a server process does not accept new
2721 connections, and a client process does not handle incoming traffic.
2722 The stopped state is cleared by `continue-process' and set by
2723 `stop-process'.
2725 :filter FILTER -- Install FILTER as the process filter.
2727 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2728 process filter are multibyte, otherwise they are unibyte.
2729 If this keyword is not specified, the strings are multibyte if
2730 the default value of `enable-multibyte-characters' is non-nil.
2732 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2734 :log LOG -- Install LOG as the server process log function. This
2735 function is called when the server accepts a network connection from a
2736 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2737 is the server process, CLIENT is the new process for the connection,
2738 and MESSAGE is a string.
2740 :plist PLIST -- Install PLIST as the new process' initial plist.
2742 :server QLEN -- if QLEN is non-nil, create a server process for the
2743 specified FAMILY, SERVICE, and connection type (stream or datagram).
2744 If QLEN is an integer, it is used as the max. length of the server's
2745 pending connection queue (also known as the backlog); the default
2746 queue length is 5. Default is to create a client process.
2748 The following network options can be specified for this connection:
2750 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2751 :dontroute BOOL -- Only send to directly connected hosts.
2752 :keepalive BOOL -- Send keep-alive messages on network stream.
2753 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2754 :oobinline BOOL -- Place out-of-band data in receive data stream.
2755 :priority INT -- Set protocol defined priority for sent packets.
2756 :reuseaddr BOOL -- Allow reusing a recently used local address
2757 (this is allowed by default for a server process).
2758 :bindtodevice NAME -- bind to interface NAME. Using this may require
2759 special privileges on some systems.
2761 Consult the relevant system programmer's manual pages for more
2762 information on using these options.
2765 A server process will listen for and accept connections from clients.
2766 When a client connection is accepted, a new network process is created
2767 for the connection with the following parameters:
2769 - The client's process name is constructed by concatenating the server
2770 process' NAME and a client identification string.
2771 - If the FILTER argument is non-nil, the client process will not get a
2772 separate process buffer; otherwise, the client's process buffer is a newly
2773 created buffer named after the server process' BUFFER name or process
2774 NAME concatenated with the client identification string.
2775 - The connection type and the process filter and sentinel parameters are
2776 inherited from the server process' TYPE, FILTER and SENTINEL.
2777 - The client process' contact info is set according to the client's
2778 addressing information (typically an IP address and a port number).
2779 - The client process' plist is initialized from the server's plist.
2781 Notice that the FILTER and SENTINEL args are never used directly by
2782 the server process. Also, the BUFFER argument is not used directly by
2783 the server process, but via the optional :log function, accepted (and
2784 failed) connections may be logged in the server process' buffer.
2786 The original argument list, modified with the actual connection
2787 information, is available via the `process-contact' function.
2789 usage: (make-network-process &rest ARGS) */)
2790 (ptrdiff_t nargs, Lisp_Object *args)
2792 Lisp_Object proc;
2793 Lisp_Object contact;
2794 struct Lisp_Process *p;
2795 #ifdef HAVE_GETADDRINFO
2796 struct addrinfo ai, *res, *lres;
2797 struct addrinfo hints;
2798 const char *portstring;
2799 char portbuf[128];
2800 #else /* HAVE_GETADDRINFO */
2801 struct _emacs_addrinfo
2803 int ai_family;
2804 int ai_socktype;
2805 int ai_protocol;
2806 int ai_addrlen;
2807 struct sockaddr *ai_addr;
2808 struct _emacs_addrinfo *ai_next;
2809 } ai, *res, *lres;
2810 #endif /* HAVE_GETADDRINFO */
2811 struct sockaddr_in address_in;
2812 #ifdef HAVE_LOCAL_SOCKETS
2813 struct sockaddr_un address_un;
2814 #endif
2815 int port;
2816 int ret = 0;
2817 int xerrno = 0;
2818 int s = -1, outch, inch;
2819 struct gcpro gcpro1;
2820 ptrdiff_t count = SPECPDL_INDEX ();
2821 ptrdiff_t count1;
2822 Lisp_Object QCaddress; /* one of QClocal or QCremote */
2823 Lisp_Object tem;
2824 Lisp_Object name, buffer, host, service, address;
2825 Lisp_Object filter, sentinel;
2826 int is_non_blocking_client = 0;
2827 int is_server = 0, backlog = 5;
2828 int socktype;
2829 int family = -1;
2831 if (nargs == 0)
2832 return Qnil;
2834 /* Save arguments for process-contact and clone-process. */
2835 contact = Flist (nargs, args);
2836 GCPRO1 (contact);
2838 #ifdef WINDOWSNT
2839 /* Ensure socket support is loaded if available. */
2840 init_winsock (TRUE);
2841 #endif
2843 /* :type TYPE (nil: stream, datagram */
2844 tem = Fplist_get (contact, QCtype);
2845 if (NILP (tem))
2846 socktype = SOCK_STREAM;
2847 #ifdef DATAGRAM_SOCKETS
2848 else if (EQ (tem, Qdatagram))
2849 socktype = SOCK_DGRAM;
2850 #endif
2851 #ifdef HAVE_SEQPACKET
2852 else if (EQ (tem, Qseqpacket))
2853 socktype = SOCK_SEQPACKET;
2854 #endif
2855 else
2856 error ("Unsupported connection type");
2858 /* :server BOOL */
2859 tem = Fplist_get (contact, QCserver);
2860 if (!NILP (tem))
2862 /* Don't support network sockets when non-blocking mode is
2863 not available, since a blocked Emacs is not useful. */
2864 is_server = 1;
2865 if (TYPE_RANGED_INTEGERP (int, tem))
2866 backlog = XINT (tem);
2869 /* Make QCaddress an alias for :local (server) or :remote (client). */
2870 QCaddress = is_server ? QClocal : QCremote;
2872 /* :nowait BOOL */
2873 if (!is_server && socktype != SOCK_DGRAM
2874 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2876 #ifndef NON_BLOCKING_CONNECT
2877 error ("Non-blocking connect not supported");
2878 #else
2879 is_non_blocking_client = 1;
2880 #endif
2883 name = Fplist_get (contact, QCname);
2884 buffer = Fplist_get (contact, QCbuffer);
2885 filter = Fplist_get (contact, QCfilter);
2886 sentinel = Fplist_get (contact, QCsentinel);
2888 CHECK_STRING (name);
2890 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2891 ai.ai_socktype = socktype;
2892 ai.ai_protocol = 0;
2893 ai.ai_next = NULL;
2894 res = &ai;
2896 /* :local ADDRESS or :remote ADDRESS */
2897 address = Fplist_get (contact, QCaddress);
2898 if (!NILP (address))
2900 host = service = Qnil;
2902 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2903 error ("Malformed :address");
2904 ai.ai_family = family;
2905 ai.ai_addr = alloca (ai.ai_addrlen);
2906 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
2907 goto open_socket;
2910 /* :family FAMILY -- nil (for Inet), local, or integer. */
2911 tem = Fplist_get (contact, QCfamily);
2912 if (NILP (tem))
2914 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
2915 family = AF_UNSPEC;
2916 #else
2917 family = AF_INET;
2918 #endif
2920 #ifdef HAVE_LOCAL_SOCKETS
2921 else if (EQ (tem, Qlocal))
2922 family = AF_LOCAL;
2923 #endif
2924 #ifdef AF_INET6
2925 else if (EQ (tem, Qipv6))
2926 family = AF_INET6;
2927 #endif
2928 else if (EQ (tem, Qipv4))
2929 family = AF_INET;
2930 else if (TYPE_RANGED_INTEGERP (int, tem))
2931 family = XINT (tem);
2932 else
2933 error ("Unknown address family");
2935 ai.ai_family = family;
2937 /* :service SERVICE -- string, integer (port number), or t (random port). */
2938 service = Fplist_get (contact, QCservice);
2940 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2941 host = Fplist_get (contact, QChost);
2942 if (!NILP (host))
2944 if (EQ (host, Qlocal))
2945 /* Depending on setup, "localhost" may map to different IPv4 and/or
2946 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
2947 host = build_string ("127.0.0.1");
2948 CHECK_STRING (host);
2951 #ifdef HAVE_LOCAL_SOCKETS
2952 if (family == AF_LOCAL)
2954 if (!NILP (host))
2956 message (":family local ignores the :host \"%s\" property",
2957 SDATA (host));
2958 contact = Fplist_put (contact, QChost, Qnil);
2959 host = Qnil;
2961 CHECK_STRING (service);
2962 memset (&address_un, 0, sizeof address_un);
2963 address_un.sun_family = AF_LOCAL;
2964 if (sizeof address_un.sun_path <= SBYTES (service))
2965 error ("Service name too long");
2966 strcpy (address_un.sun_path, SSDATA (service));
2967 ai.ai_addr = (struct sockaddr *) &address_un;
2968 ai.ai_addrlen = sizeof address_un;
2969 goto open_socket;
2971 #endif
2973 /* Slow down polling to every ten seconds.
2974 Some kernels have a bug which causes retrying connect to fail
2975 after a connect. Polling can interfere with gethostbyname too. */
2976 #ifdef POLL_FOR_INPUT
2977 if (socktype != SOCK_DGRAM)
2979 record_unwind_protect (unwind_stop_other_atimers, Qnil);
2980 bind_polling_period (10);
2982 #endif
2984 #ifdef HAVE_GETADDRINFO
2985 /* If we have a host, use getaddrinfo to resolve both host and service.
2986 Otherwise, use getservbyname to lookup the service. */
2987 if (!NILP (host))
2990 /* SERVICE can either be a string or int.
2991 Convert to a C string for later use by getaddrinfo. */
2992 if (EQ (service, Qt))
2993 portstring = "0";
2994 else if (INTEGERP (service))
2996 sprintf (portbuf, "%"pI"d", XINT (service));
2997 portstring = portbuf;
2999 else
3001 CHECK_STRING (service);
3002 portstring = SSDATA (service);
3005 immediate_quit = 1;
3006 QUIT;
3007 memset (&hints, 0, sizeof (hints));
3008 hints.ai_flags = 0;
3009 hints.ai_family = family;
3010 hints.ai_socktype = socktype;
3011 hints.ai_protocol = 0;
3013 #ifdef HAVE_RES_INIT
3014 res_init ();
3015 #endif
3017 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3018 if (ret)
3019 #ifdef HAVE_GAI_STRERROR
3020 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3021 #else
3022 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3023 #endif
3024 immediate_quit = 0;
3026 goto open_socket;
3028 #endif /* HAVE_GETADDRINFO */
3030 /* We end up here if getaddrinfo is not defined, or in case no hostname
3031 has been specified (e.g. for a local server process). */
3033 if (EQ (service, Qt))
3034 port = 0;
3035 else if (INTEGERP (service))
3036 port = htons ((unsigned short) XINT (service));
3037 else
3039 struct servent *svc_info;
3040 CHECK_STRING (service);
3041 svc_info = getservbyname (SSDATA (service),
3042 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3043 if (svc_info == 0)
3044 error ("Unknown service: %s", SDATA (service));
3045 port = svc_info->s_port;
3048 memset (&address_in, 0, sizeof address_in);
3049 address_in.sin_family = family;
3050 address_in.sin_addr.s_addr = INADDR_ANY;
3051 address_in.sin_port = port;
3053 #ifndef HAVE_GETADDRINFO
3054 if (!NILP (host))
3056 struct hostent *host_info_ptr;
3058 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3059 as it may `hang' Emacs for a very long time. */
3060 immediate_quit = 1;
3061 QUIT;
3063 #ifdef HAVE_RES_INIT
3064 res_init ();
3065 #endif
3067 host_info_ptr = gethostbyname (SDATA (host));
3068 immediate_quit = 0;
3070 if (host_info_ptr)
3072 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3073 host_info_ptr->h_length);
3074 family = host_info_ptr->h_addrtype;
3075 address_in.sin_family = family;
3077 else
3078 /* Attempt to interpret host as numeric inet address */
3080 unsigned long numeric_addr;
3081 numeric_addr = inet_addr (SSDATA (host));
3082 if (numeric_addr == -1)
3083 error ("Unknown host \"%s\"", SDATA (host));
3085 memcpy (&address_in.sin_addr, &numeric_addr,
3086 sizeof (address_in.sin_addr));
3090 #endif /* not HAVE_GETADDRINFO */
3092 ai.ai_family = family;
3093 ai.ai_addr = (struct sockaddr *) &address_in;
3094 ai.ai_addrlen = sizeof address_in;
3096 open_socket:
3098 /* Do this in case we never enter the for-loop below. */
3099 count1 = SPECPDL_INDEX ();
3100 s = -1;
3102 for (lres = res; lres; lres = lres->ai_next)
3104 ptrdiff_t optn;
3105 int optbits;
3107 #ifdef WINDOWSNT
3108 retry_connect:
3109 #endif
3111 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3112 if (s < 0)
3114 xerrno = errno;
3115 continue;
3118 #ifdef DATAGRAM_SOCKETS
3119 if (!is_server && socktype == SOCK_DGRAM)
3120 break;
3121 #endif /* DATAGRAM_SOCKETS */
3123 #ifdef NON_BLOCKING_CONNECT
3124 if (is_non_blocking_client)
3126 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3127 if (ret < 0)
3129 xerrno = errno;
3130 emacs_close (s);
3131 s = -1;
3132 continue;
3135 #endif
3137 /* Make us close S if quit. */
3138 record_unwind_protect (close_file_unwind, make_number (s));
3140 /* Parse network options in the arg list.
3141 We simply ignore anything which isn't a known option (including other keywords).
3142 An error is signaled if setting a known option fails. */
3143 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3144 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3146 if (is_server)
3148 /* Configure as a server socket. */
3150 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3151 explicit :reuseaddr key to override this. */
3152 #ifdef HAVE_LOCAL_SOCKETS
3153 if (family != AF_LOCAL)
3154 #endif
3155 if (!(optbits & (1 << OPIX_REUSEADDR)))
3157 int optval = 1;
3158 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3159 report_file_error ("Cannot set reuse option on server socket", Qnil);
3162 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3163 report_file_error ("Cannot bind server socket", Qnil);
3165 #ifdef HAVE_GETSOCKNAME
3166 if (EQ (service, Qt))
3168 struct sockaddr_in sa1;
3169 socklen_t len1 = sizeof (sa1);
3170 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3172 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3173 service = make_number (ntohs (sa1.sin_port));
3174 contact = Fplist_put (contact, QCservice, service);
3177 #endif
3179 if (socktype != SOCK_DGRAM && listen (s, backlog))
3180 report_file_error ("Cannot listen on server socket", Qnil);
3182 break;
3185 immediate_quit = 1;
3186 QUIT;
3188 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3189 xerrno = errno;
3191 if (ret == 0 || xerrno == EISCONN)
3193 /* The unwind-protect will be discarded afterwards.
3194 Likewise for immediate_quit. */
3195 break;
3198 #ifdef NON_BLOCKING_CONNECT
3199 #ifdef EINPROGRESS
3200 if (is_non_blocking_client && xerrno == EINPROGRESS)
3201 break;
3202 #else
3203 #ifdef EWOULDBLOCK
3204 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3205 break;
3206 #endif
3207 #endif
3208 #endif
3210 #ifndef WINDOWSNT
3211 if (xerrno == EINTR)
3213 /* Unlike most other syscalls connect() cannot be called
3214 again. (That would return EALREADY.) The proper way to
3215 wait for completion is pselect(). */
3216 int sc;
3217 socklen_t len;
3218 SELECT_TYPE fdset;
3219 retry_select:
3220 FD_ZERO (&fdset);
3221 FD_SET (s, &fdset);
3222 QUIT;
3223 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3224 if (sc == -1)
3226 if (errno == EINTR)
3227 goto retry_select;
3228 else
3229 report_file_error ("select failed", Qnil);
3231 eassert (sc > 0);
3233 len = sizeof xerrno;
3234 eassert (FD_ISSET (s, &fdset));
3235 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3236 report_file_error ("getsockopt failed", Qnil);
3237 if (xerrno)
3238 errno = xerrno, report_file_error ("error during connect", Qnil);
3239 else
3240 break;
3242 #endif /* !WINDOWSNT */
3244 immediate_quit = 0;
3246 /* Discard the unwind protect closing S. */
3247 specpdl_ptr = specpdl + count1;
3248 emacs_close (s);
3249 s = -1;
3251 #ifdef WINDOWSNT
3252 if (xerrno == EINTR)
3253 goto retry_connect;
3254 #endif
3257 if (s >= 0)
3259 #ifdef DATAGRAM_SOCKETS
3260 if (socktype == SOCK_DGRAM)
3262 if (datagram_address[s].sa)
3263 emacs_abort ();
3264 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3265 datagram_address[s].len = lres->ai_addrlen;
3266 if (is_server)
3268 Lisp_Object remote;
3269 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3270 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3272 int rfamily, rlen;
3273 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3274 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3275 conv_lisp_to_sockaddr (rfamily, remote,
3276 datagram_address[s].sa, rlen);
3279 else
3280 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3282 #endif
3283 contact = Fplist_put (contact, QCaddress,
3284 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3285 #ifdef HAVE_GETSOCKNAME
3286 if (!is_server)
3288 struct sockaddr_in sa1;
3289 socklen_t len1 = sizeof (sa1);
3290 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3291 contact = Fplist_put (contact, QClocal,
3292 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3294 #endif
3297 immediate_quit = 0;
3299 #ifdef HAVE_GETADDRINFO
3300 if (res != &ai)
3302 block_input ();
3303 freeaddrinfo (res);
3304 unblock_input ();
3306 #endif
3308 /* Discard the unwind protect for closing S, if any. */
3309 specpdl_ptr = specpdl + count1;
3311 /* Unwind bind_polling_period and request_sigio. */
3312 unbind_to (count, Qnil);
3314 if (s < 0)
3316 /* If non-blocking got this far - and failed - assume non-blocking is
3317 not supported after all. This is probably a wrong assumption, but
3318 the normal blocking calls to open-network-stream handles this error
3319 better. */
3320 if (is_non_blocking_client)
3321 return Qnil;
3323 errno = xerrno;
3324 if (is_server)
3325 report_file_error ("make server process failed", contact);
3326 else
3327 report_file_error ("make client process failed", contact);
3330 inch = s;
3331 outch = s;
3333 if (!NILP (buffer))
3334 buffer = Fget_buffer_create (buffer);
3335 proc = make_process (name);
3337 chan_process[inch] = proc;
3339 fcntl (inch, F_SETFL, O_NONBLOCK);
3341 p = XPROCESS (proc);
3343 pset_childp (p, contact);
3344 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3345 pset_type (p, Qnetwork);
3347 pset_buffer (p, buffer);
3348 pset_sentinel (p, sentinel);
3349 pset_filter (p, filter);
3350 pset_log (p, Fplist_get (contact, QClog));
3351 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3352 p->kill_without_query = 1;
3353 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3354 pset_command (p, Qt);
3355 p->pid = 0;
3356 p->infd = inch;
3357 p->outfd = outch;
3358 if (is_server && socktype != SOCK_DGRAM)
3359 pset_status (p, Qlisten);
3361 /* Make the process marker point into the process buffer (if any). */
3362 if (BUFFERP (buffer))
3363 set_marker_both (p->mark, buffer,
3364 BUF_ZV (XBUFFER (buffer)),
3365 BUF_ZV_BYTE (XBUFFER (buffer)));
3367 #ifdef NON_BLOCKING_CONNECT
3368 if (is_non_blocking_client)
3370 /* We may get here if connect did succeed immediately. However,
3371 in that case, we still need to signal this like a non-blocking
3372 connection. */
3373 pset_status (p, Qconnect);
3374 if (!FD_ISSET (inch, &connect_wait_mask))
3376 FD_SET (inch, &connect_wait_mask);
3377 FD_SET (inch, &write_mask);
3378 num_pending_connects++;
3381 else
3382 #endif
3383 /* A server may have a client filter setting of Qt, but it must
3384 still listen for incoming connects unless it is stopped. */
3385 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3386 || (EQ (p->status, Qlisten) && NILP (p->command)))
3388 FD_SET (inch, &input_wait_mask);
3389 FD_SET (inch, &non_keyboard_wait_mask);
3392 if (inch > max_process_desc)
3393 max_process_desc = inch;
3395 tem = Fplist_member (contact, QCcoding);
3396 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3397 tem = Qnil; /* No error message (too late!). */
3400 /* Setup coding systems for communicating with the network stream. */
3401 struct gcpro gcpro1;
3402 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3403 Lisp_Object coding_systems = Qt;
3404 Lisp_Object fargs[5], val;
3406 if (!NILP (tem))
3408 val = XCAR (XCDR (tem));
3409 if (CONSP (val))
3410 val = XCAR (val);
3412 else if (!NILP (Vcoding_system_for_read))
3413 val = Vcoding_system_for_read;
3414 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3415 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3416 /* We dare not decode end-of-line format by setting VAL to
3417 Qraw_text, because the existing Emacs Lisp libraries
3418 assume that they receive bare code including a sequence of
3419 CR LF. */
3420 val = Qnil;
3421 else
3423 if (NILP (host) || NILP (service))
3424 coding_systems = Qnil;
3425 else
3427 fargs[0] = Qopen_network_stream, fargs[1] = name,
3428 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3429 GCPRO1 (proc);
3430 coding_systems = Ffind_operation_coding_system (5, fargs);
3431 UNGCPRO;
3433 if (CONSP (coding_systems))
3434 val = XCAR (coding_systems);
3435 else if (CONSP (Vdefault_process_coding_system))
3436 val = XCAR (Vdefault_process_coding_system);
3437 else
3438 val = Qnil;
3440 pset_decode_coding_system (p, val);
3442 if (!NILP (tem))
3444 val = XCAR (XCDR (tem));
3445 if (CONSP (val))
3446 val = XCDR (val);
3448 else if (!NILP (Vcoding_system_for_write))
3449 val = Vcoding_system_for_write;
3450 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3451 val = Qnil;
3452 else
3454 if (EQ (coding_systems, Qt))
3456 if (NILP (host) || NILP (service))
3457 coding_systems = Qnil;
3458 else
3460 fargs[0] = Qopen_network_stream, fargs[1] = name,
3461 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3462 GCPRO1 (proc);
3463 coding_systems = Ffind_operation_coding_system (5, fargs);
3464 UNGCPRO;
3467 if (CONSP (coding_systems))
3468 val = XCDR (coding_systems);
3469 else if (CONSP (Vdefault_process_coding_system))
3470 val = XCDR (Vdefault_process_coding_system);
3471 else
3472 val = Qnil;
3474 pset_encode_coding_system (p, val);
3476 setup_process_coding_systems (proc);
3478 pset_decoding_buf (p, empty_unibyte_string);
3479 p->decoding_carryover = 0;
3480 pset_encoding_buf (p, empty_unibyte_string);
3482 p->inherit_coding_system_flag
3483 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3485 UNGCPRO;
3486 return proc;
3490 #if defined (HAVE_NET_IF_H)
3492 #ifdef SIOCGIFCONF
3493 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3494 doc: /* Return an alist of all network interfaces and their network address.
3495 Each element is a cons, the car of which is a string containing the
3496 interface name, and the cdr is the network address in internal
3497 format; see the description of ADDRESS in `make-network-process'. */)
3498 (void)
3500 struct ifconf ifconf;
3501 struct ifreq *ifreq;
3502 void *buf = NULL;
3503 ptrdiff_t buf_size = 512;
3504 int s, i;
3505 Lisp_Object res;
3507 s = socket (AF_INET, SOCK_STREAM, 0);
3508 if (s < 0)
3509 return Qnil;
3513 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3514 ifconf.ifc_buf = buf;
3515 ifconf.ifc_len = buf_size;
3516 if (ioctl (s, SIOCGIFCONF, &ifconf))
3518 close (s);
3519 xfree (buf);
3520 return Qnil;
3523 while (ifconf.ifc_len == buf_size);
3525 close (s);
3527 res = Qnil;
3528 ifreq = ifconf.ifc_req;
3529 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3531 struct ifreq *ifq = ifreq;
3532 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3533 #define SIZEOF_IFREQ(sif) \
3534 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3535 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3537 int len = SIZEOF_IFREQ (ifq);
3538 #else
3539 int len = sizeof (*ifreq);
3540 #endif
3541 char namebuf[sizeof (ifq->ifr_name) + 1];
3542 i += len;
3543 ifreq = (struct ifreq *) ((char *) ifreq + len);
3545 if (ifq->ifr_addr.sa_family != AF_INET)
3546 continue;
3548 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3549 namebuf[sizeof (ifq->ifr_name)] = 0;
3550 res = Fcons (Fcons (build_string (namebuf),
3551 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3552 sizeof (struct sockaddr))),
3553 res);
3556 xfree (buf);
3557 return res;
3559 #endif /* SIOCGIFCONF */
3561 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3563 struct ifflag_def {
3564 int flag_bit;
3565 const char *flag_sym;
3568 static const struct ifflag_def ifflag_table[] = {
3569 #ifdef IFF_UP
3570 { IFF_UP, "up" },
3571 #endif
3572 #ifdef IFF_BROADCAST
3573 { IFF_BROADCAST, "broadcast" },
3574 #endif
3575 #ifdef IFF_DEBUG
3576 { IFF_DEBUG, "debug" },
3577 #endif
3578 #ifdef IFF_LOOPBACK
3579 { IFF_LOOPBACK, "loopback" },
3580 #endif
3581 #ifdef IFF_POINTOPOINT
3582 { IFF_POINTOPOINT, "pointopoint" },
3583 #endif
3584 #ifdef IFF_RUNNING
3585 { IFF_RUNNING, "running" },
3586 #endif
3587 #ifdef IFF_NOARP
3588 { IFF_NOARP, "noarp" },
3589 #endif
3590 #ifdef IFF_PROMISC
3591 { IFF_PROMISC, "promisc" },
3592 #endif
3593 #ifdef IFF_NOTRAILERS
3594 #ifdef NS_IMPL_COCOA
3595 /* Really means smart, notrailers is obsolete */
3596 { IFF_NOTRAILERS, "smart" },
3597 #else
3598 { IFF_NOTRAILERS, "notrailers" },
3599 #endif
3600 #endif
3601 #ifdef IFF_ALLMULTI
3602 { IFF_ALLMULTI, "allmulti" },
3603 #endif
3604 #ifdef IFF_MASTER
3605 { IFF_MASTER, "master" },
3606 #endif
3607 #ifdef IFF_SLAVE
3608 { IFF_SLAVE, "slave" },
3609 #endif
3610 #ifdef IFF_MULTICAST
3611 { IFF_MULTICAST, "multicast" },
3612 #endif
3613 #ifdef IFF_PORTSEL
3614 { IFF_PORTSEL, "portsel" },
3615 #endif
3616 #ifdef IFF_AUTOMEDIA
3617 { IFF_AUTOMEDIA, "automedia" },
3618 #endif
3619 #ifdef IFF_DYNAMIC
3620 { IFF_DYNAMIC, "dynamic" },
3621 #endif
3622 #ifdef IFF_OACTIVE
3623 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3624 #endif
3625 #ifdef IFF_SIMPLEX
3626 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3627 #endif
3628 #ifdef IFF_LINK0
3629 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3630 #endif
3631 #ifdef IFF_LINK1
3632 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3633 #endif
3634 #ifdef IFF_LINK2
3635 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3636 #endif
3637 { 0, 0 }
3640 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3641 doc: /* Return information about network interface named IFNAME.
3642 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3643 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3644 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3645 FLAGS is the current flags of the interface. */)
3646 (Lisp_Object ifname)
3648 struct ifreq rq;
3649 Lisp_Object res = Qnil;
3650 Lisp_Object elt;
3651 int s;
3652 int any = 0;
3653 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3654 && defined HAVE_GETIFADDRS && defined LLADDR)
3655 struct ifaddrs *ifap;
3656 #endif
3658 CHECK_STRING (ifname);
3660 if (sizeof rq.ifr_name <= SBYTES (ifname))
3661 error ("interface name too long");
3662 strcpy (rq.ifr_name, SSDATA (ifname));
3664 s = socket (AF_INET, SOCK_STREAM, 0);
3665 if (s < 0)
3666 return Qnil;
3668 elt = Qnil;
3669 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3670 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3672 int flags = rq.ifr_flags;
3673 const struct ifflag_def *fp;
3674 int fnum;
3676 /* If flags is smaller than int (i.e. short) it may have the high bit set
3677 due to IFF_MULTICAST. In that case, sign extending it into
3678 an int is wrong. */
3679 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3680 flags = (unsigned short) rq.ifr_flags;
3682 any = 1;
3683 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3685 if (flags & fp->flag_bit)
3687 elt = Fcons (intern (fp->flag_sym), elt);
3688 flags -= fp->flag_bit;
3691 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3693 if (flags & 1)
3695 elt = Fcons (make_number (fnum), elt);
3699 #endif
3700 res = Fcons (elt, res);
3702 elt = Qnil;
3703 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3704 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3706 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3707 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3708 int n;
3710 any = 1;
3711 for (n = 0; n < 6; n++)
3712 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3713 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3715 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3716 if (getifaddrs (&ifap) != -1)
3718 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3719 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3720 struct ifaddrs *it;
3722 for (it = ifap; it != NULL; it = it->ifa_next)
3724 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3725 unsigned char linkaddr[6];
3726 int n;
3728 if (it->ifa_addr->sa_family != AF_LINK
3729 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3730 || sdl->sdl_alen != 6)
3731 continue;
3733 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3734 for (n = 0; n < 6; n++)
3735 p->contents[n] = make_number (linkaddr[n]);
3737 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
3738 break;
3741 #ifdef HAVE_FREEIFADDRS
3742 freeifaddrs (ifap);
3743 #endif
3745 #endif /* HAVE_GETIFADDRS && LLADDR */
3747 res = Fcons (elt, res);
3749 elt = Qnil;
3750 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3751 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3753 any = 1;
3754 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3755 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3756 #else
3757 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3758 #endif
3760 #endif
3761 res = Fcons (elt, res);
3763 elt = Qnil;
3764 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3765 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3767 any = 1;
3768 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3770 #endif
3771 res = Fcons (elt, res);
3773 elt = Qnil;
3774 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3775 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3777 any = 1;
3778 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3780 #endif
3781 res = Fcons (elt, res);
3783 close (s);
3785 return any ? res : Qnil;
3787 #endif
3788 #endif /* defined (HAVE_NET_IF_H) */
3790 /* Turn off input and output for process PROC. */
3792 static void
3793 deactivate_process (Lisp_Object proc)
3795 register int inchannel, outchannel;
3796 register struct Lisp_Process *p = XPROCESS (proc);
3798 #ifdef HAVE_GNUTLS
3799 /* Delete GnuTLS structures in PROC, if any. */
3800 emacs_gnutls_deinit (proc);
3801 #endif /* HAVE_GNUTLS */
3803 inchannel = p->infd;
3804 outchannel = p->outfd;
3806 #ifdef ADAPTIVE_READ_BUFFERING
3807 if (p->read_output_delay > 0)
3809 if (--process_output_delay_count < 0)
3810 process_output_delay_count = 0;
3811 p->read_output_delay = 0;
3812 p->read_output_skip = 0;
3814 #endif
3816 if (inchannel >= 0)
3818 /* Beware SIGCHLD hereabouts. */
3819 flush_pending_output (inchannel);
3820 emacs_close (inchannel);
3821 if (outchannel >= 0 && outchannel != inchannel)
3822 emacs_close (outchannel);
3824 p->infd = -1;
3825 p->outfd = -1;
3826 #ifdef DATAGRAM_SOCKETS
3827 if (DATAGRAM_CHAN_P (inchannel))
3829 xfree (datagram_address[inchannel].sa);
3830 datagram_address[inchannel].sa = 0;
3831 datagram_address[inchannel].len = 0;
3833 #endif
3834 chan_process[inchannel] = Qnil;
3835 FD_CLR (inchannel, &input_wait_mask);
3836 FD_CLR (inchannel, &non_keyboard_wait_mask);
3837 #ifdef NON_BLOCKING_CONNECT
3838 if (FD_ISSET (inchannel, &connect_wait_mask))
3840 FD_CLR (inchannel, &connect_wait_mask);
3841 FD_CLR (inchannel, &write_mask);
3842 if (--num_pending_connects < 0)
3843 emacs_abort ();
3845 #endif
3846 if (inchannel == max_process_desc)
3848 int i;
3849 /* We just closed the highest-numbered process input descriptor,
3850 so recompute the highest-numbered one now. */
3851 max_process_desc = 0;
3852 for (i = 0; i < MAXDESC; i++)
3853 if (!NILP (chan_process[i]))
3854 max_process_desc = i;
3860 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3861 0, 4, 0,
3862 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3863 It is read into the process' buffers or given to their filter functions.
3864 Non-nil arg PROCESS means do not return until some output has been received
3865 from PROCESS.
3867 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
3868 and milliseconds to wait; return after that much time whether or not
3869 there is any subprocess output. If SECONDS is a floating point number,
3870 it specifies a fractional number of seconds to wait.
3871 The MILLISEC argument is obsolete and should be avoided.
3873 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
3874 from PROCESS, suspending reading output from other processes.
3875 If JUST-THIS-ONE is an integer, don't run any timers either.
3876 Return non-nil if we received any output before the timeout expired. */)
3877 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
3879 intmax_t secs;
3880 int nsecs;
3882 if (! NILP (process))
3883 CHECK_PROCESS (process);
3884 else
3885 just_this_one = Qnil;
3887 if (!NILP (millisec))
3888 { /* Obsolete calling convention using integers rather than floats. */
3889 CHECK_NUMBER (millisec);
3890 if (NILP (seconds))
3891 seconds = make_float (XINT (millisec) / 1000.0);
3892 else
3894 CHECK_NUMBER (seconds);
3895 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
3899 secs = 0;
3900 nsecs = -1;
3902 if (!NILP (seconds))
3904 if (INTEGERP (seconds))
3906 if (0 < XINT (seconds))
3908 secs = XINT (seconds);
3909 nsecs = 0;
3912 else if (FLOATP (seconds))
3914 if (0 < XFLOAT_DATA (seconds))
3916 EMACS_TIME t = EMACS_TIME_FROM_DOUBLE (XFLOAT_DATA (seconds));
3917 secs = min (EMACS_SECS (t), WAIT_READING_MAX);
3918 nsecs = EMACS_NSECS (t);
3921 else
3922 wrong_type_argument (Qnumberp, seconds);
3924 else if (! NILP (process))
3925 nsecs = 0;
3927 return
3928 (wait_reading_process_output (secs, nsecs, 0, 0,
3929 Qnil,
3930 !NILP (process) ? XPROCESS (process) : NULL,
3931 NILP (just_this_one) ? 0 :
3932 !INTEGERP (just_this_one) ? 1 : -1)
3933 ? Qt : Qnil);
3936 /* Accept a connection for server process SERVER on CHANNEL. */
3938 static int connect_counter = 0;
3940 static void
3941 server_accept_connection (Lisp_Object server, int channel)
3943 Lisp_Object proc, caller, name, buffer;
3944 Lisp_Object contact, host, service;
3945 struct Lisp_Process *ps= XPROCESS (server);
3946 struct Lisp_Process *p;
3947 int s;
3948 union u_sockaddr {
3949 struct sockaddr sa;
3950 struct sockaddr_in in;
3951 #ifdef AF_INET6
3952 struct sockaddr_in6 in6;
3953 #endif
3954 #ifdef HAVE_LOCAL_SOCKETS
3955 struct sockaddr_un un;
3956 #endif
3957 } saddr;
3958 socklen_t len = sizeof saddr;
3960 s = accept (channel, &saddr.sa, &len);
3962 if (s < 0)
3964 int code = errno;
3966 if (code == EAGAIN)
3967 return;
3968 #ifdef EWOULDBLOCK
3969 if (code == EWOULDBLOCK)
3970 return;
3971 #endif
3973 if (!NILP (ps->log))
3974 call3 (ps->log, server, Qnil,
3975 concat3 (build_string ("accept failed with code"),
3976 Fnumber_to_string (make_number (code)),
3977 build_string ("\n")));
3978 return;
3981 connect_counter++;
3983 /* Setup a new process to handle the connection. */
3985 /* Generate a unique identification of the caller, and build contact
3986 information for this process. */
3987 host = Qt;
3988 service = Qnil;
3989 switch (saddr.sa.sa_family)
3991 case AF_INET:
3993 Lisp_Object args[5];
3994 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
3995 args[0] = build_string ("%d.%d.%d.%d");
3996 args[1] = make_number (*ip++);
3997 args[2] = make_number (*ip++);
3998 args[3] = make_number (*ip++);
3999 args[4] = make_number (*ip++);
4000 host = Fformat (5, args);
4001 service = make_number (ntohs (saddr.in.sin_port));
4003 args[0] = build_string (" <%s:%d>");
4004 args[1] = host;
4005 args[2] = service;
4006 caller = Fformat (3, args);
4008 break;
4010 #ifdef AF_INET6
4011 case AF_INET6:
4013 Lisp_Object args[9];
4014 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4015 int i;
4016 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4017 for (i = 0; i < 8; i++)
4018 args[i+1] = make_number (ntohs (ip6[i]));
4019 host = Fformat (9, args);
4020 service = make_number (ntohs (saddr.in.sin_port));
4022 args[0] = build_string (" <[%s]:%d>");
4023 args[1] = host;
4024 args[2] = service;
4025 caller = Fformat (3, args);
4027 break;
4028 #endif
4030 #ifdef HAVE_LOCAL_SOCKETS
4031 case AF_LOCAL:
4032 #endif
4033 default:
4034 caller = Fnumber_to_string (make_number (connect_counter));
4035 caller = concat3 (build_string (" <"), caller, build_string (">"));
4036 break;
4039 /* Create a new buffer name for this process if it doesn't have a
4040 filter. The new buffer name is based on the buffer name or
4041 process name of the server process concatenated with the caller
4042 identification. */
4044 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4045 buffer = Qnil;
4046 else
4048 buffer = ps->buffer;
4049 if (!NILP (buffer))
4050 buffer = Fbuffer_name (buffer);
4051 else
4052 buffer = ps->name;
4053 if (!NILP (buffer))
4055 buffer = concat2 (buffer, caller);
4056 buffer = Fget_buffer_create (buffer);
4060 /* Generate a unique name for the new server process. Combine the
4061 server process name with the caller identification. */
4063 name = concat2 (ps->name, caller);
4064 proc = make_process (name);
4066 chan_process[s] = proc;
4068 fcntl (s, F_SETFL, O_NONBLOCK);
4070 p = XPROCESS (proc);
4072 /* Build new contact information for this setup. */
4073 contact = Fcopy_sequence (ps->childp);
4074 contact = Fplist_put (contact, QCserver, Qnil);
4075 contact = Fplist_put (contact, QChost, host);
4076 if (!NILP (service))
4077 contact = Fplist_put (contact, QCservice, service);
4078 contact = Fplist_put (contact, QCremote,
4079 conv_sockaddr_to_lisp (&saddr.sa, len));
4080 #ifdef HAVE_GETSOCKNAME
4081 len = sizeof saddr;
4082 if (getsockname (s, &saddr.sa, &len) == 0)
4083 contact = Fplist_put (contact, QClocal,
4084 conv_sockaddr_to_lisp (&saddr.sa, len));
4085 #endif
4087 pset_childp (p, contact);
4088 pset_plist (p, Fcopy_sequence (ps->plist));
4089 pset_type (p, Qnetwork);
4091 pset_buffer (p, buffer);
4092 pset_sentinel (p, ps->sentinel);
4093 pset_filter (p, ps->filter);
4094 pset_command (p, Qnil);
4095 p->pid = 0;
4096 p->infd = s;
4097 p->outfd = s;
4098 pset_status (p, Qrun);
4100 /* Client processes for accepted connections are not stopped initially. */
4101 if (!EQ (p->filter, Qt))
4103 FD_SET (s, &input_wait_mask);
4104 FD_SET (s, &non_keyboard_wait_mask);
4107 if (s > max_process_desc)
4108 max_process_desc = s;
4110 /* Setup coding system for new process based on server process.
4111 This seems to be the proper thing to do, as the coding system
4112 of the new process should reflect the settings at the time the
4113 server socket was opened; not the current settings. */
4115 pset_decode_coding_system (p, ps->decode_coding_system);
4116 pset_encode_coding_system (p, ps->encode_coding_system);
4117 setup_process_coding_systems (proc);
4119 pset_decoding_buf (p, empty_unibyte_string);
4120 p->decoding_carryover = 0;
4121 pset_encoding_buf (p, empty_unibyte_string);
4123 p->inherit_coding_system_flag
4124 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4126 if (!NILP (ps->log))
4127 call3 (ps->log, server, proc,
4128 concat3 (build_string ("accept from "),
4129 (STRINGP (host) ? host : build_string ("-")),
4130 build_string ("\n")));
4132 if (!NILP (p->sentinel))
4133 exec_sentinel (proc,
4134 concat3 (build_string ("open from "),
4135 (STRINGP (host) ? host : build_string ("-")),
4136 build_string ("\n")));
4139 /* This variable is different from waiting_for_input in keyboard.c.
4140 It is used to communicate to a lisp process-filter/sentinel (via the
4141 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4142 for user-input when that process-filter was called.
4143 waiting_for_input cannot be used as that is by definition 0 when
4144 lisp code is being evalled.
4145 This is also used in record_asynch_buffer_change.
4146 For that purpose, this must be 0
4147 when not inside wait_reading_process_output. */
4148 static int waiting_for_user_input_p;
4150 static Lisp_Object
4151 wait_reading_process_output_unwind (Lisp_Object data)
4153 waiting_for_user_input_p = XINT (data);
4154 return Qnil;
4157 /* This is here so breakpoints can be put on it. */
4158 static void
4159 wait_reading_process_output_1 (void)
4163 /* Read and dispose of subprocess output while waiting for timeout to
4164 elapse and/or keyboard input to be available.
4166 TIME_LIMIT is:
4167 timeout in seconds
4168 If negative, gobble data immediately available but don't wait for any.
4170 NSECS is:
4171 an additional duration to wait, measured in nanoseconds
4172 If TIME_LIMIT is zero, then:
4173 If NSECS == 0, there is no limit.
4174 If NSECS > 0, the timeout consists of NSECS only.
4175 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4177 READ_KBD is:
4178 0 to ignore keyboard input, or
4179 1 to return when input is available, or
4180 -1 meaning caller will actually read the input, so don't throw to
4181 the quit handler, or
4183 DO_DISPLAY means redisplay should be done to show subprocess
4184 output that arrives.
4186 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4187 (and gobble terminal input into the buffer if any arrives).
4189 If WAIT_PROC is specified, wait until something arrives from that
4190 process. The return value is true if we read some input from
4191 that process.
4193 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4194 (suspending output from other processes). A negative value
4195 means don't run any timers either.
4197 If WAIT_PROC is specified, then the function returns true if we
4198 received input from that process before the timeout elapsed.
4199 Otherwise, return true if we received input from any process. */
4202 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4203 bool do_display,
4204 Lisp_Object wait_for_cell,
4205 struct Lisp_Process *wait_proc, int just_wait_proc)
4207 register int channel, nfds;
4208 SELECT_TYPE Available;
4209 SELECT_TYPE Writeok;
4210 int check_write;
4211 int check_delay, no_avail;
4212 int xerrno;
4213 Lisp_Object proc;
4214 EMACS_TIME timeout, end_time;
4215 int wait_channel = -1;
4216 int got_some_input = 0;
4217 ptrdiff_t count = SPECPDL_INDEX ();
4219 FD_ZERO (&Available);
4220 FD_ZERO (&Writeok);
4222 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4223 && !(CONSP (wait_proc->status)
4224 && EQ (XCAR (wait_proc->status), Qexit)))
4225 message ("Blocking call to accept-process-output with quit inhibited!!");
4227 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4228 if (wait_proc != NULL)
4229 wait_channel = wait_proc->infd;
4231 record_unwind_protect (wait_reading_process_output_unwind,
4232 make_number (waiting_for_user_input_p));
4233 waiting_for_user_input_p = read_kbd;
4235 if (time_limit < 0)
4237 time_limit = 0;
4238 nsecs = -1;
4240 else if (TYPE_MAXIMUM (time_t) < time_limit)
4241 time_limit = TYPE_MAXIMUM (time_t);
4243 /* Since we may need to wait several times,
4244 compute the absolute time to return at. */
4245 if (time_limit || 0 < nsecs)
4247 timeout = make_emacs_time (time_limit, nsecs);
4248 end_time = add_emacs_time (current_emacs_time (), timeout);
4251 while (1)
4253 int timeout_reduced_for_timers = 0;
4255 /* If calling from keyboard input, do not quit
4256 since we want to return C-g as an input character.
4257 Otherwise, do pending quit if requested. */
4258 if (read_kbd >= 0)
4259 QUIT;
4260 else if (pending_signals)
4261 process_pending_signals ();
4263 /* Exit now if the cell we're waiting for became non-nil. */
4264 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4265 break;
4267 /* Compute time from now till when time limit is up */
4268 /* Exit if already run out */
4269 if (nsecs < 0)
4271 /* A negative timeout means
4272 gobble output available now
4273 but don't wait at all. */
4275 timeout = make_emacs_time (0, 0);
4277 else if (time_limit || 0 < nsecs)
4279 EMACS_TIME now = current_emacs_time ();
4280 if (EMACS_TIME_LE (end_time, now))
4281 break;
4282 timeout = sub_emacs_time (end_time, now);
4284 else
4286 timeout = make_emacs_time (100000, 0);
4289 /* Normally we run timers here.
4290 But not if wait_for_cell; in those cases,
4291 the wait is supposed to be short,
4292 and those callers cannot handle running arbitrary Lisp code here. */
4293 if (NILP (wait_for_cell)
4294 && just_wait_proc >= 0)
4296 EMACS_TIME timer_delay;
4300 unsigned old_timers_run = timers_run;
4301 struct buffer *old_buffer = current_buffer;
4302 Lisp_Object old_window = selected_window;
4304 timer_delay = timer_check ();
4306 /* If a timer has run, this might have changed buffers
4307 an alike. Make read_key_sequence aware of that. */
4308 if (timers_run != old_timers_run
4309 && (old_buffer != current_buffer
4310 || !EQ (old_window, selected_window))
4311 && waiting_for_user_input_p == -1)
4312 record_asynch_buffer_change ();
4314 if (timers_run != old_timers_run && do_display)
4315 /* We must retry, since a timer may have requeued itself
4316 and that could alter the time_delay. */
4317 redisplay_preserve_echo_area (9);
4318 else
4319 break;
4321 while (!detect_input_pending ());
4323 /* If there is unread keyboard input, also return. */
4324 if (read_kbd != 0
4325 && requeued_events_pending_p ())
4326 break;
4328 /* A negative timeout means do not wait at all. */
4329 if (0 <= nsecs)
4331 if (EMACS_TIME_VALID_P (timer_delay))
4333 if (EMACS_TIME_LT (timer_delay, timeout))
4335 timeout = timer_delay;
4336 timeout_reduced_for_timers = 1;
4339 else
4341 /* This is so a breakpoint can be put here. */
4342 wait_reading_process_output_1 ();
4347 /* Cause C-g and alarm signals to take immediate action,
4348 and cause input available signals to zero out timeout.
4350 It is important that we do this before checking for process
4351 activity. If we get a SIGCHLD after the explicit checks for
4352 process activity, timeout is the only way we will know. */
4353 if (read_kbd < 0)
4354 set_waiting_for_input (&timeout);
4356 /* If status of something has changed, and no input is
4357 available, notify the user of the change right away. After
4358 this explicit check, we'll let the SIGCHLD handler zap
4359 timeout to get our attention. */
4360 if (update_tick != process_tick)
4362 SELECT_TYPE Atemp;
4363 SELECT_TYPE Ctemp;
4365 if (kbd_on_hold_p ())
4366 FD_ZERO (&Atemp);
4367 else
4368 Atemp = input_wait_mask;
4369 Ctemp = write_mask;
4371 timeout = make_emacs_time (0, 0);
4372 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4373 &Atemp,
4374 #ifdef NON_BLOCKING_CONNECT
4375 (num_pending_connects > 0 ? &Ctemp : NULL),
4376 #else
4377 NULL,
4378 #endif
4379 NULL, &timeout, NULL)
4380 <= 0))
4382 /* It's okay for us to do this and then continue with
4383 the loop, since timeout has already been zeroed out. */
4384 clear_waiting_for_input ();
4385 status_notify (NULL);
4386 if (do_display) redisplay_preserve_echo_area (13);
4390 /* Don't wait for output from a non-running process. Just
4391 read whatever data has already been received. */
4392 if (wait_proc && wait_proc->raw_status_new)
4393 update_status (wait_proc);
4394 if (wait_proc
4395 && ! EQ (wait_proc->status, Qrun)
4396 && ! EQ (wait_proc->status, Qconnect))
4398 int nread, total_nread = 0;
4400 clear_waiting_for_input ();
4401 XSETPROCESS (proc, wait_proc);
4403 /* Read data from the process, until we exhaust it. */
4404 while (wait_proc->infd >= 0)
4406 nread = read_process_output (proc, wait_proc->infd);
4408 if (nread == 0)
4409 break;
4411 if (0 < nread)
4413 total_nread += nread;
4414 got_some_input = 1;
4416 else if (nread == -1 && (errno == EIO || errno == EAGAIN))
4417 break;
4418 #ifdef EWOULDBLOCK
4419 else if (nread == -1 && EWOULDBLOCK == errno)
4420 break;
4421 #endif
4423 if (total_nread > 0 && do_display)
4424 redisplay_preserve_echo_area (10);
4426 break;
4429 /* Wait till there is something to do */
4431 if (wait_proc && just_wait_proc)
4433 if (wait_proc->infd < 0) /* Terminated */
4434 break;
4435 FD_SET (wait_proc->infd, &Available);
4436 check_delay = 0;
4437 check_write = 0;
4439 else if (!NILP (wait_for_cell))
4441 Available = non_process_wait_mask;
4442 check_delay = 0;
4443 check_write = 0;
4445 else
4447 if (! read_kbd)
4448 Available = non_keyboard_wait_mask;
4449 else
4450 Available = input_wait_mask;
4451 Writeok = write_mask;
4452 #ifdef SELECT_CANT_DO_WRITE_MASK
4453 check_write = 0;
4454 #else
4455 check_write = 1;
4456 #endif
4457 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4460 /* If frame size has changed or the window is newly mapped,
4461 redisplay now, before we start to wait. There is a race
4462 condition here; if a SIGIO arrives between now and the select
4463 and indicates that a frame is trashed, the select may block
4464 displaying a trashed screen. */
4465 if (frame_garbaged && do_display)
4467 clear_waiting_for_input ();
4468 redisplay_preserve_echo_area (11);
4469 if (read_kbd < 0)
4470 set_waiting_for_input (&timeout);
4473 /* Skip the `select' call if input is available and we're
4474 waiting for keyboard input or a cell change (which can be
4475 triggered by processing X events). In the latter case, set
4476 nfds to 1 to avoid breaking the loop. */
4477 no_avail = 0;
4478 if ((read_kbd || !NILP (wait_for_cell))
4479 && detect_input_pending ())
4481 nfds = read_kbd ? 0 : 1;
4482 no_avail = 1;
4485 if (!no_avail)
4488 #ifdef ADAPTIVE_READ_BUFFERING
4489 /* Set the timeout for adaptive read buffering if any
4490 process has non-zero read_output_skip and non-zero
4491 read_output_delay, and we are not reading output for a
4492 specific wait_channel. It is not executed if
4493 Vprocess_adaptive_read_buffering is nil. */
4494 if (process_output_skip && check_delay > 0)
4496 int nsecs = EMACS_NSECS (timeout);
4497 if (EMACS_SECS (timeout) > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4498 nsecs = READ_OUTPUT_DELAY_MAX;
4499 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4501 proc = chan_process[channel];
4502 if (NILP (proc))
4503 continue;
4504 /* Find minimum non-zero read_output_delay among the
4505 processes with non-zero read_output_skip. */
4506 if (XPROCESS (proc)->read_output_delay > 0)
4508 check_delay--;
4509 if (!XPROCESS (proc)->read_output_skip)
4510 continue;
4511 FD_CLR (channel, &Available);
4512 XPROCESS (proc)->read_output_skip = 0;
4513 if (XPROCESS (proc)->read_output_delay < nsecs)
4514 nsecs = XPROCESS (proc)->read_output_delay;
4517 timeout = make_emacs_time (0, nsecs);
4518 process_output_skip = 0;
4520 #endif
4522 #if defined (USE_GTK) || defined (HAVE_GCONF) || defined (HAVE_GSETTINGS)
4523 nfds = xg_select
4524 #elif defined (HAVE_NS)
4525 nfds = ns_select
4526 #else
4527 nfds = pselect
4528 #endif
4529 (max (max_process_desc, max_input_desc) + 1,
4530 &Available,
4531 (check_write ? &Writeok : (SELECT_TYPE *)0),
4532 NULL, &timeout, NULL);
4534 #ifdef HAVE_GNUTLS
4535 /* GnuTLS buffers data internally. In lowat mode it leaves
4536 some data in the TCP buffers so that select works, but
4537 with custom pull/push functions we need to check if some
4538 data is available in the buffers manually. */
4539 if (nfds == 0)
4541 if (! wait_proc)
4543 /* We're not waiting on a specific process, so loop
4544 through all the channels and check for data.
4545 This is a workaround needed for some versions of
4546 the gnutls library -- 2.12.14 has been confirmed
4547 to need it. See
4548 http://comments.gmane.org/gmane.emacs.devel/145074 */
4549 for (channel = 0; channel < MAXDESC; ++channel)
4550 if (! NILP (chan_process[channel]))
4552 struct Lisp_Process *p =
4553 XPROCESS (chan_process[channel]);
4554 if (p && p->gnutls_p && p->infd
4555 && ((emacs_gnutls_record_check_pending
4556 (p->gnutls_state))
4557 > 0))
4559 nfds++;
4560 FD_SET (p->infd, &Available);
4564 else
4566 /* Check this specific channel. */
4567 if (wait_proc->gnutls_p /* Check for valid process. */
4568 /* Do we have pending data? */
4569 && ((emacs_gnutls_record_check_pending
4570 (wait_proc->gnutls_state))
4571 > 0))
4573 nfds = 1;
4574 /* Set to Available. */
4575 FD_SET (wait_proc->infd, &Available);
4579 #endif
4582 xerrno = errno;
4584 /* Make C-g and alarm signals set flags again */
4585 clear_waiting_for_input ();
4587 /* If we woke up due to SIGWINCH, actually change size now. */
4588 do_pending_window_change (0);
4590 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4591 /* We waited the full specified time, so return now. */
4592 break;
4593 if (nfds < 0)
4595 if (xerrno == EINTR)
4596 no_avail = 1;
4597 else if (xerrno == EBADF)
4599 #ifdef AIX
4600 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4601 the child's closure of the pts gives the parent a SIGHUP, and
4602 the ptc file descriptor is automatically closed,
4603 yielding EBADF here or at select() call above.
4604 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4605 in m/ibmrt-aix.h), and here we just ignore the select error.
4606 Cleanup occurs c/o status_notify after SIGCHLD. */
4607 no_avail = 1; /* Cannot depend on values returned */
4608 #else
4609 emacs_abort ();
4610 #endif
4612 else
4613 error ("select error: %s", emacs_strerror (xerrno));
4616 if (no_avail)
4618 FD_ZERO (&Available);
4619 check_write = 0;
4622 /* Check for keyboard input */
4623 /* If there is any, return immediately
4624 to give it higher priority than subprocesses */
4626 if (read_kbd != 0)
4628 unsigned old_timers_run = timers_run;
4629 struct buffer *old_buffer = current_buffer;
4630 Lisp_Object old_window = selected_window;
4631 int leave = 0;
4633 if (detect_input_pending_run_timers (do_display))
4635 swallow_events (do_display);
4636 if (detect_input_pending_run_timers (do_display))
4637 leave = 1;
4640 /* If a timer has run, this might have changed buffers
4641 an alike. Make read_key_sequence aware of that. */
4642 if (timers_run != old_timers_run
4643 && waiting_for_user_input_p == -1
4644 && (old_buffer != current_buffer
4645 || !EQ (old_window, selected_window)))
4646 record_asynch_buffer_change ();
4648 if (leave)
4649 break;
4652 /* If there is unread keyboard input, also return. */
4653 if (read_kbd != 0
4654 && requeued_events_pending_p ())
4655 break;
4657 /* If we are not checking for keyboard input now,
4658 do process events (but don't run any timers).
4659 This is so that X events will be processed.
4660 Otherwise they may have to wait until polling takes place.
4661 That would causes delays in pasting selections, for example.
4663 (We used to do this only if wait_for_cell.) */
4664 if (read_kbd == 0 && detect_input_pending ())
4666 swallow_events (do_display);
4667 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4668 if (detect_input_pending ())
4669 break;
4670 #endif
4673 /* Exit now if the cell we're waiting for became non-nil. */
4674 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4675 break;
4677 #ifdef USABLE_SIGIO
4678 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4679 go read it. This can happen with X on BSD after logging out.
4680 In that case, there really is no input and no SIGIO,
4681 but select says there is input. */
4683 if (read_kbd && interrupt_input
4684 && keyboard_bit_set (&Available) && ! noninteractive)
4685 handle_input_available_signal (SIGIO);
4686 #endif
4688 if (! wait_proc)
4689 got_some_input |= nfds > 0;
4691 /* If checking input just got us a size-change event from X,
4692 obey it now if we should. */
4693 if (read_kbd || ! NILP (wait_for_cell))
4694 do_pending_window_change (0);
4696 /* Check for data from a process. */
4697 if (no_avail || nfds == 0)
4698 continue;
4700 for (channel = 0; channel <= max_input_desc; ++channel)
4702 struct fd_callback_data *d = &fd_callback_info[channel];
4703 if (d->func
4704 && ((d->condition & FOR_READ
4705 && FD_ISSET (channel, &Available))
4706 || (d->condition & FOR_WRITE
4707 && FD_ISSET (channel, &write_mask))))
4708 d->func (channel, d->data);
4711 for (channel = 0; channel <= max_process_desc; channel++)
4713 if (FD_ISSET (channel, &Available)
4714 && FD_ISSET (channel, &non_keyboard_wait_mask)
4715 && !FD_ISSET (channel, &non_process_wait_mask))
4717 int nread;
4719 /* If waiting for this channel, arrange to return as
4720 soon as no more input to be processed. No more
4721 waiting. */
4722 if (wait_channel == channel)
4724 wait_channel = -1;
4725 nsecs = -1;
4726 got_some_input = 1;
4728 proc = chan_process[channel];
4729 if (NILP (proc))
4730 continue;
4732 /* If this is a server stream socket, accept connection. */
4733 if (EQ (XPROCESS (proc)->status, Qlisten))
4735 server_accept_connection (proc, channel);
4736 continue;
4739 /* Read data from the process, starting with our
4740 buffered-ahead character if we have one. */
4742 nread = read_process_output (proc, channel);
4743 if (nread > 0)
4745 /* Since read_process_output can run a filter,
4746 which can call accept-process-output,
4747 don't try to read from any other processes
4748 before doing the select again. */
4749 FD_ZERO (&Available);
4751 if (do_display)
4752 redisplay_preserve_echo_area (12);
4754 #ifdef EWOULDBLOCK
4755 else if (nread == -1 && errno == EWOULDBLOCK)
4757 #endif
4758 else if (nread == -1 && errno == EAGAIN)
4760 #ifdef WINDOWSNT
4761 /* FIXME: Is this special case still needed? */
4762 /* Note that we cannot distinguish between no input
4763 available now and a closed pipe.
4764 With luck, a closed pipe will be accompanied by
4765 subprocess termination and SIGCHLD. */
4766 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4768 #endif
4769 #ifdef HAVE_PTYS
4770 /* On some OSs with ptys, when the process on one end of
4771 a pty exits, the other end gets an error reading with
4772 errno = EIO instead of getting an EOF (0 bytes read).
4773 Therefore, if we get an error reading and errno =
4774 EIO, just continue, because the child process has
4775 exited and should clean itself up soon (e.g. when we
4776 get a SIGCHLD).
4778 However, it has been known to happen that the SIGCHLD
4779 got lost. So raise the signal again just in case.
4780 It can't hurt. */
4781 else if (nread == -1 && errno == EIO)
4783 struct Lisp_Process *p = XPROCESS (proc);
4785 /* Clear the descriptor now, so we only raise the
4786 signal once. */
4787 FD_CLR (channel, &input_wait_mask);
4788 FD_CLR (channel, &non_keyboard_wait_mask);
4790 if (p->pid == -2)
4792 /* If the EIO occurs on a pty, the SIGCHLD handler's
4793 waitpid call will not find the process object to
4794 delete. Do it here. */
4795 p->tick = ++process_tick;
4796 pset_status (p, Qfailed);
4798 else
4799 handle_child_signal (SIGCHLD);
4801 #endif /* HAVE_PTYS */
4802 /* If we can detect process termination, don't consider the
4803 process gone just because its pipe is closed. */
4804 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4806 else
4808 /* Preserve status of processes already terminated. */
4809 XPROCESS (proc)->tick = ++process_tick;
4810 deactivate_process (proc);
4811 if (XPROCESS (proc)->raw_status_new)
4812 update_status (XPROCESS (proc));
4813 if (EQ (XPROCESS (proc)->status, Qrun))
4814 pset_status (XPROCESS (proc),
4815 list2 (Qexit, make_number (256)));
4818 #ifdef NON_BLOCKING_CONNECT
4819 if (FD_ISSET (channel, &Writeok)
4820 && FD_ISSET (channel, &connect_wait_mask))
4822 struct Lisp_Process *p;
4824 FD_CLR (channel, &connect_wait_mask);
4825 FD_CLR (channel, &write_mask);
4826 if (--num_pending_connects < 0)
4827 emacs_abort ();
4829 proc = chan_process[channel];
4830 if (NILP (proc))
4831 continue;
4833 p = XPROCESS (proc);
4835 #ifdef GNU_LINUX
4836 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4837 So only use it on systems where it is known to work. */
4839 socklen_t xlen = sizeof (xerrno);
4840 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4841 xerrno = errno;
4843 #else
4845 struct sockaddr pname;
4846 int pnamelen = sizeof (pname);
4848 /* If connection failed, getpeername will fail. */
4849 xerrno = 0;
4850 if (getpeername (channel, &pname, &pnamelen) < 0)
4852 /* Obtain connect failure code through error slippage. */
4853 char dummy;
4854 xerrno = errno;
4855 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
4856 xerrno = errno;
4859 #endif
4860 if (xerrno)
4862 p->tick = ++process_tick;
4863 pset_status (p, list2 (Qfailed, make_number (xerrno)));
4864 deactivate_process (proc);
4866 else
4868 pset_status (p, Qrun);
4869 /* Execute the sentinel here. If we had relied on
4870 status_notify to do it later, it will read input
4871 from the process before calling the sentinel. */
4872 exec_sentinel (proc, build_string ("open\n"));
4873 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
4875 FD_SET (p->infd, &input_wait_mask);
4876 FD_SET (p->infd, &non_keyboard_wait_mask);
4880 #endif /* NON_BLOCKING_CONNECT */
4881 } /* end for each file descriptor */
4882 } /* end while exit conditions not met */
4884 unbind_to (count, Qnil);
4886 /* If calling from keyboard input, do not quit
4887 since we want to return C-g as an input character.
4888 Otherwise, do pending quit if requested. */
4889 if (read_kbd >= 0)
4891 /* Prevent input_pending from remaining set if we quit. */
4892 clear_input_pending ();
4893 QUIT;
4896 return got_some_input;
4899 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4901 static Lisp_Object
4902 read_process_output_call (Lisp_Object fun_and_args)
4904 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4907 static Lisp_Object
4908 read_process_output_error_handler (Lisp_Object error_val)
4910 cmd_error_internal (error_val, "error in process filter: ");
4911 Vinhibit_quit = Qt;
4912 update_echo_area ();
4913 Fsleep_for (make_number (2), Qnil);
4914 return Qt;
4917 /* Read pending output from the process channel,
4918 starting with our buffered-ahead character if we have one.
4919 Yield number of decoded characters read.
4921 This function reads at most 4096 characters.
4922 If you want to read all available subprocess output,
4923 you must call it repeatedly until it returns zero.
4925 The characters read are decoded according to PROC's coding-system
4926 for decoding. */
4928 static int
4929 read_process_output (Lisp_Object proc, register int channel)
4931 register ssize_t nbytes;
4932 char *chars;
4933 register Lisp_Object outstream;
4934 register struct Lisp_Process *p = XPROCESS (proc);
4935 register ptrdiff_t opoint;
4936 struct coding_system *coding = proc_decode_coding_system[channel];
4937 int carryover = p->decoding_carryover;
4938 int readmax = 4096;
4939 ptrdiff_t count = SPECPDL_INDEX ();
4940 Lisp_Object odeactivate;
4942 chars = alloca (carryover + readmax);
4943 if (carryover)
4944 /* See the comment above. */
4945 memcpy (chars, SDATA (p->decoding_buf), carryover);
4947 #ifdef DATAGRAM_SOCKETS
4948 /* We have a working select, so proc_buffered_char is always -1. */
4949 if (DATAGRAM_CHAN_P (channel))
4951 socklen_t len = datagram_address[channel].len;
4952 nbytes = recvfrom (channel, chars + carryover, readmax,
4953 0, datagram_address[channel].sa, &len);
4955 else
4956 #endif
4958 int buffered = 0 <= proc_buffered_char[channel];
4959 if (buffered)
4961 chars[carryover] = proc_buffered_char[channel];
4962 proc_buffered_char[channel] = -1;
4964 #ifdef HAVE_GNUTLS
4965 if (p->gnutls_p)
4966 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
4967 readmax - buffered);
4968 else
4969 #endif
4970 nbytes = emacs_read (channel, chars + carryover + buffered,
4971 readmax - buffered);
4972 #ifdef ADAPTIVE_READ_BUFFERING
4973 if (nbytes > 0 && p->adaptive_read_buffering)
4975 int delay = p->read_output_delay;
4976 if (nbytes < 256)
4978 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
4980 if (delay == 0)
4981 process_output_delay_count++;
4982 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
4985 else if (delay > 0 && nbytes == readmax - buffered)
4987 delay -= READ_OUTPUT_DELAY_INCREMENT;
4988 if (delay == 0)
4989 process_output_delay_count--;
4991 p->read_output_delay = delay;
4992 if (delay)
4994 p->read_output_skip = 1;
4995 process_output_skip = 1;
4998 #endif
4999 nbytes += buffered;
5000 nbytes += buffered && nbytes <= 0;
5003 p->decoding_carryover = 0;
5005 /* At this point, NBYTES holds number of bytes just received
5006 (including the one in proc_buffered_char[channel]). */
5007 if (nbytes <= 0)
5009 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5010 return nbytes;
5011 coding->mode |= CODING_MODE_LAST_BLOCK;
5014 /* Now set NBYTES how many bytes we must decode. */
5015 nbytes += carryover;
5017 odeactivate = Vdeactivate_mark;
5018 /* There's no good reason to let process filters change the current
5019 buffer, and many callers of accept-process-output, sit-for, and
5020 friends don't expect current-buffer to be changed from under them. */
5021 record_unwind_current_buffer ();
5023 /* Read and dispose of the process output. */
5024 outstream = p->filter;
5025 if (!NILP (outstream))
5027 Lisp_Object text;
5028 bool outer_running_asynch_code = running_asynch_code;
5029 int waiting = waiting_for_user_input_p;
5031 /* No need to gcpro these, because all we do with them later
5032 is test them for EQness, and none of them should be a string. */
5033 #if 0
5034 Lisp_Object obuffer, okeymap;
5035 XSETBUFFER (obuffer, current_buffer);
5036 okeymap = BVAR (current_buffer, keymap);
5037 #endif
5039 /* We inhibit quit here instead of just catching it so that
5040 hitting ^G when a filter happens to be running won't screw
5041 it up. */
5042 specbind (Qinhibit_quit, Qt);
5043 specbind (Qlast_nonmenu_event, Qt);
5045 /* In case we get recursively called,
5046 and we already saved the match data nonrecursively,
5047 save the same match data in safely recursive fashion. */
5048 if (outer_running_asynch_code)
5050 Lisp_Object tem;
5051 /* Don't clobber the CURRENT match data, either! */
5052 tem = Fmatch_data (Qnil, Qnil, Qnil);
5053 restore_search_regs ();
5054 record_unwind_save_match_data ();
5055 Fset_match_data (tem, Qt);
5058 /* For speed, if a search happens within this code,
5059 save the match data in a special nonrecursive fashion. */
5060 running_asynch_code = 1;
5062 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5063 text = coding->dst_object;
5064 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5065 /* A new coding system might be found. */
5066 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5068 pset_decode_coding_system (p, Vlast_coding_system_used);
5070 /* Don't call setup_coding_system for
5071 proc_decode_coding_system[channel] here. It is done in
5072 detect_coding called via decode_coding above. */
5074 /* If a coding system for encoding is not yet decided, we set
5075 it as the same as coding-system for decoding.
5077 But, before doing that we must check if
5078 proc_encode_coding_system[p->outfd] surely points to a
5079 valid memory because p->outfd will be changed once EOF is
5080 sent to the process. */
5081 if (NILP (p->encode_coding_system)
5082 && proc_encode_coding_system[p->outfd])
5084 pset_encode_coding_system
5085 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5086 setup_coding_system (p->encode_coding_system,
5087 proc_encode_coding_system[p->outfd]);
5091 if (coding->carryover_bytes > 0)
5093 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5094 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5095 memcpy (SDATA (p->decoding_buf), coding->carryover,
5096 coding->carryover_bytes);
5097 p->decoding_carryover = coding->carryover_bytes;
5099 if (SBYTES (text) > 0)
5100 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5101 sometimes it's simply wrong to wrap (e.g. when called from
5102 accept-process-output). */
5103 internal_condition_case_1 (read_process_output_call,
5104 Fcons (outstream,
5105 Fcons (proc, Fcons (text, Qnil))),
5106 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5107 read_process_output_error_handler);
5109 /* If we saved the match data nonrecursively, restore it now. */
5110 restore_search_regs ();
5111 running_asynch_code = outer_running_asynch_code;
5113 /* Restore waiting_for_user_input_p as it was
5114 when we were called, in case the filter clobbered it. */
5115 waiting_for_user_input_p = waiting;
5117 #if 0 /* Call record_asynch_buffer_change unconditionally,
5118 because we might have changed minor modes or other things
5119 that affect key bindings. */
5120 if (! EQ (Fcurrent_buffer (), obuffer)
5121 || ! EQ (current_buffer->keymap, okeymap))
5122 #endif
5123 /* But do it only if the caller is actually going to read events.
5124 Otherwise there's no need to make him wake up, and it could
5125 cause trouble (for example it would make sit_for return). */
5126 if (waiting_for_user_input_p == -1)
5127 record_asynch_buffer_change ();
5130 /* If no filter, write into buffer if it isn't dead. */
5131 else if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5133 Lisp_Object old_read_only;
5134 ptrdiff_t old_begv, old_zv;
5135 ptrdiff_t old_begv_byte, old_zv_byte;
5136 ptrdiff_t before, before_byte;
5137 ptrdiff_t opoint_byte;
5138 Lisp_Object text;
5139 struct buffer *b;
5141 Fset_buffer (p->buffer);
5142 opoint = PT;
5143 opoint_byte = PT_BYTE;
5144 old_read_only = BVAR (current_buffer, read_only);
5145 old_begv = BEGV;
5146 old_zv = ZV;
5147 old_begv_byte = BEGV_BYTE;
5148 old_zv_byte = ZV_BYTE;
5150 bset_read_only (current_buffer, Qnil);
5152 /* Insert new output into buffer
5153 at the current end-of-output marker,
5154 thus preserving logical ordering of input and output. */
5155 if (XMARKER (p->mark)->buffer)
5156 SET_PT_BOTH (clip_to_bounds (BEGV,
5157 marker_position (p->mark), ZV),
5158 clip_to_bounds (BEGV_BYTE,
5159 marker_byte_position (p->mark),
5160 ZV_BYTE));
5161 else
5162 SET_PT_BOTH (ZV, ZV_BYTE);
5163 before = PT;
5164 before_byte = PT_BYTE;
5166 /* If the output marker is outside of the visible region, save
5167 the restriction and widen. */
5168 if (! (BEGV <= PT && PT <= ZV))
5169 Fwiden ();
5171 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5172 text = coding->dst_object;
5173 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5174 /* A new coding system might be found. See the comment in the
5175 similar code in the previous `if' block. */
5176 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5178 pset_decode_coding_system (p, Vlast_coding_system_used);
5179 if (NILP (p->encode_coding_system)
5180 && proc_encode_coding_system[p->outfd])
5182 pset_encode_coding_system
5183 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5184 setup_coding_system (p->encode_coding_system,
5185 proc_encode_coding_system[p->outfd]);
5188 if (coding->carryover_bytes > 0)
5190 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5191 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5192 memcpy (SDATA (p->decoding_buf), coding->carryover,
5193 coding->carryover_bytes);
5194 p->decoding_carryover = coding->carryover_bytes;
5196 /* Adjust the multibyteness of TEXT to that of the buffer. */
5197 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5198 != ! STRING_MULTIBYTE (text))
5199 text = (STRING_MULTIBYTE (text)
5200 ? Fstring_as_unibyte (text)
5201 : Fstring_to_multibyte (text));
5202 /* Insert before markers in case we are inserting where
5203 the buffer's mark is, and the user's next command is Meta-y. */
5204 insert_from_string_before_markers (text, 0, 0,
5205 SCHARS (text), SBYTES (text), 0);
5207 /* Make sure the process marker's position is valid when the
5208 process buffer is changed in the signal_after_change above.
5209 W3 is known to do that. */
5210 if (BUFFERP (p->buffer)
5211 && (b = XBUFFER (p->buffer), b != current_buffer))
5212 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5213 else
5214 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5216 update_mode_lines++;
5218 /* Make sure opoint and the old restrictions
5219 float ahead of any new text just as point would. */
5220 if (opoint >= before)
5222 opoint += PT - before;
5223 opoint_byte += PT_BYTE - before_byte;
5225 if (old_begv > before)
5227 old_begv += PT - before;
5228 old_begv_byte += PT_BYTE - before_byte;
5230 if (old_zv >= before)
5232 old_zv += PT - before;
5233 old_zv_byte += PT_BYTE - before_byte;
5236 /* If the restriction isn't what it should be, set it. */
5237 if (old_begv != BEGV || old_zv != ZV)
5238 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5241 bset_read_only (current_buffer, old_read_only);
5242 SET_PT_BOTH (opoint, opoint_byte);
5244 /* Handling the process output should not deactivate the mark. */
5245 Vdeactivate_mark = odeactivate;
5247 unbind_to (count, Qnil);
5248 return nbytes;
5251 /* Sending data to subprocess */
5253 /* In send_process, when a write fails temporarily,
5254 wait_reading_process_output is called. It may execute user code,
5255 e.g. timers, that attempts to write new data to the same process.
5256 We must ensure that data is sent in the right order, and not
5257 interspersed half-completed with other writes (Bug#10815). This is
5258 handled by the write_queue element of struct process. It is a list
5259 with each entry having the form
5261 (string . (offset . length))
5263 where STRING is a lisp string, OFFSET is the offset into the
5264 string's byte sequence from which we should begin to send, and
5265 LENGTH is the number of bytes left to send. */
5267 /* Create a new entry in write_queue.
5268 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5269 BUF is a pointer to the string sequence of the input_obj or a C
5270 string in case of Qt or Qnil. */
5272 static void
5273 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5274 const char *buf, ptrdiff_t len, int front)
5276 ptrdiff_t offset;
5277 Lisp_Object entry, obj;
5279 if (STRINGP (input_obj))
5281 offset = buf - SSDATA (input_obj);
5282 obj = input_obj;
5284 else
5286 offset = 0;
5287 obj = make_unibyte_string (buf, len);
5290 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5292 if (front)
5293 pset_write_queue (p, Fcons (entry, p->write_queue));
5294 else
5295 pset_write_queue (p, nconc2 (p->write_queue, Fcons (entry, Qnil)));
5298 /* Remove the first element in the write_queue of process P, put its
5299 contents in OBJ, BUF and LEN, and return non-zero. If the
5300 write_queue is empty, return zero. */
5302 static int
5303 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5304 const char **buf, ptrdiff_t *len)
5306 Lisp_Object entry, offset_length;
5307 ptrdiff_t offset;
5309 if (NILP (p->write_queue))
5310 return 0;
5312 entry = XCAR (p->write_queue);
5313 pset_write_queue (p, XCDR (p->write_queue));
5315 *obj = XCAR (entry);
5316 offset_length = XCDR (entry);
5318 *len = XINT (XCDR (offset_length));
5319 offset = XINT (XCAR (offset_length));
5320 *buf = SSDATA (*obj) + offset;
5322 return 1;
5325 /* Send some data to process PROC.
5326 BUF is the beginning of the data; LEN is the number of characters.
5327 OBJECT is the Lisp object that the data comes from. If OBJECT is
5328 nil or t, it means that the data comes from C string.
5330 If OBJECT is not nil, the data is encoded by PROC's coding-system
5331 for encoding before it is sent.
5333 This function can evaluate Lisp code and can garbage collect. */
5335 static void
5336 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5337 Lisp_Object object)
5339 struct Lisp_Process *p = XPROCESS (proc);
5340 ssize_t rv;
5341 struct coding_system *coding;
5343 if (p->raw_status_new)
5344 update_status (p);
5345 if (! EQ (p->status, Qrun))
5346 error ("Process %s not running", SDATA (p->name));
5347 if (p->outfd < 0)
5348 error ("Output file descriptor of %s is closed", SDATA (p->name));
5350 coding = proc_encode_coding_system[p->outfd];
5351 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5353 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5354 || (BUFFERP (object)
5355 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5356 || EQ (object, Qt))
5358 pset_encode_coding_system
5359 (p, complement_process_encoding_system (p->encode_coding_system));
5360 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5362 /* The coding system for encoding was changed to raw-text
5363 because we sent a unibyte text previously. Now we are
5364 sending a multibyte text, thus we must encode it by the
5365 original coding system specified for the current process.
5367 Another reason we come here is that the coding system
5368 was just complemented and a new one was returned by
5369 complement_process_encoding_system. */
5370 setup_coding_system (p->encode_coding_system, coding);
5371 Vlast_coding_system_used = p->encode_coding_system;
5373 coding->src_multibyte = 1;
5375 else
5377 coding->src_multibyte = 0;
5378 /* For sending a unibyte text, character code conversion should
5379 not take place but EOL conversion should. So, setup raw-text
5380 or one of the subsidiary if we have not yet done it. */
5381 if (CODING_REQUIRE_ENCODING (coding))
5383 if (CODING_REQUIRE_FLUSHING (coding))
5385 /* But, before changing the coding, we must flush out data. */
5386 coding->mode |= CODING_MODE_LAST_BLOCK;
5387 send_process (proc, "", 0, Qt);
5388 coding->mode &= CODING_MODE_LAST_BLOCK;
5390 setup_coding_system (raw_text_coding_system
5391 (Vlast_coding_system_used),
5392 coding);
5393 coding->src_multibyte = 0;
5396 coding->dst_multibyte = 0;
5398 if (CODING_REQUIRE_ENCODING (coding))
5400 coding->dst_object = Qt;
5401 if (BUFFERP (object))
5403 ptrdiff_t from_byte, from, to;
5404 ptrdiff_t save_pt, save_pt_byte;
5405 struct buffer *cur = current_buffer;
5407 set_buffer_internal (XBUFFER (object));
5408 save_pt = PT, save_pt_byte = PT_BYTE;
5410 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5411 from = BYTE_TO_CHAR (from_byte);
5412 to = BYTE_TO_CHAR (from_byte + len);
5413 TEMP_SET_PT_BOTH (from, from_byte);
5414 encode_coding_object (coding, object, from, from_byte,
5415 to, from_byte + len, Qt);
5416 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5417 set_buffer_internal (cur);
5419 else if (STRINGP (object))
5421 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5422 SBYTES (object), Qt);
5424 else
5426 coding->dst_object = make_unibyte_string (buf, len);
5427 coding->produced = len;
5430 len = coding->produced;
5431 object = coding->dst_object;
5432 buf = SSDATA (object);
5435 /* If there is already data in the write_queue, put the new data
5436 in the back of queue. Otherwise, ignore it. */
5437 if (!NILP (p->write_queue))
5438 write_queue_push (p, object, buf, len, 0);
5440 do /* while !NILP (p->write_queue) */
5442 ptrdiff_t cur_len = -1;
5443 const char *cur_buf;
5444 Lisp_Object cur_object;
5446 /* If write_queue is empty, ignore it. */
5447 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5449 cur_len = len;
5450 cur_buf = buf;
5451 cur_object = object;
5454 while (cur_len > 0)
5456 /* Send this batch, using one or more write calls. */
5457 ptrdiff_t written = 0;
5458 int outfd = p->outfd;
5459 #ifdef DATAGRAM_SOCKETS
5460 if (DATAGRAM_CHAN_P (outfd))
5462 rv = sendto (outfd, cur_buf, cur_len,
5463 0, datagram_address[outfd].sa,
5464 datagram_address[outfd].len);
5465 if (0 <= rv)
5466 written = rv;
5467 else if (errno == EMSGSIZE)
5468 report_file_error ("sending datagram", Fcons (proc, Qnil));
5470 else
5471 #endif
5473 #ifdef HAVE_GNUTLS
5474 if (p->gnutls_p)
5475 written = emacs_gnutls_write (p, cur_buf, cur_len);
5476 else
5477 #endif
5478 written = emacs_write (outfd, cur_buf, cur_len);
5479 rv = (written ? 0 : -1);
5480 #ifdef ADAPTIVE_READ_BUFFERING
5481 if (p->read_output_delay > 0
5482 && p->adaptive_read_buffering == 1)
5484 p->read_output_delay = 0;
5485 process_output_delay_count--;
5486 p->read_output_skip = 0;
5488 #endif
5491 if (rv < 0)
5493 if (errno == EAGAIN
5494 #ifdef EWOULDBLOCK
5495 || errno == EWOULDBLOCK
5496 #endif
5498 /* Buffer is full. Wait, accepting input;
5499 that may allow the program
5500 to finish doing output and read more. */
5502 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5503 /* A gross hack to work around a bug in FreeBSD.
5504 In the following sequence, read(2) returns
5505 bogus data:
5507 write(2) 1022 bytes
5508 write(2) 954 bytes, get EAGAIN
5509 read(2) 1024 bytes in process_read_output
5510 read(2) 11 bytes in process_read_output
5512 That is, read(2) returns more bytes than have
5513 ever been written successfully. The 1033 bytes
5514 read are the 1022 bytes written successfully
5515 after processing (for example with CRs added if
5516 the terminal is set up that way which it is
5517 here). The same bytes will be seen again in a
5518 later read(2), without the CRs. */
5520 if (errno == EAGAIN)
5522 int flags = FWRITE;
5523 ioctl (p->outfd, TIOCFLUSH, &flags);
5525 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5527 /* Put what we should have written in wait_queue. */
5528 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5529 wait_reading_process_output (0, 20 * 1000 * 1000,
5530 0, 0, Qnil, NULL, 0);
5531 /* Reread queue, to see what is left. */
5532 break;
5534 else if (errno == EPIPE)
5536 p->raw_status_new = 0;
5537 pset_status (p, list2 (Qexit, make_number (256)));
5538 p->tick = ++process_tick;
5539 deactivate_process (proc);
5540 error ("process %s no longer connected to pipe; closed it",
5541 SDATA (p->name));
5543 else
5544 /* This is a real error. */
5545 report_file_error ("writing to process", Fcons (proc, Qnil));
5547 cur_buf += written;
5548 cur_len -= written;
5551 while (!NILP (p->write_queue));
5554 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5555 3, 3, 0,
5556 doc: /* Send current contents of region as input to PROCESS.
5557 PROCESS may be a process, a buffer, the name of a process or buffer, or
5558 nil, indicating the current buffer's process.
5559 Called from program, takes three arguments, PROCESS, START and END.
5560 If the region is more than 500 characters long,
5561 it is sent in several bunches. This may happen even for shorter regions.
5562 Output from processes can arrive in between bunches. */)
5563 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5565 Lisp_Object proc;
5566 ptrdiff_t start1, end1;
5568 proc = get_process (process);
5569 validate_region (&start, &end);
5571 if (XINT (start) < GPT && XINT (end) > GPT)
5572 move_gap (XINT (start));
5574 start1 = CHAR_TO_BYTE (XINT (start));
5575 end1 = CHAR_TO_BYTE (XINT (end));
5576 send_process (proc, (char *) BYTE_POS_ADDR (start1), end1 - start1,
5577 Fcurrent_buffer ());
5579 return Qnil;
5582 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5583 2, 2, 0,
5584 doc: /* Send PROCESS the contents of STRING as input.
5585 PROCESS may be a process, a buffer, the name of a process or buffer, or
5586 nil, indicating the current buffer's process.
5587 If STRING is more than 500 characters long,
5588 it is sent in several bunches. This may happen even for shorter strings.
5589 Output from processes can arrive in between bunches. */)
5590 (Lisp_Object process, Lisp_Object string)
5592 Lisp_Object proc;
5593 CHECK_STRING (string);
5594 proc = get_process (process);
5595 send_process (proc, SSDATA (string),
5596 SBYTES (string), string);
5597 return Qnil;
5600 /* Return the foreground process group for the tty/pty that
5601 the process P uses. */
5602 static pid_t
5603 emacs_get_tty_pgrp (struct Lisp_Process *p)
5605 pid_t gid = -1;
5607 #ifdef TIOCGPGRP
5608 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5610 int fd;
5611 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5612 master side. Try the slave side. */
5613 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5615 if (fd != -1)
5617 ioctl (fd, TIOCGPGRP, &gid);
5618 emacs_close (fd);
5621 #endif /* defined (TIOCGPGRP ) */
5623 return gid;
5626 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5627 Sprocess_running_child_p, 0, 1, 0,
5628 doc: /* Return t if PROCESS has given the terminal to a child.
5629 If the operating system does not make it possible to find out,
5630 return t unconditionally. */)
5631 (Lisp_Object process)
5633 /* Initialize in case ioctl doesn't exist or gives an error,
5634 in a way that will cause returning t. */
5635 pid_t gid;
5636 Lisp_Object proc;
5637 struct Lisp_Process *p;
5639 proc = get_process (process);
5640 p = XPROCESS (proc);
5642 if (!EQ (p->type, Qreal))
5643 error ("Process %s is not a subprocess",
5644 SDATA (p->name));
5645 if (p->infd < 0)
5646 error ("Process %s is not active",
5647 SDATA (p->name));
5649 gid = emacs_get_tty_pgrp (p);
5651 if (gid == p->pid)
5652 return Qnil;
5653 return Qt;
5656 /* send a signal number SIGNO to PROCESS.
5657 If CURRENT_GROUP is t, that means send to the process group
5658 that currently owns the terminal being used to communicate with PROCESS.
5659 This is used for various commands in shell mode.
5660 If CURRENT_GROUP is lambda, that means send to the process group
5661 that currently owns the terminal, but only if it is NOT the shell itself.
5663 If NOMSG is zero, insert signal-announcements into process's buffers
5664 right away.
5666 If we can, we try to signal PROCESS by sending control characters
5667 down the pty. This allows us to signal inferiors who have changed
5668 their uid, for which kill would return an EPERM error. */
5670 static void
5671 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5672 int nomsg)
5674 Lisp_Object proc;
5675 register struct Lisp_Process *p;
5676 pid_t gid;
5677 int no_pgrp = 0;
5679 proc = get_process (process);
5680 p = XPROCESS (proc);
5682 if (!EQ (p->type, Qreal))
5683 error ("Process %s is not a subprocess",
5684 SDATA (p->name));
5685 if (p->infd < 0)
5686 error ("Process %s is not active",
5687 SDATA (p->name));
5689 if (!p->pty_flag)
5690 current_group = Qnil;
5692 /* If we are using pgrps, get a pgrp number and make it negative. */
5693 if (NILP (current_group))
5694 /* Send the signal to the shell's process group. */
5695 gid = p->pid;
5696 else
5698 #ifdef SIGNALS_VIA_CHARACTERS
5699 /* If possible, send signals to the entire pgrp
5700 by sending an input character to it. */
5702 struct termios t;
5703 cc_t *sig_char = NULL;
5705 tcgetattr (p->infd, &t);
5707 switch (signo)
5709 case SIGINT:
5710 sig_char = &t.c_cc[VINTR];
5711 break;
5713 case SIGQUIT:
5714 sig_char = &t.c_cc[VQUIT];
5715 break;
5717 case SIGTSTP:
5718 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5719 sig_char = &t.c_cc[VSWTCH];
5720 #else
5721 sig_char = &t.c_cc[VSUSP];
5722 #endif
5723 break;
5726 if (sig_char && *sig_char != CDISABLE)
5728 send_process (proc, (char *) sig_char, 1, Qnil);
5729 return;
5731 /* If we can't send the signal with a character,
5732 fall through and send it another way. */
5734 /* The code above may fall through if it can't
5735 handle the signal. */
5736 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5738 #ifdef TIOCGPGRP
5739 /* Get the current pgrp using the tty itself, if we have that.
5740 Otherwise, use the pty to get the pgrp.
5741 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5742 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5743 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5744 His patch indicates that if TIOCGPGRP returns an error, then
5745 we should just assume that p->pid is also the process group id. */
5747 gid = emacs_get_tty_pgrp (p);
5749 if (gid == -1)
5750 /* If we can't get the information, assume
5751 the shell owns the tty. */
5752 gid = p->pid;
5754 /* It is not clear whether anything really can set GID to -1.
5755 Perhaps on some system one of those ioctls can or could do so.
5756 Or perhaps this is vestigial. */
5757 if (gid == -1)
5758 no_pgrp = 1;
5759 #else /* ! defined (TIOCGPGRP ) */
5760 /* Can't select pgrps on this system, so we know that
5761 the child itself heads the pgrp. */
5762 gid = p->pid;
5763 #endif /* ! defined (TIOCGPGRP ) */
5765 /* If current_group is lambda, and the shell owns the terminal,
5766 don't send any signal. */
5767 if (EQ (current_group, Qlambda) && gid == p->pid)
5768 return;
5771 switch (signo)
5773 #ifdef SIGCONT
5774 case SIGCONT:
5775 p->raw_status_new = 0;
5776 pset_status (p, Qrun);
5777 p->tick = ++process_tick;
5778 if (!nomsg)
5780 status_notify (NULL);
5781 redisplay_preserve_echo_area (13);
5783 break;
5784 #endif /* ! defined (SIGCONT) */
5785 case SIGINT:
5786 case SIGQUIT:
5787 case SIGKILL:
5788 flush_pending_output (p->infd);
5789 break;
5792 /* If we don't have process groups, send the signal to the immediate
5793 subprocess. That isn't really right, but it's better than any
5794 obvious alternative. */
5795 if (no_pgrp)
5797 kill (p->pid, signo);
5798 return;
5801 /* gid may be a pid, or minus a pgrp's number */
5802 #ifdef TIOCSIGSEND
5803 if (!NILP (current_group))
5805 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
5806 kill (-gid, signo);
5808 else
5810 gid = - p->pid;
5811 kill (gid, signo);
5813 #else /* ! defined (TIOCSIGSEND) */
5814 kill (-gid, signo);
5815 #endif /* ! defined (TIOCSIGSEND) */
5818 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5819 doc: /* Interrupt process PROCESS.
5820 PROCESS may be a process, a buffer, or the name of a process or buffer.
5821 No arg or nil means current buffer's process.
5822 Second arg CURRENT-GROUP non-nil means send signal to
5823 the current process-group of the process's controlling terminal
5824 rather than to the process's own process group.
5825 If the process is a shell, this means interrupt current subjob
5826 rather than the shell.
5828 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5829 don't send the signal. */)
5830 (Lisp_Object process, Lisp_Object current_group)
5832 process_send_signal (process, SIGINT, current_group, 0);
5833 return process;
5836 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5837 doc: /* Kill process PROCESS. May be process or name of one.
5838 See function `interrupt-process' for more details on usage. */)
5839 (Lisp_Object process, Lisp_Object current_group)
5841 process_send_signal (process, SIGKILL, current_group, 0);
5842 return process;
5845 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5846 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5847 See function `interrupt-process' for more details on usage. */)
5848 (Lisp_Object process, Lisp_Object current_group)
5850 process_send_signal (process, SIGQUIT, current_group, 0);
5851 return process;
5854 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
5855 doc: /* Stop process PROCESS. May be process or name of one.
5856 See function `interrupt-process' for more details on usage.
5857 If PROCESS is a network or serial process, inhibit handling of incoming
5858 traffic. */)
5859 (Lisp_Object process, Lisp_Object current_group)
5861 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5863 struct Lisp_Process *p;
5865 p = XPROCESS (process);
5866 if (NILP (p->command)
5867 && p->infd >= 0)
5869 FD_CLR (p->infd, &input_wait_mask);
5870 FD_CLR (p->infd, &non_keyboard_wait_mask);
5872 pset_command (p, Qt);
5873 return process;
5875 #ifndef SIGTSTP
5876 error ("No SIGTSTP support");
5877 #else
5878 process_send_signal (process, SIGTSTP, current_group, 0);
5879 #endif
5880 return process;
5883 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
5884 doc: /* Continue process PROCESS. May be process or name of one.
5885 See function `interrupt-process' for more details on usage.
5886 If PROCESS is a network or serial process, resume handling of incoming
5887 traffic. */)
5888 (Lisp_Object process, Lisp_Object current_group)
5890 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5892 struct Lisp_Process *p;
5894 p = XPROCESS (process);
5895 if (EQ (p->command, Qt)
5896 && p->infd >= 0
5897 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
5899 FD_SET (p->infd, &input_wait_mask);
5900 FD_SET (p->infd, &non_keyboard_wait_mask);
5901 #ifdef WINDOWSNT
5902 if (fd_info[ p->infd ].flags & FILE_SERIAL)
5903 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
5904 #else /* not WINDOWSNT */
5905 tcflush (p->infd, TCIFLUSH);
5906 #endif /* not WINDOWSNT */
5908 pset_command (p, Qnil);
5909 return process;
5911 #ifdef SIGCONT
5912 process_send_signal (process, SIGCONT, current_group, 0);
5913 #else
5914 error ("No SIGCONT support");
5915 #endif
5916 return process;
5919 /* Return the integer value of the signal whose abbreviation is ABBR,
5920 or a negative number if there is no such signal. */
5921 static int
5922 abbr_to_signal (char const *name)
5924 int i, signo;
5925 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
5927 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
5928 name += 3;
5930 for (i = 0; i < sizeof sigbuf; i++)
5932 sigbuf[i] = c_toupper (name[i]);
5933 if (! sigbuf[i])
5934 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
5937 return -1;
5940 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
5941 2, 2, "sProcess (name or number): \nnSignal code: ",
5942 doc: /* Send PROCESS the signal with code SIGCODE.
5943 PROCESS may also be a number specifying the process id of the
5944 process to signal; in this case, the process need not be a child of
5945 this Emacs.
5946 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5947 (Lisp_Object process, Lisp_Object sigcode)
5949 pid_t pid;
5950 int signo;
5952 if (STRINGP (process))
5954 Lisp_Object tem = Fget_process (process);
5955 if (NILP (tem))
5957 Lisp_Object process_number =
5958 string_to_number (SSDATA (process), 10, 1);
5959 if (INTEGERP (process_number) || FLOATP (process_number))
5960 tem = process_number;
5962 process = tem;
5964 else if (!NUMBERP (process))
5965 process = get_process (process);
5967 if (NILP (process))
5968 return process;
5970 if (NUMBERP (process))
5971 CONS_TO_INTEGER (process, pid_t, pid);
5972 else
5974 CHECK_PROCESS (process);
5975 pid = XPROCESS (process)->pid;
5976 if (pid <= 0)
5977 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
5980 if (INTEGERP (sigcode))
5982 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
5983 signo = XINT (sigcode);
5985 else
5987 char *name;
5989 CHECK_SYMBOL (sigcode);
5990 name = SSDATA (SYMBOL_NAME (sigcode));
5992 signo = abbr_to_signal (name);
5993 if (signo < 0)
5994 error ("Undefined signal name %s", name);
5997 return make_number (kill (pid, signo));
6000 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6001 doc: /* Make PROCESS see end-of-file in its input.
6002 EOF comes after any text already sent to it.
6003 PROCESS may be a process, a buffer, the name of a process or buffer, or
6004 nil, indicating the current buffer's process.
6005 If PROCESS is a network connection, or is a process communicating
6006 through a pipe (as opposed to a pty), then you cannot send any more
6007 text to PROCESS after you call this function.
6008 If PROCESS is a serial process, wait until all output written to the
6009 process has been transmitted to the serial port. */)
6010 (Lisp_Object process)
6012 Lisp_Object proc;
6013 struct coding_system *coding;
6015 if (DATAGRAM_CONN_P (process))
6016 return process;
6018 proc = get_process (process);
6019 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6021 /* Make sure the process is really alive. */
6022 if (XPROCESS (proc)->raw_status_new)
6023 update_status (XPROCESS (proc));
6024 if (! EQ (XPROCESS (proc)->status, Qrun))
6025 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6027 if (CODING_REQUIRE_FLUSHING (coding))
6029 coding->mode |= CODING_MODE_LAST_BLOCK;
6030 send_process (proc, "", 0, Qnil);
6033 if (XPROCESS (proc)->pty_flag)
6034 send_process (proc, "\004", 1, Qnil);
6035 else if (EQ (XPROCESS (proc)->type, Qserial))
6037 #ifndef WINDOWSNT
6038 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6039 error ("tcdrain() failed: %s", emacs_strerror (errno));
6040 #endif /* not WINDOWSNT */
6041 /* Do nothing on Windows because writes are blocking. */
6043 else
6045 int old_outfd, new_outfd;
6047 #ifdef HAVE_SHUTDOWN
6048 /* If this is a network connection, or socketpair is used
6049 for communication with the subprocess, call shutdown to cause EOF.
6050 (In some old system, shutdown to socketpair doesn't work.
6051 Then we just can't win.) */
6052 if (EQ (XPROCESS (proc)->type, Qnetwork)
6053 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6054 shutdown (XPROCESS (proc)->outfd, 1);
6055 /* In case of socketpair, outfd == infd, so don't close it. */
6056 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6057 emacs_close (XPROCESS (proc)->outfd);
6058 #else /* not HAVE_SHUTDOWN */
6059 emacs_close (XPROCESS (proc)->outfd);
6060 #endif /* not HAVE_SHUTDOWN */
6061 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6062 if (new_outfd < 0)
6063 emacs_abort ();
6064 old_outfd = XPROCESS (proc)->outfd;
6066 if (!proc_encode_coding_system[new_outfd])
6067 proc_encode_coding_system[new_outfd]
6068 = xmalloc (sizeof (struct coding_system));
6069 *proc_encode_coding_system[new_outfd]
6070 = *proc_encode_coding_system[old_outfd];
6071 memset (proc_encode_coding_system[old_outfd], 0,
6072 sizeof (struct coding_system));
6074 XPROCESS (proc)->outfd = new_outfd;
6076 return process;
6079 /* The main Emacs thread records child processes in three places:
6081 - Vprocess_alist, for asynchronous subprocesses, which are child
6082 processes visible to Lisp.
6084 - deleted_pid_list, for child processes invisible to Lisp,
6085 typically because of delete-process. These are recorded so that
6086 the processes can be reaped when they exit, so that the operating
6087 system's process table is not cluttered by zombies.
6089 - the local variable PID in Fcall_process, call_process_cleanup and
6090 call_process_kill, for synchronous subprocesses.
6091 record_unwind_protect is used to make sure this process is not
6092 forgotten: if the user interrupts call-process and the child
6093 process refuses to exit immediately even with two C-g's,
6094 call_process_kill adds PID's contents to deleted_pid_list before
6095 returning.
6097 The main Emacs thread invokes waitpid only on child processes that
6098 it creates and that have not been reaped. This avoid races on
6099 platforms such as GTK, where other threads create their own
6100 subprocesses which the main thread should not reap. For example,
6101 if the main thread attempted to reap an already-reaped child, it
6102 might inadvertently reap a GTK-created process that happened to
6103 have the same process ID. */
6105 /* Handle a SIGCHLD signal by looking for known child processes of
6106 Emacs whose status have changed. For each one found, record its
6107 new status.
6109 All we do is change the status; we do not run sentinels or print
6110 notifications. That is saved for the next time keyboard input is
6111 done, in order to avoid timing errors.
6113 ** WARNING: this can be called during garbage collection.
6114 Therefore, it must not be fooled by the presence of mark bits in
6115 Lisp objects.
6117 ** USG WARNING: Although it is not obvious from the documentation
6118 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6119 signal() before executing at least one wait(), otherwise the
6120 handler will be called again, resulting in an infinite loop. The
6121 relevant portion of the documentation reads "SIGCLD signals will be
6122 queued and the signal-catching function will be continually
6123 reentered until the queue is empty". Invoking signal() causes the
6124 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6125 Inc.
6127 ** Malloc WARNING: This should never call malloc either directly or
6128 indirectly; if it does, that is a bug */
6130 static void
6131 handle_child_signal (int sig)
6133 Lisp_Object tail;
6135 /* Find the process that signaled us, and record its status. */
6137 /* The process can have been deleted by Fdelete_process, or have
6138 been started asynchronously by Fcall_process. */
6139 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6141 bool all_pids_are_fixnums
6142 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6143 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6144 Lisp_Object xpid = XCAR (tail);
6145 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6147 pid_t deleted_pid;
6148 if (INTEGERP (xpid))
6149 deleted_pid = XINT (xpid);
6150 else
6151 deleted_pid = XFLOAT_DATA (xpid);
6152 if (child_status_changed (deleted_pid, 0, 0))
6153 XSETCAR (tail, Qnil);
6157 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6158 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6160 Lisp_Object proc = XCDR (XCAR (tail));
6161 struct Lisp_Process *p = XPROCESS (proc);
6162 int status;
6164 if (p->alive && child_status_changed (p->pid, &status, WUNTRACED))
6166 /* Change the status of the process that was found. */
6167 p->tick = ++process_tick;
6168 p->raw_status = status;
6169 p->raw_status_new = 1;
6171 /* If process has terminated, stop waiting for its output. */
6172 if (WIFSIGNALED (status) || WIFEXITED (status))
6174 int clear_desc_flag = 0;
6175 p->alive = 0;
6176 if (p->infd >= 0)
6177 clear_desc_flag = 1;
6179 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6180 if (clear_desc_flag)
6182 FD_CLR (p->infd, &input_wait_mask);
6183 FD_CLR (p->infd, &non_keyboard_wait_mask);
6190 static void
6191 deliver_child_signal (int sig)
6193 deliver_process_signal (sig, handle_child_signal);
6197 static Lisp_Object
6198 exec_sentinel_unwind (Lisp_Object data)
6200 pset_sentinel (XPROCESS (XCAR (data)), XCDR (data));
6201 return Qnil;
6204 static Lisp_Object
6205 exec_sentinel_error_handler (Lisp_Object error_val)
6207 cmd_error_internal (error_val, "error in process sentinel: ");
6208 Vinhibit_quit = Qt;
6209 update_echo_area ();
6210 Fsleep_for (make_number (2), Qnil);
6211 return Qt;
6214 static void
6215 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6217 Lisp_Object sentinel, odeactivate;
6218 struct Lisp_Process *p = XPROCESS (proc);
6219 ptrdiff_t count = SPECPDL_INDEX ();
6220 bool outer_running_asynch_code = running_asynch_code;
6221 int waiting = waiting_for_user_input_p;
6223 if (inhibit_sentinels)
6224 return;
6226 /* No need to gcpro these, because all we do with them later
6227 is test them for EQness, and none of them should be a string. */
6228 odeactivate = Vdeactivate_mark;
6229 #if 0
6230 Lisp_Object obuffer, okeymap;
6231 XSETBUFFER (obuffer, current_buffer);
6232 okeymap = BVAR (current_buffer, keymap);
6233 #endif
6235 /* There's no good reason to let sentinels change the current
6236 buffer, and many callers of accept-process-output, sit-for, and
6237 friends don't expect current-buffer to be changed from under them. */
6238 record_unwind_current_buffer ();
6240 sentinel = p->sentinel;
6241 if (NILP (sentinel))
6242 return;
6244 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6245 assure that it gets restored no matter how the sentinel exits. */
6246 pset_sentinel (p, Qnil);
6247 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6248 /* Inhibit quit so that random quits don't screw up a running filter. */
6249 specbind (Qinhibit_quit, Qt);
6250 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6252 /* In case we get recursively called,
6253 and we already saved the match data nonrecursively,
6254 save the same match data in safely recursive fashion. */
6255 if (outer_running_asynch_code)
6257 Lisp_Object tem;
6258 tem = Fmatch_data (Qnil, Qnil, Qnil);
6259 restore_search_regs ();
6260 record_unwind_save_match_data ();
6261 Fset_match_data (tem, Qt);
6264 /* For speed, if a search happens within this code,
6265 save the match data in a special nonrecursive fashion. */
6266 running_asynch_code = 1;
6268 internal_condition_case_1 (read_process_output_call,
6269 Fcons (sentinel,
6270 Fcons (proc, Fcons (reason, Qnil))),
6271 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6272 exec_sentinel_error_handler);
6274 /* If we saved the match data nonrecursively, restore it now. */
6275 restore_search_regs ();
6276 running_asynch_code = outer_running_asynch_code;
6278 Vdeactivate_mark = odeactivate;
6280 /* Restore waiting_for_user_input_p as it was
6281 when we were called, in case the filter clobbered it. */
6282 waiting_for_user_input_p = waiting;
6284 #if 0
6285 if (! EQ (Fcurrent_buffer (), obuffer)
6286 || ! EQ (current_buffer->keymap, okeymap))
6287 #endif
6288 /* But do it only if the caller is actually going to read events.
6289 Otherwise there's no need to make him wake up, and it could
6290 cause trouble (for example it would make sit_for return). */
6291 if (waiting_for_user_input_p == -1)
6292 record_asynch_buffer_change ();
6294 unbind_to (count, Qnil);
6297 /* Report all recent events of a change in process status
6298 (either run the sentinel or output a message).
6299 This is usually done while Emacs is waiting for keyboard input
6300 but can be done at other times. */
6302 static void
6303 status_notify (struct Lisp_Process *deleting_process)
6305 register Lisp_Object proc, buffer;
6306 Lisp_Object tail, msg;
6307 struct gcpro gcpro1, gcpro2;
6309 tail = Qnil;
6310 msg = Qnil;
6311 /* We need to gcpro tail; if read_process_output calls a filter
6312 which deletes a process and removes the cons to which tail points
6313 from Vprocess_alist, and then causes a GC, tail is an unprotected
6314 reference. */
6315 GCPRO2 (tail, msg);
6317 /* Set this now, so that if new processes are created by sentinels
6318 that we run, we get called again to handle their status changes. */
6319 update_tick = process_tick;
6321 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6323 Lisp_Object symbol;
6324 register struct Lisp_Process *p;
6326 proc = Fcdr (XCAR (tail));
6327 p = XPROCESS (proc);
6329 if (p->tick != p->update_tick)
6331 p->update_tick = p->tick;
6333 /* If process is still active, read any output that remains. */
6334 while (! EQ (p->filter, Qt)
6335 && ! EQ (p->status, Qconnect)
6336 && ! EQ (p->status, Qlisten)
6337 /* Network or serial process not stopped: */
6338 && ! EQ (p->command, Qt)
6339 && p->infd >= 0
6340 && p != deleting_process
6341 && read_process_output (proc, p->infd) > 0);
6343 buffer = p->buffer;
6345 /* Get the text to use for the message. */
6346 if (p->raw_status_new)
6347 update_status (p);
6348 msg = status_message (p);
6350 /* If process is terminated, deactivate it or delete it. */
6351 symbol = p->status;
6352 if (CONSP (p->status))
6353 symbol = XCAR (p->status);
6355 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6356 || EQ (symbol, Qclosed))
6358 if (delete_exited_processes)
6359 remove_process (proc);
6360 else
6361 deactivate_process (proc);
6364 /* The actions above may have further incremented p->tick.
6365 So set p->update_tick again
6366 so that an error in the sentinel will not cause
6367 this code to be run again. */
6368 p->update_tick = p->tick;
6369 /* Now output the message suitably. */
6370 if (!NILP (p->sentinel))
6371 exec_sentinel (proc, msg);
6372 /* Don't bother with a message in the buffer
6373 when a process becomes runnable. */
6374 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6376 Lisp_Object tem;
6377 struct buffer *old = current_buffer;
6378 ptrdiff_t opoint, opoint_byte;
6379 ptrdiff_t before, before_byte;
6381 /* Avoid error if buffer is deleted
6382 (probably that's why the process is dead, too) */
6383 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6384 continue;
6385 Fset_buffer (buffer);
6387 opoint = PT;
6388 opoint_byte = PT_BYTE;
6389 /* Insert new output into buffer
6390 at the current end-of-output marker,
6391 thus preserving logical ordering of input and output. */
6392 if (XMARKER (p->mark)->buffer)
6393 Fgoto_char (p->mark);
6394 else
6395 SET_PT_BOTH (ZV, ZV_BYTE);
6397 before = PT;
6398 before_byte = PT_BYTE;
6400 tem = BVAR (current_buffer, read_only);
6401 bset_read_only (current_buffer, Qnil);
6402 insert_string ("\nProcess ");
6403 { /* FIXME: temporary kludge */
6404 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6405 insert_string (" ");
6406 Finsert (1, &msg);
6407 bset_read_only (current_buffer, tem);
6408 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6410 if (opoint >= before)
6411 SET_PT_BOTH (opoint + (PT - before),
6412 opoint_byte + (PT_BYTE - before_byte));
6413 else
6414 SET_PT_BOTH (opoint, opoint_byte);
6416 set_buffer_internal (old);
6419 } /* end for */
6421 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6422 UNGCPRO;
6426 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6427 Sset_process_coding_system, 1, 3, 0,
6428 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6429 DECODING will be used to decode subprocess output and ENCODING to
6430 encode subprocess input. */)
6431 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6433 register struct Lisp_Process *p;
6435 CHECK_PROCESS (process);
6436 p = XPROCESS (process);
6437 if (p->infd < 0)
6438 error ("Input file descriptor of %s closed", SDATA (p->name));
6439 if (p->outfd < 0)
6440 error ("Output file descriptor of %s closed", SDATA (p->name));
6441 Fcheck_coding_system (decoding);
6442 Fcheck_coding_system (encoding);
6443 encoding = coding_inherit_eol_type (encoding, Qnil);
6444 pset_decode_coding_system (p, decoding);
6445 pset_encode_coding_system (p, encoding);
6446 setup_process_coding_systems (process);
6448 return Qnil;
6451 DEFUN ("process-coding-system",
6452 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6453 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6454 (register Lisp_Object process)
6456 CHECK_PROCESS (process);
6457 return Fcons (XPROCESS (process)->decode_coding_system,
6458 XPROCESS (process)->encode_coding_system);
6461 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6462 Sset_process_filter_multibyte, 2, 2, 0,
6463 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6464 If FLAG is non-nil, the filter is given multibyte strings.
6465 If FLAG is nil, the filter is given unibyte strings. In this case,
6466 all character code conversion except for end-of-line conversion is
6467 suppressed. */)
6468 (Lisp_Object process, Lisp_Object flag)
6470 register struct Lisp_Process *p;
6472 CHECK_PROCESS (process);
6473 p = XPROCESS (process);
6474 if (NILP (flag))
6475 pset_decode_coding_system
6476 (p, raw_text_coding_system (p->decode_coding_system));
6477 setup_process_coding_systems (process);
6479 return Qnil;
6482 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6483 Sprocess_filter_multibyte_p, 1, 1, 0,
6484 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6485 (Lisp_Object process)
6487 register struct Lisp_Process *p;
6488 struct coding_system *coding;
6490 CHECK_PROCESS (process);
6491 p = XPROCESS (process);
6492 coding = proc_decode_coding_system[p->infd];
6493 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6499 # ifdef HAVE_GPM
6501 void
6502 add_gpm_wait_descriptor (int desc)
6504 add_keyboard_wait_descriptor (desc);
6507 void
6508 delete_gpm_wait_descriptor (int desc)
6510 delete_keyboard_wait_descriptor (desc);
6513 # endif
6515 # ifdef USABLE_SIGIO
6517 /* Return nonzero if *MASK has a bit set
6518 that corresponds to one of the keyboard input descriptors. */
6520 static int
6521 keyboard_bit_set (fd_set *mask)
6523 int fd;
6525 for (fd = 0; fd <= max_input_desc; fd++)
6526 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6527 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6528 return 1;
6530 return 0;
6532 # endif
6534 #else /* not subprocesses */
6536 /* Defined on msdos.c. */
6537 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6538 EMACS_TIME *, void *);
6540 /* Implementation of wait_reading_process_output, assuming that there
6541 are no subprocesses. Used only by the MS-DOS build.
6543 Wait for timeout to elapse and/or keyboard input to be available.
6545 TIME_LIMIT is:
6546 timeout in seconds
6547 If negative, gobble data immediately available but don't wait for any.
6549 NSECS is:
6550 an additional duration to wait, measured in nanoseconds
6551 If TIME_LIMIT is zero, then:
6552 If NSECS == 0, there is no limit.
6553 If NSECS > 0, the timeout consists of NSECS only.
6554 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6556 READ_KBD is:
6557 0 to ignore keyboard input, or
6558 1 to return when input is available, or
6559 -1 means caller will actually read the input, so don't throw to
6560 the quit handler.
6562 see full version for other parameters. We know that wait_proc will
6563 always be NULL, since `subprocesses' isn't defined.
6565 DO_DISPLAY means redisplay should be done to show subprocess
6566 output that arrives.
6568 Return true if we received input from any process. */
6571 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6572 bool do_display,
6573 Lisp_Object wait_for_cell,
6574 struct Lisp_Process *wait_proc, int just_wait_proc)
6576 register int nfds;
6577 EMACS_TIME end_time, timeout;
6579 if (time_limit < 0)
6581 time_limit = 0;
6582 nsecs = -1;
6584 else if (TYPE_MAXIMUM (time_t) < time_limit)
6585 time_limit = TYPE_MAXIMUM (time_t);
6587 /* What does time_limit really mean? */
6588 if (time_limit || 0 < nsecs)
6590 timeout = make_emacs_time (time_limit, nsecs);
6591 end_time = add_emacs_time (current_emacs_time (), timeout);
6594 /* Turn off periodic alarms (in case they are in use)
6595 and then turn off any other atimers,
6596 because the select emulator uses alarms. */
6597 stop_polling ();
6598 turn_on_atimers (0);
6600 while (1)
6602 int timeout_reduced_for_timers = 0;
6603 SELECT_TYPE waitchannels;
6604 int xerrno;
6606 /* If calling from keyboard input, do not quit
6607 since we want to return C-g as an input character.
6608 Otherwise, do pending quit if requested. */
6609 if (read_kbd >= 0)
6610 QUIT;
6612 /* Exit now if the cell we're waiting for became non-nil. */
6613 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6614 break;
6616 /* Compute time from now till when time limit is up */
6617 /* Exit if already run out */
6618 if (nsecs < 0)
6620 /* A negative timeout means
6621 gobble output available now
6622 but don't wait at all. */
6624 timeout = make_emacs_time (0, 0);
6626 else if (time_limit || 0 < nsecs)
6628 EMACS_TIME now = current_emacs_time ();
6629 if (EMACS_TIME_LE (end_time, now))
6630 break;
6631 timeout = sub_emacs_time (end_time, now);
6633 else
6635 timeout = make_emacs_time (100000, 0);
6638 /* If our caller will not immediately handle keyboard events,
6639 run timer events directly.
6640 (Callers that will immediately read keyboard events
6641 call timer_delay on their own.) */
6642 if (NILP (wait_for_cell))
6644 EMACS_TIME timer_delay;
6648 unsigned old_timers_run = timers_run;
6649 timer_delay = timer_check ();
6650 if (timers_run != old_timers_run && do_display)
6651 /* We must retry, since a timer may have requeued itself
6652 and that could alter the time delay. */
6653 redisplay_preserve_echo_area (14);
6654 else
6655 break;
6657 while (!detect_input_pending ());
6659 /* If there is unread keyboard input, also return. */
6660 if (read_kbd != 0
6661 && requeued_events_pending_p ())
6662 break;
6664 if (EMACS_TIME_VALID_P (timer_delay) && 0 <= nsecs)
6666 if (EMACS_TIME_LT (timer_delay, timeout))
6668 timeout = timer_delay;
6669 timeout_reduced_for_timers = 1;
6674 /* Cause C-g and alarm signals to take immediate action,
6675 and cause input available signals to zero out timeout. */
6676 if (read_kbd < 0)
6677 set_waiting_for_input (&timeout);
6679 /* If a frame has been newly mapped and needs updating,
6680 reprocess its display stuff. */
6681 if (frame_garbaged && do_display)
6683 clear_waiting_for_input ();
6684 redisplay_preserve_echo_area (15);
6685 if (read_kbd < 0)
6686 set_waiting_for_input (&timeout);
6689 /* Wait till there is something to do. */
6690 FD_ZERO (&waitchannels);
6691 if (read_kbd && detect_input_pending ())
6692 nfds = 0;
6693 else
6695 if (read_kbd || !NILP (wait_for_cell))
6696 FD_SET (0, &waitchannels);
6697 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
6700 xerrno = errno;
6702 /* Make C-g and alarm signals set flags again */
6703 clear_waiting_for_input ();
6705 /* If we woke up due to SIGWINCH, actually change size now. */
6706 do_pending_window_change (0);
6708 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
6709 /* We waited the full specified time, so return now. */
6710 break;
6712 if (nfds == -1)
6714 /* If the system call was interrupted, then go around the
6715 loop again. */
6716 if (xerrno == EINTR)
6717 FD_ZERO (&waitchannels);
6718 else
6719 error ("select error: %s", emacs_strerror (xerrno));
6722 /* Check for keyboard input */
6724 if (read_kbd
6725 && detect_input_pending_run_timers (do_display))
6727 swallow_events (do_display);
6728 if (detect_input_pending_run_timers (do_display))
6729 break;
6732 /* If there is unread keyboard input, also return. */
6733 if (read_kbd
6734 && requeued_events_pending_p ())
6735 break;
6737 /* If wait_for_cell. check for keyboard input
6738 but don't run any timers.
6739 ??? (It seems wrong to me to check for keyboard
6740 input at all when wait_for_cell, but the code
6741 has been this way since July 1994.
6742 Try changing this after version 19.31.) */
6743 if (! NILP (wait_for_cell)
6744 && detect_input_pending ())
6746 swallow_events (do_display);
6747 if (detect_input_pending ())
6748 break;
6751 /* Exit now if the cell we're waiting for became non-nil. */
6752 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6753 break;
6756 start_polling ();
6758 return 0;
6761 #endif /* not subprocesses */
6763 /* The following functions are needed even if async subprocesses are
6764 not supported. Some of them are no-op stubs in that case. */
6766 /* Add DESC to the set of keyboard input descriptors. */
6768 void
6769 add_keyboard_wait_descriptor (int desc)
6771 #ifdef subprocesses /* actually means "not MSDOS" */
6772 FD_SET (desc, &input_wait_mask);
6773 FD_SET (desc, &non_process_wait_mask);
6774 if (desc > max_input_desc)
6775 max_input_desc = desc;
6776 #endif
6779 /* From now on, do not expect DESC to give keyboard input. */
6781 void
6782 delete_keyboard_wait_descriptor (int desc)
6784 #ifdef subprocesses
6785 int fd;
6786 int lim = max_input_desc;
6788 FD_CLR (desc, &input_wait_mask);
6789 FD_CLR (desc, &non_process_wait_mask);
6791 if (desc == max_input_desc)
6792 for (fd = 0; fd < lim; fd++)
6793 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
6794 max_input_desc = fd;
6795 #endif
6798 /* Setup coding systems of PROCESS. */
6800 void
6801 setup_process_coding_systems (Lisp_Object process)
6803 #ifdef subprocesses
6804 struct Lisp_Process *p = XPROCESS (process);
6805 int inch = p->infd;
6806 int outch = p->outfd;
6807 Lisp_Object coding_system;
6809 if (inch < 0 || outch < 0)
6810 return;
6812 if (!proc_decode_coding_system[inch])
6813 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
6814 coding_system = p->decode_coding_system;
6815 if (! NILP (p->filter))
6817 else if (BUFFERP (p->buffer))
6819 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
6820 coding_system = raw_text_coding_system (coding_system);
6822 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
6824 if (!proc_encode_coding_system[outch])
6825 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
6826 setup_coding_system (p->encode_coding_system,
6827 proc_encode_coding_system[outch]);
6828 #endif
6831 /* Close all descriptors currently in use for communication
6832 with subprocess. This is used in a newly-forked subprocess
6833 to get rid of irrelevant descriptors. */
6835 void
6836 close_process_descs (void)
6838 #ifndef DOS_NT
6839 int i;
6840 for (i = 0; i < MAXDESC; i++)
6842 Lisp_Object process;
6843 process = chan_process[i];
6844 if (!NILP (process))
6846 int in = XPROCESS (process)->infd;
6847 int out = XPROCESS (process)->outfd;
6848 if (in >= 0)
6849 emacs_close (in);
6850 if (out >= 0 && in != out)
6851 emacs_close (out);
6854 #endif
6857 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
6858 doc: /* Return the (or a) process associated with BUFFER.
6859 BUFFER may be a buffer or the name of one. */)
6860 (register Lisp_Object buffer)
6862 #ifdef subprocesses
6863 register Lisp_Object buf, tail, proc;
6865 if (NILP (buffer)) return Qnil;
6866 buf = Fget_buffer (buffer);
6867 if (NILP (buf)) return Qnil;
6869 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6871 proc = Fcdr (XCAR (tail));
6872 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
6873 return proc;
6875 #endif /* subprocesses */
6876 return Qnil;
6879 DEFUN ("process-inherit-coding-system-flag",
6880 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
6881 1, 1, 0,
6882 doc: /* Return the value of inherit-coding-system flag for PROCESS.
6883 If this flag is t, `buffer-file-coding-system' of the buffer
6884 associated with PROCESS will inherit the coding system used to decode
6885 the process output. */)
6886 (register Lisp_Object process)
6888 #ifdef subprocesses
6889 CHECK_PROCESS (process);
6890 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
6891 #else
6892 /* Ignore the argument and return the value of
6893 inherit-process-coding-system. */
6894 return inherit_process_coding_system ? Qt : Qnil;
6895 #endif
6898 /* Kill all processes associated with `buffer'.
6899 If `buffer' is nil, kill all processes */
6901 void
6902 kill_buffer_processes (Lisp_Object buffer)
6904 #ifdef subprocesses
6905 Lisp_Object tail, proc;
6907 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6909 proc = XCDR (XCAR (tail));
6910 if (PROCESSP (proc)
6911 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
6913 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6914 Fdelete_process (proc);
6915 else if (XPROCESS (proc)->infd >= 0)
6916 process_send_signal (proc, SIGHUP, Qnil, 1);
6919 #else /* subprocesses */
6920 /* Since we have no subprocesses, this does nothing. */
6921 #endif /* subprocesses */
6924 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
6925 Swaiting_for_user_input_p, 0, 0, 0,
6926 doc: /* Returns non-nil if Emacs is waiting for input from the user.
6927 This is intended for use by asynchronous process output filters and sentinels. */)
6928 (void)
6930 #ifdef subprocesses
6931 return (waiting_for_user_input_p ? Qt : Qnil);
6932 #else
6933 return Qnil;
6934 #endif
6937 /* Stop reading input from keyboard sources. */
6939 void
6940 hold_keyboard_input (void)
6942 kbd_is_on_hold = 1;
6945 /* Resume reading input from keyboard sources. */
6947 void
6948 unhold_keyboard_input (void)
6950 kbd_is_on_hold = 0;
6953 /* Return non-zero if keyboard input is on hold, zero otherwise. */
6956 kbd_on_hold_p (void)
6958 return kbd_is_on_hold;
6962 /* Enumeration of and access to system processes a-la ps(1). */
6964 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
6965 0, 0, 0,
6966 doc: /* Return a list of numerical process IDs of all running processes.
6967 If this functionality is unsupported, return nil.
6969 See `process-attributes' for getting attributes of a process given its ID. */)
6970 (void)
6972 return list_system_processes ();
6975 DEFUN ("process-attributes", Fprocess_attributes,
6976 Sprocess_attributes, 1, 1, 0,
6977 doc: /* Return attributes of the process given by its PID, a number.
6979 Value is an alist where each element is a cons cell of the form
6981 \(KEY . VALUE)
6983 If this functionality is unsupported, the value is nil.
6985 See `list-system-processes' for getting a list of all process IDs.
6987 The KEYs of the attributes that this function may return are listed
6988 below, together with the type of the associated VALUE (in parentheses).
6989 Not all platforms support all of these attributes; unsupported
6990 attributes will not appear in the returned alist.
6991 Unless explicitly indicated otherwise, numbers can have either
6992 integer or floating point values.
6994 euid -- Effective user User ID of the process (number)
6995 user -- User name corresponding to euid (string)
6996 egid -- Effective user Group ID of the process (number)
6997 group -- Group name corresponding to egid (string)
6998 comm -- Command name (executable name only) (string)
6999 state -- Process state code, such as "S", "R", or "T" (string)
7000 ppid -- Parent process ID (number)
7001 pgrp -- Process group ID (number)
7002 sess -- Session ID, i.e. process ID of session leader (number)
7003 ttname -- Controlling tty name (string)
7004 tpgid -- ID of foreground process group on the process's tty (number)
7005 minflt -- number of minor page faults (number)
7006 majflt -- number of major page faults (number)
7007 cminflt -- cumulative number of minor page faults (number)
7008 cmajflt -- cumulative number of major page faults (number)
7009 utime -- user time used by the process, in (current-time) format,
7010 which is a list of integers (HIGH LOW USEC PSEC)
7011 stime -- system time used by the process (current-time)
7012 time -- sum of utime and stime (current-time)
7013 cutime -- user time used by the process and its children (current-time)
7014 cstime -- system time used by the process and its children (current-time)
7015 ctime -- sum of cutime and cstime (current-time)
7016 pri -- priority of the process (number)
7017 nice -- nice value of the process (number)
7018 thcount -- process thread count (number)
7019 start -- time the process started (current-time)
7020 vsize -- virtual memory size of the process in KB's (number)
7021 rss -- resident set size of the process in KB's (number)
7022 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7023 pcpu -- percents of CPU time used by the process (floating-point number)
7024 pmem -- percents of total physical memory used by process's resident set
7025 (floating-point number)
7026 args -- command line which invoked the process (string). */)
7027 ( Lisp_Object pid)
7029 return system_process_attributes (pid);
7033 /* This is not called "init_process" because that is the name of a
7034 Mach system call, so it would cause problems on Darwin systems. */
7035 void
7036 init_process_emacs (void)
7038 #ifdef subprocesses
7039 register int i;
7041 inhibit_sentinels = 0;
7043 #ifndef CANNOT_DUMP
7044 if (! noninteractive || initialized)
7045 #endif
7047 struct sigaction action;
7048 emacs_sigaction_init (&action, deliver_child_signal);
7049 sigaction (SIGCHLD, &action, 0);
7052 FD_ZERO (&input_wait_mask);
7053 FD_ZERO (&non_keyboard_wait_mask);
7054 FD_ZERO (&non_process_wait_mask);
7055 FD_ZERO (&write_mask);
7056 max_process_desc = 0;
7057 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7059 #ifdef NON_BLOCKING_CONNECT
7060 FD_ZERO (&connect_wait_mask);
7061 num_pending_connects = 0;
7062 #endif
7064 #ifdef ADAPTIVE_READ_BUFFERING
7065 process_output_delay_count = 0;
7066 process_output_skip = 0;
7067 #endif
7069 /* Don't do this, it caused infinite select loops. The display
7070 method should call add_keyboard_wait_descriptor on stdin if it
7071 needs that. */
7072 #if 0
7073 FD_SET (0, &input_wait_mask);
7074 #endif
7076 Vprocess_alist = Qnil;
7077 deleted_pid_list = Qnil;
7078 for (i = 0; i < MAXDESC; i++)
7080 chan_process[i] = Qnil;
7081 proc_buffered_char[i] = -1;
7083 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7084 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7085 #ifdef DATAGRAM_SOCKETS
7086 memset (datagram_address, 0, sizeof datagram_address);
7087 #endif
7090 Lisp_Object subfeatures = Qnil;
7091 const struct socket_options *sopt;
7093 #define ADD_SUBFEATURE(key, val) \
7094 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7096 #ifdef NON_BLOCKING_CONNECT
7097 ADD_SUBFEATURE (QCnowait, Qt);
7098 #endif
7099 #ifdef DATAGRAM_SOCKETS
7100 ADD_SUBFEATURE (QCtype, Qdatagram);
7101 #endif
7102 #ifdef HAVE_SEQPACKET
7103 ADD_SUBFEATURE (QCtype, Qseqpacket);
7104 #endif
7105 #ifdef HAVE_LOCAL_SOCKETS
7106 ADD_SUBFEATURE (QCfamily, Qlocal);
7107 #endif
7108 ADD_SUBFEATURE (QCfamily, Qipv4);
7109 #ifdef AF_INET6
7110 ADD_SUBFEATURE (QCfamily, Qipv6);
7111 #endif
7112 #ifdef HAVE_GETSOCKNAME
7113 ADD_SUBFEATURE (QCservice, Qt);
7114 #endif
7115 ADD_SUBFEATURE (QCserver, Qt);
7117 for (sopt = socket_options; sopt->name; sopt++)
7118 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7120 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7123 #if defined (DARWIN_OS)
7124 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7125 processes. As such, we only change the default value. */
7126 if (initialized)
7128 char const *release = (STRINGP (Voperating_system_release)
7129 ? SSDATA (Voperating_system_release)
7130 : 0);
7131 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7132 Vprocess_connection_type = Qnil;
7135 #endif
7136 #endif /* subprocesses */
7137 kbd_is_on_hold = 0;
7140 void
7141 syms_of_process (void)
7143 #ifdef subprocesses
7145 DEFSYM (Qprocessp, "processp");
7146 DEFSYM (Qrun, "run");
7147 DEFSYM (Qstop, "stop");
7148 DEFSYM (Qsignal, "signal");
7150 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7151 here again.
7153 Qexit = intern_c_string ("exit");
7154 staticpro (&Qexit); */
7156 DEFSYM (Qopen, "open");
7157 DEFSYM (Qclosed, "closed");
7158 DEFSYM (Qconnect, "connect");
7159 DEFSYM (Qfailed, "failed");
7160 DEFSYM (Qlisten, "listen");
7161 DEFSYM (Qlocal, "local");
7162 DEFSYM (Qipv4, "ipv4");
7163 #ifdef AF_INET6
7164 DEFSYM (Qipv6, "ipv6");
7165 #endif
7166 DEFSYM (Qdatagram, "datagram");
7167 DEFSYM (Qseqpacket, "seqpacket");
7169 DEFSYM (QCport, ":port");
7170 DEFSYM (QCspeed, ":speed");
7171 DEFSYM (QCprocess, ":process");
7173 DEFSYM (QCbytesize, ":bytesize");
7174 DEFSYM (QCstopbits, ":stopbits");
7175 DEFSYM (QCparity, ":parity");
7176 DEFSYM (Qodd, "odd");
7177 DEFSYM (Qeven, "even");
7178 DEFSYM (QCflowcontrol, ":flowcontrol");
7179 DEFSYM (Qhw, "hw");
7180 DEFSYM (Qsw, "sw");
7181 DEFSYM (QCsummary, ":summary");
7183 DEFSYM (Qreal, "real");
7184 DEFSYM (Qnetwork, "network");
7185 DEFSYM (Qserial, "serial");
7186 DEFSYM (QCbuffer, ":buffer");
7187 DEFSYM (QChost, ":host");
7188 DEFSYM (QCservice, ":service");
7189 DEFSYM (QClocal, ":local");
7190 DEFSYM (QCremote, ":remote");
7191 DEFSYM (QCcoding, ":coding");
7192 DEFSYM (QCserver, ":server");
7193 DEFSYM (QCnowait, ":nowait");
7194 DEFSYM (QCsentinel, ":sentinel");
7195 DEFSYM (QClog, ":log");
7196 DEFSYM (QCnoquery, ":noquery");
7197 DEFSYM (QCstop, ":stop");
7198 DEFSYM (QCoptions, ":options");
7199 DEFSYM (QCplist, ":plist");
7201 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7203 staticpro (&Vprocess_alist);
7204 staticpro (&deleted_pid_list);
7206 #endif /* subprocesses */
7208 DEFSYM (QCname, ":name");
7209 DEFSYM (QCtype, ":type");
7211 DEFSYM (Qeuid, "euid");
7212 DEFSYM (Qegid, "egid");
7213 DEFSYM (Quser, "user");
7214 DEFSYM (Qgroup, "group");
7215 DEFSYM (Qcomm, "comm");
7216 DEFSYM (Qstate, "state");
7217 DEFSYM (Qppid, "ppid");
7218 DEFSYM (Qpgrp, "pgrp");
7219 DEFSYM (Qsess, "sess");
7220 DEFSYM (Qttname, "ttname");
7221 DEFSYM (Qtpgid, "tpgid");
7222 DEFSYM (Qminflt, "minflt");
7223 DEFSYM (Qmajflt, "majflt");
7224 DEFSYM (Qcminflt, "cminflt");
7225 DEFSYM (Qcmajflt, "cmajflt");
7226 DEFSYM (Qutime, "utime");
7227 DEFSYM (Qstime, "stime");
7228 DEFSYM (Qtime, "time");
7229 DEFSYM (Qcutime, "cutime");
7230 DEFSYM (Qcstime, "cstime");
7231 DEFSYM (Qctime, "ctime");
7232 DEFSYM (Qpri, "pri");
7233 DEFSYM (Qnice, "nice");
7234 DEFSYM (Qthcount, "thcount");
7235 DEFSYM (Qstart, "start");
7236 DEFSYM (Qvsize, "vsize");
7237 DEFSYM (Qrss, "rss");
7238 DEFSYM (Qetime, "etime");
7239 DEFSYM (Qpcpu, "pcpu");
7240 DEFSYM (Qpmem, "pmem");
7241 DEFSYM (Qargs, "args");
7243 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7244 doc: /* Non-nil means delete processes immediately when they exit.
7245 A value of nil means don't delete them until `list-processes' is run. */);
7247 delete_exited_processes = 1;
7249 #ifdef subprocesses
7250 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7251 doc: /* Control type of device used to communicate with subprocesses.
7252 Values are nil to use a pipe, or t or `pty' to use a pty.
7253 The value has no effect if the system has no ptys or if all ptys are busy:
7254 then a pipe is used in any case.
7255 The value takes effect when `start-process' is called. */);
7256 Vprocess_connection_type = Qt;
7258 #ifdef ADAPTIVE_READ_BUFFERING
7259 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7260 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7261 On some systems, when Emacs reads the output from a subprocess, the output data
7262 is read in very small blocks, potentially resulting in very poor performance.
7263 This behavior can be remedied to some extent by setting this variable to a
7264 non-nil value, as it will automatically delay reading from such processes, to
7265 allow them to produce more output before Emacs tries to read it.
7266 If the value is t, the delay is reset after each write to the process; any other
7267 non-nil value means that the delay is not reset on write.
7268 The variable takes effect when `start-process' is called. */);
7269 Vprocess_adaptive_read_buffering = Qt;
7270 #endif
7272 defsubr (&Sprocessp);
7273 defsubr (&Sget_process);
7274 defsubr (&Sdelete_process);
7275 defsubr (&Sprocess_status);
7276 defsubr (&Sprocess_exit_status);
7277 defsubr (&Sprocess_id);
7278 defsubr (&Sprocess_name);
7279 defsubr (&Sprocess_tty_name);
7280 defsubr (&Sprocess_command);
7281 defsubr (&Sset_process_buffer);
7282 defsubr (&Sprocess_buffer);
7283 defsubr (&Sprocess_mark);
7284 defsubr (&Sset_process_filter);
7285 defsubr (&Sprocess_filter);
7286 defsubr (&Sset_process_sentinel);
7287 defsubr (&Sprocess_sentinel);
7288 defsubr (&Sset_process_window_size);
7289 defsubr (&Sset_process_inherit_coding_system_flag);
7290 defsubr (&Sset_process_query_on_exit_flag);
7291 defsubr (&Sprocess_query_on_exit_flag);
7292 defsubr (&Sprocess_contact);
7293 defsubr (&Sprocess_plist);
7294 defsubr (&Sset_process_plist);
7295 defsubr (&Sprocess_list);
7296 defsubr (&Sstart_process);
7297 defsubr (&Sserial_process_configure);
7298 defsubr (&Smake_serial_process);
7299 defsubr (&Sset_network_process_option);
7300 defsubr (&Smake_network_process);
7301 defsubr (&Sformat_network_address);
7302 #if defined (HAVE_NET_IF_H)
7303 #ifdef SIOCGIFCONF
7304 defsubr (&Snetwork_interface_list);
7305 #endif
7306 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
7307 defsubr (&Snetwork_interface_info);
7308 #endif
7309 #endif /* defined (HAVE_NET_IF_H) */
7310 #ifdef DATAGRAM_SOCKETS
7311 defsubr (&Sprocess_datagram_address);
7312 defsubr (&Sset_process_datagram_address);
7313 #endif
7314 defsubr (&Saccept_process_output);
7315 defsubr (&Sprocess_send_region);
7316 defsubr (&Sprocess_send_string);
7317 defsubr (&Sinterrupt_process);
7318 defsubr (&Skill_process);
7319 defsubr (&Squit_process);
7320 defsubr (&Sstop_process);
7321 defsubr (&Scontinue_process);
7322 defsubr (&Sprocess_running_child_p);
7323 defsubr (&Sprocess_send_eof);
7324 defsubr (&Ssignal_process);
7325 defsubr (&Swaiting_for_user_input_p);
7326 defsubr (&Sprocess_type);
7327 defsubr (&Sset_process_coding_system);
7328 defsubr (&Sprocess_coding_system);
7329 defsubr (&Sset_process_filter_multibyte);
7330 defsubr (&Sprocess_filter_multibyte_p);
7332 #endif /* subprocesses */
7334 defsubr (&Sget_buffer_process);
7335 defsubr (&Sprocess_inherit_coding_system_flag);
7336 defsubr (&Slist_system_processes);
7337 defsubr (&Sprocess_attributes);